branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep># LPA-based-on-local-cycles
Label propagation algorithm based on local cycles for community detection
<file_sep>#include "network.h"
Network::Network() : numberOfNodes(0)
{
}
bool Network::init(const string inputPath)
{
try
{
QFile inputFile(QString::fromStdString(inputPath));
if (!inputFile.open(QFile::ReadOnly)) // try to open the file
return false;
// first loop to get the number of nodes
while (!inputFile.atEnd()) // read until EOF
{
QString line = inputFile.readLine(); // read line by line
line = line.replace("\r\n", "\0"); // remove the endl
line = line.replace("\n", "\0"); // remove the endl
QStringList list = line.split('\t'); // get two nodes
int v1 = list.at(0).toInt(),
v2 = list.at(1).toInt();
int value = (v2 > v1 ? v2 : v1);
if (value > numberOfNodes)
numberOfNodes = value;
}
// now get the edges
inputFile.seek(0); // put the cursor at the beginning of the file
// node labels start from zero so we should initializr from 1 to n
edges = new SparseMatrix<int>(numberOfNodes);
nodes = new vector<Node>(numberOfNodes + 1);
for (int i = 1; i <= numberOfNodes; ++i)
{
nodes->at(i).label = i;
nodes->at(i).degree = 0;
nodes->at(i).newLabel = i;
}
// second loop to get the edges
while (!inputFile.atEnd()) // get number of nodes
{
QString line = inputFile.readLine();
line = line.replace("\r\n", "\0");
line = line.replace("\n", "\0");
QStringList list = line.split('\t');
int v1 = list.at(0).toInt(),
v2 = list.at(1).toInt();
// indirected graph; having edge in both direction
edges->set(v1, v2, 1);
edges->set(v2, v1, 1);
// add the corresponding degree
nodes->at(v1).degree++;
nodes->at(v2).degree++;
}
// close the reading file
inputFile.close();
return true;
}
catch (exception ex)
{
cerr << ex.what() << endl;
return false;
}
}
bool Network::mainFunc()
{
int t = 1;
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
srand(seed);
int e = ((double) rand() / RAND_MAX);
while (NMI() >= e
&& (t <= numberOfNodes))
{
seed = chrono::system_clock::now().time_since_epoch().count();
std::shuffle(nodes->begin() + 1, nodes->end(), default_random_engine(seed));
for (auto i = nodes->begin() + 1; i != nodes->end(); ++i)
{
vector<int> *tmpNeighbors;
*tmpNeighbors = edges->getNeighbors(i->degree);
vector<Node> neighbors(tmpNeighbors->size() + 1);
/* the calculations are based on the labels or as we call it 'newLabel'
* not the node number itself which is just a distinction of nodes
*/
for (int i = 1; i <= tmpNeighbors->size(); i++)
{
int tmp = tmpNeighbors->at(i - 1);
neighbors.at(i).label = tmp;
neighbors.at(i).degree =
nodes->at(tmpNeighbors->at(i - 1)).degree;
neighbors.at(i).newLabel =
nodes->at(tmpNeighbors->at(i - 1)).newLabel;
}
map<Node, int> neighborFreq;
foreach (auto j, neighbors)
if (neighborFreq.count(j) == 0)
neighborFreq.insert(make_pair(j, std::count(neighbors.begin(),
neighbors.end(),
j)));
map<Node, int>::iterator iter = neighborFreq.begin();
int numberOfMax = 1;
int maxFreq = iter->second;
iter++;
vector<int> maxFreqLabels;
maxFreqLabels.push_back(iter->first.label);
for (; iter != neighborFreq.end(); iter++)
{
if (iter->second > maxFreq)
{
numberOfMax = 1;
maxFreq = iter->second;
maxFreqLabels.clear();
maxFreqLabels.push_back(iter->first.label);
}
else if (iter->second == maxFreq)
{
numberOfMax++;
maxFreqLabels.push_back(iter->first.label);
}
}
/* difference between LPA and LPACL happens here cause it looks
* for cycles in case of multiple labels having the same number
* of repetition in a node's neighbors list
*/
if (numberOfMax > 1)
{
vector<int> shortestCycle;
computeShortestCycle(i->degree, neighbors, shortestCycle);
if (shortestCycle.size() > 1)
{
i->newLabel = shortestCycle.at(1);
}
else
{
// choosing a random label having the maximum frequency
i->newLabel = nodes->at(
maxFreqLabels.
at(rand() % maxFreqLabels.size() + 1)).label;
}
}
else // only one type of labels are in the node's neighbors list
{
i->newLabel = maxFreqLabels.at(0);
}
}
t++;
}
}
int Network::NMI()
{
return 1;
}
//================= reference: geeksforgeeks.org (refined) ===================
void Network::computeShortestCycle(const int startingPoint,
const vector<Node> &neighbors,
vector<int> &shortestCycle)
{
int E = edges->numberOfRowElement(startingPoint);
auto minCycle = INT32_MAX;
for (int i = 0 ; i < E ; i++)
{
/* get current edge vertices which we currently
* remove from graph and then find shortest path
* between these two vertex using Dijkstra’s
* shortest path algorithm.
*/
edges->removeEdge(startingPoint, neighbors.at(i).label);
// minimum distance between these two vertices
int distance;
vector<int> tmpShrotestCycle;
if ((distance = shortestPath(startingPoint, neighbors.at(i).label,
tmpShrotestCycle,
neighbors)) < minCycle)
{
minCycle = distance;
shortestCycle = tmpShrotestCycle;
}
// to make a cycle we have to add weight of
// currently removed edge if this is the shortest
// cycle then update minCycle
// add current edge back to the graph
edges->set(startingPoint, neighbors.at(i).label, 1);
}
}
int Network::shortestPath(const int u, const int v,
vector<int> &tmpShortestCycle,
const vector<Node> &neighbors)
{
/* find shortest path from source to destination using Dijkstra’s
* shortest path algorithm [Time complexity O(E.logV)]
*/
// Create a set to store vertices that are being processed
set< pair<int, int> > nextEdge;
// Create a vector for distances and initialize all
// distances as infinite
vector<int> dist(neighbors.size(), INT16_MAX);
// Insert source itself in Set and initialize its distance as 0
nextEdge.insert(make_pair(0, u));
dist[u] = 0;
/* Looping till all uhortest vistance are finalized
* then setds will become empty
*/
// the cycle starts from the source node
tmpShortestCycle.push_back(u);
while (!nextEdge.empty())
{
/* The first vertex in Set is the minimum distance
* vertex, extract it from set
*/
pair<int, int> tmp = *(nextEdge.begin());
nextEdge.erase(nextEdge.begin());
/* vertex label is stored in second of pair (it has to be done this
* way to keep the vertices sorted distance (distance must be first
* item in pair)
*/
int u = tmp.second;
// 'i' is used to get all adjacent vertices of vertex 'u'
for (auto i = neighbors.begin() + 1; i != neighbors.end(); ++i)
{
// Get vertex label and weight of current adjacent of 'u'
int v = (*i).label;
int weight = edges->get(u, v);
// If there is a shorter path to v through u
if (dist[v] > dist[u] + weight)
{
/* If distance of v is not INT16_MAX then it must be in
* our set, so removing it and inserting again with
* updated less distance.
* Note : We extract only those vertices from Set
* for which distance is finalized. So for them,
* we would never reach here
*/
if (dist[v] != INT16_MAX)
nextEdge.erase(nextEdge.find(make_pair(dist[v], v)));
tmpShortestCycle.push_back(v);
// Updating distance of v
dist[v] = dist[u] + weight;
nextEdge.insert(make_pair(dist[v], v));
}
}
}
// return shortest path from current Source to destination
return dist[v] ;
}
bool operator <(const Node& node1, const Node& node2)
{
return node1.degree < node2.degree;
}
bool operator ==(Node& node1, const Node& node2)
{
return node1.degree == node2.degree;
}
<file_sep>#ifndef NETWORK_H
#define NETWORK_H
#include <set>
#include <iostream>
#include <string>
#include <algorithm>
#include <QFile>
#include <iomanip>
#include <QTime>
#include <fstream>
#include <math.h>
#include <random>
#include <chrono>
#include <vector>
#include <map>
// reference: https://github.com/meysam81/Sparse-Matrix
#include "../Sparse-Matrix/src/SparseMatrix/SparseMatrix.cpp"
using namespace std;
typedef struct Node
{
int label;
int newLabel;
int degree;
} Node;
class Network
{
private:
int numberOfNodes;
vector<Node> *nodes;
SparseMatrix<int> *edges;
int numberOfRealNetwork; // cA
int NMI();
void computeShortestCycle(const int startingPoint,
const vector<Node> &neighbors,
vector<int> &shortestCycle);
int shortestPath(const int u, const int v,
vector<int> &tmpShortestCycle,
const vector<Node> &neighbors);
public:
Network();
bool init(const string inputPath);
bool mainFunc();
};
#endif // NETWORK_H
<file_sep>#include <src/network.h>
int main(int argc, char *argv[])
{
Network network;
string outputPath = "output.txt";
if (argc == 3) // just input file passed as command line argument
{
network.init(argv[1]);
}
else if (argc == 4) // input and output
{
network.init(argv[1]);
outputPath = argv[2];
}
else // none
{
cout << "Usage: main.o <input file path>"
" [<output file path>]\n";
return 4;
}
if (network.mainFunc());
return 0;
}
|
71c216ca78047d3eeb7ccb858dc4314f16785aea
|
[
"Markdown",
"C++"
] | 4
|
Markdown
|
meysam81/LPALC
|
2580fae17289c484a909c3371debcb7b2eda48bd
|
78ac1e67dd3e33b6e223a04e1fc741504ccbe1a2
|
refs/heads/master
|
<repo_name>luthfihadiana/TwitterAnalyzer<file_sep>/homeDetector.php
<?php
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumerKey = "BojzoX0hbo2apAoKl7MhQrNGm";
$consumerSecret = "<KEY>";
$access_token = "<KEY>";
$access_token_secret = "<KEY>";
$connection = new TwitterOAuth($consumerKey, $consumerSecret, $access_token, $access_token_secret);
$content = $connection->get("account/verify_credentials");
$statuses = $connection->get("statuses/home_timeline", ["count" => 20, "exclude_replies" => true]);
$index = 0;
?>
<!-- <!DOCTYPE html> -->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Tugas Besar Stima 3</title>
<link href="https://fonts.googleapis.com/css?family=Comfortaa|Lobster" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<link rel="stylesheet" type="text/css" media="screen" href="materialize.min.css" />
<!-- <script src="main.js"></script> -->
</head>
<body>
<ul class="nav">
<!-- <li><a href="default.asp">Home</a></li> -->
<a href="index.php"><img href="#" src="logo.png" class="littleLogo"></a>
<li><a href="homeDetector.php">Home Detector</a></li>
<li><a href="spammerDetector.php">Spammer Detector</a></li>
<li><a href="homeDetector.php">How to Use</a></li>
<li><a href="about.php">About</a></li>
</ul>
<div class="row">
<div class="col s12 m4 l3"> <!-- Note that "m4 l3" was added -->
<form action="homeDetector.php" method="post">
<div class="row">
<h4 class="title">Home Detector Spam</h4>
<div class="input-field col s6">
<input id="last_name" name="keyWord" type="text" class="validate">
<label for="last_name">Keyword</label>
</div>
<div class="col s12">
<p>Algoritma</p>
<br>
<p>
<label>
<input class="with-gap" name="selectedAlgo" value="Boyer-moore" type="radio"/>
<span>Bayer-Moore</span>
</label>
<label>
<input class="with-gap" name="selectedAlgo" value="Kmp" type="radio"/>
<span>KMP</span>
</label>
<label>
<input class="with-gap" name="selectedAlgo" value="Regex" type="radio"/>
<span>Regex</span>
</label>
</p>
</div>
</div>
<button class="btn waves-effect waves-light cyan accent-4" type="submit" name="action" id="btnRight">Detect</button>
</form>
</div>
<div class="col s12 m8 l9">
<h2 class="title">Result</h2>
<div class="selectedMethod">
<span style="color : lightblue;float:left;">Keyword : <?php
if (isset($_POST["keyWord"])){
echo $_POST["keyWord"];
}else{
echo '<span style="color : grey">No Input</span>';
}
?> </span>
<span style="color : lightpink; float:right;">Selected Algorithm : <?php
if (isset($_POST["selectedAlgo"])){
echo $_POST["selectedAlgo"];
}else{
echo '<span style="color : grey">No Input</span>';
}
?>
</span>
</div>
<?php
if(!isset($_POST["selectedAlgo"])){
foreach ($statuses as $iter){
echo '<div class="postContainer">
<img src=',$iter->user->profile_image_url,' alt="" class="circle">
<div>
<div class="name">
<a id="screenName" href="#">',$iter->user->name,' </a>
<span id="username">@',$iter->user->screen_name,'</span>
</div>
<div class="tweetText">
<p>',$iter->text,'</p>
</div>
</div>
</div>';
}
}else{
foreach ($statuses as $iter){
$key = $_POST["keyWord"];
if($_POST["selectedAlgo"] == "Boyer-moore"){
$flagSpam = exec("python BM.py $key \"$iter->text\"");
}
else if($_POST["selectedAlgo"] == "Kmp"){
$flagSpam = exec("python BM.py $key \"$iter->text\"");
}else{
if(exec("python RE.py $key \"$iter->text\"") == "False"){
$flagSpam = "-1";
}else{
$flagSpam = "1";
}
}
// echo '<div class="postContainer"><div class="name"><a id="screenName" href="#">',$iter->user->name,' </a><span id="username">@',$iter->user->screen_name,'</span></div><div class="tweetText"><p>',$iter->text,'</p></div></div>';
if($flagSpam == "-1"){
echo '<div class="postContainer">
<img src=',$iter->user->profile_image_url,' alt="" class="circle">
<div>
<div class="name">
<a id="screenName" href="#">',$iter->user->name,' </a>
<span id="username">@',$iter->user->screen_name,'</span>
</div>
<div class="tweetText">
<p>',$iter->text,'</p>
</div>
</div>
</div>';
}else{
echo '<div class="postContainer spam">
<img src=',$iter->user->profile_image_url,' alt="" class="circle">
<div>
<div class="name">
<a id="screenName" href="#">',$iter->user->name,' </a>
<span id="username">@',$iter->user->screen_name,'</span>
</div>
<div class="tweetText">
<p>',$iter->text,'</p>
</div>
</div>
</div>';
}
}
}
?>
</div>
</div>
</div>
</body>
<script src="materialize.min.js"></script>
</html><file_sep>/coba.py
import sys
# print("Wildan bilang : " );
# for tweet in sys.argv :
# print(tweet)
print(sys.argv[1])<file_sep>/RE_spammerDetector.py
import re
import sys
def keyword_spam(text):
# mengembalikan 1 jika ditemukan keyword spam pada postingan
# mengembalikan -1 jika tidak
patterns = [r'^[hH][tT]{2}[Pp][Ss]', r'[wW][aA][dD][uU][hH]', r'[hH][eE][yY]', r'[Ww][eEiI][bBeE][bBUu]', r'[A-Z][A-Z][A-Z]48', r'[Mm][Aa][Rr][Ii][Kk][Aa]']
for pattern in patterns :
if (bool(re.search(pattern,text))) :
return 1
return -1
# main program
print(keyword_spam(sys.argv[1]))
<file_sep>/spammerDetector.php
<?php
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumerKey = "BojzoX0hbo2apAoKl7MhQrNGm";
$consumerSecret = "<KEY>";
$access_token = "<KEY>";
$access_token_secret = "<KEY>";
$connection = new TwitterOAuth($consumerKey, $consumerSecret, $access_token, $access_token_secret);
$content = $connection->get("account/verify_credentials");
$numTweet = 25;
if(isset($_POST["userName"])){
$statuses = $connection->get("statuses/user_timeline", ["screen_name"=>$_POST["userName"],"count" => $numTweet, "exclude_replies" => true]);
$username = $statuses[0]->user->name;
}
$spamCount = 0;
$arSpam = array();
if(isset($_POST["userName"])){
foreach ($statuses as $iter){
$flagSpam = exec("python RE_spammerDetector.py \"$iter->text\"");
array_push($arSpam,$flagSpam);
if($flagSpam != "-1"){
$spamCount ++;
}
}
$numTweet = count($arSpam);
if($numTweet % 2 == 0){
if($spamCount >= ($numTweet/2)){
$category = "Spammer";
$colorCount = "Red";
}else{
$category = "Clean";
$colorCount = "#008CBA";
}
}else{
if($spamCount >= (($numTweet+1)/2)){
$category = "Spammer";
$colorCount = "Red";
}else{
$category = "Clean";
$colorCount = "#008CBA";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Tugas Besar Stima 3</title>
<link href="https://fonts.googleapis.com/css?family=Comfortaa|Lobster" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<link rel="stylesheet" type="text/css" media="screen" href="materialize.min.css" />
<!-- <script src="main.js"></script> -->
</head>
<body>
<ul class="nav">
<!-- <li><a href="default.asp">Home</a></li> -->
<a href="index.php"><img href="#" src="logo.png" class="littleLogo"></a>
<li><a href="homeDetector.php">Home Detector</a></li>
<li><a href="spammerDetector.php">Spammer Detector</a></li>
<li><a href="homeDetector.php">How to Use</a></li>
<li><a href="about.php">About</a></li>
</ul>
<div class="row">
<div class="col s12 m4 l3"> <!-- Note that "m4 l3" was added -->
<form action="spammerDetector.php" method="post">
<div class="row">
<h4 class="title">Spammer Detector</h4>
<div class="input-field col s6">
<input id="last_name" type="text" name="userName" class="validate">
<label for="last_name">username</label>
</div>
<div class="col s12">
<p>Algoritma</p>
<br>
<p>
<label>
<input class="with-gap" name="selectedAlgo" value="boyerMoore" type="radio"/>
<span>Bayer-Moore</span>
</label>
<label>
<input class="with-gap" name="selectedAlgo" value="kmp" type="radio"/>
<span>KMP</span>
</label>
<label>
<input class="with-gap" name="selectedAlgo" value="Regex" type="radio"/>
<span>Regex</span>
</label>
</p>
</div>
<div class="col s12">
<button class="btn waves-effect waves-light cyan accent-4" type="submit" name="action" id="btnRight">Check</button>
</div>
</div>
</form>
</div>
<div class="col s12 m8 l9">
<h2 class="title"><?php
if(isset($_POST["userName"]))
echo $username
?></h2>
<h3 style="margin-top : 5px; text-align : center; color : #008CBA"><?php if(isset($_POST["userName"])){echo "is";}?><br><span style="color : <?php if(isset($_POST["userName"])){echo $colorCount;}?>;"><?php if(isset($_POST["userName"])){echo $category;}?></span></h3>
<p style="color : #008CBA;"><?php if(isset($_POST["userName"])){echo "Detect";}?> : <span style= "color : <?php if(isset($_POST["userName"])){echo $colorCount;}?>;"><?php if(isset($_POST["userName"])){echo $spamCount;}?></span><?php if(isset($_POST["userName"])){echo " from ",$numTweet;}?></p>
<?php
if(isset($_POST["userName"])){
$i = 0;
foreach ($statuses as $iter){
if($arSpam[$i] == "-1"){
echo '<div class="postContainer">
<img src=',$iter->user->profile_image_url,' alt="" class="circle">
<div>
<div class="name">
<a id="screenName" href="#">',$iter->user->name,' </a>
<span id="username">@',$iter->user->screen_name,'</span>
</div>
<div class="tweetText">
<p>',$iter->text,'</p>
</div>
</div>
</div>';
}else{
echo '<div class="postContainer spam">
<img src=',$iter->user->profile_image_url,' alt="" class="circle">
<div>
<div class="name">
<a id="screenName" href="#">',$iter->user->name,' </a>
<span id="username">@',$iter->user->screen_name,'</span>
</div>
<div class="tweetText">
<p>',$iter->text,'</p>
</div>
</div>
</div>';
}
$i++;
}
}
?>
</div>
</div>
</body>
<script src="materialize.min.js"></script>
</html><file_sep>/KMP_spammerDetector.py
import sys
def KMP(text, pattern):
n, m = len(text), len(pattern)
j = 0
k = 0
fail = kmp_fail(pattern)
while j < n:
if text[j] == pattern[k]:
if k == m - 1:
return True
j += 1
k += 1
elif k > 0:
k = fail[k-1]
else:
j += 1
return False
def kmp_fail(P):
n = len(P)
fail = [0] * n
j = 1
k = 0
while j < n:
if P[j] == P[k]:
fail[j] = k + 1
j += 1
k += 1
elif k > 0:
k = fail[k - 1]
else:
j += 1
return fail
def keyword_spam(text):
# mengembalikan 1 jika ditemukan keyword spam pada postingan
# mengembalikan -1 jika tidak
patterns = ['https', 'waduh', 'hey', 'wibu', 'AKB48']
for pattern in patterns :
if (KMP(text,pattern)) :
return 1
return -1
# main program
text = sys.argv[1].lower()
print(keyword_spam(text))<file_sep>/BM.py
import sys
def generate_d_vector(text,pattern):
d = {}
for char in text:
founded = pattern.rfind(char)
if char not in d:
d[char] = len(pattern)-1-pattern.rfind(char) if founded != -1 else len(pattern)
return d
def boyer_moore(text,pattern,d):
j = len(pattern)-1
while j<len(text):
i = len(pattern)-1
while i>0 and pattern[i]==text[j]:
i,j = i-1,j-1
if i==0: return j
else:
if len(pattern)-1-i>d[text[j]]: j = j + len(pattern)-1- i + 1
else: j = j + d[text[j]]
return -1
if __name__ == "__main__":
text,pattern = sys.argv[2].lower(), sys.argv[1].lower()
print(boyer_moore(text,pattern,generate_d_vector(text,pattern)))<file_sep>/twitter-api.php
<?php
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumerKey = "BojzoX0hbo2apAoKl7MhQrNGm";
$consumerSecret = "<KEY>";
$access_token = "<KEY>";
$access_token_secret = "<KEY>";
$connection = new TwitterOAuth($consumerKey, $consumerSecret, $access_token, $access_token_secret);
$content = $connection->get("account/verify_credentials");
$statuses = $connection->get("statuses/home_timeline", ["count" => 20, "exclude_replies" => true]);
$index = 0;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Tugas Besar Stima 3</title>
<link href="https://fonts.googleapis.com/css?family=Comfortaa|Lobster" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<link rel="stylesheet" type="text/css" media="screen" href="materialize.min.css" />
<!-- <script src="main.js"></script> -->
</head>
<body>
<ul class="nav">
<!-- <li><a href="default.asp">Home</a></li> -->
<!-- <a href="news.asp"><img href="#" src="logo.png" class="littleLogo"></a> -->
<div class="dropdown">
<a href="news.asp" class="dropbtn"><img href="#" src="logo.png" class="littleLogo"></a>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
<li><a href="news.asp">Apps</a></li>
<li><a href="contact.asp">How to Use</a></li>
<li><a href="about.asp">About</a></li>
</ul>
<br>
<div class="container">
<div class="title">
<img src="logo.png" class="bigLogo">
<!-- <h1 id="Logo"><span id="Twitter">Twitter</span><span id="Analyzer">Analyzer</span></h1> -->
<p id="Caption">Analyze your tweet !!</p>
</div>
<div class="content">
<form action="index.php" method="post">
<div class="input-field col s6">
<input id="last_name" type="text" class="validate">
<label for="last_name">Keyword</label>
</div>
Algoritma
<br>
<!-- <div>
<input type="radio" name="selectedAlgo" value="boyerMoore" checked> Boyer-Moore<br>
<input type="radio" name="selectedAlgo" value="kmp"> KMP<br>
<input type="radio" name="selectedAlgo" value="Regex"> Regex
</div> -->
<p>
<label>
<input class="with-gap" name="selectedAlgo" value="boyerMoore" type="radio"/>
<span>Bayer-Moore</span>
</label>
<label>
<input class="with-gap" name="selectedAlgo" value="kmp" type="radio"/>
<span>KMP</span>
</label>
<label>
<input class="with-gap" name="selectedAlgo" value="Regex" type="radio"/>
<span>Regex</span>
</label>
</p>
<button class="btn waves-effect waves-light" type="submit" name="action" id="btnRight">Submit</button>
</form>
<br>
<hr class="style13">
<h2>Result</h2>
<?php
foreach ($statuses as $iter)
echo '<div class="postContainer"><div class="name"><a id="screenName" href="#">',$iter->user->name,' </a><span id="username">@',$iter->user->screen_name,'</span></div><div class="tweetText"><p>',$iter->text,'</p></div></div>';
?>
</div>
</div>
</body>
<script src="materialize.min.js"></script>
</html><file_sep>/template.php
<?php
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumerKey = "BojzoX0hbo2apAoKl7MhQrNGm";
$consumerSecret = "<KEY>";
$access_token = "<KEY>";
$access_token_secret = "<KEY>";
$connection = new TwitterOAuth($consumerKey, $consumerSecret, $access_token, $access_token_secret);
$content = $connection->get("account/verify_credentials");
$statuses = $connection->get("statuses/user_timeline", ["screen_name"=>"shafiraaputria","count" => 25, "exclude_replies" => true]);
$username = $statuses[0]->user->name;
$index = 0;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Tugas Besar Stima 3</title>
<link href="https://fonts.googleapis.com/css?family=Comfortaa|Lobster" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<link rel="stylesheet" type="text/css" media="screen" href="materialize.min.css" />
<!-- <script src="main.js"></script> -->
</head>
<body>
<ul class="nav">
<!-- <li><a href="default.asp">Home</a></li> -->
<a href="news.asp"><img href="#" src="logo.png" class="littleLogo"></a>
<li><a href="news.asp">Apps</a></li>
<li><a href="contact.asp">How to Use</a></li>
<li><a href="about.asp">About</a></li>
</ul>
<div class="row">
<div class="col s12 m4 l3"> <!-- Note that "m4 l3" was added -->
<form action="index.php" method="post">
<div class="row">
<h4 class="title">Spammer Detector</h4>
<div class="input-field col s6">
<input id="last_name" type="text" class="validate">
<label for="last_name">username</label>
</div>
<div class="col s12">
<p>Algoritma</p>
<br>
<p>
<label>
<input class="with-gap" name="selectedAlgo" value="boyerMoore" type="radio" checked />
<span>Bayer-Moore</span>
</label>
<label>
<input class="with-gap" name="selectedAlgo" value="kmp" type="radio"/>
<span>KMP</span>
</label>
<label>
<input class="with-gap" name="selectedAlgo" value="Regex" type="radio"/>
<span>Regex</span>
</label>
</p>
</div>
<div class="col s12">
<button class="btn waves-effect waves-light" type="submit" name="action" id="btnRight">Check</button>
</div>
</div>
</form>
</div>
<div class="col s12 m8 l9">
<h2 class="title"><?php echo $username ?></h2>
<?php foreach ($statuses as $iter)
echo '<div class="postContainer"><div class="name"><a id="screenName" href="#">',$iter->user->name,' </a><span id="username">@',$iter->user->screen_name,'</span></div><div class="tweetText"><p>',$iter->text,'</p></div></div>';
?>
</div>
</div>
</body>
<script src="materialize.min.js"></script>
</html><file_sep>/BM_spammerDetector.py
import sys
def generate_d_vector(text,pattern):
d = {}
for char in text:
founded = pattern.rfind(char)
if char not in d:
d[char] = len(pattern)-1-pattern.rfind(char) if founded != -1 else len(pattern)
return d
def boyer_moore(text,pattern,d):
j = len(pattern)-1
while j<len(text):
i = len(pattern)-1
while i>0 and pattern[i]==text[j]:
i,j = i-1,j-1
if i==0: return True
else:
if len(pattern)-1-i>d[text[j]]: j = j + len(pattern)-1- i + 1
else: j = j + d[text[j]]
return False
def keyword_spam(text):
# mengembalikan 1 jika ditemukan keyword spam pada postingan
# mengembalikan -1 jika tidak
patterns = ['https', 'waduh', 'hey', 'wibu', 'AKB48']
for pattern in patterns :
if (boyer_moore(text,pattern,generate_d_vector(text,pattern))) :
return 1
return -1
if __name__ == "__main__":
text = sys.argv[1].lower()
print(keyword_spam(text))<file_sep>/RE.py
import re
import sys
rp = sys.argv[1]
teks = sys.argv[2]
print (str(bool(re.search(rp,teks))))
|
54967e664f8f01a2e406b0a95f2af817afb920a9
|
[
"Python",
"PHP"
] | 10
|
PHP
|
luthfihadiana/TwitterAnalyzer
|
38deea014c8209620a905a17b3556ef1ddd320de
|
11715bfe9ac43120462f55b4e290dbcc52d6b712
|
refs/heads/master
|
<file_sep><?php
$g_Title = "Ändra lösenord";
include("../include/header.php");
if(isset($_SESSION['error'])) {
echo "<p>$_SESSION[error]</p>\n";
unset($_SESSION['error']);
}
?>
<h1>Ändra lösnord</h1>
<form action="../register/newpass.php" method="post" />
Nuvarande lösenord: <input type="<PASSWORD>" name="oldpass" /><br />
Nytt lösenord: <input type="<PASSWORD>" name="newpass1" /><br />
Bekräfta nytt lösenord: <input type="<PASSWORD>" name="newpass2" /><br />
<input type="submit" value="Byt lösenord" />
</form>
<?php include("../include/footer.php");?>
<file_sep><?php
include("../include/headless.php");
if($_GET['id'] == "new") {
$model['description'] = "";
$model['min_cell'] = 1;
$model['max_cell'] = 10;
$g_Title = "Skapa ny modell ";
} else {
$model = $db->query("SELECT * FROM model WHERE ID=$_GET[id]")->fetchArray();
$g_Title = "Redigera modell: $model[description] ";
}
if($model['discarded'] == 1) {$discardedvalue = "CHECKED ";} else {$discardedvalue = "";}
include("../include/header.php");
?>
<h1>Registrera Modell</h1>
<form action="../register/model.php" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id'];?>" />
<input type="text" name="description" value="<?php echo $model['description'];?>" size="30" /><br />
Antal Celler: <input type="text" name="min_cell" value="<?php echo $model['min_cell'];?>" size="3" /> -
<input type="text" name="max_cell" value="<?php echo $model['max_cell'];?>" size="4" /><br />
Kasserad Modell: <input type="checkbox" name="discarded" <?php echo $discardedvalue;?> /><br />
<input type="submit" value="Spara modell" />
</form>
<?php include("../include/footer.php");
<file_sep><?php
include("../include/headless.php");
$email = $db->escapeString($_POST['email']);
$preExists = $db->querySingle("SELECT id FROM user WHERE email=\"$email\"");
if(isset($preExists)) {
$_SESSION['error'] = "Användarnamn tidigare registrerat. Använd glömt lösenord istället";
} else {
$password = substr(generateSalt(),0,12);
$salt = generateSalt();
$email = $db->escapeString($email);
$passwordHash = hashPassword($password, $salt);
$db->exec("INSERT INTO user(email, password, salt) values(\"$email\", \"$passwordHash\", \"$salt\")");
$message = "Ditt lösenord för RCLog är: $password\<PASSWORD>. RCLog Automailer";
$headers = "From: $g_EmailAddress\r\nX-Mailer: gnuttNet RCLog";
mail($email, "Nytt konto på RCLog", $message, $headers);
$_SESSION['message'] = "Ditt konto är registrerat. Kontrollera din epost för lösenordet";
}
header("Location: ../login.php");
die();
?>
<file_sep><?php
include("include/headless.php");
if(!isset($_GET['id'])) {
header("Location: index.php");
die();
}
$info = $db->query("SELECT * FROM battery WHERE id=$_GET[id] LIMIT 1")->fetchArray();
$descr = $info['description'];
$longdescr = "$info[description] $info[mAh]mAh $info[cells]S";
$totCharge = $db->querySingle("SELECT sum(mAh) FROM charge WHERE battery=$_GET[id]");
$totCharges = $db->querySingle("SELECT count(*) FROM charge WHERE battery=$_GET[id]");
$totFlights = $db->querySingle("SELECT count(*) FROM flight WHERE battery=$_GET[id]");
$totFlightTime = $db->querySingle("SELECT sum(time) FROM flight WHERE battery=$_GET[id]");
$avgCharge = $totCharge / $totCharges;
$g_Title="Batteriinformation $longdescr ";
include("include/header.php");
?>
<h1><?php echo $longdescr;?></h1>
<p><a href="modify/battery.php?id=<?php echo $_GET['id'];?>">Redigera Batteri</a></p>
<p>
Totalt laddade mAh: <?php echo $totCharge;?><br />
Antal laddningar: <?php echo $totCharges;?><br />
Antal Flygningar: <?php echo $totFlights;?><br />
Antal Flygtimmar: <?php echo round($totFlightTime/60/60,2);?><br />
Medel mAh per Laddning: <?php echo round($avgCharge) . " (" . round($avgCharge*100 / $info['mAh']) . "%)"; ?>
</p>
<h2>Kompatibla modeller</h2>
<?php
$models = $db->query("SELECT id, description FROM model WHERE user = $_SESSION[uId] AND min_cell <= $info[cells] AND max_cell >= $info[cells] AND discarded=0");
echo "\t\t<ul>\n";
while($model = $models->fetchArray()) {
echo "\t\t\t<li><a href=\"model.php?id=$model[id]\">$model[description]</a></li>\n";
}
echo "\t\t</ul>\n";
?>
<h2>Logg</h2>
<?php
$flights = $db->query("select model.id as modelid, flight.id, model.description, flight.time, flight.datetime from flight,model where flight.model = model.id and flight.battery=$_GET[id] order by datetime desc LIMIT 10");
$charges = $db->query("select id, mAh, datetime FROM charge WHERE battery=$_GET[id] ORDER BY datetime DESC LIMIT 10");
$i = 0;
while($flight = $flights->fetchArray()) {
$loggpost_type[$i] = "flight";
$loggpost_modelid[$i] = $flight['modelid'];
$loggpost_id[$i] = $flight['id'];
$loggpost_desc[$i] = $flight['description'];
$loggpost_value[$i] = round($flight['time']/60,1) . " minuter";
$loggpost_datetime[$i] = $flight['datetime'];
$i++;
}
while($charge = $charges->fetchArray()) {
$loggpost_type[$i] = "charge";
$loggpost_modelid[$i] = "N/A";
$loggpost_id[$i] = $charge['id'];
$loggpost_desc[$i] = "<img src=\"img/battery-charge-2.png\" alt=\"Bild av laddande batteri\" /> Laddning";
$loggpost_value[$i] = $charge['mAh'] . "mAh";
$loggpost_datetime[$i] = $charge['datetime'];
$i++;
}
array_multisort($loggpost_datetime, SORT_DESC, $loggpost_value, SORT_ASC, $loggpost_desc, SORT_ASC, $loggpost_type, SORT_ASC, $loggpost_id, SORT_ASC, $loggpost_modelid, SORT_DESC);
echo "<table>\n";
for($y = 0; $y < $i; $y++) {
echo "<tr>\n";
if($loggpost_type[$y] == "charge") {
echo "<td><a href=\"modify/charge.php?id=" . $loggpost_id[$y] . "\"><img src=\"img/pencil.png\" alt=\"Redigera\" /></a></td>\n";
echo "<td>$loggpost_desc[$y]</td>\n";
} elseif($loggpost_type[$y] == "flight") {
echo "<td><a href=\"modify/flight.php?id=" . $loggpost_id[$y] . "\"><img src=\"img/pencil.png\" alt=\"Redigera\" /></a></td>\n";
echo "<td><a href=\"model.php?id=$loggpost_modelid[$y]\">$loggpost_desc[$y]</a></td>\n";
}
echo "<td>" . $loggpost_value[$y] . "</td>\n";
echo "<td>" . strftime("%Y-%m-%d %H:%M", $loggpost_datetime[$y]) . "</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
include("include/footer.php");
?>
<file_sep><?php
function generateSalt() {
return uniqid(mt_rand(), true);
}
function hashPassword($password, $salt) {
$hash = $password;
for($i = 1; $i < 512; $i++) {
$password = hash('sha256', $password . $salt);
}
return $password;
}
function find_relative_path ( $frompath, $topath ) {
$from = explode( DIRECTORY_SEPARATOR, $frompath ); // Folders/File
$to = explode( DIRECTORY_SEPARATOR, $topath ); // Folders/File
$relpath = '';
$i = 0;
// Find how far the path is the same
while ( isset($from[$i]) && isset($to[$i]) ) {
if ( $from[$i] != $to[$i] ) break;
$i++;
}
$j = count( $from ) - 1;
// Add '..' until the path is the same
while ( $i <= $j ) {
if ( !empty($from[$j]) ) $relpath .= '..'.DIRECTORY_SEPARATOR;
$j--;
}
// Go to folder from where it starts differing
while ( isset($to[$i]) ) {
if ( !empty($to[$i]) ) $relpath .= $to[$i].DIRECTORY_SEPARATOR;
$i++;
}
// Strip last separator
return substr($relpath, 0, -1);
}
function tofloat($num) {
$dotPos = strrpos($num, '.');
$commaPos = strrpos($num, ',');
$sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
if (!$sep) {
return floatval(preg_replace("/[^0-9]/", "", $num));
}
return floatval(
preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
);
}
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
function updatechargestatus($battery) {
global $db;
$lastflight = $db->querySingle("SELECT datetime FROM flight WHERE battery=$battery ORDER BY datetime DESC LIMIT 1");
$lastcharge = $db->querySingle("SELECT datetime FROM charge WHERE battery=$battery ORDER BY datetime DESC LIMIT 1");
$numcharge = $db->querySingle("SELECT count(*) FROM charge WHERE battery=$battery");
if($lastflight > $lastcharge || $numcharge == 0) {
$db->exec("UPDATE battery SET isCharged=0 WHERE id=$battery");
return 0;
} else {
$db->exec("UPDATE battery SET isCharged=1 WHERE id=$battery");
return 1;
}
}
?>
<file_sep><?php
include("include/headless.php");
if(!isset($_GET['id'])) {
header("Location: index.php");
die();
}
$data = $db->query("SELECT Description, min_cell, max_cell FROM model WHERE id=$_GET[id]");
$data = $data->fetchArray();
$name = $data['description'];
$min_cell = $data['min_cell'];
$max_cell = $data['max_cell'];
$num_batteries = $db->querySingle("SELECT count(Description) FROM battery WHERE user=$_SESSION[uId] AND cells <= $max_cell AND cells >= $min_cell AND discarded = 0");
$num_batteries_charged = $db->querySingle("SELECT count(Description) FROM battery WHERE user=$_SESSION[uId] AND cells <= $max_cell AND cells >= $min_cell AND discarded = 0 AND isCharged = 1");
$flighttime = $db->querySingle("SELECT sum(time) FROM flight WHERE model=$_GET[id]");
$g_Title="Modelinformation: $name ";
include("include/header.php");
?>
<h1>Modellinformation: <?php echo $name;?></h1>
<p><a href="modify/model.php?id=<?php echo $_GET['id'];?>">Redigera Modell</a></p>
<table>
<tr>
<th>Cellinformation</th>
<td><?php echo "$min_cell-$max_cell";?></td>
</tr>
<tr>
<th>Antal Batterier</th>
<td><?php echo $num_batteries;?></td>
<th>Laddade Batterier</th>
<td><?php echo $num_batteries_charged;?></td>
</tr>
</table>
<?php
if($num_batteries_charged > 0) {
echo "\t\t<h3>Laddade Batterier</h3>\n";
echo "\t\t<ul>\n";
$batteries = $db->query("SELECT id, Description FROM battery WHERE user = $_SESSION[uId] AND cells <= $max_cell AND cells >= $min_cell AND discarded = 0 AND isCharged=1 ORDER BY Description ASC");
while($battery = $batteries->fetchArray()) {
echo "\t\t\t<li><a href=\"battery.php?id=$battery[id]\">$battery[description]</a></li>\n";
}
echo "\t\t</ul>\n";
}
if($num_batteries - $num_batteries_charged != 0) {
echo "\t\t<h3>Oladdade Batterier</h3>\n";
echo "\t\t<ul>\n";
$batteries = $db->query("SELECT id, Description FROM battery WHERE user = $_SESSION[uId] AND cells <= $max_cell AND cells >= $min_cell AND discarded = 0 AND isCharged=0 ORDER BY Description ASC");
while($battery = $batteries->fetchArray()) {
echo "\t\t\t<li><a href=\"battery.php?id=$battery[id]\">$battery[description]</a></li>\n";
}
echo "\t\t</ul>\n";
}
?>
<h2>Registrera Flygning</h2>
<p>Total Flygtid: <?php echo round($flighttime/60/60,2) . " timmar";?></p>
<form action="register/flight.php" method="post">
<input type="hidden" name="model" value="<?php echo $_GET['id'];?>" />
Batteri: <select name="battery">
<?php
$list = $db->query("SELECT id, Description FROM battery WHERE discarded=0 AND cells <= $max_cell AND cells >= $min_cell ORDER by isCharged DESC, description");
while($row = $list->fetchArray()) {
echo "\t\t\t<option value=\"$row[id]\">$row[description]</option>\n";
}
?>
</select>
Flygtid (minuter): <input type="text" name="time" />
<input type="submit" value="Registrera Flygning" />
</form>
<h2>10 senaste Flygnigar</h2>
<table>
<tr>
<th />
<th>Datum</th>
<th>Batteri</th>
<th>Flygtid</th>
</tr>
<?php
$flights = $db->query("SELECT flight.id, battery.id as batteryid, battery.description, battery.mah, battery.cells, flight.time, flight.datetime FROM battery, flight WHERE flight.battery = battery.id AND flight.model=$_GET[id] ORDER BY datetime DESC LIMIT 10");
while($flight = $flights->fetchArray()) {
echo "<tr>\n";
echo "<td><a href=\"modify/flight.php?id=$flight[id]\"><img src=\"img/pencil.png\" alt=\"Redigera\" /></a></td>\n";
echo "<td>" . strftime("%Y-%m-%d %H:%M", $flight['datetime']) . "</td>\n";
echo "<td><a href=\"battery.php?id=$flight[batteryid]\">$flight[description] $flight[mAh] mAh $flight[cells]S</a></td>\n";
echo "<td>" . round($flight['time'] / 60, 1) . " minuter</td>\n";
echo "</tr>\n";
}
?>
</table>
<?php include("include/footer.php");?>
<file_sep><?php
include_once("settings.php");
include_once("session.php");
include_once("database.php");
include_once("functions.php");
?>
<file_sep><?php
include("../include/headless.php");
$email = $db->escapeString($_POST['email']);
$userdata = $db->query("SELECT id,salt FROM user WHERE email=\"$email\"")->fetchArray();
if($userdata == false) {
$_SESSION['error'] = "Oregistrerad epostadress, använd skapa konto istället";
} else {
$newPass = substr(generateSalt(), 0, 12);
$newPassHash = hashPassword($newPass, $userdata['salt']);
$db->exec("UPDATE user SET password=\"$<PASSWORD>\" WHERE id=$userdata[id]");
$message = "Ditt nya lösenord för RCLog är: $newPass\n\rMVH. RCLog Automailer.";
$header = "From: $g_EmailAddress\n\rX-Mailer: gnuttNet RClog";
mail($email, "Nytt lösenord för ditt konto på RCLog", $message, $headers);
$_SESSION['message'] = "Ett nytt lösenord har skickats till din epostadress.";
}
header("Location: ../login.php");
die();
?>
<file_sep><?php
$g_Title = "Lista batterier - ";
include("include/header.php");
if(isset($_GET['discarded']) && $_GET['discarded'] == 1) {
$list = $db->query("SELECT id, description, cells, mAh, drawC, chargeC FROM battery WHERE user=$_SESSION[uId] AND discarded = 1");
} else {
$list = $db->query("SELECT id, description, cells, mAh, drawC, chargeC FROM battery WHERE user=$_SESSION[uId] AND discarded = 0");
}
echo "<table>\n";
echo "<tr>\n";
echo "<th>Batteri</th>\n";
echo "<th>Antal Laddningar</th>\n";
echo "<th>Totalt Laddat A</th>\n";
echo "</tr>\n";
while($battery = $list->fetchArray()) {
$numCharges = $db->querySingle("SELECT count(id) FROM charge WHERE battery=$battery[id]");
$totCharge = ($db->querySingle("SELECT sum(mAh) FROM charge WHERE battery=$battery[id]") / 1000);
echo "<tr>\n";
echo "<td><a href=\"battery.php?id=$battery[id]\">$battery[description] $battery[mAh]mAh $battery[cells]S</a></td>\n";
echo "<td>$numCharges</td>\n";
echo "<td>$totCharge</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
include("include/footer.php");
?>
<file_sep><?php
include_once("../include/headless.php");
if(isset($_POST['id'])) {
$db->exec("UPDATE charge SET battery=$_POST[battery], mAh=$_POST[mAh], datetime=" . strtotime($_POST['datetime']) . " WHERE id=$_POST[id]");
} else {
$db->exec("INSERT INTO charge(battery,mah,datetime) values($_POST[battery],$_POST[mAh], " . mktime() . ")");
}
updatechargestatus($_POST['battery']);
header("Location: ../battery.php?id=$_POST[battery]");
die();
?>
<file_sep><?php
$g_Title = "Lista modeller - ";
include("include/header.php");
if(isset($_GET['discarded']) && $_GET['discarded'] == 1) {
$list = $db->query("SELECT model.id, model.description FROM model WHERE user=$_SESSION[uId] AND discarded = 1 ORDER BY description");
} else {
$list = $db->query("SELECT model.id, model.description FROM model WHERE user=$_SESSION[uId] AND discarded = 0 ORDER BY description");
}
echo "<table>\n";
echo "<tr>\n";
echo "<th>Modell</th>\n";
echo "<th>Flygtimmar</th>\n";
echo "<th>Antal Flygningar</th>\n";
echo "</tr>\n";
while($model = $list->fetchArray()) {
$flightHours = $db->querySingle("SELECT sum(time) FROM flight WHERE model=$model[id]");
$numFlights = $db->querySingle("SELECT count(id) FROM flight WHERE model=$model[id]");
echo "<tr>\n";
echo "<td><a href=\"model.php?id=$model[id]\">$model[description]</a></td>\n";
echo "<td>" . round(($flightHours / 60 / 60),2) . "</td>\n";
echo "<td>$numFlights</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
include("include/footer.php");
?>
<file_sep><?php
$dbPath = dirname(__FILE__);
$dbFile = $dbPath . "/rclog.sqlite";
if(file_exists($dbFile) && is_writeable($dbFile)) {
$db = new SQLite3($dbFile);
$schema = $db->query("SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY sql");
$schemaText = "";
while($row = $schema->fetchArray()) {
if($row['name'] != "sqlite_sequence") {
$schemaText .= $row['sql'] . ";\n";
}
}
$trueSchema = file_get_contents("$dbFile.schema");
if($trueSchema != $schemaText) {
echo "<pre>\n";
echo $trueSchema . "\n\n" . $schemaText;
die("Database discrepancy, check the include/rclog.sqlite.schema and update your database accordingly");
}
} else {
if(file_exists($dbFile)) {
$result = chmod($dbFile, 666);
if($result == true) {
echo "File exists, and was not writeable. Automatically changed that. Reload page!";
} else {
echo "File exists, but is not writeable, could not change it! Do it manually";
}
} else {
echo "There is no database file, and could not create it! Create it manually (touch include/rclog.sqlite;chown :www-data include/rclog.sqlite;chmod 660 include/rclog.sqlite)";
}
die();
}
?>
<file_sep><?php
include_once("headless.php");
if(!isset($_SESSION['uId']) && basename($_SERVER['PHP_SELF']) != "login.php") {
if(isset($_COOKIE['rclog-persistent'])) {
$data = explode(":", $_COOKIE['rclog-persistent']);
$uId = $data[0];
$storedHash = $data[1];
if($id = $db->querySingle("SELECT id FROM rememberme WHERE user=$uId AND hash=\"$uId:$storedHash\" AND validto < 'now' LIMIT 1")) {
$newtime = mktime()+(60*60*24*30);
$db->exec("UPDATE rememberme SET validto=datetime('now', '+30 days') WHERE id=$id");
$validto = $db->querySingle("SELECT strftime('%s', validto) FROM rememberme WHERE id=$id");
setcookie('rclog-persistent', $_COOKIE['rclog-persistent'], $validto, '/');
$_SESSION['uId'] = $uId;
} else {
header("Location: " . $prePath . "login.php");
die();
}
} else {
header("Location: " . $prePath . "login.php");
die();
}
}
if(!isset($g_Title)) {$g_Title = "";}
?>
<html>
<head>
<title><?php echo $g_Title;?>Gnutt's RC-logger</title>
</head>
<body>
<?php include("meny.php");?>
<file_sep><?php
$g_Title = "Redigera Flygning ";
include("../include/header.php");
echo "\t\t<h2>Redigera Flygning</h2>\n";
$data = $db->query("SELECT * FROM flight WHERE id=$_GET[id]")->fetchArray();
echo "<form action=\"../register/flight.php\" method=\"post\">\n";
echo "<input type=\"hidden\" name=\"id\" value=\"$_GET[id]\" />\n";
echo "Modell: <select name=\"model\">\n";
$models = $db->query("SELECT id, description FROM model WHERE user=$_SESSION[uId] AND discarded = 0 ORDER BY description");
while($model = $models->fetchArray()) {
echo "<option value=\"$model[id]\"";
if($model['id'] == $data['model']) {
echo " SELECTED";
}
echo ">$model[description]</option>\n";
}
echo "</select>\n";
echo "Batteri: <select name=\"battery\">\n";
$batteries = $db->query("SELECT id, description FROM battery WHERE user=$_SESSION[uId] AND discarded = 0 ORDER BY description");
while($battery = $batteries->fetchArray()) {
echo "<option value=\"$battery[id]\"";
if($battery['id'] == $data['battery']) {
echo " SELECTED";
}
echo ">$battery[description]</option>\n";
}
echo "</select><br />\n";
echo "Tid i minuter: <input type=\"text\" name=\"time\" value=\"" . round($data['time'] / 60,1) . "\" size=\"4\" />\n";
echo "Datum: <input type=\"text\" name=\"datetime\" value=\"" . strftime("%Y-%m-%d %H:%M", $data['datetime']) . "\" /><br />\n";
echo "<input type=\"submit\" value=\"Uppdatera flygning\" />\n";
echo "</form>\n";
include("../include/footer.php");
?>
<file_sep><?php
include_once("../include/headless.php");
$description = $db->escapeString($_POST['description']);
if($_POST['discarded'] == 'on') {$_POST['discarded'] = 1;} else {$_POST['discarded'] = 0;}
if($_POST['id'] == "new") {
$db->exec("INSERT INTO model(description, min_cell, max_cell, discarded, user) values(\"$description\", $_POST[min_cell], $_POST[max_cell], $_POST[discarded], $_SESSION[uId])");
$_POST['id'] = $db->lastInsertRowID();
} else {
$db->exec("UPDATE model SET description=\"$description\", min_cell=$_POST[min_cell], max_cell=$_POST[max_cell], discarded=$_POST[discarded] WHERE id=$_POST[id]");
}
header("Location: ../model.php?id=$_POST[id]");
die();
?>
<file_sep>rclog
=====
Logging PHP-software for RC Flights and Batteries
<file_sep><?php
$g_Title = ": Logga in";
include_once("include/header.php");
if(isset($_SESSION['message'])) {
echo "<p>$_SESSION[message]</p>\n";
unset($_SESSION['message']);
}
if(isset($_SESSION['error'])) {
echo "<p>$_SESSION[error]</p>\n";
unset($_SESSION['error']);
}
?>
<h1>Logga in</h1>
<form action="register/login.php" method="post">
Epostadress: <input type="text" name="username" /><br />
Lösenord: <input type="password" name="password" /><br />
Logga in automatiskt: <input type="checkbox" name="rememberme" /> (30 dagar)<br />
<input type="submit" value="Logga in" />
</form>
<p>
<a href="?forgot_password">Glömt Lösenord</a><br />
<a href="?register">Registrera konto</a>
</p>
<?php
if(isset($_GET['forgot_password'])) {
?>
<form action="register/forgot_password.php" method="post">
Epostadress: <input type="text" name="email" />
<input type="submit" value="Skicka nytt lösenord" />
</form>
<?php
}
if(isset($_GET['register'])) {
?>
<form action="register/register_account.php" method="post">
Epostadress: <input type="text" name="email" />
<input type="submit" value="Registrera" /><br />
<p>
När du registrerar en epost-adress så kommer ett mail med ditt första lösenord.
Med detta får du sedan logga in, för att byta ut det.
</p>
</form>
<?php
}
include_once("include/footer.php");?>
<file_sep><?php
$g_EmailAddress = "\"RCLog\" <<EMAIL>>";
?>
<file_sep><?php
include_once("../include/headless.php");
if($_POST['discarded'] == 'on') {$discardedvalue = 1;} else {$discardedvalue = 0;}
if($_POST['id'] == "new") {
$description = $db->escapeString($_POST['description']);
$db->exec("INSERT INTO battery(description,mah,cells,drawc,chargec,weight,discarded,user) values(\"$description\", $_POST[mAh], $_POST[cells], $_POST[drawC], $_POST[chargeC], $_POST[weight], $discardedvalue, $_SESSION[uId]);");
$_POST['id'] = $db->lastInsertRowID();
} else {
$description = $db->escapeString($_POST['description']);
$db->exec("UPDATE battery SET description=\"$description\", mAh=$_POST[mAh], cells=$_POST[cells], drawc=$_POST[drawC], chargeC=$_POST[chargeC], weight=$_POST[weight], discarded=$discardedvalue WHERE id=$_POST[id]");
}
header("Location: ../battery.php?id=$_POST[id]");
die();
?>
<file_sep><?php
include("../include/headless.php");
if($_GET['id'] == "new") {
$battery['description'] = "";
$battery['cells'] = "1";
$battery['mAh'] = "1000";
$battery['drawC'] = "1";
$battery['chargeC'] = "1";
$battery['weight'] = "100";
$g_Title = "Skapa nytt batteri ";
} else {
$battery = $db->query("SELECT * FROM battery WHERE ID=$_GET[id]")->fetchArray();
if($battery == false) {header("Location: ../index.php"); die();}
$g_Title = "Redigera batteri: $battery[description] ";
}
if($battery['discarded'] == 1) {$discardedvalue = 'CHECKED ';} else {$discardedvalue = '';}
include("../include/header.php");
?>
<h1>Redigera Batteri</h1>
<form action="../register/battery.php" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id'];?>" />
Beskrivning: <input type="text" name="description" value="<?php echo $battery['description'];?>" size="30" /><br />
mAh: <input type="text" name="mAh" value="<?php echo $battery['mAh'];?>" size="5" />
Celler: <input type="text" name="cells" value="<?php echo $battery['cells'];?>" size="2" /><br />
Amp C: <input type="text" name="drawC" value="<?php echo $battery['drawC'];?>" size="2" />
Ladd C: <input type="text" name="chargeC" value="<?php echo $battery['chargeC'];?>" size="2" /><br />
Vikt (g): <input type="text" name="weight" value="<?php echo $battery['weight'];?>" size="5" /><br />
Kasserat: <input type="checkbox" name="discarded" <?php echo $discardedvalue;?>/><br />
<input type="submit" value="Spara" />
</form>
<?php include("../include/footer.php");?>
<file_sep><?php
include("../include/headless.php");
$storedData = $db->query("SELECT password,salt FROM user WHERE id=$_SESSION[uId]")->fetchArray();
$validateOldPass = hashPassword($_POST['oldpass'], $storedData['salt']);
if($validateOldPass == $storedData['password']) {
if($_POST['newpass1'] != $_POST['newpass2']) {
$_SESSION['error'] = "Nytt lösenord och bekräftelse av lösenord ej samma.";
header("Location: ../modify/password.php");
die();
} else {
$newPass = hashPassword($_POST['newpass1'], $storedData['salt']);
$db->exec("UPDATE user SET password=\"<PASSWORD>\" WHERE id=$_SESSION[uId]");
$_SESSION['message'] = "Ditt lösenord är uppdaterat.";
header("Location: ../my_account.php");
die();
}
} else {
$_SESSION['error'] = "Nuvarande lösenord felaktigt.";
}
header("Location: ../modify/password.php");
die();
?>
<file_sep><?php
$g_Title="Redigera Laddning ";
include("../include/header.php");
echo "<h2>Rediera Laddning</h2>\n";
$data = $db->query("SELECT * FROM charge WHERE id=$_GET[id]")->fetchArray();
echo "<form action=\"../register/charge.php\" method=\"post\" />\n";
echo "<input type=\"hidden\" name=\"id\" value=\"$_GET[id]\" />\n";
echo "<select name=\"battery\">\n";
$batteries = $db->query("SELECT id, description FROM battery WHERE user=$_SESSION[uId] AND discarded=0");
while($battery = $batteries->fetchArray()) {
echo "<option value=\"$battery[id]\"";
if($battery['id'] == $data['battery']) {
echo " SELECTED";
}
echo ">$battery[description]</option>\n";
}
echo "</select>\n";
echo "<input type=\"text\" name=\"mAh\" value=\"$data[mAh]\" /><br />\n";
echo "<input type=\"text\" name=\"datetime\" value=\"" . strftime("%Y-%m-%d %H:%M", $data['datetime']) . "\" />\n";
echo "<input type=\"submit\" value=\"Uppdatera laddning\" />\n";
echo "</form>\n";
include("../footer.php");
?>
<file_sep><?php
include_once("../include/headless.php");
$_POST['time'] = tofloat($_POST['time']) * 60;
if(isset($_POST['id'])) {
$db->exec("UPDATE flight SET model=$_POST[model], battery=$_POST[battery], time=$_POST[time], datetime=" . strtotime($_POST['datetime']) . " WHERE id=$_POST[id]");
} else {
$db->exec("INSERT INTO flight(model, battery, time, datetime) values($_POST[model], $_POST[battery], $_POST[time], " . mktime() . ")") or die("Could not perform: " . $db->lastErrorMsg());
}
updatechargestatus($_POST['battery']);
header("Location: ../model.php?id=$_POST[model]");
die();
?>
<file_sep><?php
$currPath = dirname($_SERVER['DOCUMENT_ROOT'] . $_SERVER['PHP_SELF']);
$targetPath = realpath($dbPath . "/..");
$prePath = find_relative_path($currPath, $targetPath);
if(strlen($prePath) > 0) {$prePath .= "/";}
?>
<div id="meny">
<?php
if(isset($_SESSION['uId'])) {
?>
<form action="register/charge.php" method="post">
<select name="battery">
<?php
$list = $db->query("SELECT id, Description, Cells, mAh FROM battery WHERE discarded=0 AND user=$_SESSION[uId] ORDER BY isCharged ASC, description ASC");
while($row = $list->fetchArray()) {
echo "\t\t\t\t\t<option value=\"$row[id]\">$row[description] $row[mAh]mAh $row[cells]S</option>\n";
}
?>
</select>
mAh: <input type="text" name="mAh" />
<input type="submit" value="Registrera Laddning" />
</form>
<a href="<?php echo $prePath;?>index.php">Överblick</a>
<div class="header">Modeller</div>
<ul class="meny">
<?php
$models = $db->query("SELECT id, Description FROM model WHERE discarded=0 AND user=$_SESSION[uId] ORDER BY Description");
while($model = $models->fetchArray()) {
echo "\t\t\t\t<li><a href=\"". $prePath . "model.php?id=$model[id]\">$model[description]</a></li>\n";
}
?>
</ul>
<div class="header">Lägg till</div>
<ul>
<li><a href="<?php echo $prePath;?>modify/model.php?id=new">Modell</a></li>
<li><a href="<?php echo $prePath;?>modify/battery.php?id=new">Batteri</a></li>
</ul>
<a href="<?php echo $prePath;?>my_account.php">Mitt Konto</a><br />
<a href="<?php echo $prePath;?>register/logout.php">Logga ut</a>
<?php
} else {
echo "<a href=\"" . $prePath . "login.php\">Logga in</a>\n";
}
?>
</div>
<file_sep><?php
include("../include/session.php");
include("../include/database.php");
session_destroy();
if(isset($_COOKIE['rclog-persistent'])) {
$data = explode(':', $_COOKIE['rclog-persistent']);
$data[0] = $db->escapeString($data[0]);
$data[1] = $db->escapeString($data[1]);
$db->exec("DELETE FROM rememberme WHERE user = $data[0] AND hash=\"$data[0]:$data[1]\"");
unset($_COOKIE['rolog-persistent']);
setcookie('rclog-persistent', null, -1, '/');
}
header("Location: ../login.php");
die();
?>
<file_sep><?php
$g_Title = "Överblick ";
include("include/header.php");
$res = $db->query("SELECT id, description, cells, mAh, drawC, chargeC, weight, isCharged FROM battery WHERE user = $_SESSION[uId] AND discarded = 0 ORDER BY isCharged DESC, cells, mAh");
echo "\t\t<h2>Batterier</h2>\n";
echo "\t\t<a href=\"modify/battery.php?id=new\">Lägg till Batteri</a>\n";
echo "\t\t<table>\n";
echo "\t\t\t<tr>\n";
echo "\t\t\t\t<th>ID</th>\n";
echo "\t\t\t\t<th>Laddat</th>\n";
echo "\t\t\t\t<th>Beskrivning</th>\n";
echo "\t\t\t\t<th>Celler</th>\n";
echo "\t\t\t\t<th>mAh</th>\n";
echo "\t\t\t\t<th>C Amp</th>\n";
echo "\t\t\t\t<th>C Laddning</th>\n";
echo "\t\t\t\t<th>Vikt</th>\n";
echo "\t\t\t\t<th>Cykler</th>\n";
echo "\t\t\t</tr>\n";
while($row = $res->fetchArray()) {
echo "\t\t\t<tr>\n";
echo "\t\t\t\t<td>$row[id]</td>\n";
if($row['isCharged'] == 1) {
echo "\t\t\t\t<td><img src=\"img/battery-100-2.png\" alt=\"Batteriet är laddat\" /></td>\n";
} else {
echo "\t\t\t\t<td><img src=\"img/battery-empty-2.png\" alt=\"Batteriet behöver laddas\" /></td>\n";
}
echo "\t\t\t\t<td><a href=\"battery.php?id=$row[id]\">$row[description]</a></td>\n";
echo "\t\t\t\t<td>$row[cells]</td>\n";
echo "\t\t\t\t<td>$row[mAh]</td>\n";
echo "\t\t\t\t<td>$row[drawC]</td>\n";
echo "\t\t\t\t<td>$row[chargeC]</td>\n";
echo "\t\t\t\t<td>$row[weight]</td>\n";
$cycles = $db->querySingle("SELECT count(battery) FROM charge WHERE battery=$row[id]");
echo "\t\t\t\t<td>$cycles</td>\n";
echo "\t\t\t</tr>\n";
}
echo "\t\t</table>\n";
echo "\t\t<h2>Modeller</h2>\n";
$res = $db->query("SELECT id, description FROM model WHERE user=$_SESSION[uId] AND discarded = 0 ORDER BY description");
echo "\t\t<a href=\"modify/model.php?id=new\">Lägg till Modell</a>\n";
echo "\t\t<table>\n";
echo "\t\t\t<tr>\n";
echo "\t\t\t\t<th>ID</th>\n";
echo "\t\t\t\t<th>Namn</th>\n";
echo "\t\t\t\t<th>Flygningar</th>\n";
echo "\t\t\t\t<th>Flygtid</th>\n";
echo "\t\t\t\t<th><img src=\"img/battery-empty-2.png\" alt=\"Oladdade batterier\" /></th>\n";
echo "\t\t\t\t<th><img src=\"img/battery-100-2.png\" alt=\"Laddade batterier\" /></th>\n";
echo "\t\t\t</tr>\n";
while($row = $res->fetchArray()) {
$maxCells = $db->querySingle("SELECT max_cell FROM model WHERE id=$row[id]");
$minCells = $db->querySingle("SELECT min_cell FROM model WHERE id=$row[id]");
$flights = $db->querySingle("SELECT count(*) FROM flight WHERE model=$row[id]");
$flighttime = round($db->querySingle("SELECT sum(time) FROM flight WHERE model=$row[id]")/60/60,2);
$uncharged = $db->querySingle("SELECT count(description) FROM battery WHERE isCharged=0 AND cells >= $minCells AND cells <= $maxCells");
$charged = $db->querySingle("SELECT count(description) FROM battery WHERE isCharged=1 AND cells >= $minCells AND cells <= $maxCells");
echo "\t\t\t<tr>\n";
echo "\t\t\t\t<td>$row[id]</td>\n";
echo "\t\t\t\t<td><a href=\"model.php?id=$row[id]\">$row[description]</a></td>\n";
echo "\t\t\t\t<td>$flights</td>\n";
echo "\t\t\t\t<td>$flighttime</td>\n";
echo "\t\t\t\t<td>$uncharged</td>\n";
echo "\t\t\t\t<td>$charged</td>\n";
echo "\t\t\t</tr>\n";
}
echo "\t\t</table>\n";
include("include/footer.php");
?>
<file_sep><?php
include("../include/session.php");
include("../include/database.php");
include("../include/functions.php");
$db->exec("DELETE FROM rememberme WHERE validto > 'NOW'");
$email = $db->escapeString($_POST['username']);
$password = $db->escapeString($_POST['password']);
$uId = $db->querySingle("SELECT id FROM user WHERE email=\"$email\"");
$salt = $db->querySingle("SELECT salt FROM user WHERE id=$uId");
$hashString = hashPassword($password, $salt);
$storedHash = $db->querySingle("SELECT password FROM user WHERE id=$uId");
$r_hashData = "$uId:" . md5(generateSalt() . $_SERVER['HTTP_USER_AGENT']);
if($storedHash == $hashString) {
$_SESSION['uId'] = $uId;
header("Location: ../index.php");
if($_POST['rememberme'] == "on") {
$db->exec("INSERT INTO rememberme(user,hash) values($uId, \"$r_hashData\")");
$validto = $db->querySingle("SELECT strftime('%s',validto) FROM rememberme WHERE id=" . $db->lastInsertRowID());
setcookie('rclog-persistent', $r_hashData, $validto, '/');
}
} else {
session_destroy();
header("Location: ../login.php");
}
die();
?>
<file_sep><?php
$g_Title = "<NAME> ";
include("include/header.php");
if(isset($_SESSION['message'])) {
echo "<p>$_SESSION[message]</p>\n";
unset($_SESSION['message']);
}
?>
<p><a href="modify/password.php">Ändra lösenord</a></p>
<?php
$totalFlightTime = round($db->querySingle("SELECT sum(time) FROM flight,model WHERE flight.model = model.id AND model.user=$_SESSION[uId]") / 60 / 60, 1);
$totalActiveModels = $db->querySingle("SELECT count(id) FROM model WHERE user=$_SESSION[uId] AND discarded = 0");
$totalDiscardedModels = $db->querySingle("SELECT count(id) FROM model WHERE user=$_SESSION[uId] AND discarded = 1");
$totalActiveBatteries = $db->querySingle("SELECT count(id) FROM battery WHERE user=$_SESSION[uId] AND discarded = 0");
$totalDiscardedBatteries = $db->querySingle("SELECT count(id) FROM battery WHERE user=$_SESSION[uId] AND discarded = 1");
$totalAmps = $db->querySingle("SELECT sum(battery.mAh) FROM charge, battery WHERE charge.battery = battery.id AND battery.user = $_SESSION[uId]") / 1000;
echo "<table>\n";
echo "<tr>\n";
echo "<th>Total Flygtid</th>\n";
echo "<td>$totalFlightTime timmar</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<th>Aktiva modeller</th>\n";
echo "<td><a href=\"listmodels.php\">$totalActiveModels</a></td>\n";
echo "<th>Kasserade modeller</th>\n";
echo "<td><a href=\"listmodels.php?discarded=1\">$totalDiscardedModels</a></td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<th>Aktiva Batterier</th>\n";
echo "<td><a href=\"listbatteries.php\">$totalActiveBatteries</a></td>\n";
echo "<th>Kasserade Batterier</th>\n";
echo "<td><a href=\"listbatteries.php?discarded=1\">$totalDiscardedBatteries</a></td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<th>Totalt laddade A</th>\n";
echo "<td>$totalAmps</td>\n";
echo "</tr>\n";
echo "</table>\n";
include("include_footer.php");
?>
|
442d4ba3add42072f20bf4257fd71e01592057f3
|
[
"Markdown",
"PHP"
] | 28
|
PHP
|
daGnutt/rclog
|
8c89bad0550188dabb2ba5e89583f1fc31f2cb38
|
93d49eb2dc91ba801622a3c1331e32938d3b2866
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import { Container, Header, Content, Form, Item, Input, Button, Text, Body, Title } from 'native-base';
class Login extends Component {
render() {
return (
<Container>
<Header>
<Body>
<Title>Login</Title>
</Body>
</Header>
<Content>
<Form>
<Item>
<Input placeholder="Username" />
</Item>
<Item last>
<Input placeholder="<PASSWORD>" />
</Item>
<Button rounded >
<Text> Iniciar Sesión </Text>
</Button>
</Form>
</Content>
</Container>
);
}
}
export default Login;<file_sep>rootProject.name = 'CartBase'
include ':app'
<file_sep>import React from 'react';
import {DrawerNavigator, createStackNavigator} from 'react-navigation';
import Settings from '../menu/settings';
import Terms from '../terms';
import SideMenu from '../menu/side-menu';
import Catalog from '../scenes/Catalog';
import Login from '../scenes/Login';
import DetailProduct from '../scenes/CatalogDetail';
import ShoppingCartIcon from '../shopping-cart-icon';
const stackSettings = createStackNavigator({
CatalogScreen: {screen: Catalog},
DetailScreen: {screen: DetailProduct},
},{
initialRouteName: 'DetailScreen',
});
export const Nav = DrawerNavigator({
HomeScreen: {screen: Catalog},
SettingStack: stackSettings
},{
contentComponent: SideMenu
});
<file_sep>import React, { Component } from 'react';
import { StyleSheet, Image } from 'react-native';
import { Container, Content, Button, Text, Title, Icon, Header, Right } from 'native-base';
import HttpProduct from "../../services/Product/http-products";
import CustomHeader from '../../button/custom-header';
import { connect } from 'react-redux';
class ProductDetail extends Component {
static navigationOptions = ({ navigation }) => {
return {
header: (props) => (
<CustomHeader
title={'Detalle de Productos'}
navigation={navigation}
hasBackButton={props.navigation.state.routes.length > 1}
/>
)
}
}
constructor(props) {
super(props);
this.state = {
product: {}
}
}
componentDidMount = () => {
id = this.props.navigation.getParam('id', 'no-data');
this.getProductById(id);
}
async getProductById(id) {
const data = await HttpProduct.getProductsById(id);
this.setState({
product: data
})
console.log(data);
}
render() {
return (
<Container>
<Header>
<Right>
<ShoppingCartIcon />
</Right>
</Header>
<Content style={styles.container}>
<Image source={{ uri: this.state.product.avatar }}
style={styles.avatar}
/>
<Text> {this.state.product.brand} </Text>
<Text> {this.state.product.name} </Text>
<Text> $ {this.state.product.price} </Text>
<Text> {this.state.product.description} </Text>
<Button onPress={() => navigation.navigate('DetailScreen', { id: product._id })}>
<Title>Comprar</Title>
</Button>
<Button onPressEvent={ this.props.addItemToCart } products={this.state.product._id} >
<Icon name="add-circle" />
</Button>
</Content>
</Container>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
imageBackground: {
flex: 1,
height: 120,
justifyContent: 'center',
alignItems: 'center',
},
avatar: {
height: 100,
width: 100,
borderRadius: 50,
}
});
const mapDispatchToProps = (dispatch) => {
return {
addItemToCart: (product) => dispatch({ type: 'ADD_TO_CART', payload: product })
}
}
export default connect(null, mapDispatchToProps)(ProductDetail);
|
fddedf11ec5e82421c503dbd55e5d107093448f1
|
[
"JavaScript",
"Gradle"
] | 4
|
JavaScript
|
LopezKat/CartBase
|
493aa5d1fa2adeda0ff05668c608b7806b206698
|
547f2b013b511e9ad5d0eceb6733c17537f1dd74
|
refs/heads/main
|
<repo_name>igorfrancob/rarecarat<file_sep>/model.rarecarat/Image/ImageModel.cs
using core.rarecarat;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace model.rarecarat
{
public class ImageBaseModel
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Path { get; set; }
[Required]
public int DiamondId { get; set; }
public DiamondDetailsModel Diamond { get; set; }
}
public class ImageDetailsModel : ImageBaseModel, IDetailsModel
{
}
public class ImageUpdateModel : ImageBaseModel, IUpdateModel
{
}
public class ImageCreateModel : ImageBaseModel, ICreateModel
{
}
public class ImageListItemModel : IListItemModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Path { get; set; }
}
}
<file_sep>/data.rarecarat/Repository/Base/EFBaseRepository.cs
using core.rarecarat;
using data.rarecarat.Context;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace data.rarecarat.Repository
{
public abstract class EFBaseRepository<TEntity> : IAsyncRepository<TEntity> where TEntity : class, IEntity
{
protected readonly RarecaratContext db;
protected EFBaseRepository( RarecaratContext dbContext ) : base()
{
db = dbContext;
//_logger = CoreConfigurations.Logger;
}
public Task<object> CreateAsync( TEntity entity )
{
db.Set<TEntity>().AddAsync( entity );
db.SaveChangesAsync();
return Task.Factory.StartNew( () => GetIdFrom( entity ) );
}
public Task UpdateAsync( TEntity entity )
{
if ( !db.ChangeTracker.Entries<TEntity>().Any( x => x.Entity == entity ) )
{
db.Set<TEntity>().Attach( entity );
db.Entry( entity ).State = EntityState.Modified;
}
return db.SaveChangesAsync();
}
public async Task DeleteAsync( object id )
{
var entity = await db.Set<TEntity>().FindAsync( id );
if ( entity == null )
throw new ArgumentException( string.Format( "Entity not found for id {0}", id ) );
db.Entry( entity ).State = EntityState.Deleted;
await db.SaveChangesAsync();
}
public ValueTask<TEntity> GetByIdAsync( object id )
{
return db.Set<TEntity>().FindAsync( id );
}
protected abstract object GetIdFrom( TEntity entity );
}
}<file_sep>/model.rarecarat/Diamond/DiamondModel.cs
using core.rarecarat;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace model.rarecarat
{
public class DiamondBaseModel
{
public int Id { get; set; }
[Required]
public ShapeType Shape { get; set; }
[Required]
public CertificationType Certification { get; set; }
[Required]
public ClarityType Clarity { get; set; }
[Required]
public ColorType Color { get; set; }
[Required]
public CutType Cut { get; set; }
[Required]
public DiamondType Type { get; set; }
[Required]
public FluorescenceType Fluorescence { get; set; }
[Required]
public decimal Price { get; set; }
[Required]
public decimal Carat { get; set; }
[Required]
public int RetailerId { get; set; }
public virtual RetailerDetailsModel Retailer { get; set; }
public virtual List<ImageListItemModel> Images { get; set; }
}
public class DiamondDetailsModel : DiamondBaseModel, IDetailsModel
{
}
public class DiamondUpdateModel : DiamondBaseModel, IUpdateModel
{
}
public class DiamondCreateModel : DiamondBaseModel, ICreateModel
{
}
public class DiamondListItemModel : DiamondBaseModel, IListItemModel
{
}
}<file_sep>/model.rarecarat/_Base/Enums/DiamondType.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace core.rarecarat
{
public enum DiamondType
{
NATURAL, LAB_GROWN
}
}
<file_sep>/core.rarecarat/Utils/ConstructorHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace core.rarecarat
{
public static class ConstructorHelper
{
public static OperationResult ErrorOperationResult()
{
return new OperationResult("error occurred");
}
public static OperationResult ErrorOperationResult(string message)
{
return new OperationResult(message);
}
public static OperationResult ErrorOperationResult(Exception ex)
{
return new OperationResult(ex);
}
public static OperationResult<T> ErrorOperationResult<T>()
{
return new OperationResult<T>("error occurred");
}
public static OperationResult<T> ErrorOperationResult<T>(Exception ex)
{
return new OperationResult<T>(ex);
}
public static OperationResult<T> ErrorOperationResult<T>(string message)
{
return new OperationResult<T>(message);
}
public static ValidationResult ErrorValidationResult()
{
//Ocorreu um erro a processar o seu pedido
return new ValidationResult("error occurred");
}
public static ValidationResult ErrorValidationResult(string message)
{
return new ValidationResult(message);
}
public static ValidationResult<T> ErrorValidationResult<T>()
{
return new ValidationResult<T>(default(T), true, "error occurred");
}
public static ValidationResult<T> ErrorValidationResult<T>(string message)
{
return new ValidationResult<T>(default(T), true, message);
}
//public static void AddValidationResults( this ValidationResult validation, IEnumerable<ELValidationResult> results )
//{
// foreach ( var res in results )
// {
// validation.AddErrorValidationItem( res.Key, res.Message );
// }
//}
//public static void AddValidationResults( this ValidationResult validation, IEnumerable<ELValidationResult> results, string prefix )
//{
// foreach ( var res in results )
// {
// validation.AddErrorValidationItem( prefix, res.Key, res.Message );
// }
//}
public static void AddPrefixToErrors(this ValidationResult validation, string prefix)
{
foreach (var error in validation.ValidationErrors)
{
error.PropertyName = prefix + "." + error.PropertyName;
}
}
public static void AddErrorValidationItem(this ValidationResult validation, string prefix, string propName, string message)
{
if (!string.IsNullOrEmpty(prefix))
propName = prefix + "." + propName;
if (!(validation.ValidationErrors.Any(i => i.PropertyName == propName)))
validation.AddErrorValidationItem(propName, message);
}
}
}<file_sep>/model.rarecarat/_Base/Enums/FluorescenceType.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace core.rarecarat
{
public enum FluorescenceType
{
VERY_STRONG, STRONG, MEDIUM, FAINT, NONE
}
}
<file_sep>/api.rarecarat/Dockerfile
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
#For more information, please see https://aka.ms/containercompat
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["api.rarecarat/api.rarecarat.csproj", "api.rarecarat/"]
RUN dotnet restore "api.rarecarat/api.rarecarat.csproj"
COPY . .
WORKDIR "/src/api.rarecarat"
RUN dotnet build "api.rarecarat.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "api.rarecarat.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "api.rarecarat.dll"]<file_sep>/domain.rarecarat/Models/Customer.cs
namespace domain.rarecarat.Models
{
public class Customer
{
public long Id { get; set; }
public string Identifier { get; set; }
public string Name { get; set; }
public string AccountGrpCli { get; set; }
public string NameTwo { get; set; }
public string StreetOne { get; set; }
public string StreetTwo { get; set; }
public string PostalCode { get; set; }
public string Location { get; set; }
public string CountryCode { get; set; }
public string CountryName { get; set; }
public string Region { get; set; }
public string LanguageCode { get; set; }
public string LanguageName { get; set; }
public string Phone { get; set; }
public string MobilePhone { get; set; }
public string Mail { get; set; }
public string NIF { get; set; }
public string ClientBlocking { get; set; }
public string Provider { get; set; }
public string Kdgrp { get; set; }
public string HeadOffice { get; set; }
public string ClientHeadOffice { get; set; }
public string Directions { get; set; }
}
}<file_sep>/core.rarecarat/Entity/ValidationResultGeneric.cs
using System;
namespace core.rarecarat
{
/// <summary>
/// The data contracted validation result class of closed generic.
/// This type includes possible validation messages as result of an Operation that
/// performs validation.
/// </summary>
/// <typeparam name = "TResult">The type of data expected for the returning result.</typeparam>
public class ValidationResult<TResult> : ValidationResult, IOperationResult<TResult>
{
#region Ctors
public ValidationResult()
: base()
{
}
public ValidationResult( string message ) : base( message )
{
}
public ValidationResult( Exception e ) : base( e )
{
}
public ValidationResult( Exception e, TResult result )
{
Result = result;
Error = true;
if ( e != null )
{
Message = e.Message;
}
}
public ValidationResult( OperationResult<TResult> operationResult )
{
Result = operationResult.Result;
Error = operationResult.Error;
Message = operationResult.Message;
}
/// <summary>
/// Initializes a new instance of the <see cref = "OperationResult{TResult}" /> class.
/// </summary>
/// <param name = "result">
/// The result.
/// </param>
/// <param name = "error">
/// The error.
/// </param>
/// <param name = "message"></param>
public ValidationResult( TResult result, bool error = false, string message = null )
{
Result = result;
Error = error;
if ( error )
{
Message = message;
}
}
#endregion Ctors
public TResult Result { get; set; }
}
}<file_sep>/core.rarecarat/IRepository/Base/IEntity.cs
namespace core.rarecarat
{
public interface IEntity
{
}
}<file_sep>/domain.rarecarat/Utilities/Extensions.cs
namespace domain.rarecarat.Utilities
{
using Newtonsoft.Json;
using System;
using System.Reflection;
public static class Extensions
{
#region String Conversions
public static string ToStringObject(this object value, string property)
{
PropertyInfo pi = value.GetType().GetProperty(property);
return (string)(pi.GetValue(value, null));
}
public static object ToJasonObject(this string value)
{
return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(value.Replace('=', ':')));
}
public static string ToSerializableObject(this string value, string oldString, string newString)
{
return value.Replace(oldString, newString);
}
public static string ToSplitSecontObject(this string value, string spliter)
{
try
{
return value.Split(spliter)[1];
}
catch (Exception)
{
return value.Split(spliter)[0];
}
}
public static DateTime ToDateTime(this string value)
{
return Convert.ToDateTime(value);
}
public static DateTime? ToNullableDateTime(this string value)
{
return (DateTime?)Convert.ToDateTime(value);
}
#endregion
}
}<file_sep>/core.rarecarat/Entity/IValidationResult.cs
using System.Collections.Generic;
namespace core.rarecarat
{
public interface IValidationResult : IOperationResult
{
bool IsValid { get; set; }
List<ValidationItem> ValidationErrors { get; set; }
void AddErrorValidationItem( string message );
void AddErrorValidationItem( string propName, string message );
void AddErrorValidationItems( IEnumerable<ValidationItem> items );
void MergeValidationResults( ValidationResult resultToMerge );
}
}<file_sep>/model.rarecarat/_Base/IModels/ICreateModel.cs
namespace model.rarecarat
{
public interface IDetailModel
{
}
}<file_sep>/domain.rarecarat/AutoMapper/Profiles/DiamondProfile.cs
using data.rarecarat.Entities;
using model.rarecarat;
namespace domain.rarecarat.AutoMapper
{
public class DiamondProfile : BaseProfile
{
public DiamondProfile()
{
// Create
CreateMap<DiamondCreateModel, Diamond>();
// Details
// Edit
CreateMap<DiamondUpdateModel, Diamond>();
CreateMap<Diamond, DiamondUpdateModel>();
// Others
CreateMap<Diamond, DiamondDetailsModel>();
CreateMap<Diamond, DiamondListItemModel>();
}
}
}
<file_sep>/domain.rarecarat/Business/DiamondBusiness.cs
using System;
using System.Linq;
using System.Collections.Generic;
using AutoMapper;
using System.Threading.Tasks;
using core.rarecarat;
using model.rarecarat;
using data.rarecarat.Repository;
using data.rarecarat.Entities;
using domain.rarecarat.Contracts;
using FluentValidation;
using Microsoft.Extensions.Logging;
namespace domain.rarecarat.Business
{
public class DiamondBusiness : IDiamondBusiness
{
private IDiamondRepository _DiamondRepository;
private IMapper _mapper;
private ILogger _logger;
public DiamondBusiness( IDiamondRepository DiamondRepository, IMapper mapper, ILogger<DiamondBusiness> logger )
{
_DiamondRepository = DiamondRepository;
_mapper = mapper;
_logger = logger;
}
public async Task<ValidationResult<object>> CreateAsync( DiamondCreateModel model )
{
try
{
var result = await _DiamondRepository.CreateAsync( _mapper.Map<Diamond>( model ) );
return new ValidationResult<object>( result );
}
catch ( Exception ex )
{
_logger.LogError( ex, $"CreateAsync: {ex.Message}" );
return ConstructorHelper
.ErrorValidationResult<object>();
}
}
public async Task<OperationResult> DeleteAsync( object id )
{
try
{
await _DiamondRepository.DeleteAsync( id );
return new OperationResult();
}
catch ( Exception ex )
{
_logger.LogError( ex, $"DeleteAsync: {ex.Message}" );
return ConstructorHelper
.ErrorOperationResult();
}
}
public async Task<OperationResult<List<DiamondListItemModel>>> GetAllAsync()
{
try
{
var result = await _DiamondRepository.GetAllAsync();
return new OperationResult<List<DiamondListItemModel>>(
_mapper.ProjectTo<DiamondListItemModel>( result.AsQueryable() ).ToList() );
}
catch ( Exception ex )
{
_logger.LogError( ex, $"GetAllAsync: {ex.Message}" );
return ConstructorHelper
.ErrorOperationResult<List<DiamondListItemModel>>();
}
}
public async Task<OperationResult<DiamondDetailsModel>> GetDetailsModelAsync( object id )
{
try
{
var result = await _DiamondRepository.GetByIdAsync( id );
return new OperationResult<DiamondDetailsModel>( _mapper.Map<DiamondDetailsModel>( result ) );
}
catch ( Exception ex )
{
_logger.LogError( ex, $"GetDetailsModelAsync: {ex.Message}" );
return ConstructorHelper
.ErrorOperationResult<DiamondDetailsModel>();
}
}
public async Task<OperationResult<DiamondUpdateModel>> GetUpdateModelAsync( object id )
{
var entity = await _DiamondRepository.GetByIdAsync( id );
var details = _mapper.Map<DiamondUpdateModel>( entity );
return new OperationResult<DiamondUpdateModel>( details );
}
public async Task<ValidationResult> UpdateAsync( DiamondUpdateModel model )
{
try
{
var entity = _mapper.Map<Diamond>( model );
await _DiamondRepository.UpdateAsync( entity );
return new ValidationResult();
}
catch ( Exception ex )
{
_logger.LogError( ex, $"UpdateAsync: {ex.Message}" );
return ConstructorHelper.ErrorValidationResult();
}
}
}
}
<file_sep>/core.rarecarat/Entity/ValidationItem.cs
using System;
namespace core.rarecarat
{
public class ValidationItem
{
public string PropertyName { get; set; }
public string Message { get; set; }
public Exception Exception { get; set; }
}
}<file_sep>/data.rarecarat/Repository/Demo/DiamondRepository.cs
using core.rarecarat;
using data.rarecarat.Context;
using data.rarecarat.Entities;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
namespace data.rarecarat.Repository
{
public interface IDiamondRepository : IAsyncRepository<Diamond>
{
Task<List<Diamond>> GetAllAsync();
}
public class DiamondRepository : EFBaseRepository<Diamond>, IDiamondRepository
{
public DiamondRepository( RarecaratContext dbContext ) : base( dbContext ) { }
protected override object GetIdFrom( Diamond entity )
{
return ( entity.Id );
}
public Task<List<Diamond>> GetAllAsync()
{
return db.Diamonds
.Include( p => p.Retailer )
.Include( p => p.Images )
.ToListAsync();
}
}
}
<file_sep>/domain.rarecarat/Models/Awards.cs
namespace domain.rarecarat.Models
{
using System.Collections.Generic;
using System.Text.Json.Serialization;
public class Awards
{
public AwardAccounts Accounts { get; set; }
public Contact Contact { get; set; }
public string Name { get; set; } // -
public string Owner { get; set; } // email
public string OwnerEmail { get; set; } // email
public string Type { get; set; } // cliente/retalho
public decimal TypeCode { get; set; }
public string BusinessLine { get; set; }
public decimal? BusinessLineCode { get; set; }
public string Cl { get; set; }
public string ClCode { get; set; }
public string Currency { get; set; }
public string CurrencySymbol { get; set; }
public string CurrencyCode { get; set; }
public string CustomerRef { get; set; }
public string Department { get; set; }
public string DepartmentCode { get; set; }
public string Source { get; set; }
public decimal? SourceCode { get; set; }
public string Description { get; set; }
public string BillAddress1 { get; set; }
public string BillAddress2 { get; set; }
public string BillAddressCountry { get; set; }
public string BillAddressCity { get; set; }
public string BillAddressPostalCode { get; set; }
public string ShipAddress1 { get; set; }
public string ShipAddress2 { get; set; }
public string ShipAddressCity { get; set; }
public string ShipAddressCountry { get; set; }
public string ShipAddressPostalCode { get; set; }
public string Date { get; set; }
public string EffectiveFrom { get; set; }
public string EffectiveTo { get; set; }
public string ExpirationDate { get; set; }
public string ReceptionDate { get; set; }
public string AcceptanceDate { get; set; }
public string ExecutionLocationType { get; set; }
public string PaymentMethod { get; set; }
public string PaymentMethodCode { get; set; }
public string PaymentTerms { get; set; }
public string PaymentTermsCode { get; set; }
public string QuoteId { get; set; }
public decimal Revision { get; set; }
public string SapSONumber { get; set; }
public decimal? DiscountPercentage { get; set; }
public decimal TotalAmount { get; set; }
public decimal TotalDiscount { get; set; }
public decimal TotalTaxAmount { get; set; }
public decimal TotalTransportAmount { get; set; }
public string ActivitySector { get; set; }
public string ActivitySectorName { get; set; }
public string DistributionChannel { get; set; }
public string DistributionChannelName { get; set; }
public string OwnerNumber { get; set; }
public string OwnerClName { get; set; }
public string OwnerCl { get; set; }
public string ManagerName { get; set; }
public string ManagerNameNumber { get; set; }
public string ManagerClName { get; set; }
public string ManagerCl { get; set; }
public string SalesOffice { get; set; }
public string SalesOfficeName { get; set; }
public bool CustomerType { get; set; }
public string TaxType { get; set; }
public decimal? TaxTypeCode { get; set; }
public string ExternalID { get; set; }
public string CrmId { get; set; }
public string ProposalId { get; set; }
public string OrderCode { get; set; }
public List<Aggregator> Aggregators { get; set; }
public List<BudgetItem> Items { get; set; }
public List<BudgetComment> Comments { get; set; }
public List<Pep> Peps { get; set; }
public string PurchaseOrderNumber { get; set; }
}
}
<file_sep>/core.rarecarat/Services/CreateBaseService.cs
using ARGIL.Core.IModels;
using ARGIL.Core.IRepository;
using ARGIL.Core.Models;
namespace ARGIL.Core.Services
{
public abstract class CreateBaseService<TEntity, TCreate> : BaseService<TEntity, TCreate, NotSupportedOperation, NotSupportedOperation, NotSupportedOperation>
where TCreate : ICreateModel
where TEntity : IEntity
{
protected CreateBaseService( IUnitOfWork unitOfWork, ILogger logger ) : base( unitOfWork, logger )
{
}
}
}<file_sep>/domain.rarecarat/AutoMapper/Profiles/BaseProfile.cs
using AutoMapper;
namespace domain.rarecarat.AutoMapper
{
public class BaseProfile : Profile
{
}
}<file_sep>/model.rarecarat/Retailer/RetailerModel.cs
using core.rarecarat;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace model.rarecarat
{
public class RetailerBaseModel
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
//public virtual List<DiamondDetailsModel> Diamonds { get; set; }
}
public class RetailerDetailsModel : RetailerBaseModel, IDetailsModel
{
}
public class RetailerUpdateModel : RetailerBaseModel, IUpdateModel
{
}
public class RetailerCreateModel : RetailerBaseModel, ICreateModel
{
}
public class RetailerListItemModel : IListItemModel
{
}
}
<file_sep>/domain.rarecarat/Models/FinancialAccount.cs
namespace domain.rarecarat.Models
{
using System.Collections.Generic;
using System.Text.Json.Serialization;
public class FinancialAccount
{
[JsonPropertyName("Address1")]
public string AccountAddress1 { get; set; }
[JsonPropertyName("Address2")]
public string AccountAddress2 { get; set; }
[JsonPropertyName("AddressCity")]
public string AccountAddressCity { get; set; }
[JsonPropertyName("AddressLatitude")]
public string AccountAddressLatitude { get; set; }
[JsonPropertyName("AddressLongitude")]
public string AccountAddressLongitude { get; set; }
[JsonPropertyName("AddressPostalCode")]
public string AccountAddressPostalCode { get; set; }
[JsonPropertyName("CAE")]
public string AccountCAE { get; set; }
[JsonPropertyName("CAECode")]
public string AccountCAECode { get; set; }
[JsonPropertyName("Country")]
public string AccountCountry { get; set; }
[JsonPropertyName("CountryCode")]
public string AccountCountryCode { get; set; }
[JsonPropertyName("Email")]
public string AccountEmail { get; set; }
[JsonPropertyName("Fax")]
public string AccountFax { get; set; }
[JsonPropertyName("GUID")]
public string AccountGUID { get; set; }
[JsonPropertyName("NIF")]
public string AccountNIF { get; set; }
[JsonPropertyName("Name")]
public string AccountName { get; set; }
[JsonPropertyName("Name2")]
public string AccountName2 { get; set; }
[JsonPropertyName("Number")]
public string AccountNumber { get; set; }
[JsonPropertyName("NumberOfEmployees")]
public string AccountNumberOfEmployees { get; set; }
[JsonPropertyName("NumberOfEmployeesCode")]
public object AccountNumberOfEmployeesCode { get; set; }
[JsonPropertyName("PaymentTerms")]
public string AccountPaymentTerms { get; set; }
[JsonPropertyName("PaymentTermsCode")]
public string AccountPaymentTermsCode { get; set; }
[JsonPropertyName("Phone")]
public string AccountPhone { get; set; }
[JsonPropertyName("SalesRegion")]
public string AccountSalesRegion { get; set; }
[JsonPropertyName("SalesRegionCode")]
public string AccountSalesRegionCode { get; set; }
[JsonPropertyName("SecondPhone")]
public string AccountSecondPhone { get; set; }
[JsonPropertyName("Type")]
public string AccountType { get; set; }
[JsonPropertyName("TypeCode")]
public int AccountTypeCode { get; set; }
[JsonPropertyName("WebSite")]
public string AccountWebSite { get; set; }
[JsonPropertyName("ParentAccount")]
public string ParentAccount { get; set; }
[JsonPropertyName("ParentAccountGUID")]
public string ParentAccountGUID { get; set; }
}
}
<file_sep>/core.rarecarat/IModels/IUpdateModel.cs
namespace core.isqnet.awards
{
public interface IUpdateModel
{
}
}<file_sep>/data.rarecarat/Entities/Retailer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace data.rarecarat.Entities
{
public class Retailer
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual List<Diamond> Diamonds { get; set; }
}
}
<file_sep>/model.rarecarat/_Base/IModels/IDetailsModel.cs
namespace model.rarecarat
{
public interface IDetailsModel
{
}
}<file_sep>/model.rarecarat/_Base/Enums/ShapeType.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace core.rarecarat
{
public enum ShapeType
{
ROUND, CUSHION, OVAL, PRINCESS, EMERALD, RADIANT, PEAR, ASSCHER, MARQUISE, HEART
}
}
<file_sep>/domain.rarecarat/Models/Contact.cs
using System.Text.Json.Serialization;
namespace domain.rarecarat.Models
{
public class Contact
{
public int? Id { get; set; }
public int? CompanyId { get; set; }
public string CrmId { get; set; }
public string Salutation { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string JobTitle { get; set; }
public string Phone { get; set; }
public string MobilePhone { get; set; }
public string Fax { get; set; }
public string Email { get; set; }
public string Description { get; set; }
}
}
<file_sep>/core.rarecarat/IRepository/Base/IUnitOfWork.cs
using System;
using System.Linq;
namespace core.rarecarat
{
public interface IUnitOfWork : IDisposable
{
IRepository<TEntity> Repository<TEntity>( Type repositoryType ) where TEntity : IEntity;
TRepository Repository<TRepository>();
//void SaveChanges();
void BeginTransaction();
int Commit();
void Rollback();
//void TryRollback( CurrentLogContext logContext );
string User { get; set; }
IQueryable<TElement> SqlQuery<TElement>( string sql, params object[] parameters );
}
}<file_sep>/core.rarecarat/IServices/Base/IBaseService.cs
using model.rarecarat;
using System.Threading.Tasks;
namespace core.rarecarat
{
public interface IBaseServiceAsync<TCreate, TUpdate, TDetails>
where TCreate : ICreateModel
where TUpdate : IUpdateModel
where TDetails : IDetailsModel
{
Task<ValidationResult<object>> CreateAsync(TCreate model);
Task<ValidationResult> UpdateAsync(TUpdate model);
Task<OperationResult> DeleteAsync(object id);
Task<OperationResult<TDetails>> GetDetailsModelAsync(object id);
Task<OperationResult<TUpdate>> GetUpdateModelAsync(object id);
}
public interface IBaseServiceAsync<TCreate, TUpdate, TDetails, TListItem>
where TCreate : ICreateModel
where TUpdate : IUpdateModel
where TDetails : IDetailsModel
where TListItem : IListItemModel
{
Task<ValidationResult<object>> CreateAsync(TCreate model);
Task<ValidationResult> UpdateAsync(TUpdate model);
Task<OperationResult> DeleteAsync(object id);
Task<OperationResult<TDetails>> GetDetailsModelAsync(object id);
Task<OperationResult<TUpdate>> GetUpdateModelAsync(object id);
}
}<file_sep>/model.rarecarat/Diamond/Validators/DiamondCreateValidator.cs
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace model.rarecarat.Demo.Validators
{
public class DiamondCreateValidator : AbstractValidator<DiamondCreateModel>
{
public DiamondCreateValidator()
{
RuleFor( x => x.RetailerId ).NotEqual( 0 ).WithMessage( "Please specify a retailer" );
//RuleFor( x => x.StringValue ).NotEmpty().WithMessage( "Please specify a DiamondCreateValidator" ); ;
////RuleFor( x => x.Forename ).NotEmpty().WithMessage( "Please specify a first name" );
////RuleFor( x => x.Discount ).NotEqual( 0 ).When( x => x.HasDiscount );
////RuleFor( x => x.Address ).Length( 20, 250 );
//RuleFor( x => x.BooleanValue ).Must( BeABooleanValue ).WithMessage( "Please set as true" );
}
private bool BeABooleanValue( bool? value )
{
return ( value.HasValue && value.Value );
}
}
}
<file_sep>/api.rarecarat/Startup.cs
using AutoMapper;
using data.rarecarat.Context;
using data.rarecarat.Repository;
using domain.rarecarat.AutoMapper;
using domain.rarecarat.Business;
using domain.rarecarat.Contracts;
using domain.rarecarat.Contracts.Security;
using domain.rarecarat.Security;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using model.rarecarat.Demo.Validators;
using System;
namespace api.rarecarat
{
public class Startup
{
public Startup( IConfiguration configuration )
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices( IServiceCollection services )
{
services.AddHealthChecks();
services.AddCors( options =>
{
options.AddPolicy( "CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader() );
} );
services.AddControllers()
.AddFluentValidation( fv => fv.RegisterValidatorsFromAssemblyContaining<DiamondCreateValidator>() )
.SetCompatibilityVersion( CompatibilityVersion.Latest )
.AddJsonOptions( options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.DictionaryKeyPolicy = null;
} );
;
#region [Mappers]
// Auto Mapper Configurations
var mapperConfig = new MapperConfiguration( mc =>
{
mc.AddProfile( new DiamondProfile() );
mc.AddProfile( new ImageProfile() );
mc.AddProfile( new RetailerProfile() );
} );
IMapper mapper = mapperConfig.CreateMapper();
services.AddSingleton<IMapper>( mapper );
#endregion
#region Injections
// Auto Mapper Configurations
services.AddAutoMapper( typeof( Startup ) );
// Business
services.AddTransient<IToken, Token>();
services.AddTransient<IDiamondBusiness, DiamondBusiness>();
// Repositories
services.AddTransient<IDiamondRepository, DiamondRepository>();
#endregion
#region SQL
services.AddDbContext<RarecaratContext>( options => options.UseInMemoryDatabase( databaseName: "RarecaratDB" )
.UseQueryTrackingBehavior( QueryTrackingBehavior.NoTracking ) );
#endregion
services.AddSwaggerGen( c =>
{
c.SwaggerDoc( "v1", new OpenApiInfo { Title = "api.rarecarat", Version = "v1" } );
} );
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure( IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory )
{
loggerFactory.AddFile( "logs/log-{Date}.txt" );
app.UseHealthChecks( "/_healthz" );
if ( env.IsDevelopment() )
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI( c => c.SwaggerEndpoint( "/swagger/v1/swagger.json", "api.rarecarat v1" ) );
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints( endpoints =>
{
endpoints.MapControllers();
} );
}
}
}
<file_sep>/domain.rarecarat/AutoMapper/Profiles/RetailerProfile.cs
using data.rarecarat.Entities;
using model.rarecarat;
namespace domain.rarecarat.AutoMapper
{
public class RetailerProfile : BaseProfile
{
public RetailerProfile()
{
// Create
CreateMap<RetailerCreateModel, Retailer>();
CreateMap<RetailerDetailsModel, Retailer>();
// Details
// Edit
CreateMap<RetailerUpdateModel, Retailer>();
CreateMap<Retailer, RetailerUpdateModel>();
// Others
CreateMap<Retailer, RetailerDetailsModel>();
CreateMap<Retailer, RetailerListItemModel>();
}
}
}
<file_sep>/model.rarecarat/_Base/Enums/CutType.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace core.rarecarat
{
public enum CutType
{
GOODVERY, GOOD, EXCELLENT, RARE_CARAT_IDEAL
}
}
<file_sep>/model.rarecarat/Image/Validators/ImageUpdateValidator.cs
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace model.rarecarat.Demo.Validators
{
public class ImageUpdateValidator : AbstractValidator<DiamondUpdateModel>
{
public ImageUpdateValidator()
{
RuleFor( x => x.RetailerId ).NotEqual( 0 ).WithMessage( "Please specify a retailer" );
//RuleFor( x => x.StringValue ).NotEmpty().WithMessage( "Please specify a DiamondUpdateValidator" ); ;
//RuleFor( x => x.Forename ).NotEmpty().WithMessage( "Please specify a first name" );
//RuleFor( x => x.Discount ).NotEqual( 0 ).When( x => x.HasDiscount );
//RuleFor( x => x.Address ).Length( 20, 250 );
//RuleFor( x => x.Postcode ).Must( BeAValidPostcode ).WithMessage( "Please specify a valid postcode" );
}
//private bool BeAValidPostcode( string postcode )
//{
// // custom postcode validating logic goes here
//}
}
}
<file_sep>/domain.rarecarat/Models/AwardAccounts.cs
namespace domain.rarecarat.Models
{
using System.Text.Json.Serialization;
public class AwardAccounts
{
public Account Account { get; set; }
public Account FinancialAccount { get; set; }
}
}
<file_sep>/core.rarecarat/Services/BaseServiceHooks.cs
using ARGIL.Core.IModels;
using ARGIL.Core.IRepository;
using ARGIL.Utils.Entity;
using System;
namespace ARGIL.Core
{
#region Create Hooks
public class BaseServiceCreateHooks<TEntity, TCreate>
where TCreate : ICreateModel
where TEntity : IEntity
{
private Action<TCreate> DoBeforeCreateValidationHook { get; set; }
private Action<ValidationResult<object>, TCreate> DoAfterCreateValidationHook { get; set; }
private Func<TEntity, TCreate, IOperationResult> DoBeforeCreateHook { get; set; }
private Func<TEntity, TCreate, IOperationResult> DoAfterCreateHook { get; set; }
public BaseServiceCreateHooks<TEntity, TCreate> OnBeforeCreateValidation( Action<TCreate> hook )
{
if ( DoBeforeCreateValidationHook != null )
{
throw new ArgumentException( "Hook already defined" );
}
DoBeforeCreateValidationHook = hook;
return this;
}
public BaseServiceCreateHooks<TEntity, TCreate> OnAfterCreateValidation( Action<ValidationResult<object>, TCreate> hook )
{
if ( DoAfterCreateValidationHook != null )
{
throw new ArgumentException( "Hook already defined" );
}
DoAfterCreateValidationHook = hook;
return this;
}
public BaseServiceCreateHooks<TEntity, TCreate> OnBeforeCreate( Func<TEntity, TCreate, IOperationResult> hook )
{
if ( DoBeforeCreateHook != null )
{
throw new ArgumentException( "Hook already defined" );
}
DoBeforeCreateHook = hook;
return this;
}
public BaseServiceCreateHooks<TEntity, TCreate> OnAfterCreate( Func<TEntity, TCreate, IOperationResult> hook )
{
if ( DoAfterCreateHook != null )
{
throw new ArgumentException( "Hook already defined" );
}
DoAfterCreateHook = hook;
return this;
}
public void DoBeforeCreateValidation( TCreate model )
{
DoBeforeCreateValidationHook?
.Invoke( model );
}
public void DoAfterCreateValidation( ValidationResult<object> validation, TCreate model )
{
DoAfterCreateValidationHook?
.Invoke( validation, model );
}
public IOperationResult DoBeforeCreate( TEntity entity, TCreate model )
{
return DoBeforeCreateHook?
.Invoke( entity, model ) ??
new OperationResult();
}
public IOperationResult DoAfterCreate( TEntity entity, TCreate model )
{
return DoAfterCreateHook?
.Invoke( entity, model ) ??
new OperationResult(); ;
}
}
#endregion Create Hooks
#region Update Hooks
//TODO
#endregion Update Hooks
#region Delete Hooks
//TODO
#endregion Delete Hooks
}<file_sep>/core.rarecarat/IModels/ICreateModel.cs
namespace core.isqnet.awards
{
public interface IDetailModel
{
}
}<file_sep>/data.rarecarat/Context/RarecaratContext.cs
using System;
using data.rarecarat.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
#nullable disable
namespace data.rarecarat.Context
{
public partial class RarecaratContext : DbContext
{
public RarecaratContext()
{
}
public RarecaratContext(DbContextOptions<RarecaratContext> options)
: base(options)
{
}
public virtual DbSet<Diamond> Diamonds { get; set; }
public DbSet<Retailer> Retailer { get; set; }
public DbSet<Image> Images { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//if (!optionsBuilder.IsConfigured)
//{
// optionsBuilder.UseSqlServer("???");
//}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
<file_sep>/core.rarecarat/Services/BaseService.cs
using ARGIL.Core.Entities;
using ARGIL.Core.IModels;
using ARGIL.Core.IRepository;
using ARGIL.Core.IServices;
using ARGIL.Core.Models;
using ARGIL.Core.Utils;
using ARGIL.Core.Utils.Validators;
using ARGIL.Utils.Entity;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using ValidationResult = ARGIL.Utils.Entity.ValidationResult;
namespace ARGIL.Core
{
public abstract class BaseService<TEntity, TCreate, TUpdate, TDetails, TListItem> : Loggable, IBaseService<TCreate, TUpdate, TDetails, TListItem>
where TCreate : ICreateModel
where TUpdate : IUpdateModel
where TDetails : IDetailsModel
where TListItem : IListItemModel
where TEntity : IEntity
{
protected IUnitOfWork _unitOfWork;
protected BaseService( IUnitOfWork unitOfWork, ILogger logger ) : base()
{
_unitOfWork = unitOfWork;
_logger = logger;
}
protected IRepository<TEntity> Repository
{
get
{
return _unitOfWork.Repository<TEntity>( DoGetRepositoryType() );
}
}
public abstract Type DoGetRepositoryType();
protected abstract object GetIdFrom( TUpdate update );
#region Validation
public virtual ValidationResult<object> ValidateBusinessRulesForCreate( TCreate model )
{
if ( IsNotSupportedOperation<TCreate>() )
return ConstructorHelper.ErrorValidationResult<object>();
return new ValidationResult<object>();
}
public virtual ValidationResult ValidateBusinessRulesForUpdate( TUpdate model )
{
if ( IsNotSupportedOperation<TUpdate>() )
return ConstructorHelper.ErrorValidationResult();
return new ValidationResult();
}
#endregion Validation
#region Mapping
protected virtual TEntity Map( TCreate model )
{
return Mapper.Map<TCreate, TEntity>( model );
}
protected virtual TEntity Map( TUpdate model, TEntity entity )
{
return Mapper.Map<TUpdate, TEntity>( model, entity );
}
protected virtual TDetails MapForDetails( TEntity entity )
{
return Mapper.Map<TEntity, TDetails>( entity );
}
protected virtual TUpdate MapForUpdate( TEntity entity )
{
return Mapper.Map<TEntity, TUpdate>( entity );
}
#endregion Mapping
#region Get Details Model
public OperationResult<TDetails> GetDetailsModel( object id )
{
var logContext = Context();
try
{
if ( IsNotSupportedOperation<TDetails>() )
return ConstructorHelper.ErrorOperationResult<TDetails>();
var entity = Repository.GetById( id );
var details = MapForDetails( entity );
return new OperationResult<TDetails>( details );
}
catch ( Exception ex )
{
try
{
$"**ERROR** | Error getting details model for id <{id}>."
.Log( logContext, ex );
}
catch
{
"**ERROR** | Provided id is not a valid integer!"
.Log( logContext, ex );
}
return ConstructorHelper.ErrorOperationResult<TDetails>();
}
}
#endregion Get Details Model
#region Get Update Model
public OperationResult<TUpdate> GetUpdateModel( object id )
{
var logContext = Context();
try
{
if ( IsNotSupportedOperation<TUpdate>() )
return ConstructorHelper.ErrorOperationResult<TUpdate>();
var entity = Repository.GetById( id );
var details = MapForUpdate( entity );
return new OperationResult<TUpdate>( details );
}
catch ( Exception ex )
{
try
{
$"**ERROR** | Error getting update model for id <{id}>."
.Log( logContext, ex );
}
catch
{
$"**ERROR** | Provided id is not a valid value!"
.Log( logContext, ex );
}
return ConstructorHelper.ErrorOperationResult<TUpdate>();
}
}
#endregion Get Update Model
#region Create
public virtual ValidationResult<object> Create( TCreate model )
{
return Create( null, model );
}
public ValidationResult<object> Create(
BaseServiceCreateHooks<TEntity, TCreate> hooks, TCreate model )
{
var logContext = Context();
try
{
if ( IsNotSupportedOperation<TCreate>() )
return ConstructorHelper.ErrorValidationResult<object>();
#region DoBeforeCreateValidation
if ( hooks == null )
{
DoBeforeCreateValidation( model );
}
else
{
hooks
.DoBeforeCreateValidation( model );
}
#endregion DoBeforeCreateValidation
var validationResult = ValidateModelForCreate( model );
#region DoAfterCreateValidation
if ( hooks == null )
{
DoAfterCreateValidation( validationResult, model );
}
else
{
hooks
.DoAfterCreateValidation( validationResult, model );
}
#endregion DoAfterCreateValidation
if ( validationResult.IsValid )
{
_unitOfWork.BeginTransaction();
var entity = Map( model );
#region Before Create
IOperationResult beforeCreateResult;
if ( hooks == null )
{
beforeCreateResult =
DoBeforeCreate( entity, model );
}
else
{
beforeCreateResult = hooks
.DoBeforeCreate( entity, model );
}
if ( beforeCreateResult.Error )
{
_unitOfWork.Rollback();
validationResult.Error = true;
return validationResult;
}
#endregion Before Create
var trackedEntity = entity as ChangeTrackedEntity;
if ( trackedEntity != null )
{
AuditUtils.FillCreateInformation( trackedEntity, _unitOfWork.User );
}
validationResult.Result = Repository.Create( entity );
#region After Create
IOperationResult afterCreateResult;
if ( hooks == null )
{
afterCreateResult =
DoAfterCreate( entity, model );
}
else
{
afterCreateResult = hooks
.DoAfterCreate( entity, model );
}
if ( afterCreateResult.Error )
{
_unitOfWork.Rollback();
validationResult.Error = true;
return validationResult;
}
#endregion After Create
_unitOfWork.Commit();
}
return validationResult;
}
catch ( Exception ex )
{
_unitOfWork.Rollback();
"**ERROR**".Log( logContext, ex );
return ConstructorHelper.ErrorValidationResult<object>();
}
}
private ValidationResult<object> ValidateModelForCreate( TCreate model )
{
var validationResult = new ValidationResult<object>();
var validatable = model as IModelValidatable;
if ( validatable != null )
{
validatable.Validate( validationResult );
}
else
{
ARGILValidator.ValidateAll( model, validationResult );
}
var businessRulesForCreateValidation = ValidateBusinessRulesForCreate( model );
validationResult.MergeValidationResults( businessRulesForCreateValidation );
return validationResult;
}
protected virtual void DoBeforeCreateValidation( TCreate model )
{
}
protected virtual void DoAfterCreateValidation( ValidationResult<object> validation, TCreate model )
{
}
protected virtual IOperationResult DoBeforeCreate( TEntity entity, TCreate model )
{
return new OperationResult();
}
protected virtual IOperationResult DoAfterCreate( TEntity entity, TCreate model )
{
return new OperationResult();
}
#endregion Create
#region Update
public ValidationResult Update( TUpdate model )
{
var logContext = Context();
ValidationResult validationResult = null;
try
{
">>>".Log( logContext );
if ( IsNotSupportedOperation<TUpdate>() )
return ConstructorHelper.ErrorValidationResult();
DoBeforeUpdateValidation( model );
validationResult = ValidateModelForUpdate( model );
DoAfterUpdateValidation( validationResult, model );
}
catch ( Exception ex )
{
"<<< | **ERROR**".Log( logContext, ex );
return ConstructorHelper.ErrorValidationResult();
}
try
{
if ( validationResult.IsValid )
{
_unitOfWork.BeginTransaction();
var beforeMapResult = DoBeforeUpdateMap( model );
if ( beforeMapResult.Error )
{
_unitOfWork.Rollback();
validationResult.Error = true;
return validationResult;
}
var entity = Repository.GetById( GetIdFrom( model ) );
Repository.RemoveListElements( entity );
Map( model, entity );
AssociateReferenceKeys( entity );
#region Before Update
var beforeUpdateResult = DoBeforeUpdate( entity, model );
if ( beforeUpdateResult.Error )
{
_unitOfWork.Rollback();
validationResult.Error = true;
return validationResult;
}
#endregion Before Update
var trackedEntity = entity as ChangeTrackedEntity;
if ( trackedEntity != null )
{
AuditUtils.FillUpdateInformation( trackedEntity, _unitOfWork.User );
}
Repository.Update( entity );
#region After Update
var afterUpdateResult = DoAfterUpdate( entity, model );
if ( afterUpdateResult.Error )
{
_unitOfWork.Rollback();
validationResult.Error = true;
return validationResult;
}
#endregion After Update
_unitOfWork.Commit();
}
return "<<<".Log( logContext, validationResult );
}
catch ( Exception ex )
{
_unitOfWork.Rollback();
"<<< | **ERROR**".Log( logContext, ex );
return ConstructorHelper.ErrorValidationResult();
}
}
private ValidationResult ValidateModelForUpdate( TUpdate model )
{
var validationResult = new ValidationResult();
if ( typeof( IModelValidatable ).IsAssignableFrom( typeof( TUpdate ) ) )
{
( (IModelValidatable)model ).Validate( validationResult );
}
else
{
ARGILValidator.ValidateAll( model, validationResult );
}
var businessValidationForUpdate = ValidateBusinessRulesForUpdate( model );
validationResult.MergeValidationResults( businessValidationForUpdate );
return validationResult;
}
protected virtual void AssociateReferenceKeys( TEntity entity )
{
}
protected virtual void DoBeforeUpdateValidation( TUpdate model )
{
}
protected virtual void DoAfterUpdateValidation( ValidationResult validation, TUpdate model )
{
}
protected virtual IOperationResult DoBeforeUpdateMap( TUpdate model )
{
return new OperationResult();
}
protected virtual IOperationResult DoBeforeUpdate( TEntity entity, TUpdate documentoContabilisticoCreateUpdateModel )
{
return new OperationResult();
}
protected virtual IOperationResult DoAfterUpdate( TEntity entity, TUpdate model )
{
return new OperationResult();
}
#endregion Update
#region Delete
public OperationResult Delete( object id )
{
var logContext = Context();
try
{
">>>".Log( logContext );
_unitOfWork.BeginTransaction();
DoBeforeDelete( id );
Repository.Delete( id );
DoAfterDelete( id );
_unitOfWork.Commit();
return "<<<".Log( logContext, new OperationResult() );
}
catch ( Exception ex )
{
"<<< | **ERROR** | id={0}.".Fill( id ).Log( logContext, ex );
_unitOfWork.TryRollback( logContext );
return ConstructorHelper.ErrorOperationResult();
}
}
protected virtual void DoBeforeDelete( object id )
{
}
protected virtual void DoAfterDelete( object id )
{
}
#endregion Delete
public virtual OperationResult<IList<KeyValue>> GetKeyValueList()
{
var logContext = Context();
try
{
">>>".Log( logContext );
var result = new OperationResult<IList<KeyValue>>(
Repository.GetKeyValueList() );
return "<<<".Log( logContext, result );
}
catch ( Exception ex )
{
"<<< | **ERROR**".Log( logContext, ex );
return ConstructorHelper
.ErrorOperationResult<IList<KeyValue>>();
}
}
private bool IsNotSupportedOperation<T>()
{
return typeof( T ) == typeof( NotSupportedOperation );
}
public IEnumerable<TListItem> GetCroppedList( OperationResult<IEnumerable<TListItem>> data )
{
return ( data != null && data.Result != null ) ?
data.Result.Take( GetMaxLines() ) :
null;
}
protected virtual int GetMaxLines()
{
return 1000;
}
}
}<file_sep>/domain.rarecarat/AutoMapper/Profiles/ImageProfile.cs
using data.rarecarat.Entities;
using model.rarecarat;
namespace domain.rarecarat.AutoMapper
{
public class ImageProfile : BaseProfile
{
public ImageProfile()
{
// Create
CreateMap<ImageCreateModel, Image>();
CreateMap<ImageListItemModel, Image>();
// Details
// Edit
CreateMap<ImageUpdateModel, Image>();
CreateMap<Image, ImageUpdateModel>();
// Others
CreateMap<Image, ImageDetailsModel>();
CreateMap<Image, ImageListItemModel>();
}
}
}
<file_sep>/data.rarecarat/Entities/Diamond.cs
using core.rarecarat;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace data.rarecarat.Entities
{
public class Diamond : IEntity
{
public int Id { get; set; }
[Required]
public ShapeType Shape { get; set; }
[Required]
public CertificationType Certification { get; set; }
[Required]
public ClarityType Clarity { get; set; }
[Required]
public ColorType Color { get; set; }
[Required]
public CutType Cut { get; set; }
[Required]
public DiamondType Type { get; set; }
[Required]
public FluorescenceType Fluorescence { get; set; }
[Required]
public decimal Price { get; set; }
[Required]
public decimal Carat { get; set; }
[Required]
public int RetailerId { get; set; }
[ForeignKey( "RetailerId" )]
public virtual Retailer Retailer { get; set; }
public virtual List<Image> Images { get; set; }
}
}
<file_sep>/model.rarecarat/_Base/IModels/IDetailModel.cs
namespace model.rarecarat
{
public interface ICreateModel
{
}
}<file_sep>/core.rarecarat/IRepository/Base/IRepository.cs
namespace core.rarecarat
{
public interface IRepository<T> where T : IEntity
{
object Create( T entity );
void Update( T entity );
void Delete( object id );
void RemoveListElements( T entity );
T GetById( object id );
T GetBaseEntityById( object id );
}
}<file_sep>/domain.rarecarat/Models/BudgetComment.cs
using System.Text.Json.Serialization;
namespace domain.rarecarat.Models
{
public class BudgetComment
{
public int? Id { get; set; }
public int? BudgetId { get; set; }
public string Symbol { get; set; }
public string Text { get; set; }
}
}
<file_sep>/model.rarecarat/_Base/IModels/IUpdateModel.cs
namespace model.rarecarat
{
public interface IUpdateModel
{
}
}<file_sep>/domain.rarecarat/Models/ProductLine.cs
namespace domain.rarecarat.Models
{
public class ProductLine
{
public long Id { get; set; }
public string Identifier { get; set; }
public string Name { get; set; }
public long ServiceId { get; set; }
public virtual Service Service { get; set; }
}
}
<file_sep>/core.rarecarat/Services/BaseServiceUnhooked.cs
using ARGIL.Core.IModels;
using ARGIL.Core.IRepository;
using ARGIL.Utils.Entity;
using System;
namespace ARGIL.Core
{
public abstract class BaseServiceUnhooked<TEntity, TCreate, TUpdate, TDetails, TListItem> : BaseService<TEntity, TCreate, TUpdate, TDetails, TListItem>
where TCreate : ICreateModel
where TUpdate : IUpdateModel
where TDetails : IDetailsModel
where TListItem : IListItemModel
where TEntity : IEntity
{
public BaseServiceUnhooked( IUnitOfWork unitOfWork, ILogger logger ) : base( unitOfWork, logger )
{
}
#region Create
sealed protected override void DoBeforeCreateValidation( TCreate model )
{
throw new NotSupportedException();
}
sealed protected override void DoAfterCreateValidation( ValidationResult<object> validation, TCreate model )
{
throw new NotSupportedException();
}
sealed protected override IOperationResult DoBeforeCreate( TEntity entity, TCreate model )
{
throw new NotSupportedException();
}
sealed protected override IOperationResult DoAfterCreate( TEntity entity, TCreate model )
{
throw new NotSupportedException();
}
protected BaseServiceCreateHooks<TEntity, TCreate> OnCreate()
{
return new BaseServiceCreateHooks<TEntity, TCreate>();
}
/// <summary>
/// Este método pode e deve ser "overrided" de modo a passar os hooks pretendidos.
/// Toda a lógica de criação deverá estar no método da classe base
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public override ValidationResult<object> Create( TCreate model )
{
// Neste versão "unhooked" passamos sempre uma instancia do objecto que representa os
// hooks inicializada por omissão. Isto é importante porque esta class faz override dos métodos base
// de modo a inutilizá-los com exceptions e a impedir que sejam overrided. Se não passarmos este instancia
// o comportamento padrão atual deixa de funcionar quando não passamos hooks.
return Create( OnCreate(), model );
}
#endregion Create
#region Update
//TODO
#endregion Update
#region Delete
//TODO
#endregion Delete
}
}<file_sep>/core.rarecarat/IModels/IDetailModel.cs
namespace core.isqnet.awards
{
public interface ICreateModel
{
}
}<file_sep>/domain.rarecarat/Models/Project.cs
namespace domain.rarecarat.Models
{
using domain.rarecarat.Enums;
using System;
using System.Collections.Generic;
public class Project : BaseModel
{
public long Id { get; set; }
public string SAPIdentifier { get; set; }
public string Identifier { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string Observations { get; set; }
public long? ParentId { get; set; }
public long CustomerId { get; set; }
public Customer Customer { get; set; }
public ProjectStatus? Status { get; set; }
public IEnumerable<ProductLine> ProductLines { get; set; }
}
}
<file_sep>/model.rarecarat/_Base/Enums/ColorType.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace core.rarecarat
{
public enum ColorType
{
K, J, I, H, G, F, E, D
}
}
<file_sep>/domain.rarecarat/Models/Aggregator.cs
namespace domain.rarecarat.Models
{
public class Aggregator
{
public string Name { get; set; }
public string GUID { get; set; }
public int? FrequencyCode { get; set; }
public string Frequency { get; set; }
public string P1 { get; set; }
public string P1GUID { get; set; }
public string Responsibility { get; set; }
public string Type { get; set; }
public int TypeCode { get; set; }
public string PlaceName { get; set; }
public string PlaceGUID { get; set; }
public string PlaceAccountGUID { get; set; }
public decimal? PlaceKms { get; set; }
public decimal? PlaceHours { get; set; }
public decimal? HoursPrice { get; set; }
public decimal? KmsPrice { get; set; }
public string PlaceLatitude { get; set; }
public string PlaceLongitude { get; set; }
public string ExpirationDate { get; set; }
public string RelatedAggregatorGUID { get; set; }
public int MaxDeadline { get; set; }
}
}
<file_sep>/core.rarecarat/IModels/IDetailsModel.cs
namespace core.isqnet.awards
{
public interface IDetailsModel
{
}
}<file_sep>/core.rarecarat/IModels/IListItemModel.cs
namespace core.isqnet.awards
{
public interface IListItemModel
{
}
}<file_sep>/model.rarecarat/_Base/Enums/ClarityType.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace core.rarecarat
{
public enum ClarityType
{
SI2, SI1, VS2, VS1, VVS2, VVS1, IF, FL
}
}
<file_sep>/domain.rarecarat/Contracts/Base/IGenericPersistBusiness.cs
namespace domain.rarecarat.Contracts.Base
{
public interface IGenericPersistBusiness<TEntity> where TEntity : class
{
object Save(TEntity obj, string idUser);
object Update(TEntity obj, string idUser);
object Delete(TEntity obj);
}
}
<file_sep>/api.rarecarat/Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Formatting.Compact;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace api.rarecarat
{
public class Program
{
public static void Main( string[] args )
{
//Log.Logger = new LoggerConfiguration()
//.MinimumLevel.Information()
// .WriteTo.Debug( new RenderedCompactJsonFormatter() )
//// .WriteTo.File( "logs.txt", rollingInterval: RollingInterval.Day )
//.CreateLogger();
try
{
Log.Information( "Starting Web Host" );
CreateHostBuilder( args ).Build().Run();
}
catch ( Exception ex )
{
Log.Fatal( ex, "Host terminated unexpectedly" );
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder( string[] args ) =>
Host.CreateDefaultBuilder( args )
//.UseSerilog()
.ConfigureWebHostDefaults( webBuilder =>
{
webBuilder.UseStartup<Startup>();
} );
}
}
<file_sep>/model.rarecarat/_Base/IModels/IListItemModel.cs
namespace model.rarecarat
{
public interface IListItemModel
{
}
}<file_sep>/domain.rarecarat/Models/Pep.cs
namespace domain.rarecarat.Models
{
using System.Text.Json.Serialization;
public class Pep
{
[JsonPropertyName("Lvl")]
public int Lvl { get; set; }
[JsonPropertyName("ActivitySector")]
public string ActivitySector { get; set; }
[JsonPropertyName("ProductLine")]
public string ProductLine { get; set; }
[JsonPropertyName("Cl")]
public string Cl { get; set; }
}
}
<file_sep>/domain.rarecarat/Contracts/IDiamondBusiness.cs
using core.rarecarat;
using data.rarecarat.Entities;
using model.rarecarat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace domain.rarecarat.Contracts
{
public interface IDiamondBusiness : IBaseServiceAsync<DiamondCreateModel, DiamondUpdateModel, DiamondDetailsModel, DiamondListItemModel>
{
Task<OperationResult<List<DiamondListItemModel>>> GetAllAsync();
}
}
<file_sep>/core.rarecarat/Entity/ValidationResult.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace core.rarecarat
{
/// <summary>
/// The data contracted validation result class .
/// This type includes possible validation messages as result of an Operation that
/// performs validation.
/// </summary>
public class ValidationResult : IValidationResult
{
#region Ctors
/// <summary>
/// Initializes a new instance of the <see cref = "OperationResult{TResult}" /> class.
/// </summary>
public ValidationResult()
{
IsValid = true;
ValidationErrors = new List<ValidationItem>();
}
public ValidationResult( string error )
: this()
{
Error = true;
Message = error;
}
public ValidationResult( Exception e ) : this( e.Message )
{
}
#endregion Ctors
#region Props
public bool Error { get; set; }
public string Message { get; set; }
public bool IsValid { get; set; }
public List<ValidationItem> ValidationErrors { get; set; }
#endregion Props
#region Methods
public void AddErrorValidationItem( string message )
{
AddErrorValidationItem( "", message );
}
public void AddErrorValidationItem( string propName, string message )
{
IsValid = false;
ValidationErrors.Add( new ValidationItem()
{
PropertyName = propName,
Message = message
} );
}
public void AddErrorValidationItem( string propName, Exception exception )
{
IsValid = false;
ValidationErrors.Add( new ValidationItem()
{
PropertyName = propName,
Exception = exception
} );
}
public void AddErrorValidationItems( IEnumerable<ValidationItem> items )
{
var validationItems = items as IList<ValidationItem> ?? items.ToList();
if (validationItems != null && validationItems.Count > 0)
{
IsValid = false;
ValidationErrors.AddRange( validationItems );
}
}
public void MergeValidationResults( ValidationResult resultToMerge )
{
Error &= resultToMerge.Error;
Message = resultToMerge.Message;
IsValid &= resultToMerge.IsValid;
ValidationErrors.AddRange( resultToMerge.ValidationErrors.Where( ValidationItem => !ValidationErrors.Contains( ValidationItem ) ) );
}
#endregion Methods
}
}<file_sep>/domain.rarecarat/Models/Account.cs
namespace domain.rarecarat.Models
{
using System.Collections.Generic;
using System.Text.Json.Serialization;
public class Account
{
public int? Id { get; set; }
public string CrmId { get; set; }
public string Name { get; set; }
public string Name2 { get; set; }
public string NumberOfEmployees { get; set; }
public int? NumberOfEmployeesCode { get; set; }
public string AccountType { get; set; }
public int AccountTypeCode { get; set; }
public string ParentAccount { get; set; }
public string ParentAccountGUID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string AddressCity { get; set; }
public string AddressLatitude { get; set; }
public string AddressLongitude { get; set; }
public string AddressPostalCode { get; set; }
public string Country { get; set; }
public string CountryCode { get; set; }
public string Phone { get; set; }
public string SecondPhone { get; set; }
public string Email { get; set; }
public string Fax { get; set; }
public string WebSite { get; set; }
public string CAE { get; set; }
public string CAECode { get; set; }
public string NIF { get; set; }
public string Number { get; set; }
public string PaymentTerms { get; set; }
public string PaymentTermsCode { get; set; }
public string SalesRegion { get; set; }
public string SalesRegionCode { get; set; }
}
}
<file_sep>/core.rarecarat/IRepository/Base/IAsyncRepository.cs
//using Kendo.Mvc.UI;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace core.rarecarat
{
public interface IAsyncRepository<T> where T : IEntity
{
Task<object> CreateAsync( T entity );
Task UpdateAsync( T entity );
Task DeleteAsync( object id );
ValueTask<T> GetByIdAsync( object id );
}
}<file_sep>/model.rarecarat/_Base/IModels/IModelValidatable.cs
namespace model.isqnet.awards
{
public interface IModelValidatable
{
void Validate( ValidationResult validationResult, string prefix = "" );
}
}<file_sep>/domain.rarecarat/Models/BudgetItem.cs
using System.Text.Json.Serialization;
namespace domain.rarecarat.Models
{
public class BudgetItem
{
public int? Id { get; set; }
public int? BudgetId { get; set; }
public string AlternativeDescription { get; set; }
public string ClGUID { get; set; }
public string CurrencyGUID { get; set; }
public decimal? DiscountPercentage { get; set; }
public string ProductName { get; set; }
public decimal Quantity { get; set; }
public string QuoteDetailName { get; set; }
public decimal SequenceNumber { get; set; }
public string ShipToAddress1 { get; set; }
public string ShipToAddress2 { get; set; }
public string ShipToAddressCity { get; set; }
public string ShipToAddressCountry { get; set; }
public string ShipToAddressFax { get; set; }
public string ShipToAddressName { get; set; }
public string ShipToAddressPhone { get; set; }
public string ShipToAddressPostalCode { get; set; }
public string Description { get; set; }
public string DetailComment { get; set; }
public string DetailGUID { get; set; }
public decimal TotalAmount { get; set; }
public decimal TotalTaxAmount { get; set; }
public decimal UnitPrice { get; set; }
public string Currency { get; set; }
public string CurrencySymbol { get; set; }
public string Cl { get; set; }
public string ClCode { get; set; }
public string P1 { get; set; }
public string P1GUID { get; set; }
public string P2 { get; set; }
public string P2GUID { get; set; }
public string P3 { get; set; }
public string P3GUID { get; set; }
public string P4 { get; set; }
public string P4GUID { get; set; }
public string P5 { get; set; }
public string P5GUID { get; set; }
public string Material { get; set; }
public string MaterialName { get; set; }
public string ProductLine { get; set; }
public string ProductLineName { get; set; }
public string SalesRegion { get; set; }
public string SalesRegionName { get; set; }
public string Pep { get; set; }
public string ActivitySector { get; set; }
public string ActivitySectorName { get; set; }
public string Project { get; set; }
public string ProductType { get; set; }
public int? ProductTypeCode { get; set; }
public string AggregatorGUID { get; set; }
public string Uncertainty { get; set; }
public string QuantificationLimit { get; set; }
public int? SupplierTerm { get; set; }
public decimal? StandardCost { get; set; }
public string Unit { get; set; }
public int? DeliveryTermDays { get; set; }
public string ProductNameEN { get; set; }
public string SupplierName { get; set; }
public string SupplierGUID { get; set; }
public string SupplierEmail { get; set; }
public string SupplierProductCode { get; set; }
public string ParentSoDetailGUID { get; set; }
public bool IsBundle { get; set; }
public string ProductDescription { get; set; }
}
}
<file_sep>/core.rarecarat/IModels/ISearchFilter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace core.isqnet.awards
{
public interface ISearchFilter
{
string Trasversal { get; set; }
}
}
<file_sep>/core.rarecarat/Entity/OperationResultGeneric.cs
using System;
namespace core.rarecarat
{
/// <summary>
/// The data contracted operation result class of closed generic.
/// </summary>
/// <typeparam name = "TResult">The type of data expected for the returning result.</typeparam>
public class OperationResult<TResult> : OperationResult, IOperationResult<TResult>
{
/// <summary>
/// The operation result data.
/// </summary>
public TResult Result { get; set; }
public TResult ResultOrExceptionIfFailed()
{
if ( Error )
{
throw new Exception( Message );
}
return Result;
}
#region Ctors
public OperationResult()
{
}
public OperationResult( string message ) : base( message )
{
}
public OperationResult( Exception e ) : base( e )
{
}
public OperationResult( Exception e, TResult result )
{
Result = result;
Error = true;
if ( e != null )
{
Message = e.Message;
}
}
public OperationResult( OperationResult<TResult> operationResult )
{
Result = operationResult.Result;
Error = operationResult.Error;
Message = operationResult.Message;
}
/// <summary>
/// Initializes a new instance of the <see cref = "OperationResult{TResult}" /> class.
/// </summary>
/// <param name = "result">
/// The result.
/// </param>
/// <param name = "error">
/// The error.
/// </param>
/// <param name = "message"></param>
public OperationResult( TResult result, bool error = false, string message = null )
{
Result = result;
Error = error;
if ( error )
{
Message = message;
}
}
#endregion Ctors
}
}<file_sep>/data.rarecarat/Entities/Image.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace data.rarecarat.Entities
{
public class Image
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Path { get; set; }
[Required]
public int DiamondId { get; set; }
[ForeignKey("DiamondId")]
public Diamond Diamond { get; set; }
}
}
<file_sep>/model.rarecarat/_Base/Enums/CertificationType.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace core.rarecarat
{
public enum CertificationType
{
CERTIFICATION, GIAGCALI, GI
}
}
<file_sep>/domain.rarecarat/Models/Service.cs
namespace domain.rarecarat.Models
{
public class Service
{
public long Id { get; set; }
public string Identifier { get; set; }
public string Name { get; set; }
}
}<file_sep>/api.rarecarat/Controllers/DiamondController.cs
using domain.rarecarat.Business;
using domain.rarecarat.Contracts;
using model.rarecarat;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace api.rarecarat.Controllers
{
/// <summary>
/// Diamond Controller.
/// </summary>
[Route( "diamonds" )]
[ApiController]
public class DiamondController : ControllerBase
{
private IDiamondBusiness _diamondBusiness;
private ILogger<DiamondController> _logger;
public DiamondController( IDiamondBusiness DiamondBusiness, ILogger<DiamondController> logger )
{
_diamondBusiness = DiamondBusiness;
_logger = logger;
}
/// <summary>
/// Get Diamond data
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult<List<DiamondListItemModel>>> Get()
{
_logger.LogInformation( "Get Called" );
var response = await _diamondBusiness.GetAllAsync();
if ( !response.Error )
return Ok( response.Result );
else
return BadRequest( response.Message );
}
/// <summary>
/// Get Diamond Details
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet( "{id}" )]
public async Task<ActionResult<DiamondDetailsModel>> Get( int id )
{
_logger.LogInformation( "Get By Id Called" );
var response = await _diamondBusiness.GetDetailsModelAsync( id );
if ( !response.Error )
{
if ( response.Result == null )
return NotFound();
else
return Ok( response.Result );
}
else
return BadRequest( response.Message );
}
/// <summary>
/// Saving new Diamond
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult<int>> Post( [FromBody] DiamondCreateModel value )
{
_logger.LogInformation( "Post Called" );
var response = await _diamondBusiness.CreateAsync( value );
if ( !response.Error )
return Ok( (int)response.Result );
else
return BadRequest( response.Message );
}
/// <summary>
/// Updating Diamond
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <returns></returns>
[HttpPut( "{id}" )]
public async Task<ActionResult> Put( int id, [FromBody] DiamondUpdateModel value )
{
_logger.LogInformation( "Put Called" );
var responseDetail = await _diamondBusiness.GetDetailsModelAsync( id );
if ( !responseDetail.Error )
{
if ( responseDetail.Result == null )
return NotFound();
else
{
value.Id = id;
var responseUpdate = await _diamondBusiness.UpdateAsync( value );
if ( !responseUpdate.Error )
return Ok();
else
return BadRequest( responseUpdate.Message );
}
}
else
return BadRequest( responseDetail.Message );
}
/// <summary>
/// Deleting Diamond
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete( "{id}" )]
public async Task<ActionResult> Delete( int id )
{
_logger.LogInformation( "Delete Called" );
var response = await _diamondBusiness.GetDetailsModelAsync( id );
if ( !response.Error )
{
if ( response.Result == null )
return NotFound();
else
{
var responseDelete = await _diamondBusiness.DeleteAsync( id );
if ( !responseDelete.Error )
return Ok();
else
return BadRequest( responseDelete.Message );
}
}
else
return BadRequest( response.Message );
}
}
}
|
a07ad196d05cb6df3d90b3b01dc50c4a0d5fd382
|
[
"C#",
"Dockerfile"
] | 70
|
C#
|
igorfrancob/rarecarat
|
5d39e922e237e3bf1307d33a1c3ac57705714eaf
|
1e029bc1582dc092b955e895597b623a2d7f8831
|
refs/heads/master
|
<file_sep>import random
import numpy as np
# subframe
scaling = 1
MP = 200
MT = 40
number = 2
drx = 160
on_time = 8
inavtive_time = 100
p_c = 100 * scaling
p_cs = 300 * scaling
p_sleep = 1
p_tr = 450
sp_time = 0.5
speed = 0.5 / 7
read_speed = 2.33 / 1000
buffer = 0
bool_scheme = 1
max_buffer = 70
bool_on = 0
bool_inactive = 0
bool_sleep = 0
bool_data = 1
bool_last = 0
bool_buffer = 0
power_av = 0
time_av = 0 # 平均时延
data_sup = 0
ue_buffer = 0
for i in range(MT):
bs_buffer_record = []
ue_buffer_record = []
N_record = []
on_timer = on_time
avtive_timer = inavtive_time
sleep_timer = drx
t = 1
power_sum = 0
point = round(random.uniform(0, 1) * drx)
for j in range(number):
N = round(6000 + random.uniform(-500, 500))
N_record.append(N)
x = np.random.poisson(lam=MP, size=N)
gap = x[0]
gap_times = 0
delay = []
buffer = buffer + sp_time
while True:
if t == 1: # 开始时刻的状态判断
if point > on_time:
bool_sleep = 1
sleep_timer = drx - point
delay.append(drx - point + sp_time)
else:
bool_on = 1
on_timer = on_time - point
delay.append(sp_time)
if bool_on:
bool_on = 0
on_timer = - 1
bool_data = 0
data_sup = buffer
avtive_timer = inavtive_time
bool_inactive = 1
else:
buffer_temp = buffer
if gap == 0: # 判断数据
# 判断到来的数据是否需要开启新的active timer
bool_data = 1
if bool_inactive and buffer > 0:
bool_data = 0
gap_times = gap_times + 1
if gap_times <= N - 1:
gap = x[gap_times]
buffer = buffer + sp_time
# DRX
if avtive_timer == 0:
bool_inactive = 0
avtive_timer = avtive_timer - 1
if bool_on == 0:
power_sum = power_sum + p_tr
bool_sleep = 1
if sleep_timer == 0:
sleep_timer = drx
bool_on = 1
on_timer = on_time
bool_sleep = 0
if bool_on or bool_inactive: # Active time
if bool_inactive:
if bool_data:
bool_data = 0
data_sup = buffer
avtive_timer = inavtive_time
if data_sup > 0:
avtive_timer = inavtive_time
else:
if bool_on:
bool_sleep = 0
if buffer > 0:
data_sup = buffer
bool_data = 0
bool_inactive = 1
avtive_timer = inavtive_time
if on_timer == 0:
bool_on = 0
on_timer = on_timer - 1
if bool_inactive == 0:
power_sum = power_sum + p_tr
bool_sleep = 1
# buffer 策略
if bool_scheme:
if ue_buffer < max_buffer * 0.3 and bool_buffer == 1:
bool_buffer = 0
if ue_buffer > max_buffer * 0.7 and bool_buffer == 0:
bool_buffer = 1
if bool_buffer:
bool_on = 0
bool_inactive = 0
bool_sleep = 1
if bool_on and bool_inactive != 1:
power_sum = power_sum + p_c
if bool_inactive:
if data_sup > 0:
data_sup = data_sup - 1
if data_sup < 0:
data_sup = 0
if buffer > 0 and ue_buffer + speed * 2 < max_buffer:
buffer = buffer - speed * 2
ue_buffer = ue_buffer + speed * 2
if buffer > 0:
power_sum = power_sum + p_cs
else:
buffer = 0
power_sum = power_sum + (p_c + p_cs) * 0.5
else:
power_sum = power_sum + p_c
if bool_sleep:
power_sum = power_sum + p_sleep
# 时间的推进和定时器的减少
bs_buffer_record.append(buffer)
ue_buffer_record.append(ue_buffer)
t = t + 1
if ue_buffer > 0:
ue_buffer = ue_buffer - read_speed
if ue_buffer < 0:
ue_buffer = 0
if bool_on:
on_timer = on_timer - 1
if bool_inactive:
avtive_timer = avtive_timer - 1
sleep_timer = sleep_timer - 1
gap = gap - 1
if ue_buffer == 0 and gap_times >= N - 1:
break
power_av = power_sum / t + power_av
print('蒙特卡洛次数:', i, ', 累积能量: ', power_av)
power_result = power_av / MT + 100 / 320
<file_sep>import numpy as np
from models.model import GRU
import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
import random
# GRU net
dim_in = 6
dim_out = 1
n_layer = 1
TIME_STEP = 1 # rnn time step
LR = 0.02 # learning rate
gru = GRU(dim_in, dim_out, n_layer)
print(gru)
optimizer = torch.optim.Adam(gru.parameters(), lr=LR) # optimize all cnn parameters
loss_func = nn.MSELoss()
h_state = None # for initial hidden state
# subframe
scaling = 1
MP = 200
MT = 1
number = 2
drx = 160
on_time = 8
inavtive_time = 100
p_c = 100 * scaling
p_cs = 300 * scaling
p_sleep = 1
p_tr = 450
sp_time = 0.5
speed = [0.5/26, 0.5 / 7, 0.5/5]
read_speed = 2.33 / 1000
buffer = 0
bool_scheme = 1
max_buffer = 25
bool_on = 0
bool_inactive = 0
bool_sleep = 0
bool_data = 1
bool_last = 0
bool_buffer = 0
power_av = 0
time_av = 0 # 平均时延
data_sup = 0
ue_buffer = 0
# show data
state_tr_matrix = np.array([[0.3, 0.1, 0.1], [0.6, 0.8, 0.5], [0.1, 0.1, 0.3]])
state = 1 # [0:5% SINR, 1:50% SINR, 2:95% SINR]
state_T = 1000
loss_record = []
pre_buffer_record = []
rel_buffer_record = []
for i in range(MT):
bs_buffer_record = []
ue_buffer_record = []
N_record = []
on_timer = on_time
avtive_timer = inavtive_time
sleep_timer = drx
t = 1
power_sum = 0
buffer_prediction = 0
point = round(random.uniform(0, 1) * drx)
state_list = []
buffer_list = []
drx_list = [] # [0:sleep , 1: avtive time]
ue_buffer_list = []
for j in range(number):
N = round(2000 + random.uniform(-500, 500))
N_record.append(N)
x = np.random.poisson(lam=MP, size=N)
gap = x[0]
gap_times = 0
delay = []
buffer = buffer + sp_time
while True:
# 网络训练数据更新
if t >= 1:
state_list.insert(0, state)
buffer_list.insert(0, buffer)
if bool_inactive or bool_on:
drx_list.insert(0, 1)
else:
drx_list.insert(0, 0)
ue_buffer_list.insert(0, ue_buffer)
if len(buffer_list) > TIME_STEP:
state_list.pop(-1)
buffer_list.pop(-1)
drx_list.pop(-1)
max_buffer_list = np.ones(TIME_STEP) * max_buffer
read_speed_list = np.ones(TIME_STEP) * read_speed
data = np.vstack((max_buffer_list, read_speed_list))
data = np.vstack((data, np.array(state_list)))
data = np.vstack((data, np.array(buffer_list)))
data = np.vstack((data, np.array(drx_list)))
data = np.vstack((data, np.array(ue_buffer_list[1:])))
ue_buffer_list.pop(-1)
x_train = torch.from_numpy(data.T.reshape(1, data.T.shape[0], data.T.shape[1]))
x_train = torch.tensor(x_train, dtype=torch.float32)
y = np.array(ue_buffer_list[0]).reshape((1, 1))
prediction, h_state = gru(x_train) # rnn output
# !! next step is important !!
loss = loss_func(prediction, torch.tensor(y, dtype=torch.float32)) # calculate loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients
loss_record.append(loss.item())
if t % 100 == 0:
pre_buffer_record.append(prediction.item())
rel_buffer_record.append(y[0, 0])
print("t:", t, " loss:", loss.item())
print('t:', t, ' 预测值:', prediction.item(), '真实值:', ue_buffer)
# 信道状态转移
if t % state_T == 0:
number = random.uniform(0, 1)
cdf_prob = 0
init_state = 0
for prob in state_tr_matrix[:, state]:
cdf_prob = prob + cdf_prob
if number < cdf_prob:
state = init_state
break
else:
init_state = init_state + 1
if t == 1: # 开始时刻的状态判断
if point > on_time:
bool_sleep = 1
sleep_timer = drx - point
delay.append(drx - point + sp_time)
else:
bool_on = 1
on_timer = on_time - point
delay.append(sp_time)
if bool_on:
bool_on = 0
on_timer = - 1
bool_data = 0
data_sup = buffer
avtive_timer = inavtive_time
bool_inactive = 1
else:
buffer_temp = buffer
if gap == 0: # 判断数据
# 判断到来的数据是否需要开启新的active timer
bool_data = 1
if bool_inactive and buffer > 0:
bool_data = 0
gap_times = gap_times + 1
if gap_times <= N - 1:
gap = x[gap_times]
buffer = buffer + sp_time
# DRX
if avtive_timer == 0:
bool_inactive = 0
avtive_timer = avtive_timer - 1
if bool_on == 0:
power_sum = power_sum + p_tr
bool_sleep = 1
if sleep_timer == 0:
sleep_timer = drx
bool_on = 1
on_timer = on_time
bool_sleep = 0
if bool_on or bool_inactive: # Active time
if bool_inactive:
if bool_data:
bool_data = 0
data_sup = buffer
avtive_timer = inavtive_time
if data_sup > 0:
avtive_timer = inavtive_time
else:
if bool_on:
bool_sleep = 0
if buffer > 0:
data_sup = buffer
bool_data = 0
bool_inactive = 1
avtive_timer = inavtive_time
if on_timer == 0:
bool_on = 0
on_timer = on_timer - 1
if bool_inactive == 0:
power_sum = power_sum + p_tr
bool_sleep = 1
# buffer 策略
if bool_scheme:
if ue_buffer < max_buffer * 0.3 and bool_buffer == 1:
bool_buffer = 0
if ue_buffer > max_buffer * 0.7 and bool_buffer == 0:
bool_buffer = 1
if bool_buffer:
bool_on = 0
bool_inactive = 0
bool_sleep = 1
if bool_on and bool_inactive != 1:
power_sum = power_sum + p_c
if bool_inactive:
if data_sup > 0:
data_sup = data_sup - 1
if data_sup < 0:
data_sup = 0
if buffer > 0 and ue_buffer + speed[state] * 2 < max_buffer:
buffer = buffer - speed[state] * 2
ue_buffer = ue_buffer + speed[state] * 2
if buffer > 0:
power_sum = power_sum + p_cs
else:
buffer = 0
power_sum = power_sum + (p_c + p_cs) * 0.5
else:
power_sum = power_sum + p_c
if bool_sleep:
power_sum = power_sum + p_sleep
# 时间的推进和定时器的减少
bs_buffer_record.append(buffer)
ue_buffer_record.append(ue_buffer)
t = t + 1
# AI buffer_prediction
buffer_pre_temp = buffer_prediction
if ue_buffer > 0:
ue_buffer = ue_buffer - read_speed
if ue_buffer < 0:
ue_buffer = 0
if bool_on:
on_timer = on_timer - 1
if bool_inactive:
avtive_timer = avtive_timer - 1
sleep_timer = sleep_timer - 1
gap = gap - 1
#torch.save(gru, "./gru1.pth")
if ue_buffer == 0 and gap_times >= N - 1:
break
power_av = power_sum / t + power_av
torch.save(gru, "./gru1.pth")
plt.figure()
plt.plot(pre_buffer_record, 'r-')
plt.plot(rel_buffer_record, 'b-')
plt.savefig("buffer.png")
plt.show()
plt.figure()
plt.plot(loss_record, 'r-')
plt.savefig("loss.png")
plt.show()
power_result = power_av / MT + 100 / 320
<file_sep>import numpy as np
from models.model import GRU
import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
import random
from queue import Queue
# subframe
scaling = 1
MP = 200
MT = 20
n_video = 2
drx = 160
on_time = 8
inavtive_time = 100
p_c = 100 * scaling
p_cs = 300 * scaling
p_sleep = 1
p_tr = 450
packe_size = 0.5
speed = [0.5 / 26, 0.5 / 7, 0.5 / 5]
read_speed = 2.33 / 1000
bool_scheme = 1
max_buffer = 70
bool_on = 0
bool_inactive = 0
bool_sleep = 0
bool_data = 1
bool_last = 0
bool_buffer = 0
power_av = 0
time_av = 0 # 平均时延
break_av = 0
ue_buffer = 0
bs_queue = Queue(maxsize=0) # 用于存储到达的包,每个0.5MB
pack_queue = Queue(maxsize=0) # 用于存储到达的包的时间
# show data
state_tr_matrix = np.array([[0.3, 0.1, 0.1], [0.6, 0.8, 0.5], [0.1, 0.1, 0.3]])
state = 1 # [0:5% SINR, 1:50% SINR, 2:95% SINR]
state_T = 1000
loss_record = []
pre_buffer_record = []
rel_buffer_record = []
active_record = []
sleep_record = []
power_record = []
data_sup_record = []
for i in range(MT):
print(i)
bs_buffer_record = []
ue_buffer_record = []
N_record = []
on_timer = on_time
avtive_timer = inavtive_time
sleep_timer = drx
t = 1
power_sum = 0
buffer_prediction = 0
point = round(random.uniform(0, 1) * drx)
state_list = []
buffer_list = []
drx_list = [] # [0:sleep , 1: avtive time]
ue_buffer_list = []
data_sup = 0
delay = []
break_time = 0
x_boool = 0
for j in range(n_video):
N = round(6000 + random.uniform(-500, 500))
N_record.append(N)
x = np.random.poisson(lam=MP, size=N)
gap = x[0]
gap_times = 0
bs_queue.put(packe_size)
pack_queue.put(t)
time_x = 3200
while True:
power_x = power_sum
# 信道状态转移
# if t % state_T == 0:
# number = random.uniform(0, 1)
# cdf_prob = 0
# init_state = 0
# for prob in state_tr_matrix[:, state]:
# cdf_prob = prob + cdf_prob
# if number < cdf_prob:
# state = init_state
# break
# else:
# init_state = init_state + 1
# buffer 策略
if bool_scheme:
if ue_buffer < max_buffer * 0.3 and bool_buffer == 1:
bool_buffer = 0
if ue_buffer > max_buffer * 0.7 and bool_buffer == 0:
bool_buffer = 1
if bool_buffer:
bool_on = 0
bool_inactive = 0
bool_sleep = 1
if t == 1: # 开始时刻的状态判断
if point > on_time:
bool_sleep = 1
sleep_timer = drx - point
else:
bool_on = 1
on_timer = on_time - point
if bool_on:
bool_on = 0
on_timer = - 1
bool_data = 0
if not bs_queue.empty():
data_sup = bs_queue.get()
avtive_timer = inavtive_time
bool_inactive = 1
else:
if gap == 0: # 判断数据
# 判断到来的数据是否需要开启新的active timer
bool_data = 1
if bool_inactive and data_sup > 0:
bool_data = 0
gap_times = gap_times + 1
if gap_times <= N - 1:
gap = x[gap_times]
bs_queue.put(packe_size)
pack_queue.put(t)
# DRX
if avtive_timer == 0:
bool_inactive = 0
avtive_timer = avtive_timer - 1
if bool_on == 0 and bool_buffer == 0:
power_sum = power_sum + p_tr
bool_sleep = 1
if sleep_timer == 0:
sleep_timer = drx
if bool_buffer == 0:
bool_on = 1
on_timer = on_time
bool_sleep = 0
if (bool_on or bool_inactive) and (bool_buffer == 0): # Active time
if bool_inactive:
if bool_data:
bool_data = 0
if not bs_queue.empty():
data_sup = bs_queue.get()
avtive_timer = inavtive_time
if data_sup > 0:
avtive_timer = inavtive_time
else:
if not bs_queue.empty():
data_sup = bs_queue.get()
avtive_timer = inavtive_time
else:
if bool_on:
bool_sleep = 0
if not bs_queue.empty():
if data_sup == 0:
data_sup = bs_queue.get()
if data_sup > 0:
bool_data = 0
bool_inactive = 1
avtive_timer = inavtive_time
if on_timer == 0:
bool_on = 0
on_timer = on_timer - 1
if bool_inactive == 0 and bool_buffer == 0:
power_sum = power_sum + p_tr
bool_sleep = 1
if bool_on and bool_inactive != 1:
power_sum = power_sum + p_c
if bool_inactive:
if data_sup > 0:
if ue_buffer + speed[state] * 2 < max_buffer:
ue_buffer = ue_buffer + speed[state] * 2
data_sup = data_sup - speed[state] * 2
if data_sup < min(speed) * 2:
data_sup = 0
delay.append(t - pack_queue.get())
power_sum = power_sum + p_cs
else:
power_sum = power_sum + p_c
if bool_sleep:
power_sum = power_sum + p_sleep
# 时间的推进和定时器的减少
bs_buffer_record.append(bs_queue.qsize() + data_sup)
ue_buffer_record.append(ue_buffer)
t = t + 1
# AI buffer_prediction
buffer_pre_temp = buffer_prediction
if ue_buffer > 0:
ue_buffer = ue_buffer - read_speed
if ue_buffer < 0:
ue_buffer = 0
break_time = break_time + 1
if bool_on:
on_timer = on_timer - 1
if bool_inactive:
avtive_timer = avtive_timer - 1
sleep_timer = sleep_timer - 1
gap = gap - 1
if ue_buffer == 0 and gap_times >= N - 1 and pack_queue.empty():
break
# test
# if bool_buffer == 1:
# x_boool = 1
#
# if x_boool == 1:
# time_x = time_x - 1
# if (bool_inactive or bool_on) and bool_buffer == 0:
# active_record.append(1)
# else:
# active_record.append(0)
# sleep_record.append(bool_buffer)
# power_record.append(power_sum)
# data_sup_record.append(data_sup)
# if time_x == 0:
# print(j)
# plt.figure()
# plt.plot(active_record, c='r', label='Active')
# plt.plot(data_sup_record, c='green', label='Data_sup')
# plt.xlabel('T')
# plt.ylabel('value')
# plt.legend()
# plt.savefig("active.png")
# plt.show()
#
# plt.figure()
# plt.plot(sleep_record, c='r', label='buffer')
# plt.xlabel('T')
# plt.ylabel('value')
# plt.legend()
# plt.savefig("buffer.png")
# plt.show()
#
# plt.figure()
# plt.plot(power_record, c='r', label='power_sum')
# plt.xlabel('T')
# plt.ylabel('value')
# plt.legend()
# plt.savefig("power.png")
# plt.show()
# print("sf")
power_av = power_sum / t + power_av
#print(power_av)
time_av = sum(delay) / N + time_av
#print(time_av)
break_av = break_time / t + break_av
if i == 1:
print(N_record)
plt.figure()
plt.plot(bs_buffer_record, c='r', label='BS_buffer')
plt.plot(ue_buffer_record, c='b', label='UE_buffer')
plt.xlabel('T/ms')
plt.ylabel('Size/MB')
plt.legend()
plt.savefig("buffer.png")
plt.show()
power_av = power_av / MT + 100 / 320
print("能耗:", power_av)
time_av = time_av / MT
print("时延", time_av)
break_av = break_av / MT
print("中断概率", break_av)
<file_sep>"""
View more, visit my tutorial page: https://morvanzhou.github.io/tutorials/
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
Dependencies:
torch: 0.4
matplotlib
numpy
"""
import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
import random
# torch.manual_seed(1) # reproducible
# Hyper Parameters
TIME_STEP = 20 # rnn time step
INPUT_SIZE = 1 # rnn input size
LR = 0.02 # learning rate
# show data
state_tr_matrix = np.array([[0.3, 0.1, 0.1], [0.6, 0.8, 0.5], [0.1, 0.1, 0.3]])
state = 0
csi = []
for step in range(1000):
csi.append(state)
number = random.uniform(0, 1)
cdf_prob = 0
init_state = 0
for prob in state_tr_matrix[:, state]:
cdf_prob = prob + cdf_prob
if number < cdf_prob:
state = init_state
break
else:
init_state = init_state + 1
csi = np.array(csi)
# steps = np.linspace(0, np.pi * 2, 100, dtype=np.float32) # float32 for converting torch FloatTensor
steps = csi
x_np = csi[:-1].astype(np.float32)
y_np = csi[1:].astype(np.int64)
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.rnn = nn.LSTM( # if use nn.RNN(), it hardly learns
input_size=INPUT_SIZE,
hidden_size=64, # rnn hidden unit
num_layers=1, # number of rnn layer
batch_first=True, # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
)
self.out = nn.Linear(64, 3)
def forward(self, x):
# x (batch, time_step, input_size)
# h_state (n_layers, batch, hidden_size)
# r_out (batch, time_step, hidden_size)
r_out, (h_n, h_c) = self.rnn(x, None)
outs = self.out(r_out[:, -1, :])
return outs
# instead, for simplicity, you can replace above codes by follows
# r_out = r_out.view(-1, 32)
# outs = self.out(r_out)
# outs = outs.view(-1, TIME_STEP, 1)
# return outs, h_state
# or even simpler, since nn.Linear can accept inputs of any dimension
# and returns outputs with same dimension except for the last
# outs = self.out(r_out)
# return outs
rnn = RNN()
print(rnn)
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR) # optimize all cnn parameters
# loss_func = nn.MSELoss()
loss_func = nn.CrossEntropyLoss()
h_state = None # for initial hidden state
plt.figure(1, figsize=(12, 5))
plt.ion() # continuously plot
pred_y_list = []
pred_y_list2 = []
total_ac = []
for step in range(900):
start, end = step, step + TIME_STEP # time range
# use sin predicts cos
steps = np.linspace(start, end, TIME_STEP, dtype=int,
endpoint=False)
x_np_train = x_np[steps]
y_np_train = y_np[steps]
x = torch.from_numpy(x_np_train[np.newaxis, :, np.newaxis]) # shape (batch, time_step, input_size)
y = torch.from_numpy(y_np_train[np.newaxis, :, np.newaxis])
output = rnn(x) # rnn output
loss = loss_func(output, y[-1, -1, :]) # cross entropy loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step()
# plotting
# plt.plot(steps, y_np_train.flatten(), 'r-')
# plt.plot(steps[-1], prediction.data.numpy().flatten(), 'b-')
# plt.draw()
# plt.pause(0.05)
x_np_test = x_np[steps+1]
y_np_test = y_np[steps+1]
x = torch.from_numpy(x_np_train[np.newaxis, :, np.newaxis])
y = torch.from_numpy(y_np_train[np.newaxis, :, np.newaxis])
test_output = rnn(x) # (samples, time_step, input_size)
pred_y = torch.max(test_output, 1)[1].data.numpy()
accuracy = float((pred_y == y[-1, -1, :].numpy()).astype(int).sum())
print('Epoch: ', end + 1, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
total_ac.append(accuracy)
pred_y_list.append(pred_y[-1])
pred_y_list2.append(y[-1, -1, :].numpy()[-1])
print('test accuracy: %.2f' % (sum(total_ac)/len(total_ac)))
plt.figure()
plt.plot(pred_y_list2)
plt.plot(pred_y_list)
plt.savefig("filename.png")
plt.show()
<file_sep>"""
View more, visit my tutorial page: https://morvanzhou.github.io/tutorials/
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
Dependencies:
torch: 0.4
matplotlib
numpy
"""
import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
import random
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.rnn = nn.RNN(
input_size=INPUT_SIZE,
hidden_size=32, # rnn hidden unit
num_layers=1, # number of rnn layer
batch_first=True, # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
)
self.out = nn.Linear(32, 3)
def forward(self, x, h_state):
# x (batch, time_step, input_size)
# h_state (n_layers, batch, hidden_size)
# r_out (batch, time_step, hidden_size)
r_out, h_state = self.rnn(x, h_state)
outs = self.out(r_out[:, -1, :])
return outs, h_state
# instead, for simplicity, you can replace above codes by follows
# r_out = r_out.view(-1, 32)
# outs = self.out(r_out)
# outs = outs.view(-1, TIME_STEP, 1)
# return outs, h_state
# or even simpler, since nn.Linear can accept inputs of any dimension
# and returns outputs with same dimension except for the last
# outs = self.out(r_out)
# return outs
# torch.manual_seed(1) # reproducible
# Hyper Parameters
TIME_STEP = 1 # rnn time step
INPUT_SIZE = 1 # rnn input size
LR = 0.02 # learning rate
accuracy_av = 0
for i in range(100):
# show data
state_tr_matrix = np.array([[0.3, 0.1, 0.1], [0.6, 0.8, 0.5], [0.1, 0.1, 0.3]])
state = 0
csi = []
for step in range(2000):
csi.append(state)
number = random.uniform(0, 1)
cdf_prob = 0
init_state = 0
for prob in state_tr_matrix[:, state]:
cdf_prob = prob + cdf_prob
if number < cdf_prob:
state = init_state
break
else:
init_state = init_state + 1
csi = np.array(csi)
# steps = np.linspace(0, np.pi * 2, 100, dtype=np.float32) # float32 for converting torch FloatTensor
steps = csi
x_np = csi[:-1].astype(np.float32)
y_np = csi[1:].astype(np.int64)
rnn = RNN()
print(rnn)
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR) # optimize all cnn parameters
# loss_func = nn.MSELoss()
loss_func = nn.CrossEntropyLoss()
h_state = None # for initial hidden state
pred_y_list = []
pred_y_list2 = []
total_ac = []
for step in range(1900):
start, end = step, step + TIME_STEP # time range
# use sin predicts cos
steps = np.linspace(start, end, TIME_STEP, dtype=int,
endpoint=False)
x_np_train = x_np[steps]
y_np_train = y_np[steps]
x = torch.from_numpy(x_np_train[np.newaxis, :, np.newaxis]) # shape (batch, time_step, input_size)
y = torch.from_numpy(y_np_train[np.newaxis, :, np.newaxis])
prediction, h_state = rnn(x, h_state) # rnn output
# !! next step is important !!
h_state = h_state.data # repack the hidden state, break the connection from last iteration
loss = loss_func(prediction, y[-1, -1, :]) # calculate loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients
# plotting
# plt.plot(steps, y_np_train.flatten(), 'r-')
# plt.plot(steps[-1], prediction.data.numpy().flatten(), 'b-')
# plt.draw()
# plt.pause(0.05)
if step > 1800:
x_np_test = x_np[steps + 1]
y_np_test = y_np[steps + 1]
x = torch.from_numpy(x_np_train[np.newaxis, :, np.newaxis])
y = torch.from_numpy(y_np_train[np.newaxis, :, np.newaxis])
test_output, h_state_temp = rnn(x, h_state) # (samples, time_step, input_size)
pred_y = torch.max(test_output, 1)[1].data.numpy()
accuracy = float((pred_y == y[-1, -1, :].numpy()).astype(int).sum())
print('Epoch: ', end + 1, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
total_ac.append(accuracy)
pred_y_list.append(pred_y[-1])
pred_y_list2.append(y[-1, -1, :].numpy()[-1])
accuracy_av = sum(total_ac) / len(total_ac) + accuracy_av
print('test accuracy: %.2f' % accuracy_av)
<file_sep>import random
import numpy as np
from models.model import GRU
import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
import random
from queue import Queue
bs_queue = Queue(maxsize=0)
bs_queue.put(1)
print(bs_queue.qsize())
x = bs_queue.get()
print(bs_queue.qsize())
print(bs_queue.empty())
xx = []
xx.append(3)
print(xx)
xx.append(2)
print(xx)
xx.append(1)
print(min(xx))
xx.pop(-2)
print(len(xx))
xx.insert(0, 333)
print(xx)
|
72c71a1a28152f54b968d1ad85d71ae9a6e06735
|
[
"Python"
] | 6
|
Python
|
berserkersss/CSI_prediction_RNN
|
b24eb0dd979a230d7517e340b079aef07f834cc0
|
6af67cb1221f0d4a483fad182a956c92087717f7
|
refs/heads/master
|
<repo_name>saurabhipro/cmms_hls<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/web/SaveJobAction.java
package com.iprosonic.cmms.modules.job.transactions.job.web;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;
import java.io.StringWriter;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobExplBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRigBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRunBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobServiceBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobWellBean;
import com.iprosonic.cmms.modules.job.transactions.job.service.JobNumberingService;
import com.iprosonic.cmms.pjcommons.utility.DateUtil;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
import com.iprosonic.cmms.pjcommons.utility.WorkFlow;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class SaveJobAction extends ActionSupport {
private InputStream inputStream = null;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
private static final long serialVersionUID = 1L;
private JobNumberingService saveJobService = new JobNumberingService();
public String execute() {
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
Transaction transaction = null;
try {
Session session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Set<JobRigBean> rigBeanSet = new HashSet<JobRigBean>();
Set<JobRunBean> jobRunBeanSet = new HashSet<JobRunBean>();
Set<JobServiceBean> jobServiceBeanSet = new HashSet<JobServiceBean>();
Set<JobExplBean> jobExplBeanSet = new HashSet<JobExplBean>();
JobBean jobBean = new JobBean();
JobRigBean jobRigBean = null;
JobRunBean jobRunBean = null;
JobServiceBean jobServiceBean = null;
JobExplBean jobExplBean = null;
String rigIdFormat = "rig-1";// 5
String runIdFormat = "rig-1-run-1";// 11
String serIdFormat = "rig-1-run-1-ser-01";// 18
String expIdFormat = "rig-1-run-1-ser-01-exp-1";
request.getSession(true);
HttpSession sessionData = request.getSession(true);
if (sessionData.isNew()) {
response.sendRedirect(response.encodeRedirectUrl("LoginAction.action"));
}
String unitNo = request.getParameter("unitNo").trim();
String engineer = request.getParameter("engineer").trim();
String crew = request.getParameter("crew").trim();
String wellNo = request.getParameter("wellNo");
String clientName = request.getParameter("clientName");
String unitReachedBase = request.getParameter("unitReachedBase");
String unitReachedSite = request.getParameter("unitReachedSite");
String unitLeftBase = request.getParameter("unitLeftBase");
String unitLeftSite = request.getParameter("unitLeftSite");
String truckMileage = request.getParameter("truckMileage");
String vanMileage = request.getParameter("vanMileage");
String lostTime = request.getParameter("lostTime");
String unitMileage = request.getParameter("unitMileage");
String ejcs1 = request.getParameter("ejcs1");
String ejcs2 = request.getParameter("ejcs2");
String ejcs3 = request.getParameter("ejcs3");
String ejcs4 = request.getParameter("ejcs4");
String safetyMeet = request.getParameter("safetyMeet");
String remarks = request.getParameter("remarks").trim();
String jobNoHlsa = request.getParameter("jobNoHlsa");
String field = request.getParameter("field");
String latitude_d = request.getParameter("latitude_d");
String latitude_m = request.getParameter("latitude_m");
String latitude_s = request.getParameter("latitude_s");
String longitude_d = request.getParameter("longitude_d");
String longitude_m = request.getParameter("longitude_m");
String longitude_s = request.getParameter("longitude_s");
String kb = request.getParameter("kb");
String dl = request.getParameter("dl");
String td = request.getParameter("td");
String casing_size = request.getParameter("casing_size");
String casing_size_at_depth = request.getParameter("casing_size_at_depth");
String rigName = request.getParameter("rigName");
String tdDriller = request.getParameter("tdDriller");
String csDriller = request.getParameter("csDriller");
String wp = request.getParameter("wp");
String bitSize = request.getParameter("bitSize");
String startCirculation = request.getParameter("startCirculation");
String stopCirculation = request.getParameter("stopCirculation");
String gf = request.getParameter("gf");
String density = request.getParameter("density");
String viscosity = request.getParameter("viscosity");
String ph = request.getParameter("ph");
String salinity = request.getParameter("salinity");
String barities = request.getParameter("barities");
String deviation = request.getParameter("deviation");
String rmValue = request.getParameter("rmValue");
String rmTemp = request.getParameter("rmTemp");
String rmf = request.getParameter("rmf");
String rmc = request.getParameter("rmc");
String solid = request.getParameter("solid");
String jobDate = request.getParameter("jobDate");
jobBean.setUnitNo(unitNo);
String latestNo = saveJobService.genereateJobCd("JOB", unitNo);
String jobNo = "JOB-" + unitNo + "-" + clientName + "-" + DateUtil.getCurrentMonth() + DateUtil.getCurrentYear() + "-" + latestNo;
jobBean.setJobNo(jobNo.trim());
jobBean.setEngineer(engineer);
jobBean.setJobStatus(WorkFlow.PENDING_WITH_ENGINEER);
if (jobDate == null) {
jobDate = DateUtil.getCurrentDateWasCpi();
}
jobBean.setJobDate(DateUtil.getJobDate(jobDate));
jobBean.setCrew(crew);
jobBean.setUnitNo(unitNo);
jobBean.setWellNo(wellNo);
jobBean.setClientName(clientName);
jobBean.setUnitLeftBase(unitLeftBase);
jobBean.setUnitLeftSite(unitLeftSite);
jobBean.setUnitReachedBase(unitReachedBase);
jobBean.setUnitReachedSite(unitReachedSite);
jobBean.setTruckMileage(truckMileage);
jobBean.setVanMileage(vanMileage);
jobBean.setLostTime(lostTime);
jobBean.setEjcs1(ejcs1);
jobBean.setEjcs2(ejcs2);
jobBean.setEjcs3(ejcs3);
jobBean.setEjcs4(ejcs4);
double sum = toNumeric(ejcs1) + toNumeric(ejcs2) + toNumeric(ejcs3) + toNumeric(ejcs4);
double av = sum / 4;
jobBean.setEjcs5(av + "");
jobBean.setSafetyMeet(safetyMeet);
jobBean.setRemarks(remarks);
jobBean.setJobNoHlsa(jobNoHlsa);
JobWellBean jobWellBean = new JobWellBean();
jobWellBean.setHoleSize("NA");
jobWellBean.setJobNo(jobNo.trim());
jobWellBean.setField(field);
jobWellBean.setLatitude_d(latitude_d);
jobWellBean.setLatitude_m(latitude_m);
jobWellBean.setLatitude_s(latitude_s);
jobWellBean.setLongitude_d(longitude_d);
jobWellBean.setLongitude_m(longitude_m);
jobWellBean.setLongitude_s(longitude_s);
jobWellBean.setKb(kb);
jobWellBean.setDl(dl);
jobWellBean.setTd(td);
jobWellBean.setCasingSize(casing_size);
jobWellBean.setCasingSizeDepth(casing_size_at_depth);
jobWellBean.setRigName(rigName);
jobWellBean.setTdDriller(tdDriller);
jobWellBean.setCsDriller(csDriller);
jobWellBean.setWeekPoint(wp);
jobWellBean.setBitSize(bitSize);
jobWellBean.setStartCirculation(startCirculation);
jobWellBean.setStopCirculation(stopCirculation);
jobWellBean.setGf(gf);
jobWellBean.setDensity(density);
jobWellBean.setPh(ph);
jobWellBean.setSalinity(salinity);
jobWellBean.setBarities(barities);
jobWellBean.setRmValue(rmValue);
jobWellBean.setRmTemp(rmTemp);
jobWellBean.setRmf(rmf);
jobWellBean.setRmc(rmc);
jobWellBean.setSolid(solid);
jobWellBean.setDeviation(deviation);
jobWellBean.setViscosity(viscosity);
String rig = request.getParameter("hiddenRig");
String run = request.getParameter("hiddenRun");
String ser = request.getParameter("hiddenSer");
String exp = request.getParameter("hiddenExpl");
String rigArray[] = rig.split("/");
String runArray[] = run.split("/");
String serArray[] = ser.split("/");
if (rig != "") {
for (int i = 0; i < rigArray.length; i++) {
String rigValArr[] = rigArray[i].split(",");
jobRigBean = new JobRigBean();
jobRigBean.setJobNo(jobNo.trim());
jobRigBean.setRigNo(jobNo + "-" + rigValArr[0].substring(0, rigIdFormat.length()));
jobRigBean.setRigUpStart(rigValArr[1]);
jobRigBean.setRigUpEnd(rigValArr[2]);
jobRigBean.setRigDownStart(rigValArr[3]);
jobRigBean.setRigDownEnd(rigValArr[4]);
jobRigBean.setOpTime(DateUtil.getOpTime(rigValArr[2], rigValArr[1]));
rigBeanSet.add(jobRigBean);
}
}
if (run != "") {
for (int i = 0; i < runArray.length; i++) {
String runValArr[] = runArray[i].split(",");
jobRunBean = new JobRunBean();
String rigNo = jobNo + "-" + runValArr[0].substring(0, rigIdFormat.length());
String runNo = jobNo + "-" + runValArr[0].substring(0, runIdFormat.length());
jobRunBean.setRigNo(rigNo);
jobRunBean.setRunNo(runNo);
jobRunBean.setJobNo(jobNo.trim());
jobRunBean.setBht(runValArr[1].trim());
jobRunBean.setRih(runValArr[2].trim());
jobRunBean.setPooh(runValArr[3].trim());
jobRunBean.setOt(DateUtil.getOpTime(runValArr[2], runValArr[3]));
if (!runValArr[4].toString().equals("")) {
jobRunBean.setWt(Double.parseDouble(runValArr[4]) + "");
} else {
jobRunBean.setWt(Double.parseDouble("0") + "");
}
jobRunBeanSet.add(jobRunBean);
}
}
if (ser != "") {
for (int i = 0; i < serArray.length; i++) {
String serValArr[] = serArray[i].split(",");
String runNo = jobNo + "-" + serValArr[0].substring(0, runIdFormat.length());
String serNo = jobNo + "-" + serValArr[0].substring(0, serIdFormat.length());
jobServiceBean = new JobServiceBean();
jobServiceBean.setRunNo(runNo);
jobServiceBean.setJobNo(jobNo.trim());
jobServiceBean.setServiceNo(serNo);
jobServiceBean.setServiceType(serValArr[1]);
jobServiceBean.setServiceName(serValArr[2]);
jobServiceBean.setLossTime(serValArr[3]);
jobServiceBean.setDeepestDepth(serValArr[4]);
jobServiceBean.setMeterageLogged(serValArr[5]);
jobServiceBean.setRev(serValArr[6]);
jobServiceBean.setFailureGroup(serValArr[7]);
jobServiceBean.setPretestCount(serValArr[8]);
jobServiceBean.setPumpOutTime(serValArr[9]);
jobServiceBean.setDryTestCount(serValArr[10]);
jobServiceBean.setPvtSample(serValArr[11]);
jobServiceBean.setNormalSample(serValArr[12]);
jobServiceBean.setLevelCount(serValArr[13]);
jobServiceBean.setCoresCount(serValArr[14]);
jobServiceBean.setGunSize(serValArr[15]);
jobServiceBean.setSpf(serValArr[16]);
jobServiceBean.setMeteragePerforated(serValArr[17]);
jobServiceBean.setSurfacePressure(serValArr[18]);
jobServiceBean.setChruns(serValArr[19]);
jobServiceBean.setChmisRuns(serValArr[20]);
jobServiceBean.setTcpmissrun(serValArr[21]);
jobServiceBean.setAssetCd(serValArr[22]);
jobServiceBean.setSerialNo(serValArr[23]);
jobServiceBean.setEngi(serValArr[24]);
jobServiceBean.setCrew(serValArr[25]);
jobServiceBean.setLogSendFromBase(serValArr[27]);
jobServiceBean.setRemarks(serValArr[26]);
jobServiceBean.setLogRcieveAtHo(serValArr[28]);
jobServiceBean.setLqaDoneDate(serValArr[29]);
jobServiceBean.setLqaTechnical(serValArr[30]);
jobServiceBean.setLqaPresentation(serValArr[31]);
jobServiceBean.setSnpSnd(serValArr[32]);
jobServiceBeanSet.add(jobServiceBean);
}
}
if (exp != "") {
String expArray[] = exp.split("/");
for (int i = 0; i < expArray.length; i++) {
jobExplBean = new JobExplBean();
String expValArr[] = expArray[i].split(",");
String serNo = jobNo + "-" + expValArr[0].substring(0, serIdFormat.length());
String expNo = jobNo + "-" + expValArr[0].substring(0, expIdFormat.length());
jobExplBean.setServiceNo(serNo);
jobExplBean.setExplNo(expNo);
jobExplBean.setPartCd(expValArr[1]);
jobExplBean.setQty(expValArr[2]);
jobExplBean.setUom(expValArr[3]);
jobExplBean.setJobNo(jobNo.trim());
jobExplBeanSet.add(jobExplBean);
}
}
try {
jobBean.setJobWellBean(jobWellBean);
jobWellBean.setJobBean(jobBean);
if (rigBeanSet.size() > 0) {
jobBean.setJobRigBean(rigBeanSet);
}
if (jobRunBeanSet.size() > 0) {
jobRigBean.setJobRunBeanSet(jobRunBeanSet);
}
if (jobServiceBeanSet.size() > 0) {
jobRunBean.setJobServiceBeanSet(jobServiceBeanSet);
}
if (jobExplBeanSet.size() > 0) {
jobServiceBean.setJobExplBeanSet(jobExplBeanSet);
}
session.save(jobBean);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
return ERROR;
} finally {
session.flush();
session.clear();
session.close();
}
String message = "Job No. " + jobNo + " generated succefully.";
request.setAttribute("message", message);
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
StringBufferInputStream sbis = new StringBufferInputStream(stacktrace);
setInputStream(sbis);
// transaction.rollback();
String message = "Please add rig ,run and services error occure at server -[" + e.getMessage() + "]";
request.setAttribute("message", message);
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
public double toNumeric(String data) {
Double d = null;
try {
d = Double.parseDouble(data);
} catch (Exception e) {
return 0.0;
}
return d;
}
}<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/utility/MyPropertiesReader.java
package com.iprosonic.cmms.pjcommons.utility;
import java.io.InputStream;
import java.util.Properties;
public class MyPropertiesReader {
String propValue;
public MyPropertiesReader() {
}
public String getFilePath(String PropertyName) {
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("com/iprosonic/cmms/pjcommons/utility/ApplicationResource.properties");
try {
Properties properties = new Properties();
properties.load(inputStream);
propValue = properties.getProperty(PropertyName);
} catch (Exception e) {
e.printStackTrace();
}
return propValue;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/valuelist/ServiceFlgStrAction.java
package com.iprosonic.cmms.pjcommons.valuelist;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.job.masters.service.domain.ServiceMstBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class ServiceFlgStrAction {
public static String getServiceFlg(String name) {
Session session = null;
String listString = ";";
Criteria criteria = null;
try {
session = HibernateSession.getSessionFactory().openSession();
criteria = session.createCriteria(ServiceMstBean.class);
criteria.add(Restrictions.eq("serviceName", name));
List<ServiceMstBean> lt = criteria.list();
// 24
for (ServiceMstBean serviceMstBean : lt) {
listString += serviceMstBean.getDeepestDepth() + ";"
+ serviceMstBean.getMeterageLogged() + ";"
+ serviceMstBean.getRevenue() + ";"
+ serviceMstBean.getFailureGroup() + ";"
+ serviceMstBean.getPretestCount() + ";"
+ serviceMstBean.getPumpOutTime() + ";"
+ serviceMstBean.getDryTestCount() + ";"
+ serviceMstBean.getPvtSample() + ";"
+ serviceMstBean.getNormalSample() + ";"
+ serviceMstBean.getLevelCount() + ";"
+ serviceMstBean.getCoresCount() + ";"
+ serviceMstBean.getGunSize() + ";"
+ serviceMstBean.getSpf() + ";"
+ serviceMstBean.getMeteragePerforated() + ";"
+ serviceMstBean.getSurfacePressure() + ";"
+ serviceMstBean.getChRuns() + ";"
+ serviceMstBean.getChMisRuns() + ";"
+ "Y"+";"
+ "Y"+";"
+ "Y"+";"
+ "Y"+";"
+ "Y"+";"
+ serviceMstBean.getRemarks() + ";"
+ serviceMstBean.getLogSentFromBase() + ";"
+ serviceMstBean.getLogRecievedAtHo() + ";"
+ serviceMstBean.getLqaDoneDate() + ";"
+ serviceMstBean.getLqaTpoints() + ";"
+"Y"+";"
+ serviceMstBean.getSnpSnd();
}
System.out.println(listString);
} catch (HibernateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return listString;
}
}
<file_sep>/cmms/WebContent/js/stdlib.js
// **************************************************************************
// Copyright 2007 - 2008 The JSLab Team, <NAME> and <NAME>
// Contact: http://www.jslab.dk/contact.php
//
// This file is part of the JSLab Standard Library (JSL) Program.
//
// JSL is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// any later version.
//
// JSL is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// ***************************************************************************
// File created 2009-01-23 17:22:36
// Decoding function. Default is decodeURIComponent
Cookie.decode = decodeURIComponent;
// Copy an array
Array.prototype.copy =
function() {
return [].concat(this);
};
// Return elements which are in A but not in arg0 through argn
Array.prototype.diff =
function() {
var a1 = this;
var a = a2 = null;
var n = 0;
while(n < arguments.length) {
a = [];
a2 = arguments[n];
var l = a1.length;
var l2 = a2.length;
var diff = true;
for(var i=0; i<l; i++) {
for(var j=0; j<l2; j++) {
if (a1[i] === a2[j]) {
diff = false;
break;
}
}
diff ? a.push(a1[i]) : diff = true;
}
a1 = a;
n++;
}
return a.unique();
};
// Check whether n number of arrays are disjoint
Array.prototype.disjoint =
function() {
var args = [];
var l = arguments.length;
if (!l)
return true;
for(var i=0; i<l; i++)
args.push(arguments[i]);
return Array.prototype.intersect.apply(this,args).length > 0 ? false : true;
};
// Compute the intersection of n arrays
Array.prototype.intersect =
function() {
if (!arguments.length)
return [];
var a1 = this;
var a = a2 = null;
var n = 0;
while(n < arguments.length) {
a = [];
a2 = arguments[n];
var l = a1.length;
var l2 = a2.length;
for(var i=0; i<l; i++) {
for(var j=0; j<l2; j++) {
if (a1[i] === a2[j])
a.push(a1[i]);
}
}
a1 = a;
n++;
}
return a.unique();
};
// Apply each member of the array as the first argument to the function f
Array.prototype.mapFunction =
function(f) {
var l = this.length;
for(var i=0; i<l; i++)
f(this[i]);
};
// Apply the method m to each member of an array
Array.prototype.mapMethod =
function(m) {
var a = [];
for(var i=1; i<arguments.length; i++)
a.push(arguments[i]);
var l = this.length;
for(var i=0; i<l; i++)
m.apply(this[i],a);
};
// Pad an array to given size with a given value
Array.prototype.pad =
function(s,v) {
var l = Math.abs(s) - this.length;
var a = [].concat(this);
if (l <= 0)
return a;
for(var i=0; i<l; i++)
s < 0 ? a.unshift(v) : a.push(v);
return a;
};
// Randomize elements in an array
Array.prototype.randomize =
function(ru) {
if (!ru)
this.sort(function(){return ((Math.random() * 3) | 0) - 1;});
else {
var a = [].concat(this);
var l = this.length;
var al = n = 0;
for(var i=0; i<l; i++) {
al = a.length;
// Get random integer in [0,a.length-1]
n = Math.floor((Math.random() * al));
// Copy random element from a to this
this[i] = a[n];
// If n was last element in a just pop a[n]
if (n == al - 1)
a.pop();
// Else copy last element from a to n and pop last element from a
else {
a[n] = a[al - 1];
a.pop();
}
}
}
};
// Remove values from an array optionally using a custom function
Array.prototype.remove =
function(f) {
if (!f)
f = function(i) {return i == undefined || i == null ? true : false;};
var l = this.length;
var n = 0;
for(var i=0; i<l; i++)
f(this[i]) ? n++ : this[i-n] = this[i];
this.length = this.length - n;
};
// Get the union of n arrays
Array.prototype.union =
function() {
var a = [].concat(this);
var l = arguments.length;
for(var i=0; i<l; i++) {
a = a.concat(arguments[i]);
}
return a.unique();
};
// Return new array with duplicate values removed
Array.prototype.unique =
function() {
var a = [];
var l = this.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (this[i] === this[j])
j = ++i;
}
a.push(this[i]);
}
return a;
};
// Default name/value seperator is ':'
Cookie.valueSeparator = ':';
// Cookie object constructor
function Cookie(name, age, path, domain, secure) {
// Friendly name of cookie
this.$name = name;
// Lifetime in seconds. Default value is 0
this.$age = age ? age : 0;
// Creation date
this.$date = (new Date()).getTime();
// Default path is path from where document originated
this.$path = path ? path : window.location.pathname.replace(/(\/)[^\/]*$/,'$1');
// Default domain is domain from where document originated
this.$domain = domain ? domain : window.location.hostname;
// Default is insecure (HTTP)
this.$secure = secure ? secure : false;
}
// Encoding function. Default is encodeURIComponent
Cookie.encode = encodeURIComponent;
// Test whether cookies are enabled
Cookie.isEnabled =
function() {
var c = new Cookie('test');
c.write();
try {
Cookie.read('test');
}
catch(e) {
return false;
}
c.remove();
return true;
};
// Get stored cookie
Cookie.read =
function(name) {
// Start position of cookie
var pos = document.cookie.indexOf(name+'=');
if (pos != -1) {
var c = new Cookie(name);
// Start position of named cookie
var s = pos + name.length + 1;
// End position of named cookie
var e = document.cookie.indexOf(';',s);
if (e != -1)
var p = document.cookie.substring(s,e);
else
var p = document.cookie.substring(s);
// Decode and split into array
var a = Cookie.decode(p).split(Cookie.pairSeparator);
// Temp. variable
var t = null;
for(var i=0; i<a.length; i++) {
t = a[i].split(Cookie.valueSeparator);
c[t[0]] = t[1];
}
return c;
}
else
throw new Error('Cookie: No cookie with name \'' + name + '\' found.');
};
// Delete cookie
Cookie.prototype.remove =
function() {
// Setting the age to -1 * now will create an expiration
// date of 1/1 1970 when the cookie is written
this.$age = (new Date()).getTime() / -1000;
this.write();
};
// Custom toString method
Cookie.prototype.toString =
function() {
var d = new Date(this.$date * 1);
var e = new Date(this.$date * 1 + this.$age * 1000);
var s = 'Name: ' + this.$name + '\nCreated: ' + d + '\nMax-age: ' + this.$age + '\nExpires on: ' + e + '\nPath: ' + this.$path + '\nDomain: ' + this.$domain + '\nSecure: ' + this.$secure + '\n\n';
for(var p in this) {
if (this[p].constructor != Function && p.charAt(0) != '$')
s += p + ': ' + this[p] + '\n';
}
return s;
};
// Write a named cookie
Cookie.prototype.write =
function() {
var s = '';
// Don't save methods
for(var p in this)
s += this[p].constructor != Function ? p + Cookie.valueSeparator + this[p] + Cookie.pairSeparator : '';
// Delete trailing pairSeparator and encode string
s = Cookie.encode(s.substring(0, s.length-1));
// expire date for IE
var d = (new Date()).getTime() + this.$age * 1000;
d = (new Date(d)).toUTCString();
// Save cookie
document.cookie = this.$name + '=' + s + '; expires=' + d + '; max-age=' + this.$age + '; path=' + this.$path + '; domain=' + this.$domain + '; ' + this.$secure + ';';
};
// Name of the months
Date.nameOfMonths = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Return date of monday in any given week and year
Date.getFirstDateInWeek =
function (y,w) {
// 4th of january is always in week 1 of any year
var d = (new Date(y, 0, 4)).getISODay() - 1;
return new Date(y, 0, 4 - d + (w - 1) * 7);
};
// Format a date according to a specified format
Date.prototype.format =
function(s,utc) {
// Split into array
s = s.split('');
var l = s.length;
var r = '';
var n = m = null;
for (var i=0; i<l; i++) {
switch(s[i]) {
// Day of the month, 2 digits with leading zeros: 01 to 31
case 'd':
n = utc ? this.getUTCDate() : this.getDate();
if (n * 1 < 10)
r += '0';
r += n;
break;
// A textual representation of a day, three letters: Mon through Sun
case 'D':
r += this.getNameOfDay(utc).substring(0,3);
break;
// Day of the month without leading zeros: 1 to 31
case 'j':
r += utc ? this.getUTCDate() : this.getDate();
break;
// Lowercase l A full textual representation of the day of the week: Sunday (0) through Saturday (6)
case 'l':
r += this.getNameOfDay(utc);
break;
// ISO-8601 numeric representation of the day of the week: 1 (for Monday) through 7 (for Sunday)
case 'N':
r += this.getISODay(utc);
break;
// English ordinal suffix for the day of the month, 2 characters
case 'S':
r += this.getDaySuffix(utc);
break;
// Numeric representation of the day of the week: 0 (for Sunday) through 6 (for Saturday)
case 'w':
r += utc ? this.getUTCDay() : this.getDay();
break;
// The day of the year (starting from 0) 0 through 365
case 'z':
n = 0;
m = utc ? this.getUTCMonth() : this.getMonth();
for(var i=0; i<m; i++)
n += Date.daysInMonth[i]
if (this.isLeapYear())
n++;
n += utc ? this.getUTCDate() : this.getDate();
n--;
r += n;
break;
// break;
// ISO-8601 week number of year, weeks starting on Monday
case 'W':
r += this.getISOWeek(utc);
break;
// A full textual representation of a month, such as January or March: January through December
case 'F':
r += this.getNameOfMonth(utc);
break;
// Numeric representation of a month, with leading zeros 01 through 12
case 'm':
n = utc ? this.getUTCMonth() : this.getMonth();
n++;
if (n < 10)
r += '0';
r += n;
break;
// A short textual representation of a month, three letters: Jan through Dec
case 'M':
r += this.getNameOfMonth(utc).substring(0,3);
break;
// Numeric representation of a month, without leading zeros: 1 through 12
case 'n':
n = utc ? this.getUTCMonth() : this.getMonth();
r += ++n;
break;
// Number of days in the given month: 28 through 31
case 't':
r += this.getDaysInMonth(utc);
break;
// Whether it's a leap year: 1 if it is a leap year, 0 otherwise.
case 'L':
if (this.isLeapYear(utc))
r += '1';
else
r += '0';
break;
// ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead
/*
case 'o':
break;
*/
// A full numeric representation of a year, 4 digits
case 'Y':
r += utc ? this.getUTCFullYear() : this.getFullYear();
break;
// A two digit representation of a year
case 'y':
n = utc ? this.getUTCFullYear() : this.getFullYear();
r += (n + '').substring(2);
break;
// Lowercase Ante meridiem and Post meridiem am or pm
case 'a':
n = utc ? this.getUTCHours() : this.getHours();
r += n < 12 ? 'am' : 'pm';
break;
// Uppercase Ante meridiem and Post meridiem AM or PM
case 'A':
n = utc ? this.getUTCHours() : this.getHours();
r += n < 12 ? 'AM' : 'PM';
break;
// Swatch Internet time 000 through 999
// case 'B':
// break;
// 12-hour format of an hour without leading zeros
case 'g':
n = utc ? this.getUTCHours() : this.getHours();
if (n > 12)
n -= 12;
r += n;
break;
// 24-hour format of an hour without leading zeros 0 through 23
case 'G':
r += this.getHours();
break;
// 12-hour format of an hour with leading zeros 01 through 12
case 'h':
n = utc ? this.getUTCHours() : this.getHours();
if (n > 12)
n -= 12;
if (n < 10)
r += '0';
r += n;
break;
// 24-hour format of an hour with leading zeros 00 through 23
case 'H':
n = utc ? this.getUTCHours() : this.getHours();
if (n < 10)
r += '0';
r += n;
break;
// i Minutes with leading zeros 00 to 59
case 'i':
n = utc ? this.getUTCMinutes() : this.getMinutes();
if (n < 10)
r += '0';
r += n;
break;
// s Seconds, with leading zeros 00 through 59
case 's':
n = utc ? this.getUTCSeconds() : this.getSeconds();
if (n < 10)
r += '0';
r += n;
break;
// Milliseconds
case 'u':
r += utc ? this.getUTCMilliseconds() : this.getMilliseconds();
break;
// Timezone identifier
// case 'e':
// break;
// Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise.
case 'I':
if (this.getMinutes() != this.getUTCMinutes)
r += '1';
else
r += '0';
break;
// Difference to Greenwich time (GMT) in hours
case 'O':
n = this.getTimezoneOffset() / 60;
if (n >= 0)
r += '+';
else
r += '-';
n = Math.abs(n);
if (Math.abs(n) < 10)
r += '0';
r += n + '00';
break;
// Difference to Greenwich time (GMT) with colon between hours and minutes: Example: +02:00
case 'P':
n = this.getTimezoneOffset() / 60;
if (n >= 0)
r += '+';
else
r += '-';
n = Math.abs(n);
if (Math.abs(n) < 10)
r += '0';
r += n + ':00';
break;
// T Timezone abbreviation EST, MDT etc.
// case 'T':
// break;
// Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.
case 'Z':
r += this.getTimezoneOffset() * 60;
break;
// ISO 8601 date: 2004-02-12T15:19:21+00:00
case 'c':
r += this.format('Y-m-d',utc) + 'T' + this.format('H:i:sP',utc);
break;
// RFC 2822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
case 'r':
r += this.format('D, j M Y H:i:s P',utc);
break;
case 'U':
r += this.getTime();
break;
default:
r += s[i];
}
}
return r
};
// Gen the english suffix for dates
Date.prototype.getDaySuffix =
function(utc) {
var n = utc ? this.getUTCDate() : this.getDate();
// If not the 11th and date ends at 1
if (n != 11 && (n + '').match(/1$/))
return 'st';
// If not the 12th and date ends at 2
else if (n != 12 && (n + '').match(/2$/))
return 'nd';
// If not the 13th and date ends at 3
else if (n != 13 && (n + '').match(/3$/))
return 'rd';
else
return 'th';
};
// Return the number of days in the month
Date.prototype.getDaysInMonth =
function(utc) {
var m = utc ? this.getUTCMonth() : this.getMonth();
// If feb.
if (m == 1)
return this.isLeapYear() ? 29 : 28;
// If Apr, Jun, Sep or Nov return 30; otherwise 31
return (m == 3 || m == 5 || m == 8 || m == 10) ? 30 : 31;
};
// Return the ISO day number for a date
Date.prototype.getISODay =
function(utc) {
// Native JS method - Sunday is 0, monday is 1 etc.
var d = utc ? this.getUTCDay() : this.getDay();
// Return d if not sunday; otherwise return 7
return d ? d : 7;
};
// Get ISO week number of the year
// The algorithm is credit to <NAME> and is taken from his calendar FAQ
// See http://www.tondering.dk/claus/cal/node8.html#SECTION00880000000000000000
// for more information
// Integer division: a/b|0
Date.prototype.getISOWeek =
function(utc) {
var y = utc ? this.getUTCFullYear(): this.getFullYear();
var m = utc ? this.getUTCMonth() + 1: this.getMonth() + 1;
var d = utc ? this.getUTCDate() : this.getDate();
// If month jan. or feb.
if (m < 3) {
var a = y - 1;
var b = (a / 4 | 0) - (a / 100 | 0) + (a / 400 | 0);
var c = ( (a - 1) / 4 | 0) - ( (a - 1) / 100 | 0) + ( (a - 1) / 400 | 0);
var s = b - c;
var e = 0;
var f = d - 1 + 31 * (m - 1);
}
// If month mar. through dec.
else {
var a = y;
var b = (a / 4 | 0) - ( a / 100 | 0) + (a / 400 | 0);
var c = ( (a - 1) / 4 | 0) - ( (a - 1) / 100 | 0) + ( (a - 1) / 400 | 0);
var s = b - c;
var e = s + 1;
var f = d + ( (153 * (m - 3) + 2) / 5 | 0) + 58 + s;
}
var g = (a + b) % 7;
// ISO Weekday (0 is monday, 1 is tuesday etc.)
var d = (f + g - e) % 7;
var n = f + 3 - d;
if (n < 0)
var w = 53 - ( (g - s) / 5 | 0);
else if (n > 364 + s)
var w = 1;
else
var w = (n / 7 | 0) + 1;
return w;
};
// Return the name of the weekday
Date.prototype.getNameOfDay =
function(utc) {
var d = this.getISODay(utc) - 1;
return Date.nameOfDays[d];
};
// Return the name of the month
Date.prototype.getNameOfMonth =
function(utc) {
var m = utc ? this.getUTCMonth() : this.getMonth();
return Date.nameOfMonths[m];
};
// Rewrite native Date.getTimezoneOffset to return values with correct sign
Date.prototype._getTimezoneOffset = Date.prototype.getTimezoneOffset;
Date.prototype.getTimezoneOffset =
function() {
return this._getTimezoneOffset() * -1;
};
// Retuns true if year is a leap year; otherwise false
Date.prototype.isLeapYear =
function(utc) {
var y = utc ? this.getUTCFullYear() : this.getFullYear();
return !(y % 4) && (y % 100) || !(y % 400) ? true : false;
};
// Set the week number of a date. The date becomes the monday of that week
Date.prototype.setISOWeek =
function(w,utc) {
var y = utc ? this.getUTCFullYear() : this.getFullYear();
var d = Date.getFirstDateInWeek(y,w);
this.setTime(d.getTime());
};
Function.prototype.defer =
function(n,o) {
// Get arguments as array
var a = [];
for(var i=2; i<arguments.length; i++)
a.push(arguments[i]);
var that = this;
window.setTimeout(function(){return that.apply(o,a);},n);
};
// Return the names of the arguments as strings in a an array
Function.prototype.getArguments =
function() {
// Get content between first ( and last )
var m = this.toString().match(/\((.*)\)/)[1];
// Strip spaces
m = m.replace(/\s*/g,'');
// String to array
return m.split(',');
};
// Return the body of a function
Function.prototype.getBody =
function() {
// Get content between first { and last }
var m = this.toString().match(/\{([\s\S]*)\}/m)[1];
// Strip comments
return m.replace(/^\s*\/\/.*$/mg,'');
};
// Return the name of a function
Function.prototype.getName =
function() {
var m = this.toString().match(/^function\s(\w+)/);
return m ? m[1] : "anonymous";
};
// Time a function n times and return a custom object with statistics for the trials
Function.prototype.time =
function(n,obj) {
if (n < 1)
return;
var o = {f:this, a:[], n:n, mean:0, s:0, sd: 0};
for(var i=2; i<arguments.length; i++)
o.a.push(arguments[i]);
var t1,t2;
var t = ts = 0;
for(var i=0; i<n; i++) {
t1 = new Date();
this.apply(obj,o.a);
t2 = (new Date()) - t1;
t += t2;
ts += t2 * t2;
}
o.mean = t / n;
o.s = n > 1 ? (ts - t * o.mean) / ( n - 1) : 0;
o.sd = Math.sqrt(o.s);
o.toString =
function() {
return 'Running ' + this.f.getName() + ' ' + this.n + ' times:\n\nMean:\t'+ (this.mean).toFixed(8) + '\nVariance:\t' + (this.s).toFixed(8) + '\nSD:\t' + (this.sd).toFixed(8);
};
return o;
};
// Find the nth fibonacci number
Math.fibonacci =
function(n) {
// Golden ratio
var g = (1 + Math.sqrt(5)) / 2;
return Math.round((Math.pow(g,n) - Math.pow(-g,-n)) / Math.sqrt(5));
};
// Return the logarithm of n using base b
function logN(x,b) {
if (b == 2)
return Math.LOG2E * Math.log(x);
if (b == 10)
return Math.LOG10E * Math.log(x);
return Math.log(x) / Math.log(b);
};
// Return the nth root of x
Math.nRoot =
function(x,n) {
var y = Math.log(x) / n;
return Math.pow(Math.E,y);
};
// Return a random integer in the interval [0,n]
Math.randomN =
function(n) {
return (Math.random() * (n + 1)) | 0;
};
// Return true if number is a float
Number.prototype.isFloat =
function() {
return /\./.test(this.toString());
};
// Return true if number is an integer
Number.prototype.isInteger =
function() {
return Math.floor(this) == this ? true : false;
};
// Return the hexidecimal string representation of an integer
Number.prototype.toHex =
function() {
// Only convert integers
if (!this.isInteger())
throw new Error('Number is not an integer');
// Can't assign to 'this' so we must copy
var d = this;
// Quotient and remainder
var q = r = null
// Return value
var s = '';
do {
q = Math.floor(d / 16);
r = d % 16;
// If r > 9 then get correct letter (A-F)
s = r < 10 ? r + s : String.fromCharCode(r + 55) + s;
d = q;
}
while(q)
return s;
};
// Convert HTML breaks to newline
String.prototype.br2nl =
function() {
return this.replace(/<br\s*\/?>/mg,"\n");
};
/*
Calculate the Levensthein distance (LD) of two strings
Algorithm is taken from http://www.merriampark.com/ld.htm. The algorithm is considered to be public domain.
1
Set n to be the length of s.
Set m to be the length of t.
If n = 0, return m and exit.
If m = 0, return n and exit.
Construct a matrix containing 0..m rows and 0..n columns.
2
Initialize the first row to 0..n.
Initialize the first column to 0..m.
3
Examine each character of s (i from 1 to n).
4
Examine each character of t (j from 1 to m).
5
If s[i] equals t[j], the cost is 0.
If s[i] doesn't equal t[j], the cost is 1.
6
Set cell d[i,j] of the matrix equal to the minimum of:
a. The cell immediately above plus 1: d[i-1,j] + 1.
b. The cell immediately to the left plus 1: d[i,j-1] + 1.
c. The cell diagonally above and to the left plus the cost: d[i-1,j-1] + cost.
7
After the iteration steps (3, 4, 5, 6) are complete, the distance is found in cell d[n,m].
*/
String.prototype.levenshtein=
function(t) {
// ith character of s
var si;
// cost
var c;
// Step 1
var n = this.length;
var m = t.length;
if (!n)
return m;
if (!m)
return n;
// Matrix
var mx = [];
// Step 2 - Init matrix
for (var i=0; i<=n; i++) {
mx[i] = [];
mx[i][0] = i;
}
for (var j=0; j<=m; j++)
mx[0][j] = j;
// Step 3 - For each character in this
for (var i=1; i<=n; i++) {
si = this.charAt(i - 1);
// Step 4 - For each character in t do step 5 (si == t.charAt(j - 1) ? 0 : 1) and 6
for (var j=1; j<=m; j++)
mx[i][j] = Math.min(mx[i - 1][j] + 1, mx[i][j - 1] + 1, mx[i - 1][j - 1] + (si == t.charAt(j - 1) ? 0 : 1));
}
// Step 7
return mx[n][m];
};
// Convert HTML whitespace to normal whitespace
String.prototype.nbsp2s =
function() {
return this.replace(/ ?/mg," ");
};
// Count the number of times a substring is in a string.
String.prototype.substrCount =
function(s) {
return this.length && s ? (this.split(s)).length - 1 : 0;
};
// Return a new string without leading and trailing whitespace
// Double spaces whithin the string are removed as well
String.prototype.trimAll =
function() {
return this.replace(/^\s+|(\s+(?!\S))/mg,"");
};
// Return a new string without leading whitespace
String.prototype.trimLeft =
function() {
return this.replace(/^\s+/,"");
};
// Return a new string without trailing whitespace
String.prototype.trimRight =
function() {
return this.replace(/\s+$/,"");
};
// Insert a node after another node
HTMLElement.prototype.insertAfter =
function(newNode, refNode) {
return refNode.nextSibling ? this.insertBefore(newNode, refNode.nextSibling) : this.appendChild(newNode);
};
// Default name/value pair seperator is '&'
Cookie.valueSeparator = '&';
// Get absolute position of element
HTMLElement.prototype.getPosition =
function() {
var o = {x:0,y:0};
var n = this;
do {
o.x += n.offsetLeft;
o.y += n.offsetTop;
n = n.offsetParent;
}
while(n)
return o;
};
// Set an error handler for a function
Function.prototype.setErrorHandler =
function(f,v) {
// Throw error if no user function is provided
if (!f)
throw new Error('Function.setErrorHandler: No function provided.');
var that = this;
// New function to return
var g =
function() {
try {
var a = [];
for(var i=0; i<arguments.length; i++)
a.push(arguments[i]);
that.apply(null,a);
}
catch(e) {
return f(g,e,v);
}
};
// Save ref. to original function
g.old = this;
return g;
};
// Check whether XMLHttpRequest is supported
XHR.isEnabled =
function() {
return XHR.factory ? true : false;
};
// Names of the week days
Date.nameOfDays = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
// Return a new string without leading and trialing whitespace
String.prototype.trim =
function() {
return this.replace(/^\s+(.*?)\s+$/,'$1');
};
// Retry a request
XHR.prototype.retry =
function() {
this._onretry();
};
// http://www.w3.org/TR/XMLHttpRequest/
// Constructor
function XHR(timeout, retries) {
if (!XHR.factory)
throw new Error('XHR: XMLHttpRequest not supported');
// Actual XMLHttpRequest object
this.req = XHR.factory();
// Pseudo readyState property. Used to work around second state of 1 in IE and Firefox
this._readyState = XHR.READYSTATE_UNINITIALIZED;
// Work around for IE and Firefox
this.aborted = false;
// Set onreadystatechange
var that = this;
this.req.onreadystatechange = function(){that._onreadystatechange();};
// Timeout for reuest in milliseconds. Default value is 30 seconds
this.timeout = timeout ? timeout : 30000;
// Ref. to opaque value returned by window.setTimeout for clearing setTimeout
this.timeoutRef = null;
// Parameters from open and send call for recreating request when retrying.
this.retryParams = {};
// Number of retires. 0 is default
this.retries = retries ? retries : 0;
}
// Request id. Set and incremented when request is sent
XHR.ridCounter = 0;
// readyState constants
XHR.READYSTATE_UNINITIALIZED = 0;
XHR.READYSTATE_OPEN = 1;
XHR.READYSTATE_SENT = 2;
XHR.READYSTATE_RECIEVING = 3;
XHR.READYSTATE_LOADED = 4;
// Define factory function
// Execute as anomymous function. Only executed once
(function() {
try {
// Provoke error if XMLHttpRequest does not exist
new XMLHttpRequest();
XHR.factory =
function() {
return new XMLHttpRequest();
};
}
catch(e) {
try {
// Provoke error if ActiveXObject("Msxml2.XMLHTTP") does not exist
new ActiveXObject("Msxml2.XMLHTTP");
XHR.factory =
function() {
return new ActiveXObject("Msxml2.XMLHTTP");
};
}
catch(e) {
try {
// Provoke error if ActiveXObject("Microsoft.XMLHTTP") does not exist
new ActiveXObject("Microsoft.XMLHTTP");
XHR.factory =
function() {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
catch(e) {
XHR.factory = null;
}
}
}
})();
// Generic onreadystatechange for all request
XHR.prototype._onreadystatechange =
function() {
// Work around for duplicate state 1 for IE and Firefox
if (this._readyState == XHR.READYSTATE_OPEN && this.req.readyState == XHR.READYSTATE_OPEN)
return;
this._readyState = this.req.readyState;
// Work around for request.abort triggering change to readystate 4
// in IE and Firefox
if (this.req.readyState == XHR.READYSTATE_LOADED && this.aborted)
return;
// Switch on request object readystate
switch (this.req.readyState) {
// open() not called yet
case XHR.READYSTATE_UNINITIALIZED:
this.aborted = false;
break;
// open() called, send() not called yet
case XHR.READYSTATE_OPEN:
// Set request ID
this.rid = XHR.ridCounter++;
// User defined event handler for state
if (this.onreadystateopen)
this.onreadystateopen();
break;
// send() called, no respons yet
case XHR.READYSTATE_SENT:
// Code placed here is *not* executed until repsonse is recieved.
// This is a bug in IE, Firefox and Safari. It works correctly in Opera 9
// User defined event handler is moved to XHR.prototype.send function
break;
// Recieving respons
case XHR.READYSTATE_RECIEVING:
// User defined event handler for state
if (this.onreadystaterecieving)
this.onreadystaterecieving();
break;
// Response complete
case XHR.READYSTATE_LOADED:
// Clear timeout if exist
if (this.timeoutRef) {
window.clearTimeout(this.timeoutRef);
this.timeoutRef = null;
}
// Get transmission time
this.time = (new Date()).getTime() - this.time;
// User defined event handler for state
if (this.onreadystateloaded)
this.onreadystateloaded();
// Response has been handled. Any cleanup code goes here
// Break possible circular ref. between XHR and XMLHttpRequest objects
this.breakRef();
break
default:
break;
}
};
// Break cicular reference between XHR and XMLHttpRequest object
XHR.prototype.breakRef =
function() {
this.req.onreadystatechange = null;
this.req = null;
};
// Generic event function for timeout
XHR.prototype._ontimeout =
function() {
// First action should be to abort. Thus ontimeout is *always* fired after onabort
this.abort();
// Clear window.setTimeout opaque value
this.timeoutRef = null;
// User event handler for timeout if provided
if (this.ontimeout)
this.ontimeout();
// Retry if there are any retries left
if (this.retries > 0)
this.retry();
};
// Generic event function for retry
XHR.prototype._onretry =
function() {
this.retries--;
// User event handler for retrying if provided
if (this.onretry)
this.onretry();
// Reset XHR obeject (don't know why we have to make a new XMLHttpRequest object)
this.reset();
// Re-open command
this.open(this.retryParams.method, this.retryParams.url, this.retryParams.async, this.retryParams.username, this.retryParams.password);
// Re-send command
this.send(this.retryParams.body);
};
// Generic event function for abort
XHR.prototype._onabort =
function() {
this.aborted = true;
// Cancel request. This will trigger a change in readystate to 4 in IE and Firefox
// Safari does not reset readystate to 0
this.req.abort();
// User event handler for abortion if provided
if (this.onabort)
this.onabort();
};
// Reset XHR object prior to resending request
XHR.prototype.reset =
function() {
// Break circular reference
this.breakRef();
// Reset workaround properties
this.aborted = false;
this._readyState = XHR.READYSTATE_UNINITIALIZED;
// Create new XMLHttpRequest instance
this.req = XHR.factory();
// Bind onreadystatechange event handler
var that = this;
this.req.onreadystatechange = function(){that._onreadystatechange();};
};
// Open a request
XHR.prototype.open =
function(method, url, async, username, password) {
// Save parameters for retry
this.retryParams.method = method;
this.retryParams.url = url;
this.retryParams.async = async;
this.retryParams.username = username;
this.retryParams.password = <PASSWORD>;
// Open request
this.req.open(method, url, async, username, password);
};
// Send a request
XHR.prototype.send =
function(body) {
if (body === undefined)
body = null;
// Save parameters for retry
this.retryParams.body = body;
// Set timestamp of request. Have to be done before readyState = 3
this.time = (new Date()).getTime();
// setTimeout must be called before readyState = 3
var that = this;
// Function arg to setTimeout must be wrapped in anonymous function
// otherwise 'this' is not resolved correctly
this.timeoutRef = window.setTimeout(function(){that._ontimeout();}, this.timeout);
// Send request
this.req.send(body);
// User defined event handler for state
// readyState 2 is handled wrong by IE, Firefox and Safari
// so functionality must be placed here
if (this.onreadystatesent)
this.onreadystatesent();
};
// Abort a request
XHR.prototype.abort =
function() {
// Generic event handler for abortion
this._onabort();
};
// Mapping of native getAllResponseHeaders
XHR.prototype.getAllResponseHeaders =
function() {
return this.req.getAllResponseHeaders();
};
// Mapping of native getResponseHeader
XHR.prototype.getResponseHeader =
function(s) {
return this.req.getResponseHeader(s);
};
// Mapping of native setRequestHeader
XHR.prototype.setRequestHeader =
function(p,v) {
return this.req.setRequestHeader(p,v);
};
// Mostly for debugging
XHR.prototype.toString =
function() {
var s = 'XHR Info\n--------\n';
s += 'rid: ' + this.rid + '\n';
s += 'timeout: ' + this.timeout + '\n';
s += 'retries: ' + this.retries + '\n';
s += 'time: ' + this.time + '\n';
s += 'aborted: ' + this.aborted + '\n';
s += 'method: ' + this.retryParams.method + '\n';
s += 'url: ' + this.retryParams.url + '\n';
s += 'async: ' + this.retryParams.async + '\n';
s += 'username: ' + this.retryParams.username + '\n';
s += 'password: ' + this.retryParams.password + '\n';
s += 'body: ' + this.retryParams.body + '\n';
s += 'readyState: ' + this.req.readyState + '\n';
return s;
};
// Remove an error handler previously set with Function.setErrorHandler
Function.prototype.removeErrorHandler =
function() {
return this.old ? this.old : this;
};
Error.lineSeparator = '\n-----------------------\n';
// Get stacktrace
Error.getStackTrace =
function(f,e,ver) {
var stack = '';
// If IE
if (document.createEventObject) {
var j = 0;
var tmp = dump = null;
var a = null;
//var f = arguments.callee.caller;
while(f) {
stack += 'Stack count: ' + (j++) + '\nFunction: ';
if (ver > 0) {
// Get parameter names
a = f.getArguments();
dump = '';
tmp = '';
// Get values for parameter names
for(var i=0; i<a.length; i++) {
if (!a[i])
a[i] = 'arg' + i;
if (f.arguments && f.arguments[i] !== undefined) {
// If argument is a string add quotes
if (f.arguments[i].constructor == String)
tmp += a[i] + ':\'' + f.arguments[i] + '\', ';
// If argument value is another simple type
else if (f.arguments[i].constructor == Number || f.arguments[i].constructor == Boolean || f.arguments[i] === null)
tmp += a[i] + ':' + f.arguments[i] + ', ';
// Else just log 'type' of object
else if (f.arguments[i].constructor)
tmp += a[i] + ':[' + f.arguments[i].constructor.getName + '], ';
// Event object
else if (f.arguments[i].srcElement !== undefined)
tmp += a[i] + ':window.event , ';
// Unknown - dump entire object
else {
tmp += a[i] + ':n/a , ';
if (ver > 2) {
dump += 'Enumeration of ' + a[i] + ':\n';
for(var p in f.arguments[i])
dump += p + ': ' + f.arguments[i][p] + '\n';
}
}
}
else
tmp += a[i] + ':undefined, ';
}
stack += f.getName() + '(' + tmp.substring(0,tmp.length - 2) + ')\n';
stack += dump;
}
else
stack += f.getName();
// If anonymous or verbosity > 1
if (ver > 1 || (ver > 0 && f.getName() == 'anonymous')) {
stack += f.getBody();
}
// Iterate to next function on callstack
stack += Error.Separator;
f = f.caller;
}
}
// Firefox
else if (e.stack)
stack = e.stack + Error.Separator;
// Opera
else if (e.stacktrace)
stack = e.stacktrace + Error.Separator;
// Safari provides no stacktrace
else
stack = "Unavailable" + Error.Separator;
return "Stacktrace" + Error.Separator + stack;
};
// Create report
Error.report =
function(func, error, ver) {
// Default verbosity level is 1
ver = ver !== undefined ? ver : 1;
var evt = null;
if (func.arguments && func.arguments[0] && func.arguments[0].eventPhase !== undefined)
evt = func.arguments[0];
else if (window.event)
evt = window.event;
var s = '';
try {
s = 'Error info' + Error.Separator;
s += 'Name: ' + error.name + '\n';
s += 'Message: ' + error.message + '\n';
s += 'File: ' + Error.getFilename(error);
s += 'Line: ' + Error.getLinenumber(error) + Error.Separator;
s += Error.getClientInfo(ver);
s += Error.getStackTrace(func,error,ver);
s += Error.getEventInfo(evt,ver);
}
catch(e) {
s = 'An error occured in the error handler itself. To avoid endless recursion the error handler is terminating.' + (s ? '\nDumping available information on initial error:' + Error.Separator + s : '');
}
return 'JSLab Error Report GPLv3 (http://www.jslab.dk/library.error.php)\nVerbosity level: ' + ver + Error.Separator + s + 'End of error report.';
};
// Get file name
Error.getFilename =
function(e) {
var s = '';
// Firefox
if (e.fileName)
s += e.fileName;
// Safari
else if (e.sourceURL)
s += e.sourceURL;
// Opera
else if (e.stacktrace) {
var m = e.message.match(/in\s+(.*?\:\/\/\S+)/m);
if (m && m[1])
s += m[1];
else
s += 'Couldn\'t extract filename from message. See error message for filename.';
}
// IE
else
s += location.href + ' (unreliable)';
return s + '\n';
};
// Get line number
Error.getLinenumber =
function(e) {
var s = '';
// Firefox
if (e.lineNumber)
s += e.lineNumber + '';
// Safari
else if (e.line)
s += e.line;
// IE/Opera
else
s += 'Unavailable. Try message for details.';
return s + '\n';
};
// Get info about client
Error.getClientInfo =
function(ver) {
var s = 'Client' + Error.lineSeparator;
if (ver < 1)
s += 'User agent: ' + window.navigator.userAgent + Error.lineSeparator;
else
s += 'Enumeration of window.navigator:\n' + Error.Enumerate(window.navigator,ver);
return s;
};
// Get info about event
Error.getEventInfo =
function(e,ver) {
var s = 'Event object' + Error.lineSeparator;
// If event was detected
if (e) {
// Get event constructor
if (e.constructor)
s += 'Event class: ' + e + '\n';
else
s += 'Event class: Unavailable\n';
// Get object which fired the event
if (!e.target)
e.target = e.srcElement;
if (ver < 1) {
s += 'Event type: ' + e.type + '\n';
s += 'Event target (tag name): ' + e.target.nodeName + Error.lineSeparator;
}
if (ver > 0) {
// Get target path
var n = e.target;
var tmp = '';
var a = [];
while(n) {
tmp = n.nodeName;
if (n.id)
tmp += '#' + n.id;
if (n.className)
tmp += '.' + n.className.replace(/\s/g,'___') + '';
a.push(tmp);
n = n.parentNode;
}
a.reverse();
a = a.join(' -> ');
s += 'Event target path: ' + a + '\n';
}
if (ver > 1) {
s += 'Enumeration of event target:\n' + Error.Enumerate(e.target,ver);
s += 'Enumeration of Event object:\n' + Error.Enumerate(e,ver);
}
else
s += Error.lineSeparator;
}
else
s += 'Unavailable' + Error.Enumerate(e,ver);
return s;
};
// Enumerate object for error reporting
Error.Enumerate =
function(obj,ver) {
var s = '';
for(var p in obj) {
// Don't include native functions
if (ver > 3)
s += p + ': ' + obj[p] + '\n';
else if (ver > 2 && !(obj[p] && typeof obj[p] == 'function' && /native\s+code/im.test(obj[p])))
s += p + ': ' + obj[p] + '\n';
else if (!(obj[p] && typeof obj[p] == 'function'))
s += p + ': ' + obj[p] + '\n';
}
return s + Error.lineSeparator;
};
// Check whether an element has scrollbars
HTMLElement.prototype.hasScrollbars =
function() {
// Move scroll bars
this.scrollLeft++;
this.scrollTop++;
// Assume no scrollbars
var d = 0;
// Check for x,y
if (this.scrollLeft > 0 && this.scrollTop > 0)
d = 3;
// Check for x
else if (this.scrollLeft > 0)
d = 1;
// Check for y
else if (this.scrollTop > 0)
d = 2;
this.scrollLeft--;
this.scrollTop--;
return d;
};
// Enable/Disable all inputs in a fieldset
HTMLFieldSetElement.prototype.disable =
function(b) {
var c = this.getElementsByTagName('input');
var l = c.length;
for(var i=0; i<l; i++)
c[i].disabled = b;
};
// Return array of nodes by node type
HTMLElement.prototype.getNodesByType =
function getTextNodes(nodeType) {
// For all childnodes in this element
var a = [];
var l = this.childNodes.length;
for(var i=0; i<l; i++) {
// If correct node type include in matches
if (this.childNodes[i].nodeType == nodeType)
a.push(this.childNodes[i]);
// Only recurse on Node.ELEMENT_NODE (1)
if (this.childNodes[i].nodeType == 1)
a = a.concat(this.childNodes[i].getNodesByType(nodeType));
}
return a;
};
// Parse a string to a date. Modelled after the PHP function strtotime
Date.parse =
function(s,rd) {
// If s is not specified
if (!s)
return new Date();
// Trim s
s = s.replace(/^\s+|\s+$/g,"");
// If no reference date is provided the reference is now
if (!rd)
rd = new Date();
// Get keywords used for relative parsing
var t = '';
for(var p in Date.parse.keywords)
t += p + '|';
t = t.substring(0, t.length-1);
var rgx = new RegExp(t,'i');
// Determine to parse absolute or relative
if (rgx.test(s))
return Date.parse.relative(s, rd);
else
return Date.parse.absolute(s, rd);
};
// Parse absolute date
Date.parse.absolute =
function(s, rd) {
var r = null, y = null, m = null, d = null, h = null, mi = null, se = null, ms = null;
// Date format 1972-09-24, 72-9-24, 72-09-24
if (r = s.match(/^(\d{4}|\d{2})-(\d{1,2})-(\d{1,2})/)) {
// Year
y = r[1] * 1;
// Month - JS months is zero based
m = r[2] * 1 - 1;
// Date
d = r[3] * 1;
}
// US date format 9/24/72 (m/d/y)
else if (r = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4}|\d{2})/)) {
// Month
m = r[1] * 1 - 1;
// Date
d = r[2] * 1;
// Year
y = r[3] * 1;
}
// Month written litteraly
// Date format 4 September 1972, 24 Sept 72, 24 Sep 72, 24-sep-72
else if (r = s.match(/^(\d{1,2})(\s*|-)([a-z]{3,})((\s+|-)(\d{4}|\d{2}))?/i)) {
// Date
d = r[1] * 1;
// Month
var rgx = new RegExp('^' + r[3],'i');
for(var i=0; i<11; i++) {
if (rgx.test(Date.nameOfMonths[i])) {
m = i;
break;
}
}
if (m === null)
throw new Error('Date.parse: Unknown month specified litteraly');
// Year
if (r[6])
y = r[6] * 1;
}
// Check date
// Check year
if (y < 100)
y = y > 68 && y < 100 ? 1900 + y : 2000 + y;
else if (y && (y < 1972 || y > 2068))
throw new Error('Date.parse: Year out of range. Valid input is 1972 through 2068');
// Check month
if (m && (m < 0 || m > 11))
throw new Error('Date.parse: Month out of range. Valid input is 01 through 12');
// Check date - don't check for 28/29 in feb etc. Just overflow dates
if (d && (d < 1 || d > 31))
throw new Error('Date.parse: Date out of range. Valid input is 01 through 31');
// Set date
if (y)
rd.setFullYear(y);
if (m !== null)
rd.setMonth(m);
if (d)
rd.setDate(d);
// ***
// Parse time
// ***
// Old regex used to detect timezone - contains am/pm error
//if (r = s.match(/(\d{1,2})\:(\d{1,2})(?:(?:\:(\d{1,2})(?:\.(\d{1,3}))?)(?:(am|pm)?))?(?:([\+-])(\d{2})\:?(\d{2}))?/)) {
if (r = s.match(/(\d{1,2})\:(\d{1,2})(?:(?:\:(\d{1,2})(?:\.(\d{1,3}))?)?(?:\s*(am|pm)?))?/)) {
/*
Timezone
TZ sign is r[6]
TZ hour is r[7]
TZ minutes is r[8]
It doesn't make sense to adjust timezones as the you can't change timezone with JS
*/
// Hour
h = r[1] * 1;
// If am/pm is specified
if (r[5]) {
if (h < 1 || h > 12)
throw new Error('Date.parse: Hour out of range (using am/pm). Valid input is 1 through 12');
// If am
if (r[5] == 'am') {
if (h == 12)
h = 0;
}
// If pm
else {
if (h != 12)
h = h + 12;
}
}
else {
if (h > 24)
throw new Error('Date.parse: Hour out of range. Valid input is 00 through 23');
}
// Minute
if (r[2]) {
mi = r[2] * 1;
if (mi > 59)
throw new Error('Date.parse: Minute out of range. Valid input is 00 through 59');
}
// Seconds
if (r[3]) {
se = r[3] * 1;
if (se > 59)
throw new Error('Date.parse: Seconds out of range. Valid input is 00 through 59');
}
// Msecs
if (r[4]) {
// For whatever reason the multiplication becomes slightly incorrect and have to be ceiled.
ms = Math.ceil(('1.' + r[4]) * 1000) - 1000;
}
}
// Set time
if (h !== null)
rd.setHours(h);
if (mi !== null)
rd.setMinutes(mi);
if (se !== null)
rd.setSeconds(se);
if (ms !== null)
rd.setMilliseconds(ms);
return rd;
};
// Parse relative date
Date.parse.relative =
function(s,rd) {
// If relative date is given as a single word - ie. now, today, tomorrow, yesterday, fortnight
if (/^now|today|tomorrow|fortnight|yesterday$/.test(s)) {
rd.setDate(rd.getDate() + Date.parse.keywords[s]);
}
else {
var mod;
var p = /(last|this|next|first|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|eleventh|twelfth|(?:[\+-]?\d+))\s+([a-z]+)(?:\s+(ago))?/g;
while((r = p.exec(s)) != null) {
// r[1] is relative number or word
// r[2] is time interval
// r[3] is optional 'ago'
// If modifier is not a number 'ago' does not apply
if (/(?:[\+-]?\d+)/.test(r[1]))
mod = !r[3] ? parseInt(r[1]) : -1 * parseInt(r[1]);
else
mod = Date.parse.keywords[r[1]];
// Remove plural s and convert to lower case
r[2] = r[2].replace(/s$/,'').toLowerCase();
// Switch on interval
switch(r[2]) {
case 'year':
rd.setFullYear(rd.getFullYear() + mod);
break;
case 'month':
rd.setMonth(rd.getMonth() + mod);
break;
case 'week':
rd.setDate(rd.getDate() + mod * 7);
break;
case 'day':
rd.setDate(rd.getDate() + mod);
break;
case 'hour':
rd.setHours(rd.getHours() + mod);
break;
case 'minute':
rd.setMinutes(rd.getMinutes() + mod);
break;
case 'second':
rd.setSeconds(rd.getSeconds() + mod);
break;
default:
// Check for weekdays
var rgx = new RegExp('^' + r[2],'i');
for(var i=0; i<7; i++) {
if (rgx.test(Date.nameOfDays[i]))
break;
}
// If weekday exists
if (i < 7) {
var d = rd.getISODay() - 1;
// If weekday is in the future
if (i > d)
rd.setDate(rd.getDate() + (i - d) + ((mod - 1) * 7));
else
rd.setDate(rd.getDate() + (i - d) + ((mod - 1) * 7) + 7);
}
else
throw new Error('Date.parse: Unknown keyword in input');
break;
}
}
}
return rd;
};
// Valid keywords in input string
Date.parse.keywords =
{
// Absolute. Numbers are offsets in days
now: 0,
today: 0,
tomorrow: 1,
fortnight: 14,
yesterday: -1,
// Relative
last: -1,
'this': 1,
next: 1,
// Ordinal numbers
first: 1,
third: 3,
fourth: 4,
fifth: 5,
sixth: 6,
seventh: 7,
eighth: 8,
ninth: 9,
tenth: 10,
eleventh: 11,
twelfth: 12,
// Intervals
second: null,
minute: null,
hour: null,
day: null,
week: null,
month: null,
year: null
};
// Memoize (cache) results of a function call
Function.prototype.memoize =
function() {
// If no calls yet
if (!this.results)
this.results = {};
// Convert arguments object to array
var args = Array.prototype.slice.call(arguments);
// If results exist
if (this.results[args])
return this.results[args];
// Else compute and store result
this.results[args] = this.apply(null, args);
// Return result of original function
return this.results[args];
};
<file_sep>/cmms/src/com/iprosonic/cmms/modules/masters/location/dao/LocationmstDAO.java
package com.iprosonic.cmms.modules.masters.location.dao;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import com.iprosonic.cmms.modules.masters.client.domain.ClientMasterBean;
import com.iprosonic.cmms.modules.masters.location.domain.Locationmst;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
import static org.hibernate.criterion.Example.create;
/**
* A data access object (DAO) providing persistence and search support for
* Locationmst entities. Transaction control of the save(), update() and
* delete() operations can directly support Spring container-managed
* transactions or they can be augmented to handle user-managed Spring
* transactions. Each of these methods provides additional information for how
* to configure it for the desired type of transaction control.
*
* @see org.iprosonic.com.Locationmst
* @author MyEclipse Persistence Tools
*/
public class LocationmstDAO {
private static final Log log = LogFactory.getLog(LocationmstDAO.class);
// property constants
public static final String LOCATION_CD = "locationCd";
public static final String LOCATION_NAME = "locationName";
public static final String COUNTRY_NAME = "countryName";
public static final String STATE_NAME = "stateName";
public static final String CITY_NAME = "cityName";
public static final String DESCRIPTION = "description";
public static final String LOCATION_STATUS = "locationStatus";
public void save(Locationmst transientInstance) {
log.debug("saving Locationmst instance");
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
session.save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
} finally {
session.beginTransaction();
session.close();
}
}
public void delete(Locationmst persistentInstance) {
log.debug("deleting Locationmst instance");
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
session.delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
} finally {
session.beginTransaction();
session.close();
}
}
public Locationmst findById(java.lang.Integer id) {
log.debug("getting Locationmst instance with id: " + id);
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
Locationmst instance = (Locationmst) session.get("org.iprosonic.com.Locationmst", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
} finally {
session.beginTransaction();
session.close();
}
}
public List<Locationmst> findByExample(Locationmst instance) {
log.debug("finding Locationmst instance by example");
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
List<Locationmst> results = (List<Locationmst>) session.createCriteria("org.iprosonic.com.Locationmst").add(create(instance)).list();
log.debug("find by example successful, result size: " + results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
} finally {
session.beginTransaction();
session.close();
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Locationmst instance with property: " + propertyName + ", value: " + value);
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
String queryString = "from Locationmst as model where model." + propertyName + "= ?";
Query queryObject = session.createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
} finally {
session.beginTransaction();
session.close();
}
}
public List<Locationmst> findByLocationCd(Object locationCd) {
return findByProperty(LOCATION_CD, locationCd);
}
public List<Locationmst> findByLocationName(Object locationName) {
return findByProperty(LOCATION_NAME, locationName);
}
public List<Locationmst> findByCountryName(Object countryName) {
return findByProperty(COUNTRY_NAME, countryName);
}
public List<Locationmst> findByStateName(Object stateName) {
return findByProperty(STATE_NAME, stateName);
}
public List<Locationmst> findByCityName(Object cityName) {
return findByProperty(CITY_NAME, cityName);
}
public List<Locationmst> findByDescription(Object description) {
return findByProperty(DESCRIPTION, description);
}
public List<Locationmst> findByLocationStatus(Object locationStatus) {
return findByProperty(LOCATION_STATUS, locationStatus);
}
public List findAll() {
log.debug("finding all Locationmst instances");
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
String queryString = "from Locationmst";
Query queryObject = session.createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
} finally {
session.beginTransaction();
session.close();
}
}
public Locationmst merge(Locationmst detachedInstance) {
log.debug("merging Locationmst instance");
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
Locationmst result = (Locationmst) session.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
} finally {
session.beginTransaction();
session.close();
}
}
public void attachDirty(Locationmst instance) {
log.debug("attaching dirty Locationmst instance");
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
session.saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
} finally {
session.beginTransaction();
session.close();
}
}
public void attachClean(Locationmst instance) {
log.debug("attaching clean Locationmst instance");
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
session.lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
} finally {
session.beginTransaction();
session.close();
}
}
public List<String> getLocationNameList() {
Session session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Locationmst.class);
Projection projection = Projections.distinct(Projections.property("locationName"));
criteria.setProjection(projection);
List<String> list = criteria.list();
session.close();
return list;
}
public List<Locationmst> getLocation() {
// TODO Auto-generated method stub
Session session = HibernateSession.getSessionFactory().openSession();
List<Locationmst> list;
try {
list = (List<Locationmst>) session.createCriteria(Locationmst.class).list();
session.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return list;
}
public boolean getlocationId(int id) {
// TODO Auto-generated method stub
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
Locationmst cl = (Locationmst) session.get(Locationmst.class, id);
if (cl == null) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.getTransaction().commit();
session.close();
}
return true;
}
public void editLocationById(Locationmst bean) {
// TODO Auto-generated method stub
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
session.update(bean);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.getTransaction().commit();
session.close();
}
}
public void saveLocation(Locationmst bean) {
// TODO Auto-generated method stub
Session session = HibernateSession.getSessionFactory().openSession();
session.beginTransaction();
try {
session.save(bean);
log.debug("save is done...");
} catch (Exception e) {
e.printStackTrace();
} finally {
session.getTransaction().commit();
session.flush();
session.close();
}
}
public void deleteLocationById(Locationmst bean) {
// TODO Auto-generated method stub
Locationmst cl = (Locationmst) bean;
Session session = HibernateSession.getSessionFactory().openSession();
session.beginTransaction();
try {
session.delete(cl);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.getTransaction().commit();
session.close();
}
}
public List<String> getUnitCd() {
// TODO Auto-generated method stub
Session session = HibernateSession.getSessionFactory().openSession();
session.beginTransaction();
try {
Criteria cr = session.createCriteria(Locationmst.class);
Projection pro = Projections.distinct(Projections.property("locationCd"));
cr.setProjection(pro);
List<String> list = cr.list();
log.debug("save is done...");
} catch (Exception e) {
e.printStackTrace();
} finally {
session.getTransaction().commit();
session.flush();
session.close();
}
return null;
}
}<file_sep>/cmms/src/com/iprosonic/cmms/modules/masters/user/web/SearchEmployeeAction.java
package com.iprosonic.cmms.modules.masters.user.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.iprosonic.cmms.modules.masters.user.dao.EmployeeDaoImpl;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class SearchEmployeeAction extends ActionSupport implements
ModelDriven<EmployeeBean> {
private static final long serialVersionUID = 1L;
private Map<String, String> accordion;
private EmployeeBean employeeBean = new EmployeeBean();
private List<EmployeeBean> employeeList = new ArrayList<EmployeeBean>();
private EmployeeDaoImpl employeeDao = new EmployeeDaoImpl();
public String execute() {
HttpServletRequest httpServletRequest = ServletActionContext
.getRequest();
String cd = httpServletRequest.getParameter("employeeCd");
String name = httpServletRequest.getParameter("employeeName");
setEmployeeList(employeeDao.listUser(cd, name));
return SUCCESS;
}
public Map<String, String> getAccordion() {
return accordion;
}
public void setEmployeeBean(EmployeeBean employeeBean) {
this.employeeBean = employeeBean;
}
public EmployeeBean getEmployeeBean() {
return employeeBean;
}
public void setEmployeeList(List<EmployeeBean> employeeList) {
this.employeeList = employeeList;
}
public List<EmployeeBean> getEmployeeList() {
return employeeList;
}
@Override
public EmployeeBean getModel() {
return getEmployeeBean();
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/masters/user/web/InitEmployeeMstAction.java
package com.iprosonic.cmms.modules.masters.user.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.iprosonic.cmms.modules.masters.user.dao.EmployeeDaoImpl;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
import com.opensymphony.xwork2.ActionSupport;
public class InitEmployeeMstAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private Map<String, String> accordion;
private EmployeeBean employeeBean = new EmployeeBean();
private List<EmployeeBean> employeeList = new ArrayList<EmployeeBean>();
private EmployeeDaoImpl employeeDao = new EmployeeDaoImpl();
public void validate() {
}
public String execute() {
setEmployeeList(employeeDao.listUser());
return SUCCESS;
}
public Map<String, String> getAccordion() {
return accordion;
}
public void setEmployeeBean(EmployeeBean employeeBean) {
this.employeeBean = employeeBean;
}
public EmployeeBean getEmployeeBean() {
return employeeBean;
}
public void setEmployeeList(List<EmployeeBean> employeeList) {
this.employeeList = employeeList;
}
public List<EmployeeBean> getEmployeeList() {
return employeeList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/utility/DownloadExcelUtil.java
package com.iprosonic.cmms.pjcommons.utility;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobBean;
import com.iprosonic.cmms.modules.job.transactions.job.service.DownloadWasService;
public class DownloadExcelUtil {
public static void downloadExcelUtil(ServletContext context,
HttpServletResponse response, String jobNo) throws Exception {
File file = null;
MyPropertiesReader myPropertiesReader = new MyPropertiesReader();
String downloadPath = myPropertiesReader.getFilePath("downloadPath");
String filePath = context.getRealPath(downloadPath);
filePath = filePath + File.separator + jobNo + ".xls";
System.out.println("**********filePath********"+filePath);
DownloadWasService.generateWas(jobNo, filePath);
ServletOutputStream out = null;
FileInputStream fis = null;
file = new File(filePath);
fis = new FileInputStream(file);
out = response.getOutputStream();
byte[] outputByte = new byte[(int) file.length()];
while (fis.read(outputByte, 0, (int) file.length()) != -1) {
out.write(outputByte, 0, (int) file.length());
}
}
public static void downloadExcelAllJobUtil(ServletContext context,
HttpServletResponse response,List jobList) throws Exception {
File file = null;
MyPropertiesReader myPropertiesReader = new MyPropertiesReader();
String downloadPath = myPropertiesReader.getFilePath("downloadPath");
String filePath = context.getRealPath(downloadPath);
filePath = filePath + File.separator+"AllJobExcel.xls";
System.out.println("**********filePath********"+filePath);
DownloadWasService.genrateAllWas(jobList,filePath);
Iterator itr=jobList.iterator();
while (itr.hasNext()) {
JobBean object = (JobBean) itr.next();
}
ServletOutputStream out = null;
FileInputStream fis = null;
file = new File(filePath);
fis = new FileInputStream(file);
out = response.getOutputStream();
byte[] outputByte = new byte[(int) file.length()];
while (fis.read(outputByte, 0, (int) file.length()) != -1) {
out.write(outputByte, 0, (int) file.length());
}
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/dao/JobRunDaoImpl.java
package com.iprosonic.cmms.modules.job.transactions.job.dao;
import java.text.ParseException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRigBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRunBean;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
import com.iprosonic.cmms.pjcommons.utility.DateUtil;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class JobRunDaoImpl{
private Session session;
public JobRunBean getRunByNo(String runNo) throws Exception {
JobRunBean jobRunBean = null;
Session session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(JobRunBean.class);
criteria.add(Restrictions.like("runNo", runNo));
@SuppressWarnings("unchecked")
Iterator<JobRunBean> itr = criteria.list().iterator();
while (itr.hasNext()) {
jobRunBean = itr.next();
}
session.close();
HibernateSession.shoutDown();
return jobRunBean;
}
public JobRunBean getRunByJobNo(String jobNo) throws Exception {
JobRunBean jobRunBean = null;
session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(JobRunBean.class);
criteria.add(Restrictions.like("jobNo", jobNo));
criteria.addOrder(Order.desc("runNo"));
@SuppressWarnings("unchecked")
Iterator<JobRunBean> itr = criteria.list().iterator();
while (itr.hasNext()) {
jobRunBean = itr.next();
}
session.close();
HibernateSession.shoutDown();
return jobRunBean;
}
public void updateJobRun(JobRunBean jobRunBean) {
session = HibernateSession.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.update(jobRunBean);
transaction.commit();
session.flush();
// session.evict(jobRunBean);
session.flush();
session.clear();
session.close();
}
public String getJobBonusReport(String fromDate, String toDate, String jobNo) {
int i = 0;
String width = "100%";
JobRigBean jobRigBean = null;
String totalOpTime = "";
StringBuffer stringBuffer = new StringBuffer();
Session session = HibernateSession.getSessionFactory().openSession();
stringBuffer
.append("<div align='center' style='width: auto; height:600px;'>");
stringBuffer
.append("<div class='CSSTableGenerator' style='width: 90%; height: auto;'>");
stringBuffer.append("<table>");
stringBuffer.append("<tr>");
stringBuffer.append("<td>Job No</td>");
stringBuffer.append("<td>Rig No</td>");
stringBuffer.append("<td>OP Time</td>");
stringBuffer.append("<td>Empoyee</td>");
stringBuffer.append("<td>Role</td>");
stringBuffer.append("</tr>");
Set<JobRigBean> jobRigBeanSet = null;
Criteria jobCriteria = session.createCriteria(JobBean.class);
jobCriteria.add(Restrictions.ge("jobDate", fromDate));
jobCriteria.add(Restrictions.le("jobDate", toDate));
if (!jobNo.equalsIgnoreCase("-Select-")) {
jobCriteria.add(Restrictions.like("jobNo", jobNo));
}
Integer hours = 0;
Integer minutes = 0;
String oipTime = null;
List<JobBean> jobList = jobCriteria.list();
Iterator<JobBean> jobItr = jobList.iterator();
while (jobItr.hasNext()) {
jobRigBeanSet = jobItr.next().getJobRigBean();
Iterator<JobRigBean> jobRigItr = jobRigBeanSet.iterator();
while (jobRigItr.hasNext()) {
jobRigBean = jobRigItr.next();
jobNo = jobRigBean.getJobNo();
String ru = jobRigBean.getRigDownStart();
String rd = jobRigBean.getRigDownEnd();
try {
totalOpTime = DateUtil.getTotalOpTime(ru, rd);
hours += Integer.parseInt(totalOpTime.split(";")[0]);
minutes = +Integer.parseInt(totalOpTime.split(";")[1]);
} catch (ParseException e) {
e.printStackTrace();
}
oipTime = jobRigBean.getOpTime();
String rigNo = jobRigBean.getRigNo();
Criteria jobRunCriteria = session
.createCriteria(JobRunBean.class);
jobRunCriteria.add(Restrictions.like("rigNo", rigNo));
@SuppressWarnings("unchecked")
Iterator<JobRunBean> jobRunItr = jobRunCriteria.list()
.iterator();
while (jobRunItr.hasNext()) {
JobRunBean jobRunBean = jobRunItr.next();
String userSortName = jobRunBean.getEngi()
+ jobRunBean.getCrew();
Set<EmployeeBean> userSet = getUserList(userSortName);
getUserList(userSortName);
for (EmployeeBean emp : userSet) {
stringBuffer.append("<tr>");
stringBuffer.append("<td>" + jobNo + "</td>");
stringBuffer.append("<td>" + rigNo + "</td>");
stringBuffer.append("<td>" + oipTime + "</td>");
stringBuffer.append("<td>" + emp.getEmployeeShortName()
+ "</td>");
stringBuffer.append("<td>" + emp.getRoleCd() + "</td>");
stringBuffer.append("</tr>");
}
}
}
}
stringBuffer.append("<tr>");
stringBuffer.append("<td></td>");
stringBuffer.append("<td></td>");
stringBuffer.append("<td>Gross Total time " + hours + "Hrs," + minutes
+ "Mins</td>");
stringBuffer.append("<td></td>");
stringBuffer.append("<td></td>");
stringBuffer.append("</tr>");
stringBuffer.append("</div>");
stringBuffer.append("</div>");
stringBuffer.append("</table>");
session.close();
HibernateSession.shoutDown();
return stringBuffer.toString();
}
@SuppressWarnings("unchecked")
public Set<EmployeeBean> getUserList(String employeeShortName) {
Set<EmployeeBean> set = new HashSet<EmployeeBean>();
String[] crewArr = employeeShortName.split(";");
Session session = HibernateSession.getSessionFactory().openSession();
for (String empSortName : crewArr) {
Criteria criteria = session.createCriteria(EmployeeBean.class);
criteria.add(Restrictions.like("employeeShortName", empSortName));
Iterator<EmployeeBean> itr = criteria.list().iterator();
while (itr.hasNext()) {
EmployeeBean employeeBean = itr.next();
set.add(employeeBean);
}
}
return set;
}
public Integer getRunCount(String jobNo) {
Integer size = 0;
Session session = HibernateSession.getSessionFactory().openSession();
size = session.createCriteria(JobRunBean.class)
.add(Restrictions.like("jobNo", jobNo)).list().size();
return size;
}
public JobRunBean getLastRunNo(String jobNo){
JobRunBean jobRunBean = null;
session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(JobRunBean.class);
criteria.add(Restrictions.like("jobNo", jobNo));
criteria.addOrder(Order.desc("runNo"));
jobRunBean = (JobRunBean) criteria.list().get(0);
session.close();
HibernateSession.shoutDown();
return jobRunBean;
}
public List<JobRunBean> getRunList(){
session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(JobRunBean.class);
List l=criteria.list();
session.close();
HibernateSession.shoutDown();
return l;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/web/DeleteJob.java
package com.iprosonic.cmms.modules.job.transactions.job.web;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobBean;
import com.iprosonic.cmms.modules.job.transactions.job.service.DatabaseConnection;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
import com.mysql.jdbc.PreparedStatement;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DeleteJob extends ActionSupport {
private static final long serialVersionUID = 1L;
public String execute() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse responce = (HttpServletResponse) ActionContext
.getContext().get(ServletActionContext.HTTP_RESPONSE);
Map session = (Map) ActionContext.getContext().get("session");
String jobNo = request.getParameter("jobNo");
Session hibernateSession= HibernateSession.getSessionFactory().openSession();
try {
hibernateSession.beginTransaction();
JobBean jobBean=(JobBean) hibernateSession.load(JobBean.class, jobNo);
jobBean.setJobStatus("DELETED");
hibernateSession.saveOrUpdate(jobBean);
hibernateSession.getTransaction().commit();
String message = "Job No. " + jobNo + " deleted succefully.";
request.setAttribute("message", message);
} catch (Exception e) {
// TODO Auto-generated catch block
hibernateSession.getTransaction().rollback();
request.setAttribute("message", "Error : "+e.getMessage());
}finally{
if(hibernateSession.isOpen()){
hibernateSession.close();
}
}
return SUCCESS;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/valuelist/SectionSrNoStrAction.java
package com.iprosonic.cmms.pjcommons.valuelist;
import java.util.Collections;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.cpi.masters.assets.domain.AssetBean;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class SectionSrNoStrAction {
public String getSectionSrNo(String sectionName, String type) {
List<String> sectionSrNoList = null;
Session session = null;
String listString = "-Select-:";
Criteria criteria = null;
try {
session = HibernateSession.getSessionFactory().openSession();
if (type.equalsIgnoreCase("getSectionSerialNo1")) {
criteria = session.createCriteria(AssetBean.class);
criteria.add(Restrictions.like("sectionCd", sectionName));
criteria.setProjection(Projections.distinct(Projections.property("sectionSerialNo")));
sectionSrNoList = criteria.list();
}
for (String assetSr1 : sectionSrNoList) {
listString += assetSr1 + ":";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return listString;
}
public String getSectionSrNo(String sectionSerialNo) {
List<String> sectionSrNoList = null;
Session session = null;
String listString = "-Select-:";
Criteria criteria = null;
try {
session = HibernateSession.getSessionFactory().openSession();
criteria = session.createCriteria(AssetBean.class);
criteria.add(Restrictions.like("assetSerialNo", sectionSerialNo));
criteria.setProjection(Projections.distinct(Projections.property("sectionSerialNo")));
sectionSrNoList = criteria.list();
Collections.sort(sectionSrNoList);
for (String assetSr1 : sectionSrNoList) {
listString += assetSr1 + ":";
}
} catch (Exception e) {
}
return listString;
}
public List<String> getSectionSrNoList() {
List<String> sectionSrNoList = null;
Session session = null;
Criteria criteria = null;
try {
session = HibernateSession.getSessionFactory().openSession();
criteria = session.createCriteria(CpiBean.class);
criteria.setProjection(Projections.distinct(Projections.property("sectionSerialNo")));
sectionSrNoList = criteria.list();
System.out.println("Serial no." + sectionSrNoList);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return sectionSrNoList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/dao/JobRigDaoImpl.java
package com.iprosonic.cmms.modules.job.transactions.job.dao;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRigBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class JobRigDaoImpl {
private Session session;
private Transaction transaction;
public void updateJobRig(final JobRigBean jobRigBean) {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
JobRigBean rigBean = (JobRigBean) session.get(JobRigBean.class,
jobRigBean.getRigNo());
rigBean.setRigUpStart(jobRigBean.getRigUpStart());
rigBean.setRigUpEnd(jobRigBean.getRigUpEnd());
rigBean.setRigDownStart(jobRigBean.getRigDownStart());
rigBean.setRigDownEnd(jobRigBean.getRigDownEnd());
session.update(rigBean);
transaction.commit();
session.flush();
session.clear();
session.close();
}
public JobRigBean getRigByNo(String no) throws Exception {
session = HibernateSession.getSessionFactory().openSession();
JobRigBean jobRigBean = null;
Criteria criteria = session.createCriteria(JobRigBean.class);
criteria.add(Restrictions.like("rigNo", no));
@SuppressWarnings("unchecked")
Iterator<JobRigBean> itr = criteria.list().iterator();
while (itr.hasNext()) {
jobRigBean = itr.next();
}
return jobRigBean;
}
public JobRigBean getRigByJobNo(String jobNo) throws Exception {
session = HibernateSession.getSessionFactory().openSession();
JobRigBean jobRigBean = null;
Criteria criteria = session.createCriteria(JobRigBean.class);
criteria.add(Restrictions.like("jobNo", jobNo));
criteria.addOrder(Order.desc("rigNo"));
@SuppressWarnings("unchecked")
Iterator<JobRigBean> itr = criteria.list().iterator();
while (itr.hasNext()) {
jobRigBean = itr.next();
}
return jobRigBean;
}
public List<JobRigBean> getRigList() throws Exception {
session = HibernateSession.getSessionFactory().openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(JobRigBean.class);
List l=criteria.list();
session.getTransaction().commit();
session.close();
return l;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/valuelist/ExplosivePart.java
package com.iprosonic.cmms.pjcommons.valuelist;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.classic.Session;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.masters.part.domain.PartMstBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateAnnotationSession;
public class ExplosivePart {
public static List<String> getExplosivePart() {
Session session = HibernateAnnotationSession.getSessionFactory()
.openSession();
Criteria criteria = session.createCriteria(PartMstBean.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("partCd"));
criteria.add(Restrictions.like("l3CategoryCd", "Explosives"));
criteria.setProjection(projectionList);
List<String> list = criteria.list();
session.close();
HibernateAnnotationSession.shoutDown();
return list;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/valuelist/ServiceNameStrAction.java
package com.iprosonic.cmms.pjcommons.valuelist;
import java.sql.*;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.job.masters.service.domain.ServiceMstBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class ServiceNameStrAction {
public static String getServiceName(String serviceType) {
Session session = null;
Transaction transaction = null;
List<String> list = null;
String listString = "-Select-:";
Criteria criteria = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
criteria = session.createCriteria(ServiceMstBean.class);
criteria.add(Restrictions.like("serviceType", serviceType));
criteria.setProjection(Projections.distinct(Projections
.property("serviceName")));
criteria.addOrder(Order.asc("serviceName"));
list = criteria.list();
for (String s : list) {
listString += s + ":";
}
transaction.commit();
} catch (HibernateException e) {
if (transaction.wasCommitted()) {
transaction.rollback();
e.printStackTrace();
}
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return listString;
//========================= JDBC Search In Database ====================================
/*String listString = "-Select-:";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wascpi_demo","root","password");
PreparedStatement pst=conn.prepareStatement("select distinct serviceName from serviceMaster where serviceType='"+serviceType+"'");
ResultSet rs=pst.executeQuery();
while(rs.next()){
listString += rs.getString(1) + ":";
}
conn.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return listString;
*/
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/masters/group/domain/CpiGroupBean.java
package com.iprosonic.cmms.modules.cpi.masters.group.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "cpigroupmst")
public class CpiGroupBean {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "groupCd")
private String groupCd;
@Column(name = "groupCdName")
private String groupCdName;
@Column(name = "subGroupCd")
private String subGroupCd;
@Column(name = "subGroupName")
private String subGroupName;
public String getGroupCd() {
return groupCd;
}
public void setGroupCd(String groupCd) {
this.groupCd = groupCd;
}
public String getGroupCdName() {
return groupCdName;
}
public void setGroupCdName(String groupCdName) {
this.groupCdName = groupCdName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubGroupCd() {
return subGroupCd;
}
public void setSubGroupCd(String subGroupCd) {
this.subGroupCd = subGroupCd;
}
public String getSubGroupName() {
return subGroupName;
}
public void setSubGroupName(String subGroupName) {
this.subGroupName = subGroupName;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/action/ErrorAction.java
package com.iprosonic.cmms.pjcommons.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;
public class ErrorAction extends ActionSupport {
private static final long serialVersionUID = 1L;
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
String message = (String) request.getAttribute("message");
request.setAttribute("message", message);
ValueStack stack = ActionContext.getContext().getValueStack();
Map<String, Object> context = new HashMap<String, Object>();
context.put("message", message);
stack.push(context);
return SUCCESS;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/service/EmpCompare.java
package com.iprosonic.cmms.modules.job.transactions.job.service;
import java.util.Comparator;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
public class EmpCompare implements Comparator<EmployeeBean> {
@Override
public int compare(EmployeeBean o1, EmployeeBean o2) {
// TODO Auto-generated method stub
String name1=o1.getEmployeeName();
String name2=o2.getEmployeeName();
int coms=name1.compareTo(name2);
if(coms!=0){
return coms;
}else{
String code1=o1.getEmployeeShortName();
String code2=o2.getEmployeeShortName();
return code1.compareTo(code2);
}
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/action/DownloadExcelAction.java
package com.iprosonic.cmms.pjcommons.action;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.iprosonic.cmms.pjcommons.utility.DownloadExcelUtil;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadExcelAction extends ActionSupport {
private static final long serialVersionUID = 1L;
public String downloadExcel() {
HttpServletRequest request=null;
try
{
ServletContext context = ServletActionContext.getServletContext();
HttpServletResponse response = ServletActionContext.getResponse();
request = ServletActionContext.getRequest();
String jobNo= request.getParameter("jobNo").toString();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="+jobNo + ".xls");
DownloadExcelUtil.downloadExcelUtil(context, response, jobNo);
}
catch (Exception e) {
String message="Problem is on the server";
request.setAttribute("message", message);
e.printStackTrace();
return ERROR;
}
return null;
}
public String downloadAllJob() {
HttpServletRequest request=null;
try
{
ServletContext context = ServletActionContext.getServletContext();
HttpServletResponse response = ServletActionContext.getResponse();
request = ServletActionContext.getRequest();
HttpSession session=request.getSession(false);
List jobList=(List) session.getAttribute("jobList");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=AllJobExcel.xls");
DownloadExcelUtil.downloadExcelAllJobUtil(context, response,jobList);
}
catch (Exception e) {
String message="Problem is on the server";
request.setAttribute("message", message);
e.printStackTrace();
return ERROR;
}
return null;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/transactions/cpi/service/SaveOrUpdateCPIService.java
package com.iprosonic.cmms.modules.cpi.transactions.cpi.service;
import com.iprosonic.cmms.modules.masters.user.dao.EmployeeDaoImpl;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
public class SaveOrUpdateCPIService {
private EmployeeDaoImpl userDAO = new EmployeeDaoImpl();
public String saveOrUpdate(EmployeeBean user) {
try {
userDAO.saveOrUpdateEmployee(user);
} catch (Exception e) {
e.printStackTrace();
}
return "SUCCESS";
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/service/EditJobService.java
package com.iprosonic.cmms.modules.job.transactions.job.service;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobExplBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRigBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRunBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobServiceBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class EditJobService {
public String[] getValueRigToExplosive(String jobNo, String role) {
String[] rigToExplosive = new String[5];
StringBuffer stringBuffer = new StringBuffer();
Session session = HibernateSession.getSessionFactory().openSession();
stringBuffer.append("<table id='datatable'>");
Criteria jobRigCriteria = session.createCriteria(JobRigBean.class);
jobRigCriteria.add(Restrictions.eq("jobNo", jobNo));
List<JobRigBean> list = jobRigCriteria.list();
Iterator<JobRigBean> jobRigItr = list.iterator();
Integer rigCount = list.size();
Integer runCount = 0;
Integer serviceCount = 0;
Integer explosiveCount = 0;
int i = 0;
String width = "80px";
String width_disabled = "80px";
String width_date = "110px";
while (jobRigItr.hasNext()) {
JobRigBean jobRigBean = jobRigItr.next();
String rigNo = jobRigBean.getRigNo();
stringBuffer.append("<tr id='" + jobRigBean.getRigNo()
+ "' class='rig'>");
stringBuffer.append("<td><input type ='radio' name='chk1' "
+ "value= '" + jobRigBean.getRigNo() + "' id='"
+ jobRigBean.getRigNo() + "' />");
i++;
stringBuffer.append("<td>" + "<input id='" + jobRigBean.getRigNo()
+ "' style='width:" + width_disabled
+ "' type='text' readonly='true' value='"
+ jobRigBean.getRigNo() + "'</input></td>");
stringBuffer.append("<td>Rig Up Start</td>");
stringBuffer
.append("<td><input type='text' readOnly='true' style='width:"
+ width_date
+ "' id='rigUpStart' value='"
+ jobRigBean.getRigUpStart() + "'</input></td>");
stringBuffer.append("<td>Rig Up End</td>");
stringBuffer
.append("<td><input type='text' readOnly='true' style='width:"
+ width_date
+ "' id='rigUpEnd' value='"
+ jobRigBean.getRigUpEnd() + "'</input></td>");
stringBuffer.append("<td>Rig Down Start</td>");
stringBuffer
.append("<td><input type='text' readOnly='true' style='width:"
+ width_date
+ "' id='rigDownStart' value='"
+ jobRigBean.getRigDownStart() + "'</input></td>");
stringBuffer.append("<td>Rig Down End</td>");
stringBuffer
.append("<td><input type='text' readOnly='true' style='width:"
+ width_date
+ "' id='rigDownEnd' value='"
+ jobRigBean.getRigDownEnd() + "'</input></td>");
stringBuffer.append("</tr>");
Criteria jobRunCriteria = session.createCriteria(JobRunBean.class);
jobRunCriteria.add(Restrictions.eq("rigNo", rigNo));
Iterator<JobRunBean> jobRunItr = jobRunCriteria.list().iterator();
while (jobRunItr.hasNext()) {
runCount++;
JobRunBean jobRunBean = jobRunItr.next();
String runNo = jobRunBean.getRunNo();
stringBuffer.append("<tr id='" + i + "' class='run'>");
stringBuffer.append("<td><input type ='radio'"
+ "name='chk1' value= '" + jobRunBean.getRunNo()
+ "' id='" + jobRunBean.getRunNo() + "' />");
i++;
stringBuffer.append("<td style='visibility:visible'>"
+ "<input id='jobNo' type='text' style='width:"
+ width_disabled + "' readonly='true' value='"
+ jobRunBean.getRunNo() + "'</input></td>");
stringBuffer.append("<td>BHT</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobRunBean.getBht() + "></input></td>");
stringBuffer.append("<td>Operating time start</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width_date
+ "' type='text' value='"
+ jobRunBean.getRih() + "'</input></td>");
stringBuffer.append("<td>Operating time stop</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width_date
+ "' type='text' value='"
+ jobRunBean.getPooh() + "'</input></td>");
stringBuffer.append("<td>OT</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobRunBean.getOt() + "'</input></td>");
stringBuffer.append("<td>WT</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobRunBean.getWt() + "'</input></td>");
stringBuffer.append("</tr>");
//-------------------------------------------SERVICE--------------------------------------------------------
Query q=session.createQuery("from JobServiceBean where runNo=:run");
q.setParameter("run", runNo);
Iterator<JobServiceBean> jobServiceItr = q.list().iterator();
while (jobServiceItr.hasNext()) {
JobServiceBean jobServiceBean = jobServiceItr.next();
serviceCount++;
String serviceNo = jobServiceBean.getServiceNo();
stringBuffer.append("<tr id='" + i + "' class='ser'>");
stringBuffer.append("<td><input type ='radio' name='chk1'"
+ " value= '" + jobServiceBean.getServiceNo()
+ "' id='" + jobServiceBean.getServiceNo()
+ "' />");
i++;
stringBuffer.append("<td style='visibility: visible'>"
+ "<input id='jobNo' style='width:"
+ width_disabled
+ "' type='text' readonly='true' value='"
+ jobServiceBean.getServiceNo() + "'</input></td>");
stringBuffer.append("<td>Service Type</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobServiceBean.getServiceType()
+ "></input></td>");
stringBuffer.append("<td>Service Name</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobServiceBean.getServiceName()
+ "></input></td>");
stringBuffer.append("<td>Loss Time</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getLossTime()
+ "'></input></td>");
stringBuffer.append("</tr>");
stringBuffer.append("<tr class='ser'>");
stringBuffer.append("<td>Deepest Depth</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobServiceBean.getDeepestDepth()
+ "></input></td>");
stringBuffer.append("<td>Meterage Logged</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobServiceBean.getMeterageLogged()
+ "></input></td>");
stringBuffer.append("<td>Rev($)</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getRev()
+ "'</input></td>");
stringBuffer.append("<td>Failure Group</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getFailureGroup()
+ "'</input></td>");
stringBuffer.append("</tr>");
stringBuffer.append("<tr class='ser'>");
stringBuffer.append("<td>Pretest Count</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getPretestCount()
+ "'</input></td>");
stringBuffer.append("<td>PumpOut Time</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getPumpOutTime()
+ "'</input></td>");
stringBuffer.append("<td>DryTest Count</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getDryTestCount()
+ "'</input></td>");
stringBuffer.append("<td>Pvt Sample</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getPvtSample()
+ "'</input></td>");
stringBuffer.append("<td>Normal Sample</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getNormalSample()
+ "'</input></td>");
stringBuffer.append("</tr>");
stringBuffer.append("<tr class='ser'>");
stringBuffer.append("<td>Level Count</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getLevelCount()
+ "'</input></td>");
stringBuffer.append("<td>Cross Count</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getCoresCount()
+ "'</input></td>");
stringBuffer.append("</tr>");
stringBuffer.append("<tr class='ser'>");
stringBuffer.append("<td>Gun Size</td>");
stringBuffer
.append("<td><input id='gunSize' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getGunSize()
+ "'</input></td>");
stringBuffer.append("<td>SPF</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getSpf()
+ "'</input></td>");
stringBuffer.append("<td>Meterage Perforated</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobServiceBean.getMeteragePerforated()
+ "></input></td>");
stringBuffer.append("<td>Surface Pressure</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getSurfacePressure()
+ "'</input></td>");
stringBuffer.append("</tr>");
stringBuffer.append("<tr class='ser'>");
stringBuffer.append("<td>Ch Run</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobServiceBean.getChruns()
+ "></input></td>");
stringBuffer.append("<td>Ch MisRuns</td>");
stringBuffer
.append("<td><input id='chMisRuns' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getChmisRuns()
+ "'</input></td>");
stringBuffer.append("<td>TCPMissRun</td>");
stringBuffer
.append("<td><input id='tcpmissrun' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getTcpmissrun()
+ "'</input></td>");
stringBuffer.append("</tr>");
stringBuffer.append("<tr class='ser'>");
stringBuffer.append("<td>Asset Code</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobServiceBean.getAssetCd()
+ "></input></td>");
stringBuffer.append("<td>Serial No</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobServiceBean.getSerialNo()
+ "></input></td>");
stringBuffer.append("<td>Engi</td>");
stringBuffer
.append("<td><input id='engi' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getEngi()
+ "'</input></td>");
stringBuffer.append("<td>Crew</td>");
stringBuffer
.append("<td><input id='crew' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getCrew()
+ "'</input></td>");
stringBuffer.append("<td>Remarks</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getRemarks()
+ "'</input></td>");
stringBuffer.append("</tr>");
stringBuffer.append("<tr class='ser'>");
stringBuffer.append("<td>Log Send From Base</td>");
stringBuffer
.append("<td><input id='spf' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getLogSendFromBase()
+ "'</input></td>");
stringBuffer.append("<td>Log Recieve at HO</td>");
stringBuffer
.append("<td><input id='logRcieveAtHo' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getLogRcieveAtHo()
+ "'</input></td>");
/* stringBuffer.append("</tr>");
stringBuffer.append("<tr class='ser'>");*/
// if (role.equalsIgnoreCase("FSQC"))
stringBuffer.append("<td>LqaDoneDate</td>");
stringBuffer
.append("<td><input id='lquDoneDate' readOnly='true' style='width:"
+ width_date
+ "' type='text' value='"
+ jobServiceBean.getLqaDoneDate()
+ "'</input></td>");
stringBuffer.append("<td>Lqa Technical</td>");
stringBuffer
.append("<td><input id='lquDoneDate' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getLqaTechnical()
+ "'</input></td>");
stringBuffer.append("<td>Lqa Presentation</td>");
stringBuffer
.append("<td><input id='lquDoneDate' readOnly='true' style='width:"
+ width
+ "' type='text' value='"
+ jobServiceBean.getLqaPresentation()
+ "'</input></td>");
stringBuffer.append("</tr><tr><td colspan='33'><hr></td></tr>");
// -----------------------------------Explosives-------------------------------------------------------------------
Query q1=session.createQuery("from JobExplBean where serviceNo=:service");
q1.setParameter("service", serviceNo);
@SuppressWarnings("unchecked")
Iterator<JobExplBean> jobExplItr = q1.list().iterator();
while (jobExplItr.hasNext()) {
JobExplBean jobExplBean = jobExplItr.next();
explosiveCount++;
stringBuffer.append("<tr id='" + i + "' class='expl'>");
stringBuffer.append("<td><input type ='radio' name='chk1' "+ "value='" + jobExplBean.getExplNo()
+ "' id='"+ jobExplBean.getExplNo() + "' />");
i++;
stringBuffer
.append("<td style='visibility: visibility'>"
+ "<input id='jobNo' style='width:"
+ width
+ "'type='text' readonly='true' value='"
+ jobExplBean.getExplNo()
+ "'</input></td>");
stringBuffer.append("<td>PartCd</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobExplBean.getPartCd()
+ "></input></td>");
stringBuffer.append("<td>Qty</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobExplBean.getQty()
+ "></input></td>");
stringBuffer.append("<td>uom</td>");
stringBuffer
.append("<td><input id='jobNo' readOnly='true' style='width:"
+ width
+ "' type='text' value="
+ jobExplBean.getUom()
+ "></input></td>");
stringBuffer.append("</tr>");
}
}
}
}
stringBuffer.append("</table>");
rigToExplosive[0] = stringBuffer.toString();
rigToExplosive[1] = String.valueOf(rigCount);
rigToExplosive[2] = String.valueOf(runCount);
rigToExplosive[3] = String.valueOf(serviceCount);
rigToExplosive[4] = String.valueOf(explosiveCount);
session.close();
HibernateSession.shoutDown();
return rigToExplosive;
}
}
<file_sep>/cmms/WebContent/js/job/updateJobService.js
var abled_cell_backround_color = "yellow";
var disabled_cell_backround_color = "#D3E397";
var role = "NA";
function setRole(roleSess) {
role = roleSess;
}
function disableField() {
if (role == "FSQC") {
document.getElementById("logRcieveAtHo").readOnly=false;
document.getElementById("lqaDoneDate").readOnly=false;
document.getElementById("lqaTechnical").readOnly=false;
document.getElementById("lqaPresentation").readOnly=false;
document.getElementById("lqaPresentation").readOnly=false;
}
else {
document.getElementById("logRcieveAtHo").readOnly=true;
document.getElementById("lqaDoneDate").readOnly=true;
document.getElementById("lqaTechnical").readOnly=true;
document.getElementById("lqaPresentation").readOnly=false;
//document.getElementById("logSendFromBase").readOnly=true;
}
}
function disable_fields_in_service(obj) {
var serviceName = obj.value;
var data=document.getElementById("serviceType");
var ser_id = obj.id;
var fieldsId = ";";
var fields = ";";
var inputs = document.getElementsByTagName("input");
for ( var i = 0; i < inputs.length; i++) {
if (inputs[i].getAttribute('type') == 'text') {
fields = inputs[i].getAttribute('name');
if (fields != "lossTime" && fields != "serialNo"&& fields != "assetCd") {
fieldsId += inputs[i].getAttribute('name') + ";";
}
}
}
url = 'GetListAction.action?param=getServiceFlg&serviceName='
+ serviceName;
$.post(
url,
function(results) {
$('.result').html(results);
var map_to_enable_fields_in_ser = new Array();
map_to_enable_fields_in_ser = results.split(";");
fieldIdArr = fieldsId.split(";");
for ( var i = 1; i < 24; i++) {
if (map_to_enable_fields_in_ser[i] == "Y") {
document.getElementById(fieldIdArr[i]).readOnly=false;
document.getElementById(fieldIdArr[i]).style.backgroundColor = abled_cell_backround_color;
document.getElementById(fieldIdArr[i]).style.borderColor = abled_cell_border_color;
} else {
document.getElementById(fieldIdArr[i]).style.backgroundColor = disabled_cell_backround_color;
document.getElementById(fieldIdArr[i]).style.borderColor = disabled_cell_border_color;
document.getElementById(fieldIdArr[i]).readOnly=true;
}
}
});
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/domain/JobWellBean.java
package com.iprosonic.cmms.modules.job.transactions.job.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
@Entity
@Table(name = "jobswell")
public class JobWellBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 8388314243817471040L;
@Id
@Column(name = "jobNo")
private String jobNo;
@OneToOne
@PrimaryKeyJoinColumn
private JobBean jobBean;
@Column(name = "holeSize")
private String holeSize;
@Column(name = "field")
private String field;
@Column(name = "latitude_d")
private String latitude_d;
@Column(name = "latitude_m")
private String latitude_m;
@Column(name = "latitude_s")
private String latitude_s;
@Column(name = "longitude_d")
private String longitude_d;
@Column(name = "longitude_m")
private String longitude_m;
@Column(name = "longitude_s")
private String longitude_s;
@Column(name = "kb")
private String kb;
@Column(name = "dl")
private String dl;
@Column(name = "td")
private String td;
@Column(name = "casingSize")
private String casingSize;
@Column(name = "casingSizeDepth")
private String casingSizeDepth;
@Column(name = "rigName")
private String rigName;
@Column(name = "tdDriller")
private String tdDriller;
@Column(name = "csDriller")
private String csDriller;
@Column(name = "weekPoint")
private String weekPoint;
@Column(name = "bitSize")
private String bitSize;
@Column(name = "deviation")
private String deviation;
@Column(name = "startCirculation")
private String startCirculation;
@Column(name = "stopCirculation")
private String stopCirculation;
@Column(name = "gf")
private String gf;
@Column(name = "density")
private String density;
@Column(name = "viscosity")
private String viscosity;
@Column(name = "ph")
private String ph;
@Column(name = "salinity")
private String salinity;
@Column(name = "barities")
private String barities;
@Column(name = "rmValue")
private String rmValue;
@Column(name = "rmTemp")
private String rmTemp;
@Column(name = "rmf")
private String rmf;
@Column(name = "rmc")
private String rmc;
@Column(name = "solid")
private String solid;
public void setHoleSize(String holeSize) {
this.holeSize = holeSize;
}
public String getHoleSize() {
return holeSize;
}
public void setField(String field) {
this.field = field;
}
public String getField() {
return field;
}
public void setKb(String kb) {
this.kb = kb;
}
public String getKb() {
return kb;
}
public void setDl(String dl) {
this.dl = dl;
}
public String getDl() {
return dl;
}
public void setTd(String td) {
this.td = td;
}
public String getTd() {
return td;
}
public void setCasingSize(String casingSize) {
this.casingSize = casingSize;
}
public String getCasingSize() {
return casingSize;
}
public void setCasingSizeDepth(String casingSizeDepth) {
this.casingSizeDepth = casingSizeDepth;
}
public String getCasingSizeDepth() {
return casingSizeDepth;
}
public void setRigName(String rigName) {
this.rigName = rigName;
}
public String getRigName() {
return rigName;
}
public void setTdDriller(String tdDriller) {
this.tdDriller = tdDriller;
}
public String getTdDriller() {
return tdDriller;
}
public void setCsDriller(String csDriller) {
this.csDriller = csDriller;
}
public String getCsDriller() {
return csDriller;
}
public void setWeekPoint(String weekPoint) {
this.weekPoint = weekPoint;
}
public String getWeekPoint() {
return weekPoint;
}
public void setBitSize(String bitSize) {
this.bitSize = bitSize;
}
public String getBitSize() {
return bitSize;
}
public void setDeviation(String deviation) {
this.deviation = deviation;
}
public String getDeviation() {
return deviation;
}
public void setStartCirculation(String startCirculation) {
this.startCirculation = startCirculation;
}
public String getStartCirculation() {
return startCirculation;
}
public void setGf(String gf) {
this.gf = gf;
}
public String getGf() {
return gf;
}
public void setDensity(String density) {
this.density = density;
}
public String getDensity() {
return density;
}
public void setViscosity(String viscosity) {
this.viscosity = viscosity;
}
public String getViscosity() {
return viscosity;
}
public void setPh(String ph) {
this.ph = ph;
}
public String getPh() {
return ph;
}
public void setSalinity(String salinity) {
this.salinity = salinity;
}
public String getSalinity() {
return salinity;
}
public void setBarities(String barities) {
this.barities = barities;
}
public String getBarities() {
return barities;
}
public void setRmValue(String rmValue) {
this.rmValue = rmValue;
}
public String getRmValue() {
return rmValue;
}
public void setRmTemp(String rmTemp) {
this.rmTemp = rmTemp;
}
public String getRmTemp() {
return rmTemp;
}
public void setRmf(String rmf) {
this.rmf = rmf;
}
public String getRmf() {
return rmf;
}
public void setRmc(String rmc) {
this.rmc = rmc;
}
public String getRmc() {
return rmc;
}
public void setSolid(String solid) {
this.solid = solid;
}
public String getSolid() {
return solid;
}
public void setJobNo(String jobNo) {
this.jobNo = jobNo;
}
public String getJobNo() {
return jobNo;
}
public void setJobBean(JobBean jobBean) {
this.jobBean = jobBean;
}
public JobBean getJobBean() {
return jobBean;
}
public void setStopCirculation(String stopCirculation) {
this.stopCirculation = stopCirculation;
}
public String getStopCirculation() {
return stopCirculation;
}
public String getLatitude_d() {
return latitude_d;
}
public void setLatitude_d(String latitude_d) {
this.latitude_d = latitude_d;
}
public String getLatitude_m() {
return latitude_m;
}
public void setLatitude_m(String latitude_m) {
this.latitude_m = latitude_m;
}
public String getLatitude_s() {
return latitude_s;
}
public void setLatitude_s(String latitude_s) {
this.latitude_s = latitude_s;
}
public String getLongitude_d() {
return longitude_d;
}
public void setLongitude_d(String longitude_d) {
this.longitude_d = longitude_d;
}
public String getLongitude_m() {
return longitude_m;
}
public void setLongitude_m(String longitude_m) {
this.longitude_m = longitude_m;
}
public String getLongitude_s() {
return longitude_s;
}
public void setLongitude_s(String longitude_s) {
this.longitude_s = longitude_s;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/transactions/cpi/web/SaveCPIAction.java
package com.iprosonic.cmms.modules.cpi.transactions.cpi.web;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.dao.CpiDAOImpl;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.service.CpiService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class SaveCPIAction extends ActionSupport implements
ModelDriven<CpiBean> {
private static final long serialVersionUID = 1L;
private CpiBean cpiBean = new CpiBean();
CpiDAOImpl cpiDAOImpl = new CpiDAOImpl();
CpiService cpiService = new CpiService();
private String unitCd;
private String cpiCd;
@Override
public String execute() {
try {
cpiCd = cpiDAOImpl.saveCpi(cpiBean);
setCpiCd(cpiCd);
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
@Override
public CpiBean getModel() {
return cpiBean;
}
public void setCpiBean(CpiBean cpiBean) {
this.cpiBean = cpiBean;
}
public CpiBean getCpiBean() {
return cpiBean;
}
public void setCpiCd(String cpiCd) {
this.cpiCd = cpiCd;
}
public String getCpiCd() {
return cpiCd;
}
public void setUnitCd(String unitCd) {
this.unitCd = unitCd;
}
public String getUnitCd() {
return unitCd;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/transactions/cpi/web/InitPrintCpiAction.java
package com.iprosonic.cmms.modules.cpi.transactions.cpi.web;
import java.util.List;
import java.util.Map;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.pjcommons.valuelist.CpiGetList;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class InitPrintCpiAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private CpiBean cpiBean = new CpiBean();
private List<String> cpiCdList;
CpiGetList cpiGetList = new CpiGetList();
@Override
public String execute() {
Map<String, Object> session = ActionContext.getContext().getSession();
cpiCdList= cpiGetList.getCpiCd();
session.put("cpiCd", cpiCdList);
return SUCCESS;
}
public void setCpiBean(CpiBean cpiBean) {
this.cpiBean = cpiBean;
}
public CpiBean getCpiBean() {
return cpiBean;
}
public void setCpiCdList(List<String> cpiCdList) {
this.cpiCdList = cpiCdList;
}
public List<String> getCpiCdList() {
return cpiCdList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/action/GenerateExcel.java
package com.iprosonic.cmms.pjcommons.action;
import java.io.File;
import java.io.FileInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.service.CpiService;
import com.iprosonic.cmms.pjcommons.utility.ContextFile;
import com.iprosonic.cmms.pjcommons.utility.MyPropertiesReader;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class GenerateExcel extends ActionSupport implements
ModelDriven<CpiBean> {
private static final long serialVersionUID = 1L;
private CpiBean cpiBean = new CpiBean();
CpiService cpiService = new CpiService();
@Override
public String execute() {
String cpiCd = getModel().getCpiCd();
cpiService.generateCpiExcel(cpiCd);
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename="
+ cpiCd+".xls");
File file = null;
MyPropertiesReader myPropertiesReader = new MyPropertiesReader();
String downloadPath = myPropertiesReader.getFilePath("exceldownload");
String filePath= ContextFile.getContextFile(downloadPath);
ServletOutputStream out = null;
FileInputStream fis = null;
try {
file = new File(filePath);
fis = new FileInputStream(file);
out = response.getOutputStream();
byte[] outputByte = new byte[(int) file.length()];
while (fis.read(outputByte, 0, (int) file.length()) != -1) {
out.write(outputByte, 0, (int) file.length());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return NONE;
}
@Override
public CpiBean getModel() {
return cpiBean;
}
public void setCpiBean(CpiBean cpiBean) {
this.cpiBean = cpiBean;
}
public CpiBean getCpiBean() {
return cpiBean;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/masters/service/domain/ServiecExReportBean.java
package com.iprosonic.cmms.modules.job.masters.service.domain;
import java.util.Set;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobExplBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobServiceBean;
public class ServiecExReportBean {
private String jobNo;
private Set<JobExplBean> jobExplNos;
private Set<JobServiceBean> jobServiceNos;
public String getJobNo() {
return jobNo;
}
public void setJobNo(String jobNo) {
this.jobNo = jobNo;
}
public Set<JobServiceBean> getJobServiceNos() {
return jobServiceNos;
}
public void setJobServiceNos(Set<JobServiceBean> jobServiceNos) {
this.jobServiceNos = jobServiceNos;
}
public Set<JobExplBean> getJobExplNos() {
return jobExplNos;
}
public void setJobExplNos(Set<JobExplBean> jobExplNos) {
this.jobExplNos = jobExplNos;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/valuelist/MaintainanceTypeCdAction.java
package com.iprosonic.cmms.pjcommons.valuelist;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MaintainanceTypeCdAction
{
public List<String> getMaintenanceType() {
List<String> maintenanceTypeList = null;
try {
maintenanceTypeList = new ArrayList<String>();
maintenanceTypeList.add("CABLES");
maintenanceTypeList.add("ELECTRONICS");
maintenanceTypeList.add("FIELD ENGG CELL");
maintenanceTypeList.add("HEADS");
maintenanceTypeList.add("MECHANICAL");
maintenanceTypeList.add("PERFORATION");
maintenanceTypeList.add("PRODUCTION");
maintenanceTypeList.add("SONDE");
maintenanceTypeList.add("WHE");
maintenanceTypeList.add("SAMPLING");
maintenanceTypeList.add("SOFTWARE");
maintenanceTypeList.add("TCP");
maintenanceTypeList.add("OTHERS");
Collections.sort(maintenanceTypeList);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return maintenanceTypeList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/utility/ApplicationResource.properties
fileDownloadPathReports=D:\\wascpi\\jrxml\\
logoPath=D:\\wascpi\\webapps\\images\\logo.jpg
downloadPath=download
cpijrxml=jrxml\\cpijrxml\\cpi.jasper
logoPath=images\\logo.jpg
pdfdownload=downloadfile\\cpi.pdf
exceldownload=downloadfile\\cpi.xls
historyCardExcelPath=downloadfile\\historyCard.xls<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/service/UpdateJobService.java
package com.iprosonic.cmms.modules.job.transactions.job.service;
import com.iprosonic.cmms.modules.job.transactions.job.dao.JobServiceDaoImpl;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobServiceBean;
public class UpdateJobService {
public void updateJobService(JobServiceBean jobServiceBean)
throws Exception {
JobServiceDaoImpl JobServiceDao = new JobServiceDaoImpl();
JobServiceDao.updateJobService(jobServiceBean);
}
public void updateJobStatus(String jobNo, String jobStatus) {
JobServiceDaoImpl JobServiceDao = new JobServiceDaoImpl();
JobServiceDao.updateJobStatus(jobNo, jobStatus);
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/masters/client/web/EditClientMstAction.java
package com.iprosonic.cmms.modules.masters.client.web;
import java.util.List;
import com.iprosonic.cmms.modules.masters.client.domain.ClientMasterBean;
import com.iprosonic.cmms.modules.masters.client.service.SearchClientMaster;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class EditClientMstAction extends ActionSupport implements ModelDriven<ClientMasterBean>{
private static final long serialVersionUID = 1L;
private SearchClientMaster searchClientMaster=new SearchClientMaster();
private List<ClientMasterBean> clientMasterList=null;
private ClientMasterBean clientMasterBean=new ClientMasterBean();
public ClientMasterBean getClientMasterBean() {
return clientMasterBean;
}
public void setClientMasterBean(ClientMasterBean clientMasterBean) {
this.clientMasterBean = clientMasterBean;
}
@Override
public ClientMasterBean getModel() {
// TODO Auto-generated method stub
return clientMasterBean;
}
public List<ClientMasterBean> getClientMasterList() {
return clientMasterList;
}
public void setClientMasterList(List<ClientMasterBean> clientMasterList) {
this.clientMasterList = clientMasterList;
}
@Override
public String execute() {
// TODO Auto-generated method stub
try{
clientMasterList=searchClientMaster.getClientList();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return SUCCESS;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/masters/role/domain/RoleBean.java
package com.iprosonic.cmms.modules.masters.role.domain;
public class RoleBean
{
private String roleName;
private String roleCd;
private int id;
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleName() {
return roleName;
}
public void setRoleCd(String roleCd) {
this.roleCd = roleCd;
}
public String getRoleCd() {
return roleCd;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/action/LoginInterceptor.java
package com.iprosonic.cmms.pjcommons.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginInterceptor
extends AbstractInterceptor implements StrutsStatics {
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context
.get(HTTP_REQUEST);
HttpSession session = request.getSession(false);
if (session == null) {
return "loginErrorLayout";
} else{
return invocation.invoke();
}
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/domain/JobServiceBean.java
package com.iprosonic.cmms.modules.job.transactions.job.domain;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@Entity
@Table(name = "jobservice")
public class JobServiceBean implements Serializable {
private static final long serialVersionUID = 4834199195444805898L;
@ManyToMany(fetch = FetchType.EAGER, targetEntity = JobExplBean.class, cascade = CascadeType.ALL)
@JoinColumn(name = "serviceNo", referencedColumnName = "serviceNo")
private Set<JobExplBean> jobExplBeanSet = new HashSet<JobExplBean>(0);
@Id
@Column(name = "serviceNo", unique = true, nullable = false, length = 100)
private String serviceNo;
@JoinColumn(name = "runNo")
private String runNo;
@Column(name = "jobNo")
private String jobNo;
@Column(name = "serviceStatus")
private String serviceStatus;
@Column(name = "jobType")
private String jobType;
@Column(name = "serviceType")
private String serviceType;
@Column(name = "serviceName")
private String serviceName;
@Column(name = "lossTime")
private String lossTime;
@Column(name = "serialNo")
private String serialNo;
@Column(name = "assetCd")
private String assetCd;
@Column(name = "deepestDepth")
private String deepestDepth;
@Column(name = "meterageLogged")
private String meterageLogged;
@Column(name = "meteragePerforated")
private String meteragePerforated;
@Column(name = "chruns")
private String chruns;
@Column(name = "chmisRuns")
private String chmisRuns;
@Column(name = "spf")
private String spf;
@Column(name = "coresCount")
private String coresCount;
@Column(name = "surfacePressure")
private String surfacePressure;
@Column(name = "levelCount")
private String levelCount;
@Column(name = "pretestCount")
private String pretestCount;
@Column(name = "dryTestCount")
private String dryTestCount;
@Column(name = "pumpOutTime")
private String pumpOutTime;
@Column(name = "pvtSample")
private String pvtSample;
@Column(name = "normalSample")
private String normalSample;
@Column(name = "rev")
private String rev;
@Column(name = "remarks")
private String remarks;
@Column(name = "failureGroup")
private String failureGroup;
@Column(name = "gunSize")
private String gunSize;
@Column(name = "logSendFromBase")
private String logSendFromBase;
@Column(name = "logRcieveAtBase")
private String logRcieveAtBase;
@Column(name = "logRcieveAtHo")
private String logRcieveAtHo;
@Column(name = "lqaDoneDate")
private String lqaDoneDate;
@Column(name = "lqaTechnical")
private String lqaTechnical;
@Column(name = "lqaPresentation")
private String lqaPresentation;
@Column(name = "snpSnd")
private String snpSnd;
@Column(name = "engi")
private String engi;
@Column(name = "crew")
private String crew;
@Column(name="tcpmissrun")
private String tcpmissrun;
public String getTcpmissrun() {
return tcpmissrun;
}
public void setTcpmissrun(String tcpmissrun) {
this.tcpmissrun = tcpmissrun;
}
public String getCrew() {
return crew;
}
public void setCrew(String crew) {
this.crew = crew;
}
public String getEngi() {
return engi;
}
public void setEngi(String engi) {
this.engi = engi;
}
public void setServiceStatus(String serviceStatus) {
this.serviceStatus = serviceStatus;
}
public String getServiceStatus() {
return serviceStatus;
}
public void setJobType(String jobType) {
this.jobType = jobType;
}
public String getJobType() {
return jobType;
}
public void setLossTime(String lossTime) {
this.lossTime = lossTime;
}
public String getLossTime() {
return lossTime;
}
public void setAssetCd(String assetCd) {
this.assetCd = assetCd;
}
public String getAssetCd() {
return assetCd;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
public String getSerialNo() {
return serialNo;
}
public void setDeepestDepth(String deepestDepth) {
this.deepestDepth = deepestDepth;
}
public String getDeepestDepth() {
return deepestDepth;
}
public void setRev(String rev) {
this.rev = rev;
}
public String getRev() {
return rev;
}
public void setChruns(String chruns) {
this.chruns = chruns;
}
public String getChruns() {
return chruns;
}
public void setChmisRuns(String chmisRuns) {
this.chmisRuns = chmisRuns;
}
public String getChmisRuns() {
return chmisRuns;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getRemarks() {
return remarks;
}
public void setFailureGroup(String failureGroup) {
this.failureGroup = failureGroup;
}
public String getFailureGroup() {
return failureGroup;
}
public void setRunNo(String runNo) {
this.runNo = runNo;
}
public String getRunNo() {
return runNo;
}
public void setServiceNo(String serviceNo) {
this.serviceNo = serviceNo;
}
public String getServiceNo() {
return serviceNo;
}
public void setJobNo(String jobNo) {
this.jobNo = jobNo;
}
public String getJobNo() {
return jobNo;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public String getServiceType() {
return serviceType;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getServiceName() {
return serviceName;
}
public void setPvtSample(String pvtSample) {
this.pvtSample = pvtSample;
}
public String getPvtSample() {
return pvtSample;
}
public void setNormalSample(String normalSample) {
this.normalSample = normalSample;
}
public String getNormalSample() {
return normalSample;
}
public void setLogRcieveAtBase(String logRcieveAtBase) {
this.logRcieveAtBase = logRcieveAtBase;
}
public String getLogRcieveAtBase() {
return logRcieveAtBase;
}
public void setLogRcieveAtHo(String logRcieveAtHo) {
this.logRcieveAtHo = logRcieveAtHo;
}
public String getLogRcieveAtHo() {
return logRcieveAtHo;
}
public void setLqaDoneDate(String lqaDoneDate) {
this.lqaDoneDate = lqaDoneDate;
}
public String getLqaDoneDate() {
return lqaDoneDate;
}
public void setLqaTechnical(String lqaTechnical) {
this.lqaTechnical = lqaTechnical;
}
public String getLqaTechnical() {
return lqaTechnical;
}
public void setLqaPresentation(String lqaPresentation) {
this.lqaPresentation = lqaPresentation;
}
public String getLqaPresentation() {
return lqaPresentation;
}
public void setMeterageLogged(String meterageLogged) {
this.meterageLogged = meterageLogged;
}
public String getMeterageLogged() {
return meterageLogged;
}
public void setMeteragePerforated(String meteragePerforated) {
this.meteragePerforated = meteragePerforated;
}
public String getMeteragePerforated() {
return meteragePerforated;
}
public void setSpf(String spf) {
this.spf = spf;
}
public String getSpf() {
return spf;
}
public void setCoresCount(String coresCount) {
this.coresCount = coresCount;
}
public String getCoresCount() {
return coresCount;
}
public void setSurfacePressure(String surfacePressure) {
this.surfacePressure = surfacePressure;
}
public String getSurfacePressure() {
return surfacePressure;
}
public void setLevelCount(String levelCount) {
this.levelCount = levelCount;
}
public String getLevelCount() {
return levelCount;
}
public void setPretestCount(String pretestCount) {
this.pretestCount = pretestCount;
}
public String getPretestCount() {
return pretestCount;
}
public void setDryTestCount(String dryTestCount) {
this.dryTestCount = dryTestCount;
}
public String getDryTestCount() {
return dryTestCount;
}
public void setPumpOutTime(String pumpOutTime) {
this.pumpOutTime = pumpOutTime;
}
public String getPumpOutTime() {
return pumpOutTime;
}
public void setLogSendFromBase(String logSendFromBase) {
this.logSendFromBase = logSendFromBase;
}
public String getLogSendFromBase() {
return logSendFromBase;
}
public void setGunSize(String gunSize) {
this.gunSize = gunSize;
}
public String getGunSize() {
return gunSize;
}
public void setSnpSnd(String snpSnd) {
this.snpSnd = snpSnd;
}
public String getSnpSnd() {
return snpSnd;
}
public void setJobExplBeanSet(Set<JobExplBean> jobExplBeanSet) {
this.jobExplBeanSet = jobExplBeanSet;
}
public Set<JobExplBean> getJobExplBeanSet() {
return jobExplBeanSet;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/reports/jobbonus/service/JobBonusReportService.java
package com.iprosonic.cmms.modules.job.reports.jobbonus.service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import com.iprosonic.cmms.modules.job.transactions.job.dao.JobDAOImpl;
import com.iprosonic.cmms.modules.job.transactions.job.dao.JobRunDaoImpl;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class JobBonusReportService {
private JobRunDaoImpl jobRunDaoImpl = null;
public JobBonusReportService() {
jobRunDaoImpl = new JobRunDaoImpl();
}
public String getBonusReport(String fromDate, String toDate,
String jobNo) {
return jobRunDaoImpl.getJobBonusReport(fromDate, toDate, jobNo);
}
public List<String> getJobNoList() throws Exception {
JobDAOImpl iJobDAO = new JobDAOImpl();
List<String> jobNoList = new ArrayList<String>();
Session session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(JobBean.class);
List<JobBean> jobBeanList = iJobDAO.getJobList(criteria);
Iterator<JobBean> itr = jobBeanList.iterator();
while (itr.hasNext()) {
JobBean jobBean = itr.next();
jobNoList.add(jobBean.getJobNo());
}
session.close();
return jobNoList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/valuelist/CPITypeAction.java
package com.iprosonic.cmms.pjcommons.valuelist;
import java.util.ArrayList;
import java.util.List;
public class CPITypeAction
{
public List<String> getCpiTypeList() {
List<String> cpiNatureList = null;
try {
cpiNatureList = new ArrayList<String>();
cpiNatureList.add("PM3");
cpiNatureList.add("PM2");
cpiNatureList.add("JOBP");
cpiNatureList.add("REPR");
cpiNatureList.add("MECH");
cpiNatureList.add("ROUTINE");
cpiNatureList.add("OTHERS");
} catch (Exception e) {
e.printStackTrace();
}
return cpiNatureList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/reports/historycard/service/HistoryCardReportService.java
package com.iprosonic.cmms.modules.cpi.reports.historycard.service;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.dao.CpiDAOImpl;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
public class HistoryCardReportService {
public void generateHistoryCardReport(String assetType, String assetCode,
String assetSrNo, String sectionName, String sectionSrNo,String excelPath) {
CpiDAOImpl cpiDAOImpl = new CpiDAOImpl();
List<CpiBean> cpiBeansList = cpiDAOImpl.getCpiList(sectionName,sectionSrNo);
try {
String historyCardHeaderArray[] = { "Asset Type", "Asset Code",
"Asset Sr No", "Section Name" };
String historyCardValueArray[] = { assetType, assetCode, assetSrNo,
sectionSrNo };
String maintainanceHeaderArray[] = { "SL No","CPI No", "Location Code","Tool Code","CPI Open Date","CPI Nature","Asset Type 1","Asset Name","Asset Sr No","Faulty Section Name","Faulty Section Sr No","Problem Details","CA1 Done ByProblem Details","CA1 Done(Remarks)","CA2 Done By","CA2 Done(Remarks)","Update Date","CPI Status","Why Open"};
String nomemHeaderArray[] ={"CPI NO", "CPI Date", "CPI CREATED BY"};
String nomemValueArray[] = { "NA", "NA", "NA" };
String oebHeaderArray[] = { "CPI NO", "CPI Date", "CPI CREATED BY" };
String oebValueArray[] = { "NA", "NA", "NA" };
String counterReadingHeaderArray[] = { "Date", "used Hrs",
"Max Temperature Exposed", "Job No.", "Vibration",
"Special Job(TPL,Fishing)", "Value", "Counter" };
String counterReadingValueArray[] = { "0", "0", "0", "0", "0", "0",
"0", "0" };
String jobHeaderArray[] = { "CPI NO", "CPI Date", "CPI CREATED BY" };
String jobValuesArray[] = { "CPI NO", "CPI Date", "CPI CREATED BY" };
String movementsHeaderArray[] = { "Date", "Location(To)","Location(From)", "Assign/Done", "Remarks" };
String movementsValuesArray[] = { "Date", "Location(To)","Location(From)", "Assign/Done", "Remarks" };
String fileDownloadPath = excelPath;
FileOutputStream fileOut = null;
String filePath = null;
// filePath = fileDownloadPath + "historyCard.xls";
filePath=fileDownloadPath;
fileOut = new FileOutputStream(filePath);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = null;
HSSFCell cell = null;
short rowNum = 1;
sheet.setColumnWidth(0, (10000));
HSSFCellStyle styleH = wb.createCellStyle();
styleH.setFillForegroundColor(HSSFColor.GREEN.index);
styleH.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
Font font = wb.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
font.setFontHeight((short) 3000);
HSSFCellStyle styleY = wb.createCellStyle();
styleY.setFillForegroundColor(HSSFColor.YELLOW.index);
styleY.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
for (int i = 0; i < historyCardHeaderArray.length; i++) {
row = sheet.createRow(rowNum++);
cell = row.createCell(0);
cell.setCellStyle(styleH);
cell.setCellValue(historyCardValueArray[i]);
cell = row.createCell(1);
cell.setCellValue(historyCardValueArray[i]);
}
row = sheet.createRow(rowNum++);
for (int i = 0; i < maintainanceHeaderArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleH);
cell.setCellValue(maintainanceHeaderArray[i]);
}
row = sheet.createRow(rowNum++);
Iterator<CpiBean> cpiBeanLitIterator = cpiBeansList.iterator();
int slNo= 1;
while (cpiBeanLitIterator.hasNext()) {
CpiBean cpiBean = cpiBeanLitIterator.next();
row = sheet.createRow(rowNum++);
cell = row.createCell(0);
cell.setCellStyle(styleY);
cell.setCellValue(slNo);
cell = row.createCell(1);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getCpiCd());
cell = row.createCell(2);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getLocationCd());
cell = row.createCell(3);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getAssetType());
cell = row.createCell(4);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getOpenDate1());
cell = row.createCell(5);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getCpiNature());
cell = row.createCell(6);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getAssetName());
cell = row.createCell(7);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getAssetName());
cell = row.createCell(8);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getAssetSrNo());
cell = row.createCell(9);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getSectionName());
cell = row.createCell(10);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getAssetSrNo());
cell = row.createCell(11);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getCorrectiveActionCode1());
cell = row.createCell(12);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getCorrectiveAction1());
cell = row.createCell(13);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getCorrectiveActionDoneBy1());
cell = row.createCell(14);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getCorrectiveAction2());
cell = row.createCell(15);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getUpdateDate());
cell = row.createCell(16);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getCpiStatus());
cell = row.createCell(17);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getWhyOpen());
cell = row.createCell(18);
cell.setCellStyle(styleY);
cell.setCellValue(cpiBean.getWhyOpen());
slNo++;
}
// NOMEM OEB
row = sheet.createRow(rowNum++);
for (int i = 0; i < nomemHeaderArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleH);
cell.setCellValue(nomemHeaderArray[i]);
}
row = sheet.createRow(rowNum++);
for (int i = 0; i < nomemHeaderArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleY);
cell.setCellValue(nomemValueArray[i]);
}
// OEB
row = sheet.createRow(rowNum++);
row = sheet.createRow(rowNum++);
for (int i = 0; i < oebHeaderArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleH);
cell.setCellValue(oebHeaderArray[i]);
}
row = sheet.createRow(rowNum++);
for (int i = 0; i < oebHeaderArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleY);
cell.setCellValue(oebValueArray[i]);
}
// Counter
row = sheet.createRow(rowNum++);
row = sheet.createRow(rowNum++);
for (int i = 0; i < counterReadingHeaderArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleH);
cell.setCellValue(counterReadingHeaderArray[i]);
}
row = sheet.createRow(rowNum++);
for (int i = 0; i < counterReadingValueArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleY);
cell.setCellValue(counterReadingValueArray[i]);
}
// JOB
row = sheet.createRow(rowNum++);
row = sheet.createRow(rowNum++);
for (int i = 0; i < jobHeaderArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleH);
cell.setCellValue(jobHeaderArray[i]);
}
row = sheet.createRow(rowNum++);
for (int i = 0; i < jobValuesArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleY);
cell.setCellValue(jobValuesArray[i]);
}
// MOVEMENTS
row = sheet.createRow(rowNum++);
row = sheet.createRow(rowNum++);
for (int i = 0; i < movementsHeaderArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleH);
cell.setCellValue(movementsHeaderArray[i]);
}
row = sheet.createRow(rowNum++);
for (int i = 0; i < movementsValuesArray.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(styleY);
cell.setCellValue(movementsValuesArray[i]);
}
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/service/JobNumberingService.java
package com.iprosonic.cmms.modules.job.transactions.job.service;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobBean;
import com.iprosonic.cmms.pjcommons.model.NumberingBean;
import com.iprosonic.cmms.pjcommons.utility.DateUtil;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class JobNumberingService {
public String genereateLatest(String codeType, String unitCd) {
return null;
}
public String genereateJobCd(String codeType, String unitCd) {
String latestJobNo = "";
Session session = null;
Transaction transaction = null;
List<String> codeTypeList = null;
String updateQuery = null;
String updateNo = "";
int nextNo = 0;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(NumberingBean.class);
ProjectionList projectionList = Projections.projectionList();
criteria.add(Restrictions.like("codeType", codeType));
criteria.add(Restrictions.like("unitCd", unitCd));
projectionList.add(Projections.property("latestNo"));
criteria.setProjection(projectionList);
codeTypeList = criteria.list();
Iterator<String> codeTypeIterator = codeTypeList.iterator();
while (codeTypeIterator.hasNext()) {
latestJobNo = codeTypeIterator.next();
}
nextNo = Integer.parseInt(latestJobNo) + 1;
updateNo = String.valueOf(nextNo);
updateQuery = "update NumberingBean set latestNo =:latestNo where codeType =:codeType and unitCd =:unitCd";
Query updateNumberingQuery = session.createQuery(updateQuery);
updateNumberingQuery.setString("latestNo", updateNo);
updateNumberingQuery.setString("codeType", codeType);
updateNumberingQuery.setString("unitCd", unitCd);
updateNumberingQuery.executeUpdate();
transaction.commit();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return updateNo;
}
public void resetNumberingNo(String unitNo, String codeType) {
int count = 0;
int currentMonth = Integer.parseInt(DateUtil.getCurrentMonth());
Session session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(JobBean.class);
criteria.add(Restrictions.like("unitNo", unitNo));
List<JobBean> list = criteria.list();
Iterator<JobBean> itr = list.iterator();
while (itr.hasNext()) {
JobBean jobBean = itr.next();
int jobMonth = Integer.parseInt((jobBean.getJobDate().substring(5,
7)));
if (currentMonth == jobMonth) {
count++;
}
}
if (count == 0) {
String updateQuery = "update NumberingBean set latestNo =:latestNo where codeType =:codeType and unitCd =:unitCd";
session = HibernateSession.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Query updateNumberingQuery = session.createQuery(updateQuery);
updateNumberingQuery.setString("latestNo", "0");
updateNumberingQuery.setString("codeType", codeType);
updateNumberingQuery.setString("unitCd", unitNo);
updateNumberingQuery.executeUpdate();
transaction.commit();
}
}
public String getLatestNo(String codeType, String unitCd) {
String latestNo = "";
Session session = null;
List<String> codeTypeList = null;
try {
session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(NumberingBean.class);
ProjectionList projectionList = Projections.projectionList();
criteria.add(Restrictions.like("codeType", codeType));
criteria.add(Restrictions.like("unitCd", unitCd));
projectionList.add(Projections.property("latestNo"));
criteria.setProjection(projectionList);
codeTypeList = criteria.list();
Iterator<String> codeTypeIterator = codeTypeList.iterator();
while (codeTypeIterator.hasNext()) {
latestNo = codeTypeIterator.next();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateSession.shoutDown();
}
if (latestNo == "") {
latestNo = "0";
}
return String.valueOf(Integer.parseInt(latestNo) - 1);
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/transactions/cpi/web/InitSearchCPIAction.java
package com.iprosonic.cmms.modules.cpi.transactions.cpi.web;
import java.util.List;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.dao.CpiDAOImpl;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.service.CpiService;
import com.iprosonic.cmms.pjcommons.valuelist.AssetCdStrAction;
import com.iprosonic.cmms.pjcommons.valuelist.CPICdListAction;
import com.iprosonic.cmms.pjcommons.valuelist.CpiGetList;
import com.iprosonic.cmms.pjcommons.valuelist.SectionSrNoStrAction;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class InitSearchCPIAction extends ActionSupport implements SessionAware, ModelDriven<CpiBean> {
private static final long serialVersionUID = 1L;
private Map<String, Object> session;
private List<String> cpiCdList;
private List<String> cpiStatusList;
private List<String> assetCdList;
private List<String> sectionSrNoList;
private CpiBean cpiBean = new CpiBean();
CpiService cpiService = new CpiService();
CpiGetList cpiGetList = new CpiGetList();
CPICdListAction cpiCdListAction = new CPICdListAction();
AssetCdStrAction assetCdStrAction = new AssetCdStrAction();
SectionSrNoStrAction sectionSrNoStrAction = new SectionSrNoStrAction();
CpiDAOImpl cpiDAOImpl = new CpiDAOImpl();
@Override
public String execute() {
cpiBean = cpiDAOImpl.getDefaultValue();
cpiCdList = cpiCdListAction.getCpiCdList();
cpiStatusList = cpiGetList.getCpiStatus();
assetCdList = AssetCdStrAction.getAssetCdList();
sectionSrNoList = sectionSrNoStrAction.getSectionSrNoList();
session.put("cpiCd", cpiCdList);
session.put("cpiStatus", cpiStatusList);
session.put("assetCd", assetCdList);
session.put("sectionSerialNo", sectionSrNoList);
return SUCCESS;
}
public void setCpiCdList(List<String> cpiCdList) {
this.cpiCdList = cpiCdList;
}
public List<String> getCpiCdList() {
return cpiCdList;
}
public void setCpiBean(CpiBean cpiBean) {
this.cpiBean = cpiBean;
}
public CpiBean getCpiBean() {
return cpiBean;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public Map<String, Object> getSession() {
return this.session;
}
@Override
public CpiBean getModel() {
return cpiBean;
}
public void setCpiStatusList(List<String> cpiStatusList) {
this.cpiStatusList = cpiStatusList;
}
public List<String> getCpiStatusList() {
return cpiStatusList;
}
public void setAssetCdList(List<String> assetCdList) {
this.assetCdList = assetCdList;
}
public List<String> getAssetCdList() {
return assetCdList;
}
public void setSectionSrNoList(List<String> sectionSrNoList) {
this.sectionSrNoList = sectionSrNoList;
}
public List<String> getSectionSrNoList() {
return sectionSrNoList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/login/service/LoginService.java
package com.iprosonic.cmms.modules.login.service;
import java.util.Iterator;
import com.iprosonic.cmms.modules.masters.user.dao.EmployeeDaoImpl;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
public class LoginService {
public boolean getValidLoginUser(String employeeCd, String pwd
) {
EmployeeDaoImpl empDao = new EmployeeDaoImpl();
boolean result = false;
Iterator userIterator = empDao.listUser().iterator();
while (userIterator.hasNext()) {
EmployeeBean emp = (EmployeeBean) userIterator.next();
if (emp.getEmployeeCd().equalsIgnoreCase(employeeCd)
&& emp.getPassword().equals(pwd)
) {
result = true;
break;
}
}
return result;
}
public EmployeeBean getEmployeeByCode(String cd) {
EmployeeDaoImpl empDao = new EmployeeDaoImpl();
return empDao.getEmployeeByCd(cd);
}
public String getRoleCd(String loginId) {
EmployeeDaoImpl empDao = new EmployeeDaoImpl();
return empDao.getRoleCd(loginId);
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/masters/service/web/EditServiceAction.java
package com.iprosonic.cmms.modules.job.masters.service.web;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.iprosonic.cmms.modules.job.masters.service.domain.ServiceMstBean;
import com.iprosonic.cmms.modules.job.masters.service.service.SearcheService;
import com.opensymphony.xwork2.ActionSupport;
public class EditServiceAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private ServiceMstBean serviceMstBean = new ServiceMstBean();
private SearcheService searcheService = new SearcheService();
public String execute() {
System.out
.println("----------------------EditServiceAction--------------------------");
HttpServletRequest request = ServletActionContext.getRequest();
setServiceMstBean(searcheService.searchServiceById(Integer
.parseInt(request.getParameter("id"))));
return SUCCESS;
}
public void setServiceMstBean(ServiceMstBean serviceMstBean) {
this.serviceMstBean = serviceMstBean;
}
public ServiceMstBean getServiceMstBean() {
return serviceMstBean;
}
}
<file_sep>/cmms/WebContent/js/dashboard.js
$(document).ready(function(){
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
$("ul.tabs li").click(function()
{
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active content
return false;
});
getChartFusionCharts();
});
function getChartFusionCharts()
{
var fromDate = document.getElementById('fromDate').value;
var toDate = document.getElementById('toDate').value;
var stype=document.getElementById('srvcType').value;
url='FusionJobAction.action?fromDate='+fromDate+'&enddate='+toDate+'&serviceType='+stype;
$.post(url, function(results)
{
var arry=results.split(";");
var charta = new FusionCharts(
"FusionCharts/col3D/FCF_Column3D.swf",
"ChartIda", "350", "300", {
debugMode : false,
registerWithJS : true
});
charta.setDataXML(arry[0]);
charta.render("jobvseng");
var chart23 = new FusionCharts(
"FusionCharts/MSLine/FCF_Column2D.swf",
"ChartIda23", "350", "300", {
debugMode : false,
registerWithJS : true
});
chart23.setDataXML(arry[1]);
chart23.render("job23");
var charta3 = new FusionCharts(
"FusionCharts/COL2D/FCF_Column2D.swf",
"ChartIda3", "350", "300", {
debugMode : false,
registerWithJS : true
});
charta3
.setDataXML(arry[2]);
charta3.render("job13");
var chart21 = new FusionCharts(
"FusionCharts/line21/FCF_Column2D.swf",
"ChartIda3", "350", "300", {
debugMode : false,
registerWithJS : true
});
chart21
.setDataXML(arry[3]);
chart21.render("job21");
var chart22 = new FusionCharts(
"FusionCharts/MSCOL3D1/FCF_Column2D.swf",
"ChartIda21", "350", "300", {
debugMode : false,
registerWithJS : true
});
chart22
.setDataXML(arry[4]);
chart22.render("job22");
var charta2 = new FusionCharts(
"FusionCharts/line2D/FCF_Column2D.swf",
"ChartIda2", "350", "300", {
debugMode : false,
registerWithJS : true
});
charta2
.setDataXML(arry[5]);
charta2.render("job12");
});
}<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/web/InsertServiceExplAction.java
package com.iprosonic.cmms.modules.job.transactions.job.web;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.iprosonic.cmms.modules.job.transactions.job.dao.JobServiceDaoImpl;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobExplBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobServiceBean;
import com.iprosonic.cmms.modules.job.transactions.job.service.SearchJobService;
import com.iprosonic.cmms.modules.job.transactions.job.service.UpdateJobExplosive;
import com.iprosonic.cmms.modules.job.transactions.job.service.UpdateJobService;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class InsertServiceExplAction extends ActionSupport
{
private static final long serialVersionUID = 1L;
private UpdateJobService updateJobService=new UpdateJobService();
private SearchJobService searchJobService = new SearchJobService();
JobServiceDaoImpl jobServiceDaoImpl = new JobServiceDaoImpl();
public String execute() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) ActionContext
.getContext().get(ServletActionContext.HTTP_RESPONSE);
Session session= HibernateSession.getSessionFactory().openSession();
Transaction transaction=session.beginTransaction();
try {
JobExplBean jobExpBean=new JobExplBean();
String expid=request.getParameter("expno").trim();
int len=expid.length();
jobExpBean.setJobNo(request.getParameter("jobNo").trim());
jobExpBean.setPartCd(request.getParameter("partNo").trim());
jobExpBean.setQty(request.getParameter("qty"));
jobExpBean.setUom(request.getParameter("uom"));
jobExpBean.setServiceNo(request.getParameter("serviceNo").trim());
Query q=session.createQuery("from JobExplBean where serviceNo=:service");
q.setParameter("service", request.getParameter("serviceNo").trim());
List<JobExplBean> list=q.list();
Set<JobExplBean> ss = new HashSet<JobExplBean>(list);
TreeSet<Integer> t = new TreeSet<Integer>();
int SizeofEx=0;
if (ss.size() == 0) {
SizeofEx=1;
} else {
for (JobExplBean jeb : ss) {
int i = jeb.getExplNo().toCharArray().length;
String exNo = jeb.getExplNo().substring(i - 1);
t.add(Integer.parseInt(exNo));
}
SizeofEx=t.last()+1;
}
String genExpId = request.getParameter("serviceNo").trim() + "-exp-" + SizeofEx + "";
jobExpBean.setExplNo(genExpId);
Query qq=session.createQuery("from JobServiceBean where serviceNo=:service");
qq.setParameter("service", request.getParameter("serviceNo").trim());
JobServiceBean jobServiceBean=(JobServiceBean) session.get(JobServiceBean.class, request.getParameter("serviceNo").trim());
jobServiceBean.getJobExplBeanSet().add(jobExpBean);
session.saveOrUpdate(jobServiceBean);
/*String hqlQuery = "update JobServiceBean set jobStatus =:jobStatus WHERE serviceNo =:serviceNo";
Query query = session.createQuery(hqlQuery);
query.setString("jobStatus", jobStatus);
query.setString("serviceNo", jobServiceBean);
query.executeUpdate();*/
transaction.commit();
request.setAttribute("jobNo", request.getParameter("jobNo"));
PrintWriter out= response.getWriter();
out.write("Exp Inserted successfully please close these window and referce parent window");
/* response.setIntHeader("Refresh", 2);*/
} catch (Exception e) {
e.printStackTrace();
}finally
{
session.flush();
session.clear();
session.close();
}
return null;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/valuelist/EmployeeCdListAction.java
package com.iprosonic.cmms.pjcommons.valuelist;
import java.util.Collections;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class EmployeeCdListAction {
public List<String> getOriginatedByString() {
List<String> originatedByCdList = null;
Transaction transaction = null;
Session session = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(EmployeeBean.class);
criteria.setProjection(Projections.distinct(Projections
.property("employeeName")));
originatedByCdList = criteria.list();
Collections.sort(originatedByCdList);
transaction.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
}
return originatedByCdList;
}
}<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/valuelist/CpiGetList.java
package com.iprosonic.cmms.pjcommons.valuelist;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.cpi.masters.assets.domain.AssetBean;
import com.iprosonic.cmms.modules.cpi.masters.group.domain.CpiMasterBean;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.dao.CpiDAOImpl;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
import com.iprosonic.cmms.pjcommons.model.NumberingBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class CpiGetList {
public List<String> correctiveActionDoneBy() {
List<String> correctiveActionDoneByList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(EmployeeBean.class);
criteria.setProjection(Projections.distinct(Projections.property("employeeName")));
correctiveActionDoneByList = criteria.list();
// Collections.sort(correctiveActionDoneByList);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return correctiveActionDoneByList;
}
public String getCpiNo(String codeType) {
String latestCpiNo = "";
Session session = null;
Transaction transaction = null;
List<String> codeTypeList = null;
String updateQuery = null;
String updateNo = "";
int nextNo = 0;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(NumberingBean.class);
ProjectionList projectionList = Projections.projectionList();
criteria.add(Restrictions.like("codeType", codeType));
projectionList.add(Projections.property("latestNo"));
criteria.setProjection(projectionList);
codeTypeList = criteria.list();
Iterator<String> codeTypeIterator = codeTypeList.iterator();
while (codeTypeIterator.hasNext()) {
latestCpiNo = codeTypeIterator.next();
}
transaction.commit();
session.close();
nextNo = Integer.parseInt(latestCpiNo) + 1;
updateNo = String.valueOf(nextNo);
updateQuery = "update NumberingBean set latestNo =:latestNo where codeType=:codeType";
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Query updateNumberingQuery = session.createQuery(updateQuery);
updateNumberingQuery.setString("latestNo", updateNo);
updateNumberingQuery.setString("codeType", codeType);
updateNumberingQuery.executeUpdate();
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return latestCpiNo;
}
public List<String> getCorrectiveActionDoneById(int id) {
List<String> correctiveActionDoneList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(CpiBean.class);
criteria.add(Restrictions.like("id", id));
correctiveActionDoneList = criteria.list();
transaction.commit();
} catch (Exception e) {
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return correctiveActionDoneList;
}
public List<CpiBean> getCpiListById(int id) {
List<CpiBean> cpiBeanListById = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(CpiBean.class);
criteria.add(Restrictions.like("id", id));
cpiBeanListById = criteria.list();
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return cpiBeanListById;
}
public List<CpiBean> getCpiList(String cpiCd) {
List<CpiBean> cpiBeanList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(CpiBean.class);
if (!cpiCd.equalsIgnoreCase("-Select-")) {
criteria.add(Restrictions.like("cpiCd", cpiCd));
}
cpiBeanList = criteria.list();
transaction.commit();
} catch (HibernateException e) {
if (transaction.wasCommitted()) {
transaction.rollback();
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return cpiBeanList;
}
public Set<String> getRegionCd() {
Set<String> regionSet = null;
CpiDAOImpl cpiDAOImpl = null;
try {
cpiDAOImpl = new CpiDAOImpl();
List<CpiBean> cpiList = cpiDAOImpl.getCpiList();
Iterator<CpiBean> cpiListIterator = cpiList.iterator();
regionSet = new HashSet<String>();
while (cpiListIterator.hasNext()) {
CpiBean cpiBean = cpiListIterator.next();
String regionCd = cpiBean.getRegionCd();
regionSet.add(regionCd);
}
} catch (Exception e) {
e.printStackTrace();
}
return regionSet;
}
public String getLocationCdString(String regionCd) {
List<String> locationCdList = null;
String listString = "-Select-:";
Session session = null;
try {
session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(CpiBean.class);
criteria.add(Restrictions.like("regionCd", regionCd));
criteria.setProjection(Projections.distinct(Projections.property("locationCd")));
locationCdList = criteria.list();
for (String s : locationCdList) {
listString += s + ":";
}
} catch (Exception e) {
e.printStackTrace();
}
return listString;
}
public String getUnitCdString(String locationCd) {
List<String> unitCdList = null;
String listString = "-Select-:";
Session session = null;
try {
session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(CpiBean.class);
criteria.add(Restrictions.like("locationCd", locationCd));
criteria.setProjection(Projections.distinct(Projections.property("unitCd")));
unitCdList = criteria.list();
for (String s : unitCdList) {
listString += s + ":";
}
} catch (Exception e) {
e.printStackTrace();
}
return listString;
}
public String getClientCdString(String unitCd) {
List<String> clientCdList = null;
String listString = "-Select-:";
Session session = null;
try {
session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(CpiBean.class);
criteria.add(Restrictions.like("unitCd", unitCd));
criteria.setProjection(Projections.distinct(Projections.property("clientCd")));
clientCdList = criteria.list();
for (String s : clientCdList) {
listString += s + ":";
}
} catch (Exception e) {
e.printStackTrace();
}
return listString;
}
public String getOriginatedByString(String clientCd) {
List<String> originatedByCdList = null;
String listString = "-Select-:";
Session session = null;
try {
session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(CpiBean.class);
criteria.setProjection(Projections.distinct(Projections.property("originatedBy")));
originatedByCdList = criteria.list();
for (String s : originatedByCdList) {
listString += s + ":";
}
} catch (Exception e) {
e.printStackTrace();
}
return listString;
}
public List<String> getPriority() {
List<String> prioritylist = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(CpiBean.class);
criteria.setProjection(Projections.distinct(Projections.property("priority")));
prioritylist = criteria.list();
} catch (Exception e) {
if (transaction.wasCommitted()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return prioritylist;
}
public String getCpiType(String priority) {
List<String> cpiTypeList = null;
Session session = null;
Transaction transaction = null;
String listString = "-Select-:";
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(CpiBean.class);
criteria.add(Restrictions.like("priority", priority));
criteria.setProjection(Projections.distinct(Projections.property("cpiType")));
cpiTypeList = criteria.list();
for (String s : cpiTypeList) {
listString += s + ":";
}
} catch (Exception e) {
if (transaction.wasCommitted()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return listString;
}
public String getMaintenanceType(String cpiType) {
List<String> maintenanceTypeList = null;
Session session = null;
String listString = "-Select-:";
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(CpiBean.class);
criteria.add(Restrictions.like("cpiType", cpiType));
criteria.setProjection(Projections.distinct(Projections.property("maintanenceType")));
maintenanceTypeList = criteria.list();
for (String s : maintenanceTypeList) {
listString += s + ":";
}
} catch (Exception e) {
if (transaction.wasCommitted()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return listString;
}
public List<String> getAssetType1() {
List<String> assetTypeList1 = null;
try {
assetTypeList1 = new ArrayList<String>();
assetTypeList1.add("ASQS");
assetTypeList1.add("DTHL");
assetTypeList1.add("FILD");
} catch (Exception e) {
e.printStackTrace();
}
return assetTypeList1;
}
public String getAssetCd(String assetType, String type) {
Session session = null;
Transaction transaction = null;
List<String> assetCdList = null;
String listString = "-Select-:";
Criteria criteria = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
if (type.equalsIgnoreCase("getAssetCd1")) {
criteria = session.createCriteria(AssetBean.class);
criteria.add(Restrictions.like("assetType", assetType));
criteria.setProjection(Projections.distinct(Projections.property("assetCd")));
assetCdList = criteria.list();
}
assetCdList = criteria.list();
for (String s : assetCdList) {
listString += s + ":";
}
transaction.commit();
} catch (HibernateException e) {
if (transaction.wasCommitted()) {
transaction.rollback();
e.printStackTrace();
}
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return listString;
}
public String getAssetSrNo(String assertCd1, String type) {
List<String> assetSrNo1List = null;
Session session = null;
Transaction transaction = null;
Criteria criteria = null;
String listString = "-Select-:";
try {
session = HibernateSession.getSessionFactory().openSession();
if (type.equalsIgnoreCase("getAssetSrNo1")) {
criteria = session.createCriteria(AssetBean.class);
transaction = session.beginTransaction();
criteria.add(Restrictions.like("assetCd", assertCd1));
criteria.setProjection(Projections.distinct(Projections.property("assetSerialNo")));
assetSrNo1List = criteria.list();
for (String assetSrNo : assetSrNo1List) {
listString += assetSrNo + ":";
}
transaction.commit();
}
}
catch (Exception e) {
if (transaction.wasCommitted()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return listString;
}
public String getSectionName(String assetSrNo, String type) {
List<String> sectionNameList = null;
Session session = null;
Transaction transaction = null;
Criteria criteria = null;
String listString = "-Select-:";
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
if (type.equalsIgnoreCase("getSectionName1")) {
criteria = session.createCriteria(AssetBean.class);
criteria.add(Restrictions.like("assetSerialNo", assetSrNo));
criteria.setProjection(Projections.distinct(Projections.property("sectionCd")));
sectionNameList = criteria.list();
}
for (String assetSr1 : sectionNameList) {
listString += assetSr1 + ":";
}
} catch (Exception e) {
if (transaction.wasCommitted()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return listString;
}
public String getSectionSrNo(String sectionName, String type) {
List<String> sectionSrNoList = null;
Session session = null;
Transaction transaction = null;
String listString = "-Select:-";
Criteria criteria = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
if (type.equalsIgnoreCase("getSectionSerialNo1")) {
criteria = session.createCriteria(AssetBean.class);
criteria.add(Restrictions.like("sectionCd", sectionName));
criteria.setProjection(Projections.distinct(Projections.property("sectionSerialNo")));
sectionSrNoList = criteria.list();
}
for (String assetSr1 : sectionSrNoList) {
listString += assetSr1 + ":";
}
} catch (Exception e) {
if (transaction.wasCommitted()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return listString;
}
public List<String> getCpiProcess() {
List<String> cpiProcessList = null;
try {
cpiProcessList = new ArrayList<String>();
cpiProcessList.add("Diagnosis");
cpiProcessList.add("Partially_Diagnosed");
cpiProcessList.add("Ready_For_Analysis");
cpiProcessList.add("Partially_Analysed");
cpiProcessList.add("Waiting_For_Job");
cpiProcessList.add("Job_Done");
cpiProcessList.add("Closed");
} catch (Exception e) {
e.printStackTrace();
}
return cpiProcessList;
}
/*-Common for Search Cpi and MWAS REPORT INPUT Criteria
* INPUT 1--> CpiCd
*/
public synchronized List<String> getCpiCd() {
List<String> cpiCdList = null;
Session session = null;
Transaction transaction = null;
Criteria criteria = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
criteria = session.createCriteria(CpiBean.class);
criteria.setProjection(Projections.distinct(Projections.property("cpiCd")));
cpiCdList = criteria.list();
} catch (Exception e) {
if (transaction.wasCommitted()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return cpiCdList;
}
// --------------- cpi master
public List<String> getCpiStatus() {
List<String> cpiStatusList = null;
try {
cpiStatusList = new ArrayList<String>();
cpiStatusList.add("OPEN_YELLOW");
cpiStatusList.add("OPEN_RED");
cpiStatusList.add("OPEN_BLUE");
cpiStatusList.add("CLOSE_GREEN");
} catch (Exception e) {
e.printStackTrace();
}
return cpiStatusList;
}
public List<String> getWhyOpen() {
Session session = null;
Transaction transaction = null;
List<String> cpiWhyOpenList = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria whyOpenCriteria = session.createCriteria(CpiMasterBean.class);
whyOpenCriteria.setProjection(Projections.distinct(Projections.property("whyOpen")));
cpiWhyOpenList = whyOpenCriteria.list();
transaction.commit();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
return cpiWhyOpenList;
}
// --
public List<String> getAssetTypeList() {
List<String> assetTypeList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria assetTypeCriteria = session.createCriteria(AssetBean.class);
assetTypeCriteria.setProjection(Projections.distinct(Projections.property("assetType")));
assetTypeList = assetTypeCriteria.list();
Collections.sort(assetTypeList);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return assetTypeList;
}
public List<String> getAssetNameList() {
List<String> assetNameList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria assetNameCriteria = session.createCriteria(AssetBean.class);
assetNameCriteria.setProjection(Projections.distinct(Projections.property("assetCd")));
assetNameList = assetNameCriteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return assetNameList;
}
public List<String> getassetCdList() {
List<String> assertCdList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(AssetBean.class);
criteria.setProjection(Projections.distinct(Projections.property("assetCd")));
assertCdList = criteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return assertCdList;
}
public List<String> getAssetSrNoList() {
List<String> assetSrNoList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(AssetBean.class);
criteria.setProjection(Projections.distinct(Projections.property("assetSerialNo")));
assetSrNoList = criteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return assetSrNoList;
}
public List<String> getSectionNoList() {
List<String> sectionCdList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(AssetBean.class);
criteria.setProjection(Projections.distinct(Projections.property("sectionCd")));
sectionCdList = criteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return sectionCdList;
}
public List<String> getSectionSerialNoList() {
List<String> sectionSerialNoList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(AssetBean.class);
criteria.setProjection(Projections.distinct(Projections.property("sectionSerialNo")));
sectionSerialNoList = criteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return sectionSerialNoList;
}
// -------CPI Master
public List<String> getTypeOfCpiList() {
List<String> typeOfCpiList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria typeOfCpiCriteria = session.createCriteria(CpiMasterBean.class);
typeOfCpiCriteria.setProjection(Projections.distinct(Projections.property("typeOfCpi")));
typeOfCpiList = typeOfCpiCriteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return typeOfCpiList;
}
public List<String> getSourceOfCpiList() {
List<String> sourceOfCpiList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria sourceOfCpiCriteria = session.createCriteria(CpiMasterBean.class);
sourceOfCpiCriteria.setProjection(Projections.distinct(Projections.property("sourceOfCpi")));
sourceOfCpiList = sourceOfCpiCriteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return sourceOfCpiList;
}
public List<String> getSubSourceOfCpiList() {
List<String> subSourceOfCpiList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria subSourceOfCpiCriteria = session.createCriteria(CpiMasterBean.class);
subSourceOfCpiCriteria.setProjection(Projections.distinct(Projections.property("subSourceOfCpi")));
subSourceOfCpiList = subSourceOfCpiCriteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return subSourceOfCpiList;
}
// ------
public List<String> getsubGroupCdList() {
List<String> subGroupCdList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria subGroupCdCriteria = session.createCriteria(CpiMasterBean.class);
subGroupCdCriteria.setProjection(Projections.distinct(Projections.property("subGroupName")));
subGroupCdList = subGroupCdCriteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return subGroupCdList;
}
public List<String> getCpiCategoryList() {
List<String> cpiCategoryList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria cpiCategoryCriteria = session.createCriteria(CpiMasterBean.class);
cpiCategoryCriteria.setProjection(Projections.distinct(Projections.property("category")));
cpiCategoryList = cpiCategoryCriteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return cpiCategoryList;
}
public List<String> getCpiSubCategoryList() {
List<String> cpiSubCategoryList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria cpiSubCategoryCriteria = session.createCriteria(CpiMasterBean.class);
cpiSubCategoryCriteria.setProjection(Projections.distinct(Projections.property("subCategory")));
cpiSubCategoryList = cpiSubCategoryCriteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return cpiSubCategoryList;
}
/*-MWAS REPORT INPUT Criteria
* INPUT 2--> UnitCd
*/
public List<String> getUnitCdList() {
List<String> unitCdList = null;
Session session = null;
Transaction transaction = null;
try {
session = HibernateSession.getSessionFactory().openSession();
transaction = session.beginTransaction();
Criteria unitCdCriteria = session.createCriteria(AssetBean.class);
unitCdCriteria.setProjection(Projections.distinct(Projections.property("unitCd")));
unitCdList = unitCdCriteria.list();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session.isConnected()) {
session.close();
HibernateSession.shoutDown();
}
}
return unitCdList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/masters/service/web/UpdateServiveMasterAction.java
package com.iprosonic.cmms.modules.job.masters.service.web;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.iprosonic.cmms.modules.job.masters.service.domain.ServiceMstBean;
import com.iprosonic.cmms.modules.job.masters.service.service.UpdateService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class UpdateServiveMasterAction extends ActionSupport implements
ModelDriven<ServiceMstBean> {
private static final long serialVersionUID = 1L;
private ServiceMstBean serviceMstBean = new ServiceMstBean();
private UpdateService updateService= new UpdateService();
public String execute() {
getUpdateService().updateService(getModel());
String message = "Service type " + getModel().getServiceType()
+ " updated succefully.";
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("message", message);
return SUCCESS;
}
@Override
public ServiceMstBean getModel() {
return serviceMstBean;
}
public void setUpdateService(UpdateService updateService) {
this.updateService = updateService;
}
public UpdateService getUpdateService() {
return updateService;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/domain/JobBean.java
package com.iprosonic.cmms.modules.job.transactions.job.domain;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name = "job", uniqueConstraints = { @UniqueConstraint(columnNames = "jobNo") })
public class JobBean implements Serializable
{
private static final long serialVersionUID = -8767337896773261247L;
@Id
@Column(name = "jobNo", unique = true, nullable = false)
private String jobNo;
@OneToOne(mappedBy = "jobBean", cascade = CascadeType.ALL)
private JobWellBean jobWellBean;
@ManyToMany(fetch = FetchType.LAZY, targetEntity = JobRigBean.class, cascade = CascadeType.ALL)
@JoinColumn(name = "jobNo", referencedColumnName = "jobNo")
private Set<JobRigBean> jobRigBean = new HashSet<JobRigBean>();
@Column(name = "jobNoHlsa")
private String jobNoHlsa;
@Column(name = "unitNo")
private String unitNo;
@Column(name = "engineer")
private String engineer;
@Column(name = "jobDate")
private String jobDate;
@Column(name = "jobStatus")
private String jobStatus;
@Column(name = "crew")
private String crew;
@Column(name = "wellNo")
private String wellNo;
@Column(name = "clientName")
private String clientName;
@Column(name = "unitLeftBase")
private String unitLeftBase;
@Column(name = "unitReachedBase")
private String unitReachedBase;
@Column(name = "unitReachedSite")
private String unitReachedSite;
@Column(name = "unitLeftSite")
private String unitLeftSite;
@Column(name = "truckMileage")
private String truckMileage;
@Column(name = "vanMileage")
private String vanMileage;
@Column(name = "lostTime")
private String lostTime;
@Column(name = "ejcs1")
private String ejcs1;
@Column(name = "ejcs2")
private String ejcs2;
@Column(name = "ejcs3")
private String ejcs3;
@Column(name = "ejcs4")
private String ejcs4;
@Column(name = "ejcs5")
private String ejcs5;
@Column(name = "safetyMeet")
private String safetyMeet;
@Column(name = "remarks",length=5000)
private String remarks;
public void setEngineer(String engineer) {
this.engineer = engineer;
}
public String getEngineer() {
return engineer;
}
public void setCrew(String crew) {
this.crew = crew;
}
public String getCrew() {
return crew;
}
public void setWellNo(String wellNo) {
this.wellNo = wellNo;
}
public String getWellNo() {
return wellNo;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientName() {
return clientName;
}
public void setUnitReachedSite(String unitReachedSite) {
this.unitReachedSite = unitReachedSite;
}
public String getUnitReachedSite() {
return unitReachedSite;
}
public void setUnitLeftSite(String unitLeftSite) {
this.unitLeftSite = unitLeftSite;
}
public String getUnitLeftSite() {
return unitLeftSite;
}
public void setTruckMileage(String truckMileage) {
this.truckMileage = truckMileage;
}
public String getTruckMileage() {
return truckMileage;
}
public void setVanMileage(String vanMileage) {
this.vanMileage = vanMileage;
}
public String getVanMileage() {
return vanMileage;
}
public void setLostTime(String lostTime) {
this.lostTime = lostTime;
}
public String getLostTime() {
return lostTime;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getRemarks() {
return remarks;
}
public void setUnitNo(String unitNo) {
this.unitNo = unitNo;
}
public String getUnitNo() {
return unitNo;
}
public void setUnitLeftBase(String unitLeftBase) {
this.unitLeftBase = unitLeftBase;
}
public String getUnitLeftBase() {
return unitLeftBase;
}
public void setUnitReachedBase(String unitReachedBase) {
this.unitReachedBase = unitReachedBase;
}
public String getUnitReachedBase() {
return unitReachedBase;
}
public void setJobWellBean(JobWellBean jobWellBean) {
this.jobWellBean = jobWellBean;
}
public JobWellBean getJobWellBean() {
return jobWellBean;
}
public void setJobRigBean(Set<JobRigBean> jobRigBean) {
this.jobRigBean = jobRigBean;
}
public Set<JobRigBean> getJobRigBean() {
return jobRigBean;
}
public void setSafetyMeet(String safetyMeet) {
this.safetyMeet = safetyMeet;
}
public String getSafetyMeet() {
return safetyMeet;
}
public void setJobDate(String jobDate) {
this.jobDate = jobDate;
}
public String getJobDate() {
return jobDate;
}
public void setJobStatus(String jobStatus) {
this.jobStatus = jobStatus;
}
public String getJobStatus() {
return jobStatus;
}
public String getEjcs1() {
return ejcs1;
}
public void setEjcs1(String ejcs1) {
this.ejcs1 = ejcs1;
}
public String getEjcs2() {
return ejcs2;
}
public void setEjcs2(String ejcs2) {
this.ejcs2 = ejcs2;
}
public String getEjcs3() {
return ejcs3;
}
public void setEjcs3(String ejcs3) {
this.ejcs3 = ejcs3;
}
public String getEjcs4() {
return ejcs4;
}
public void setEjcs4(String ejcs4) {
this.ejcs4 = ejcs4;
}
public String getEjcs5() {
return ejcs5;
}
public void setEjcs5(String ejcs5) {
this.ejcs5 = ejcs5;
}
public void setJobNoHlsa(String jobNoHlsa) {
this.jobNoHlsa = jobNoHlsa;
}
public String getJobNoHlsa() {
return jobNoHlsa;
}
public void setJobNo(String jobNo) {
this.jobNo = jobNo;
}
public String getJobNo() {
return jobNo;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/transactions/cpi/web/InitCpiAction.java
package com.iprosonic.cmms.modules.cpi.transactions.cpi.web;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.dao.CpiDAOImpl;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.service.CpiService;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
import com.iprosonic.cmms.pjcommons.valuelist.AssetTypeListAction;
import com.iprosonic.cmms.pjcommons.valuelist.CPICdListAction;
import com.iprosonic.cmms.pjcommons.valuelist.CPIProcessListAction;
import com.iprosonic.cmms.pjcommons.valuelist.CPITypeAction;
import com.iprosonic.cmms.pjcommons.valuelist.CpiGetList;
import com.iprosonic.cmms.pjcommons.valuelist.EmployeeCdListAction;
import com.iprosonic.cmms.pjcommons.valuelist.MaintainanceTypeCdAction;
import com.iprosonic.cmms.pjcommons.valuelist.OriginatedByAction;
import com.iprosonic.cmms.pjcommons.valuelist.PriorityCdAction;
import com.iprosonic.cmms.pjcommons.valuelist.RegionCdListAction;
import com.iprosonic.cmms.pjcommons.valuelist.WhyOpenCdListAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class InitCpiAction extends ActionSupport implements
ModelDriven<CpiBean> {
private CpiBean cpiBean = new CpiBean();
RegionCdListAction regionCdListAction = new RegionCdListAction();
PriorityCdAction priorityCdAction = new PriorityCdAction();
CPIProcessListAction cpiProcessListAction = new CPIProcessListAction();
CPICdListAction cpiCdListAction = new CPICdListAction();
WhyOpenCdListAction whyOpenCdListAction = new WhyOpenCdListAction();
AssetTypeListAction assetTypeListAction = new AssetTypeListAction();
MaintainanceTypeCdAction maintainanceTypeCdAction = new MaintainanceTypeCdAction();
CPITypeAction cpiTypeAction = new CPITypeAction();
EmployeeCdListAction employeeCdListAction = new EmployeeCdListAction();
CpiService cpiService = new CpiService();
CpiGetList cpiGetList = new CpiGetList();
RegionCdListAction regionCdList = new RegionCdListAction();
CpiDAOImpl cpiDAOImpl = new CpiDAOImpl();
OriginatedByAction originatedByAction = new OriginatedByAction();
private static final long serialVersionUID = 1L;
private List<EmployeeBean> userList;
private Set<String> regionCdSet;
private List<String> priorityList;
private List<String> maintenanceTypeList;
private List<String> assetCdList;
private List<String> cpiProcessList;
private List<String> cpiCdList;
private List<String> cpiStatusList;
private List<String> cpiWhyOpenList;
private List<String> assetTypeList;
private List<String> orientedByList;
private List<String> employeeList;
private List<String> cpiTypeList;
// ---------
public String execute() {
cpiBean = cpiDAOImpl.getDefaultValue();
Map<String, Object> session = ActionContext.getContext().getSession();
regionCdSet = regionCdListAction.getRegionCd();
priorityList = priorityCdAction.getPriority();
cpiProcessList = cpiProcessListAction.getCpiProcess();
cpiCdList = cpiCdListAction.getCpiCdList();
cpiWhyOpenList = whyOpenCdListAction.getWhyOpen();
assetTypeList = assetTypeListAction.getAssetType();
employeeList = employeeCdListAction.getOriginatedByString();
maintenanceTypeList = maintainanceTypeCdAction.getMaintenanceType();
cpiTypeList = cpiTypeAction.getCpiTypeList();
session.put("assetType1", assetTypeList);
session.put("regionCd", regionCdSet);
session.put("priority", priorityList);
session.put("assetCd", assetCdList);
session.put("cpiType", cpiTypeList);
session.put("maintenanceTypeList", maintenanceTypeList);
session.put("cpiCd", cpiCdList);
session.put("cpiStatus", cpiStatusList);
session.put("whyOpen", cpiWhyOpenList);
session.put("originatedBy", employeeList);
return SUCCESS;
}
@Override
public CpiBean getModel() {
return cpiBean;
}
public void setUserList(List<EmployeeBean> userList) {
this.userList = userList;
}
public List<EmployeeBean> getUserList() {
return userList;
}
public void setCpiBean(CpiBean cpiBean) {
this.cpiBean = cpiBean;
}
public CpiBean getCpiBean() {
return cpiBean;
}
public void setPriorityList(List<String> priorityList) {
this.priorityList = priorityList;
}
public List<String> getPriorityList() {
return priorityList;
}
public void setMaintenanceTypeList(List<String> maintenanceTypeList) {
this.maintenanceTypeList = maintenanceTypeList;
}
public List<String> getMaintenanceTypeList() {
return maintenanceTypeList;
}
public void setCpiProcessList(List<String> cpiProcessList) {
this.cpiProcessList = cpiProcessList;
}
public List<String> getCpiProcessList() {
return cpiProcessList;
}
public void setCpiCdList(List<String> cpiCdList) {
this.cpiCdList = cpiCdList;
}
public List<String> getCpiCdList() {
return cpiCdList;
}
public void setCpiStatusList(List<String> cpiStatusList) {
this.cpiStatusList = cpiStatusList;
}
public List<String> getCpiStatusList() {
return cpiStatusList;
}
public void setCpiWhyOpenList(List<String> cpiWhyOpenList) {
this.cpiWhyOpenList = cpiWhyOpenList;
}
public List<String> getCpiWhyOpenList() {
return cpiWhyOpenList;
}
public void setassetTypeList(List<String> assetTypeList) {
this.assetTypeList = assetTypeList;
}
public List<String> getassetTypeList() {
return assetTypeList;
}
public void setOrientedByList(List<String> orientedByList) {
this.orientedByList = orientedByList;
}
public List<String> getOrientedByList() {
return orientedByList;
}
public void setEmployeeList(List<String> employeeList) {
this.employeeList = employeeList;
}
public List<String> getEmployeeList() {
return employeeList;
}
}
<file_sep>/cmms/build/classes/com/iprosonic/cmms/modules/job/transactions/job/service/mysqlconninfo.properties
driver=com.mysql.jdbc.Driver
urlstring=jdbc\:mysql\://192.168.1.55\:3306/wascpi_demo
user=root
password=<PASSWORD>
<file_sep>/cmms/src/com/iprosonic/cmms/modules/masters/client/dao/ClientMasterDaoImpl.java
package com.iprosonic.cmms.modules.masters.client.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import com.iprosonic.cmms.modules.masters.client.domain.ClientMasterBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class ClientMasterDaoImpl {
public List<String> getClientNameList() {
Session session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(ClientMasterBean.class);
Projection projection = Projections.distinct(Projections.property("clientName"));
criteria.setProjection(projection);
List<String> list = criteria.list();
session.close();
return list;
}
public List<ClientMasterBean> getClient() {
Session session = HibernateSession.getSessionFactory().openSession();
session.beginTransaction();
List<ClientMasterBean> list = (List<ClientMasterBean>) session.createCriteria(ClientMasterBean.class).list();
session.close();
return list;
}
public void saveClient(Object ob) {
ClientMasterBean cl = (ClientMasterBean) ob;
Session session = HibernateSession.getSessionFactory().openSession();
session.beginTransaction();
try {
session.save(cl);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.getTransaction().commit();
session.close();
}
}
public void deleteClientById(ClientMasterBean bean) {
// TODO Auto-generated method stub
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
session.delete(bean);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.getTransaction().commit();
session.close();
}
}
public void editClientById(ClientMasterBean bean) {
// TODO Auto-generated method stub
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
session.update(bean);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.getTransaction().commit();
session.close();
}
}
public boolean getClientId(int id) {
// TODO Auto-generated method stub
Session session = HibernateSession.getSessionFactory().openSession();
try {
session.beginTransaction();
ClientMasterBean cl = (ClientMasterBean) session.get(ClientMasterBean.class, id);
if (cl == null) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.getTransaction().commit();
session.close();
}
return true;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/reports/was/web/InitMWasReportAction.java
package com.iprosonic.cmms.modules.job.reports.was.web;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.struts2.interceptor.SessionAware;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.pjcommons.valuelist.AssetTypeListAction;
import com.iprosonic.cmms.pjcommons.valuelist.CpiGetList;
import com.iprosonic.cmms.pjcommons.valuelist.EmployeeCdListAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class InitMWasReportAction extends ActionSupport implements SessionAware {
private static final long serialVersionUID = 1L;
private CpiBean cpiBean = new CpiBean();
CpiGetList cpiGetList = new CpiGetList();
EmployeeCdListAction employeeCdListAction = new EmployeeCdListAction();
AssetTypeListAction assetTypeListAction = new AssetTypeListAction();
private List<String> cpiCdList;
private List<String> unitCdList;
private Map<String, Object> session;
private List<String> cpiStatusList;
private List<String> assetTypeList;
private Set<String> impactToCoustomerSet;
private Set<String> effectOnCustomerSet;
private List<String> typeOfCpiList;
private List<String> subSourceOfCpiList;
private List<String> subGroupCdList;
private Set<String> subGroupCdSet;
private List<String> cpiCategoryList;
private List<String>frcaDoneByList;
private List<String>prcaDoneByList;
private List<String> sourceOfCpiList;
private List<String>cpiSubCategoryList;
private List<String>correctiveActionDoneByList;
@Override
public String execute() {
session = ActionContext.getContext().getSession();
cpiCdList = cpiGetList.getCpiCd();
unitCdList = cpiGetList.getUnitCdList();
cpiStatusList = cpiGetList.getCpiStatus();
setAssetTypeList(assetTypeListAction.getAssetType());
subSourceOfCpiList = cpiGetList.getSubSourceOfCpiList();
cpiCategoryList = cpiGetList.getCpiCategoryList();
frcaDoneByList = employeeCdListAction.getOriginatedByString();
prcaDoneByList = employeeCdListAction.getOriginatedByString();
correctiveActionDoneByList= employeeCdListAction.getOriginatedByString();
typeOfCpiList = cpiGetList.getTypeOfCpiList();
setSubGroupCdList(cpiGetList.getsubGroupCdList());
cpiCategoryList = cpiGetList.getCpiCategoryList();
sourceOfCpiList =cpiGetList.getSourceOfCpiList();
setCpiSubCategoryList(cpiGetList.getCpiSubCategoryList());
session.put("cpiCd", cpiCdList);
session.put("unitCd", unitCdList);
session.put("cpiStatus", cpiStatusList);
session.put("assetType", getAssetTypeList());
session.put("correctiveActionDoneBy1", correctiveActionDoneByList);
session.put("sourceOfCpi", sourceOfCpiList);
session.put("subSourceOfCpi", subSourceOfCpiList);
session.put("subGroupCd", subGroupCdList);
session.put("typeOfCpi", typeOfCpiList);
session.put("frcaDoneBy", frcaDoneByList);
session.put("prcaDoneBy", prcaDoneByList);
session.put("category", cpiCategoryList);
session.put("subCategory", cpiSubCategoryList);
return SUCCESS;
}
public void setCpiCdList(List<String> cpiCdList) {
this.cpiCdList = cpiCdList;
}
public List<String> getCpiCdList() {
return cpiCdList;
}
public void setUnitCdList(List<String> unitCdList) {
this.unitCdList = unitCdList;
}
public List<String> getUnitCdList() {
return unitCdList;
}
public void setCpiBean(CpiBean cpiBean) {
this.cpiBean = cpiBean;
}
public CpiBean getCpiBean() {
return cpiBean;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public Map<String, Object> getSession() {
return this.session;
}
public void setCpiStatusList(List<String> cpiStatusList) {
this.cpiStatusList = cpiStatusList;
}
public List<String> getCpiStatusList() {
return cpiStatusList;
}
public void setImpactToCoustomerSet(Set<String> impactToCoustomerSet) {
this.impactToCoustomerSet = impactToCoustomerSet;
}
public Set<String> getImpactToCoustomerSet() {
return impactToCoustomerSet;
}
public void setEffectOnCustomerSet(Set<String> effectOnCustomerSet) {
this.effectOnCustomerSet = effectOnCustomerSet;
}
public Set<String> getEffectOnCustomerSet() {
return effectOnCustomerSet;
}
public void setSubGroupCdSet(Set<String> subGroupCdSet) {
this.subGroupCdSet = subGroupCdSet;
}
public Set<String> getSubGroupCdSet() {
return subGroupCdSet;
}
public void setFrcaDoneByList(List<String> frcaDoneByList) {
this.frcaDoneByList = frcaDoneByList;
}
public List<String> getFrcaDoneByList() {
return frcaDoneByList;
}
public void setPrcaDoneByList(List<String> prcaDoneByList) {
this.prcaDoneByList = prcaDoneByList;
}
public List<String> getPrcaDoneByList() {
return prcaDoneByList;
}
public void setAssetTypeList(List<String> assetTypeList) {
this.assetTypeList = assetTypeList;
}
public List<String> getAssetTypeList() {
return assetTypeList;
}
public void setTypeOfCpiList(List<String> typeOfCpiList) {
this.typeOfCpiList = typeOfCpiList;
}
public List<String> getTypeOfCpiList() {
return typeOfCpiList;
}
public void setSourceOfCpiList(List<String> sourceOfCpiList) {
this.sourceOfCpiList = sourceOfCpiList;
}
public List<String> getSourceOfCpiList() {
return sourceOfCpiList;
}
public void setSubGroupCdList(List<String> subGroupCdList) {
this.subGroupCdList = subGroupCdList;
}
public List<String> getSubGroupCdList() {
return subGroupCdList;
}
public void setCpiSubCategoryList(List<String> cpiSubCategoryList) {
this.cpiSubCategoryList = cpiSubCategoryList;
}
public List<String> getCpiSubCategoryList() {
return cpiSubCategoryList;
}
public void setCorrectiveActionDoneByList(
List<String> correctiveActionDoneByList) {
this.correctiveActionDoneByList = correctiveActionDoneByList;
}
public List<String> getCorrectiveActionDoneByList() {
return correctiveActionDoneByList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/masters/user/service/EditEmployeeService.java
package com.iprosonic.cmms.modules.masters.user.service;
import com.iprosonic.cmms.modules.masters.user.dao.EmployeeDaoImpl;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
public class EditEmployeeService {
private EmployeeBean emp = new EmployeeBean();
private EmployeeDaoImpl empDao = new EmployeeDaoImpl();
public EmployeeBean edit(String id) {
emp= empDao.listEmployeeById(Integer.parseInt(id));
return emp;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/reports/jobbonus/web/InitJobBonusReportAction.java
package com.iprosonic.cmms.modules.job.reports.jobbonus.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.iprosonic.cmms.modules.job.reports.jobbonus.service.JobBonusReportService;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRunBean;
import com.iprosonic.cmms.pjcommons.utility.DateUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class InitJobBonusReportAction extends ActionSupport implements
ModelDriven<JobBean> {
private static final long serialVersionUID = 1L;
private JobBean jobBean = new JobBean();
private List<String> jobNoList = new ArrayList<String>();
private List<JobRunBean> jobRunList = new ArrayList<JobRunBean>();
private JobBonusReportService jobBonusReportService = new JobBonusReportService();
@Override
public String execute() {
Map session = (Map) ActionContext.getContext().get("session");
try {
jobBean.setJobDate(DateUtil.getCurrentJobDate());
jobNoList = jobBonusReportService.getJobNoList();
session.put("jobNoList", jobNoList);
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
public void setJobNoList(List<String> jobNoList) {
this.jobNoList = jobNoList;
}
public List<String> getJobNoList() {
return jobNoList;
}
public void setJobRunList(List<JobRunBean> jobRunList) {
this.jobRunList = jobRunList;
}
public List<JobRunBean> getJobRunList() {
return jobRunList;
}
@Override
public JobBean getModel() {
return jobBean;
}
public void setJobBean(JobBean jobBean) {
this.jobBean = jobBean;
}
public JobBean getJobBean() {
return jobBean;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/transactions/cpi/web/EditCPIAction.java
package com.iprosonic.cmms.modules.cpi.transactions.cpi.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.dao.CpiDAOImpl;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.service.CpiService;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.service.EditCPIService;
import com.iprosonic.cmms.pjcommons.valuelist.CpiGetList;
import com.iprosonic.cmms.pjcommons.valuelist.GroupCodeListAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class EditCPIAction extends ActionSupport implements
ModelDriven<CpiBean> {
private static final long serialVersionUID = 1L;
private CpiBean cpiBean = new CpiBean();
CpiDAOImpl cpiDAOImpl = new CpiDAOImpl();
CpiService cpiService = new CpiService();
CpiGetList cpiGetList = new CpiGetList();
GroupCodeListAction groupCodeListAction = new GroupCodeListAction();
EditCPIService editCpiService = new EditCPIService();
private List<String> cpiProcessList;
private List<String> cpiStatusList;
private List<String> cpiWhyOpenList;
private List<String> assetTypeList;
private List<String> assetNameList;
private List<String> assetSrNoList;
private List<String> sectionCdList;
private List<String> sectionSerialNoList;
private List<String> correctiveActionDoneByList;
private List<String> typeOfCpiList;
private List<String> sourceOfCpiList;
private List<String> subSourceOfCpiList;
private List<String> subGroupCdList;
private List<String> cpiCategoryList;
private List<String> cpiSubCategoryList;
private List<String> gropCdList;
public String execute() {
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
request.setAttribute("edit", "true");
edit();
cpiProcessList = cpiGetList.getCpiProcess();
cpiStatusList = cpiGetList.getCpiStatus();
cpiWhyOpenList = cpiGetList.getWhyOpen();
assetTypeList = cpiGetList.getAssetTypeList();
assetNameList = cpiGetList.getAssetNameList();
assetSrNoList = cpiGetList.getAssetSrNoList();
sectionCdList = cpiGetList.getSectionNoList();
sectionSerialNoList = cpiGetList.getSectionSerialNoList();
correctiveActionDoneByList = cpiGetList.correctiveActionDoneBy();
typeOfCpiList = cpiGetList.correctiveActionDoneBy();
sourceOfCpiList = cpiGetList.getSourceOfCpiList();
subSourceOfCpiList = cpiGetList.getSubSourceOfCpiList();
subGroupCdList = cpiGetList.getsubGroupCdList();
cpiCategoryList = cpiGetList.getCpiCategoryList();
cpiSubCategoryList = cpiGetList.getCpiSubCategoryList();
gropCdList = groupCodeListAction.getGroupCodeList();
return SUCCESS;
}
public void edit() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(ServletActionContext.HTTP_REQUEST);
cpiBean = editCpiService.edit(request.getParameter("id"));
setCpiBean(cpiBean);
}
@Override
public CpiBean getModel() {
// TODO Auto-generated method stub
return cpiBean;
}
public void setCpiBean(CpiBean cpiBean) {
this.cpiBean = cpiBean;
}
public CpiBean getCpiBean() {
return cpiBean;
}
public void setCpiProcessList(List<String> cpiProcessList) {
this.cpiProcessList = cpiProcessList;
}
public List<String> getCpiProcessList() {
return cpiProcessList;
}
public void setCpiStatusList(List<String> cpiStatusList) {
this.cpiStatusList = cpiStatusList;
}
public List<String> getCpiStatusList() {
return cpiStatusList;
}
public void setCpiWhyOpenList(List<String> cpiWhyOpenList) {
this.cpiWhyOpenList = cpiWhyOpenList;
}
public List<String> getCpiWhyOpenList() {
return cpiWhyOpenList;
}
public void setAssetTypeList(List<String> assetTypeList) {
this.assetTypeList = assetTypeList;
}
public List<String> getAssetTypeList() {
return assetTypeList;
}
public void setAssetNameList(List<String> assetNameList) {
this.assetNameList = assetNameList;
}
public List<String> getAssetNameList() {
return assetNameList;
}
public void setAssetSrNoList(List<String> assetSrNoList) {
this.assetSrNoList = assetSrNoList;
}
public List<String> getAssetSrNoList() {
return assetSrNoList;
}
public void setSectionCdList(List<String> sectionCdList) {
this.sectionCdList = sectionCdList;
}
public List<String> getSectionCdList() {
return sectionCdList;
}
public void setSectionSerialNoList(List<String> sectionSerialNoList) {
this.sectionSerialNoList = sectionSerialNoList;
}
public List<String> getSectionSerialNoList() {
return sectionSerialNoList;
}
public void setCorrectiveActionDoneByList(
List<String> correctiveActionDoneByList) {
this.correctiveActionDoneByList = correctiveActionDoneByList;
}
public List<String> getCorrectiveActionDoneByList() {
return correctiveActionDoneByList;
}
public void setTypeOfCpiList(List<String> typeOfCpiList) {
this.typeOfCpiList = typeOfCpiList;
}
public List<String> getTypeOfCpiList() {
return typeOfCpiList;
}
public void setSourceOfCpiList(List<String> sourceOfCpiList) {
this.sourceOfCpiList = sourceOfCpiList;
}
public List<String> getSourceOfCpiList() {
return sourceOfCpiList;
}
public void setSubSourceOfCpiList(List<String> subSourceOfCpiList) {
this.subSourceOfCpiList = subSourceOfCpiList;
}
public List<String> getSubSourceOfCpiList() {
return subSourceOfCpiList;
}
public void setSubGroupCdList(List<String> subGroupCdList) {
this.subGroupCdList = subGroupCdList;
}
public List<String> getSubGroupCdList() {
return subGroupCdList;
}
public void setCpiCategoryList(List<String> cpiCategoryList) {
this.cpiCategoryList = cpiCategoryList;
}
public List<String> getCpiCategoryList() {
return cpiCategoryList;
}
public void setCpiSubCategoryList(List<String> cpiSubCategoryList) {
this.cpiSubCategoryList = cpiSubCategoryList;
}
public List<String> getCpiSubCategoryList() {
return cpiSubCategoryList;
}
public void setGropCdList(List<String> gropCdList) {
this.gropCdList = gropCdList;
}
public List<String> getGropCdList() {
return gropCdList;
}
}<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/masters/assets/web/SearchAssetAction.java
package com.iprosonic.cmms.modules.cpi.masters.assets.web;
import java.util.List;
import com.iprosonic.cmms.modules.cpi.masters.assets.domain.AssetBean;
import com.iprosonic.cmms.modules.cpi.masters.assets.service.AssetService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class SearchAssetAction extends ActionSupport implements
ModelDriven<AssetBean> {
private static final long serialVersionUID = 1L;
private AssetBean assetBean = new AssetBean();
private List<AssetBean> assetBeansList;
AssetService assetService = new AssetService();
@Override
public String execute() {
String assetType = getModel().getAssetType();
String assetName = getModel().getAssetCd();
assetBeansList = assetService.getAssertList(assetType, assetName);
return SUCCESS;
}
@Override
public AssetBean getModel() {
return assetBean;
}
public void setAssetBean(AssetBean assetBean) {
this.assetBean = assetBean;
}
public AssetBean getAssetBean() {
return assetBean;
}
public void setAssetBeansList(List<AssetBean> assetBeansList) {
this.assetBeansList = assetBeansList;
}
public List<AssetBean> getAssetBeansList() {
return assetBeansList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/service/UpdateJobRigService.java
package com.iprosonic.cmms.modules.job.transactions.job.service;
import com.iprosonic.cmms.modules.job.transactions.job.dao.JobRigDaoImpl;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRigBean;
public class UpdateJobRigService {
public void updateRig(JobRigBean jobRigBean)
{
JobRigDaoImpl RigDao = new JobRigDaoImpl();
RigDao.updateJobRig(jobRigBean);
}
}
<file_sep>/cmms/WebContent/js/searchasset.js
function appValuesInCombo(str, combo) {
for (i = combo.options.length - 1; i >= 0; i--)
combo.remove(i);
var arr = str.split(":");
for (i = 0; i < arr.length; i++) {
var option = document.createElement("option");
option.text = arr[i];
option.value = arr[i];
try {
combo.add(option, null);
} catch (error) {
combo.add(option);
}
}
}
var updateId;
var formName;
var element_Id;
var displayDiv;
function appValuesInCombo(str, combo) {
for (i = combo.options.length - 1; i >= 0; i--)
combo.remove(i);
var arr = str.split(":");
for (i = 0; i < arr.length; i++) {
var option = document.createElement("option");
option.text = arr[i];
option.value = arr[i];
try {
combo.add(option, null);
} catch (error) {
combo.add(option);
}
}
}
function getAssetCd(obj) {
var assetType1 = obj.value;
url = 'GetListAction.action?param=getAssetCd1' + '&assetType1='
+ assetType1;
$.post(url, function(results) {
$('.result').html(results);
destinationCombo = document.getElementById("formValidate_assetCd");
appValuesInCombo(results, destinationCombo);
});
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/service/UpdateJobExplosive.java
package com.iprosonic.cmms.modules.job.transactions.job.service;
import com.iprosonic.cmms.modules.job.transactions.job.dao.JobExplosiveDaoImpl;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobExplBean;
public class UpdateJobExplosive {
public void updateJobExplosive(JobExplBean jobExplBean) throws Exception
{
JobExplosiveDaoImpl JobSExplosiveDao = new JobExplosiveDaoImpl();
JobSExplosiveDao.updateJobExplosive(jobExplBean);
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/transactions/cpi/web/SuccessAction.java
package com.iprosonic.cmms.modules.cpi.transactions.cpi.web;
import com.opensymphony.xwork2.ActionSupport;
public class SuccessAction extends ActionSupport {
public String execute() throws Exception {
return SUCCESS;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/transactions/cpi/web/SearchCpiAction.java
package com.iprosonic.cmms.modules.cpi.transactions.cpi.web;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.domain.CpiBean;
import com.iprosonic.cmms.modules.cpi.transactions.cpi.service.CpiService;
import com.iprosonic.cmms.pjcommons.utility.DateUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class SearchCpiAction extends ActionSupport implements SessionAware, ModelDriven<CpiBean> {
private static final long serialVersionUID = 1L;
private List<CpiBean> cpiBeanList;
private Map<String, Object> session;
private CpiBean cpiBean = new CpiBean();
CpiService cpiService = new CpiService();
public String execute() {
cpiBean.setDateOfCpi(DateUtil.getCurrentDateWasCpi());
HttpServletRequest request = ServletActionContext.getRequest();
String fromDate = request.getParameter("fromDate");
String toDate = request.getParameter("toDate");
cpiBeanList = cpiService.getCpi(fromDate, toDate, getModel().getCpiCd(), getModel().getCpiStatus(), getModel().getAssetName(), getModel().getSectionSerialNo());
session = ActionContext.getContext().getSession();
session.put("cpiBeanList", cpiBeanList);
return SUCCESS;
}
@Override
public CpiBean getModel() {
return cpiBean;
}
public void setCpiBean(CpiBean cpiBean) {
this.cpiBean = cpiBean;
}
public CpiBean getCpiBean() {
return cpiBean;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public Map<String, Object> getSession() {
return this.session;
}
public void setCpiBeanList(List<CpiBean> cpiBeanList) {
this.cpiBeanList = cpiBeanList;
}
public List<CpiBean> getCpiBeanList() {
return cpiBeanList;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/dao/JobExplosiveDaoImpl.java
package com.iprosonic.cmms.modules.job.transactions.job.dao;
import java.util.Iterator;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobExplBean;
import com.iprosonic.cmms.pjcommons.utility.HibernateSession;
public class JobExplosiveDaoImpl {
public JobExplBean getExplosiveByNo(String explNo) throws Exception {
JobExplBean jobExplBean = null;
Session session = HibernateSession.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(JobExplBean.class);
criteria.add(Restrictions.like("explNo", explNo));
Iterator<JobExplBean> itr = criteria.list().iterator();
while (itr.hasNext()) {
jobExplBean = itr.next();
}
session.close();
HibernateSession.shoutDown();
return jobExplBean;
}
public void updateJobExplosive(JobExplBean jobExplBean) throws Exception {
Session session = HibernateSession.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(jobExplBean);
transaction.commit();
session.close();
HibernateSession.shoutDown();
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/masters/location/domain/Locationmst.java
package com.iprosonic.cmms.modules.masters.location.domain;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Locationmst entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "locationmst", catalog = "wascpi_demo")
public class Locationmst {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "locationCd", length = 20)
private String locationCd;
@Column(name = "locationName", length = 100)
private String locationName;
@Column(name = "countryName", length = 100)
private String countryName;
@Column(name = "stateName", length = 100)
private String stateName;
@Column(name = "cityName", length = 100)
private String cityName;
@Column(name = "description")
private String description;
@Column(name = "locationStatus", length = 29)
private String locationStatus;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLocationCd() {
return locationCd;
}
public void setLocationCd(String locationCd) {
this.locationCd = locationCd;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocationStatus() {
return locationStatus;
}
public void setLocationStatus(String locationStatus) {
this.locationStatus = locationStatus;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/masters/service/service/SaveService.java
package com.iprosonic.cmms.modules.job.masters.service.service;
import java.util.Iterator;
import java.util.List;
import com.iprosonic.cmms.modules.job.masters.service.dao.ServiceDaoImpl;
import com.iprosonic.cmms.modules.job.masters.service.domain.ServiceMstBean;
public class SaveService {
private ServiceDaoImpl iServiceDao = null;
public SaveService()
{
iServiceDao = new ServiceDaoImpl();
}
public void saveService(ServiceMstBean serviceMstBean) {
iServiceDao.saveService(serviceMstBean);
}
public boolean isServiveTypeExists(String type) {
boolean res = false;
List<ServiceMstBean> list = iServiceDao.searchServiceListByType(type);
Iterator<ServiceMstBean> itr = list.iterator();
while (itr.hasNext()) {
ServiceMstBean jobTypeBean = itr.next();
if (jobTypeBean.getServiceType().equalsIgnoreCase(type)) {
res = true;
}
}
return res;
}
public void updateService(ServiceMstBean model) {
// TODO Auto-generated method stub
iServiceDao.updateSerivce(model);
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/reports/was/web/ServiceReportCrewWise.java
package com.iprosonic.cmms.modules.job.reports.was.web;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.iprosonic.cmms.modules.job.transactions.job.dao.JobRunDaoImpl;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobRunBean;
import com.iprosonic.cmms.modules.job.transactions.job.domain.JobServiceBean;
import com.iprosonic.cmms.modules.job.transactions.job.service.SearchJobService;
import com.iprosonic.cmms.modules.masters.user.dao.EmployeeDaoImpl;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
import com.iprosonic.cmms.pjcommons.utility.EmpContainsMatch;
import com.opensymphony.xwork2.ActionSupport;
public class ServiceReportCrewWise extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private int noofJobs;
private int totalmissruns;
private double totalchRuns;
private double totallosstime;
private double totallqat;
private double totallqap;
private int noofServices;
private String error;
SimpleDateFormat fromformat=new SimpleDateFormat("yyyy-MM-01");
SimpleDateFormat toformat=new SimpleDateFormat("yyyy-MM-dd");
private String fromDate=fromformat.format(new Date()).toString();
private String toDate=toformat.format(new Date()).toString();
private String crew;
private List<String> crewList=new ArrayList<String>();
private EmployeeDaoImpl employeeDaoImpl = new EmployeeDaoImpl();
private SearchJobService searchJobService = new SearchJobService();
private Set<JobServiceBean> serviceBeanList=new HashSet<JobServiceBean>();
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public int getNoofServices() {
return noofServices;
}
public void setNoofServices(int noofServices) {
this.noofServices = noofServices;
}
public int getTotalmissruns() {
return totalmissruns;
}
public void setTotalmissruns(int totalmissruns) {
this.totalmissruns = totalmissruns;
}
public int getNoofJobs() {
return noofJobs;
}
public void setNoofJobs(int noofJobs) {
this.noofJobs = noofJobs;
}
public double getTotalchRuns() {
return totalchRuns;
}
public void setTotalchRuns(double totalchRuns) {
this.totalchRuns = totalchRuns;
}
public double getTotallosstime() {
return totallosstime;
}
public void setTotallosstime(double totallosstime) {
this.totallosstime = totallosstime;
}
public double getTotallqat() {
return totallqat;
}
public void setTotallqat(double totallqat) {
this.totallqat = totallqat;
}
public double getTotallqap() {
return totallqap;
}
public void setTotallqap(double totallqap) {
this.totallqap = totallqap;
}
public void setTotallqap(int totallqap) {
this.totallqap = totallqap;
}
public Set<JobServiceBean> getServiceBeanList() {
return serviceBeanList;
}
public void setServiceBeanList(Set<JobServiceBean> serviceBeanList) {
this.serviceBeanList = serviceBeanList;
}
public List<String> getCrewList() {
List<EmployeeBean> employees = employeeDaoImpl.crewlist();
for (EmployeeBean employeeBean : employees) {
crewList.add(employeeBean.getEmployeeShortName());
}
return crewList;
}
public void setCrewList(List<String> crewList) {
this.crewList = crewList;
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getEngi() {
return crew;
}
public void setEngi(String engi) {
this.crew = engi;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
Set<JobBean> jobListByDate = searchJobService.getJobListSetByDate(fromDate, toDate);
Set<JobServiceBean> serviceList = searchJobService
.getJobServiceSet();
JobRunDaoImpl jobRunDaoImpl = new JobRunDaoImpl();
Set<JobRunBean> jobRunBeans = new HashSet<JobRunBean>(
jobRunDaoImpl.getRunList());
serviceBeanList = serviceListByDate(jobListByDate, serviceList,jobRunBeans);
return INPUT;
}
private Set<JobServiceBean> serviceListByDate(Set<JobBean> jobListByDate,
Set<JobServiceBean> serviceList, Set<JobRunBean> jobRunBeans) {
Set<JobServiceBean> services = new HashSet<JobServiceBean>();
Boolean isContains= false;
try{
for (JobBean jobBean : jobListByDate) {
for (JobServiceBean jobServiceBean : serviceList) {
{
if (jobBean.getJobNo().equals(jobServiceBean.getJobNo()) ) {
String engArr=jobServiceBean.getCrew()!=null ? jobServiceBean.getCrew().trim() : "";
isContains = EmpContainsMatch.matchEmp(
engArr,
crew);
if(isContains){
JobServiceBean bean=new JobServiceBean();
bean.setJobNo(jobServiceBean.getJobNo());
bean.setChmisRuns(isNumeric(jobServiceBean.getChmisRuns()) ? jobServiceBean.getChmisRuns(): "0" );
bean.setChruns(isNumeric((jobServiceBean.getChruns())) ? jobServiceBean.getChruns(): "0" );
bean.setLossTime(isNumeric((jobServiceBean.getLossTime())) ? jobServiceBean.getLossTime(): "0" );
bean.setLqaPresentation(isNumeric((jobServiceBean.getLqaPresentation())) ? jobServiceBean.getLqaPresentation(): "0" );
bean.setLqaTechnical(isNumeric((jobServiceBean.getLqaTechnical())) ? jobServiceBean.getLqaTechnical(): "0" );
bean.setServiceNo(jobServiceBean.getServiceNo());
services.add(bean);
}
}
}
}
}
// }
int countLQAT=0;
int countLQAP=0;
double totalOT=0;
Set<String> set=new HashSet<String>();
for (JobServiceBean jobServiceBean : services) {
for (JobRunBean jobRunBean : jobRunBeans) {
if(jobServiceBean.getJobNo().equals(jobRunBean.getJobNo())){
double d=calculateOT(jobRunBean.getOt());
if(d <= 0.0d){
error="error";
}
}
}
totalmissruns=totalmissruns+Integer.parseInt(jobServiceBean.getChmisRuns().equals("") ?"0" :jobServiceBean.getChmisRuns());
totalchRuns=totalchRuns+Double.parseDouble(jobServiceBean.getChruns().equals("")? "0" :jobServiceBean.getChruns());
totallosstime=totallosstime+Double.parseDouble(jobServiceBean.getLossTime().equals("")?"0":jobServiceBean.getLossTime());
totallqat=totallqat+Integer.parseInt(jobServiceBean.getLqaTechnical().equals("")?"0":jobServiceBean.getLqaTechnical());
if(Integer.parseInt(jobServiceBean.getLqaTechnical()) > 0 ){
countLQAT=countLQAT+1;
}
totallqap=totallqap+Integer.parseInt(jobServiceBean.getLqaPresentation().equals("")?"0":jobServiceBean.getLqaPresentation());
if(Integer.parseInt(jobServiceBean.getLqaPresentation()) > 0 ){
countLQAP=countLQAP+1;
}
set.add(jobServiceBean.getJobNo());
}
noofServices=services.size();
noofJobs=set.size();
if(countLQAT < totallqat){
totallqat=totallqat/countLQAT;
}
if(countLQAP < totallqap){
totallqap=totallqap/countLQAP;
}
}catch(Exception e){
e.printStackTrace();
totallqat=0;
totallqap=0;
}
return services;
}
public boolean isNumeric(String data) {
try {
Double.parseDouble(data);
} catch (Exception e) {
return false;
}
return true;
}
private double calculateOT(String ot) {
// TODO Auto-generated method stub
double doubleOT=0.0d;
try {
String[] sOT=ot.split(",");
String hstr=sOT[0].replace("Hrs", "");
String mstr=sOT[1].replace("Mins", "");
doubleOT = Double.parseDouble(hstr)+Double.parseDouble(mstr)/60;
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("input ot="+ot);
e.printStackTrace();
}
return doubleOT;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/cpi/reports/historycard/web/HistoryCardReportAction.java
package com.iprosonic.cmms.modules.cpi.reports.historycard.web;
import java.io.File;
import java.io.FileInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.iprosonic.cmms.modules.cpi.reports.historycard.service.HistoryCardReportService;
import com.iprosonic.cmms.pjcommons.utility.ContextFile;
import com.opensymphony.xwork2.ActionSupport;
public class HistoryCardReportAction extends ActionSupport {
private static final long serialVersionUID = 1L;
HistoryCardReportService historyCardReportService = new HistoryCardReportService();
@Override
public String execute() {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/vnd.ms-excel");
String excelPath=ContextFile.getContextFile("historyCardExcelPath");
historyCardReportService.generateHistoryCardReport(
request.getParameter("assetType"),
request.getParameter("assetName"),
request.getParameter("assetSrNo"),
request.getParameter("sectionName"),
request.getParameter("sectionSerialNo"),excelPath);
File file = null;
String downloadPath = excelPath;
ServletOutputStream out = null;
FileInputStream fis = null;
try {
file = new File(downloadPath);
fis = new FileInputStream(file);
out = response.getOutputStream();
byte[] outputByte = new byte[(int) file.length()];
while (fis.read(outputByte, 0, (int) file.length()) != -1) {
out.write(outputByte, 0, (int) file.length());
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fis.close();
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
// file.delete();
return NONE;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/masters/service/service/UpdateService.java
package com.iprosonic.cmms.modules.job.masters.service.service;
import com.iprosonic.cmms.modules.job.masters.service.dao.ServiceDaoImpl;
import com.iprosonic.cmms.modules.job.masters.service.domain.ServiceMstBean;
public class UpdateService {
private ServiceDaoImpl iServiceDao = null;
public UpdateService() {
iServiceDao = new ServiceDaoImpl();
}
public void updateService(ServiceMstBean serviceMstBean) {
iServiceDao.updateSerivce(serviceMstBean);
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/job/transactions/job/domain/JobRigBean.java
package com.iprosonic.cmms.modules.job.transactions.job.domain;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "jobrig")
public class JobRigBean implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "rigNo", unique = true, nullable = false, length = 100)
private String rigNo;
@ManyToMany(fetch = FetchType.LAZY, targetEntity = JobRunBean.class, cascade = CascadeType.ALL)
@JoinColumn(name = "rigNo", referencedColumnName = "rigNo")
private Set<JobRunBean> jobRunBeanSet = new HashSet<JobRunBean>();
@JoinColumn(name = "jobNo",nullable=false)
private String jobNo;
@Column(name = "rigUpStart")
private String rigUpStart;
@Column(name = "rigUpEnd")
private String rigUpEnd;
@Column(name = "rigDownStart")
private String rigDownStart;
@Column(name = "rigDownEnd")
private String rigDownEnd;
@Column(name = "opTime")
private String opTime;
public void setOpTime(String opTime) {
this.opTime = opTime;
}
public String getOpTime() {
return opTime;
}
public void setJobNo(String jobNo) {
this.jobNo = jobNo;
}
public String getJobNo() {
return jobNo;
}
public void setRigNo(String rigNo) {
this.rigNo = rigNo;
}
public String getRigNo() {
return rigNo;
}
public void setJobRunBeanSet(Set<JobRunBean> jobRunBeanSet) {
this.jobRunBeanSet = jobRunBeanSet;
}
public Set<JobRunBean> getJobRunBeanSet() {
return jobRunBeanSet;
}
public void setRigUpStart(String rigUpStart) {
this.rigUpStart = rigUpStart;
}
public String getRigUpStart() {
return rigUpStart;
}
public void setRigUpEnd(String rigUpEnd) {
this.rigUpEnd = rigUpEnd;
}
public String getRigUpEnd() {
return rigUpEnd;
}
public void setRigDownStart(String rigDownStart) {
this.rigDownStart = rigDownStart;
}
public String getRigDownStart() {
return rigDownStart;
}
public void setRigDownEnd(String rigDownEnd) {
this.rigDownEnd = rigDownEnd;
}
public String getRigDownEnd() {
return rigDownEnd;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/modules/masters/user/web/EditEmployeeAction.java
package com.iprosonic.cmms.modules.masters.user.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.iprosonic.cmms.modules.masters.user.dao.EmployeeDaoImpl;
import com.iprosonic.cmms.modules.masters.user.domain.EmployeeBean;
import com.iprosonic.cmms.modules.masters.user.service.EditEmployeeService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class EditEmployeeAction extends ActionSupport implements
ModelDriven<EmployeeBean> {
private static final long serialVersionUID = -6659925652584240539L;
private EmployeeBean employeeBean = new EmployeeBean();
private List<EmployeeBean> employeeList = new ArrayList<EmployeeBean>();
private EmployeeDaoImpl employeeDao = new EmployeeDaoImpl();
private String userName;
EditEmployeeService editUserService = new EditEmployeeService();
public String execute() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(ServletActionContext.HTTP_REQUEST);
String message = "Employee updated succesfully";
request.setAttribute("message", message);
request.setAttribute("edit", "true");
edit();
setEmployeeList(employeeDao.listUser());
return SUCCESS;
}
public void edit() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(ServletActionContext.HTTP_REQUEST);
setEmployeeBean(editUserService.edit(request.getParameter("id")));
}
@Override
public EmployeeBean getModel() {
return null;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setEmployeeList(List<EmployeeBean> employeeList) {
this.employeeList = employeeList;
}
public List<EmployeeBean> getEmployeeList() {
return employeeList;
}
public void setEmployeeBean(EmployeeBean employeeBean) {
this.employeeBean = employeeBean;
}
public EmployeeBean getEmployeeBean() {
return employeeBean;
}
}
<file_sep>/cmms/src/com/iprosonic/cmms/pjcommons/action/GoBackAction.java
package com.iprosonic.cmms.pjcommons.action;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class GoBackAction extends ActionSupport {
private static final long serialVersionUID = 1L;
public String execute() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) ActionContext
.getContext().get(ServletActionContext.HTTP_RESPONSE);
String oldURL = request.getParameter("oldURL");
try {
response.sendRedirect(oldURL);
} catch (IOException e) {
e.printStackTrace();
}
return NONE;
}
}
|
46478d517a35028f832471e012aed6f6d830eb93
|
[
"JavaScript",
"Java",
"INI"
] | 68
|
Java
|
saurabhipro/cmms_hls
|
c9a232bcaa7423b8fade149e618a9130e67f8093
|
598ec1f56fd873139b9ecebdc6d6be298492ca2a
|
refs/heads/master
|
<repo_name>Karsus7/Employee_Summary<file_sep>/lib/Engineer.js
// TODO: Write code to define and export the Engineer class. HINT: This class should inherit from Employee.
// Line below causes the file to pull from Employess.js
// See 10-OOP activities 20 and 21 for examples of subclasses.
const Employee = require("./Employee.js");
// Engineer Class
class Engineer extends Employee{
constructor(name, id, email, gitName){
super(name, id, email);
this.role = "Engineer";
this.github = gitName;
}
// Above constructor details derived from test.
//Getters/Setters
getGithub(){return this.github;}
}
module.exports = Engineer;<file_sep>/app.js
// This is the actual program. First, there must be a manager,
// then the user may add as many interns and engineers as they want.
const Manager = require("./lib/Manager");
const Engineer = require("./lib/Engineer");
const Intern = require("./lib/Intern");
const inquirer = require("inquirer");
const path = require("path");
const fs = require("fs");
// The two lines below explain the need for the output folder, and the team.html file.
// team.html is where the answers to the questions are displayed.
const OUTPUT_DIR = path.resolve(__dirname, "output")
const outputPath = path.join(OUTPUT_DIR, "team.html");
//The line below connects this to the htmlRenderer.js file.
const render = require("./lib/htmlRenderer");
// Function prompts the user to ask what type of employee you are.
// (Manager is seperate, it is assumed there is one manager.)
function getEmployeeType(){
return inquirer.prompt([
{
type:'list',
message:`Enter the Employee's role : `,
choices:['Engineer','Intern'],
name:'role'
}
]);
}
// Each employee type (manager, engineer, or intern) has different information required. (See tests)
function getStandardQuestions(role){
// Standard questions to ask all employees. See Employee.js/Employee.test.js
const standardQuestions = [
{
type:'input',
message:`Name of ${role}: `,
name:'name'
},
{
type:'input',
message:`ID# of ${role}: `,
name:'id'
},
{
type:'input',
message:`Email for ${role}: `,
name:'email'
},
];
let questions;
// Specialized questions for each of the three positions.
// See 10-OOP activities 20 and 21 for examples of subclasses.
if (role=="Engineer"){
questions = [...standardQuestions,
{
type:'input',
message:`GitHub for ${role}: `,
name:'github'
}]
}
else if (role=="Intern"){
questions = [...standardQuestions,
{
type:'input',
message:`School for ${role}: `,
name:'school'
}]
}
else if (role=="Manager"){
questions = [...standardQuestions,
{
type:'input',
message:`Office Number for ${role}: `,
name:'officeNumber'
}]
}
return inquirer.prompt(questions);
}
// Prompt provides "yes or No" question to restart questions to add another employee.
function addMorePrompt(){
return inquirer.prompt([
{
type:'list',
message:`Add more users? : `,
choices:['Yes',"No"],
name:'confirm'
}
]);
}
async function run(){
const employees = [];
let firstRun = true;
// loop through the employee creation untill the user says do not add more
do{
// Write code to use inquirer to gather information about the development team members,
// The first run must be the Manager, and there can only be one Manager.
if(!firstRun){
type = await getEmployeeType();
}
else{
firstRun = false;
type = {role:"Manager"}
}
let data = await getStandardQuestions(type.role);
// and to create objects for each team member (using the correct classes as blueprints!)
switch(type.role){
case 'Engineer':
employees.push( new Engineer(data.name, data.id, data.email, data.github));
break;
case 'Intern':
employees.push( new Intern(data.name, data.id, data.email, data.school));
break;
case 'Manager':
employees.push( new Manager(data.name, data.id, data.email, data.officeNumber));
break;
}
// If the addMorePrompt function is answered "no", the loop ends.
var getMore = await addMorePrompt();
} while (getMore.confirm!= "No");
//console.log( employees );
// After the user has input all employees desired, call the `render` function (required
// above) and pass in an array containing all employee objects; the `render` function will
// generate and return a block of HTML including templated divs for each employee!
const html = render(employees);
//console.log(html);
// After you have your html, you're now ready to create an HTML file using the HTML
// returned from the `render` function. Now write it to a file named `team.html` in the
// `output` folder. You can use the variable `outputPath` above target this location.
// try and catch serve to report errors. See 09-NodeJS activities 38 and 40 for examples.
try{
if (!fs.existsSync(OUTPUT_DIR)) {
fs.mkdirSync(OUTPUT_DIR);
}
}
catch(err){
return console.log(err);
}
fs.writeFile(outputPath, html, function(err){
if (err){return console.log(err)}
console.log("Successfully wrote team.html.");
})
}
// Line below causes code to actually run, by triggering the above async function. (IMPORTANT)
run();
// Write code to use inquirer to gather information about the development team members,
// and to create objects for each team member (using the correct classes as blueprints!)
// After the user has input all employees desired, call the `render` function (required
// above) and pass in an array containing all employee objects; the `render` function will
// generate and return a block of HTML including templated divs for each employee!
// After you have your html, you're now ready to create an HTML file using the HTML
// returned from the `render` function. Now write it to a file named `team.html` in the
// `output` folder. You can use the variable `outputPath` above target this location.
// Hint: you may need to check if the `output` folder exists and create it if it
// does not.
// HINT: each employee type (manager, engineer, or intern) has slightly different
// information; write your code to ask different questions via inquirer depending on
// employee type.
// HINT: make sure to build out your classes first! Remember that your Manager, Engineer,
// and Intern classes should all extend from a class named Employee; see the directions
// for further information. Be sure to test out each class and verify it generates an
// object with the correct structure and methods. This structure will be crucial in order
// for the provided `render` function to work! ```
<file_sep>/lib/Intern.js
// TODO: Write code to define and export the Intern class. HINT: This class should inherit from Employee.
// Line below causes the file to pull from Employee.js
// See 10-OOP activities 20 and 21 for examples of subclasses.
const Employee = require("./Employee.js")
// Intern Class
class Intern extends Employee{
constructor(name, id, email, school){
super(name, id, email);
this.role = "Intern";
this.school = school;
}
// Above constructor details derived from test.
//Getters/Setters
getSchool(){return this.school;}
}
module.exports = Intern;<file_sep>/lib/Manager.js
// TODO: Write code to define and export the Manager class. HINT: This class should inherit from Employee.
// Line below causes the file to pull from Employess.js
// See 10-OOP activities 20 and 21 for examples of subclasses.
const Employee = require("./Employee.js");
// Manager Class
class Manager extends Employee{
constructor(name, id, email, office){
super(name, id, email);
this.role = "Manager";
this.officeNumber = office;
}
// Above constructor details derived from test.
//Getters/Setters
getOfficeNumber(){return this.officeNumber}
}
//export so this class can be inclulded in other files
module.exports = Manager;<file_sep>/README.md
# Employee Directory 
## Description
A cli tool using template Engines to create contact cards for each employee for a given team
## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [License](#license)
* [Credits](#contributing)
* [Testing](#tests)
* [Questions](#questions)
* [Demo](#demo)
## Installation
fork or duplicate project.
to set up all required dependencies, navigate to the project in terminal, and run:
```
npm install
```
## Usage
running the terminal at the project location, run:
```
node app.js
```
## License
MIT
## Contributing
[<NAME>](https://github.com/Karsus7)
<img src="https://avatars3.githubusercontent.com/u/61363843?v=4" height="50" width="50">
## Tests
Tested with Jest.
## Demo

|
60b4c2bcc8d22b455c02ce855092867f25cf170a
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
Karsus7/Employee_Summary
|
df628b7eed5aa13b62d5b5a227b45a948c32d22c
|
5eee6b8b43d9cb5d9cbdcd925d4a32cb261e7a4d
|
refs/heads/master
|
<file_sep>import { Todo } from "./todolist";
export function todoByID(ID: string) {
return (todo: Todo) => todo.ID === ID
}
export function notTodoByID(ID: string) {
return (todo: Todo) => todo.ID !== ID
}<file_sep>export const AppColors = {
appTheme: '#3A2B85',
headerColor: '#2C2C2C',
subHeaderColor: '#848484',
hrColor: '#D3D3D3',
todoListItem: 'white',
buttonText: 'white',
addButton: '#3A2B85',
completeButton: '#41D3BD',
deleteButton: '#E03535',
pointsColor: '#41d3bd',
// Default building colors
windowColor: '#077187',
windowBorderColor: '#C6D8D3',
flatRoofColor: '#C6D8D3',
flatRoofShadow: '#889390',
garageDoorColor: '#B8C5D6',
garageDoorBorderColor: '#889390',
doorColor: '#66635B'
}<file_sep>import { Todo } from "../todolist";
import { todoByID } from "../todoHelpers";
const testTodo: Todo = {
ID: 'test',
text: 'text',
timeStarted: new Date(),
timeEnded: new Date()
}
describe('todoByID tests', () => {
it('should work by returning true by the right ID', () => {
expect(todoByID('test')(testTodo)).toBeTruthy()
})
it('should work by returning true by the right ID', () => {
expect(todoByID('nope')(testTodo)).toBeFalsy()
})
})<file_sep>import { todoByID, notTodoByID } from "./todoHelpers";
import shortID from 'shortid'
import { format } from "date-fns";
import { TIME_FORMAT } from "../../common/date";
import { pointsCalculator } from "../points/pointsCalculator";
export enum TodoListActions {
ADD,
REMOVE,
COMPLETE,
SET
}
export interface Todo {
ID: string;
text: string;
timeStarted: Date
timeEnded?: Date
points?: number
}
export interface TodoListState {
inProgressTodoList: Todo[]
completedTodos: CompletedTodos;
}
export type CompletedTodos = { [key: string]: Todo[] };
export interface AddTodoAction {
type: TodoListActions.ADD,
payload: Todo
}
export interface RemoveTodoAction {
type: TodoListActions.REMOVE,
payload: string
}
export interface CompleteTodoAction {
type: TodoListActions.COMPLETE,
payload: {
todoID: string,
timeEnded: Date,
points: number
}
}
export interface SetTodoAction {
type: TodoListActions.SET,
payload: TodoListState
}
export type TodoAction = AddTodoAction | RemoveTodoAction | CompleteTodoAction | SetTodoAction
// -- Constants --
export const initialTodoListState: TodoListState = {
inProgressTodoList: [],
completedTodos: {}
}
// -- Action Creators --
export function addTodo(text: string): AddTodoAction {
return {
type: TodoListActions.ADD,
payload: {
ID: shortID.generate(),
text,
timeStarted: new Date()
}
}
}
export function removeTodo(todoID: string): RemoveTodoAction {
return {
type: TodoListActions.REMOVE,
payload: todoID
}
}
export function completeTodo(todoID: string, timeEnded: Date, points: number): CompleteTodoAction {
return {
type: TodoListActions.COMPLETE,
payload: {
todoID,
timeEnded,
points
}
}
}
export function setTodo(state: TodoListState): SetTodoAction {
return {
type: TodoListActions.SET,
payload: state
}
}
// -- Reducer --
export function todoListReducer(state: TodoListState = initialTodoListState, action: TodoAction): TodoListState {
switch (action.type) {
case TodoListActions.ADD:
return addTodoHelper(state, action.payload)
case TodoListActions.COMPLETE:
return completeTodoHelper(state, action.payload.todoID, action.payload.timeEnded, action.payload.points)
case TodoListActions.REMOVE:
return removeTodoHelper(state, action.payload)
case TodoListActions.SET:
return action.payload
default:
return state
}
}
// -- Reducer Helpers --
function addTodoHelper(state: TodoListState, todo: Todo): TodoListState {
return {
...state,
inProgressTodoList: [...state.inProgressTodoList, todo]
}
}
function completeTodoHelper(state: TodoListState, todoID: string, timeEnded: Date, points: number): TodoListState {
const { completedTodos } = state;
const todo = state.inProgressTodoList.find(todoByID(todoID)) as Todo
const completedTodo = {
...todo,
timeEnded,
points
}
const dateKey = format(completedTodo.timeEnded, TIME_FORMAT)
const newCompletedTodos = completedTodos[dateKey] ? [...completedTodos[dateKey], completedTodo] : [completedTodo]
return {
inProgressTodoList: state.inProgressTodoList.filter(notTodoByID(todoID)),
completedTodos: {
...completedTodos,
[dateKey]: newCompletedTodos
}
}
}
function removeTodoHelper(state: TodoListState, todoID: string): TodoListState {
return {
...state,
inProgressTodoList: state.inProgressTodoList.filter(notTodoByID(todoID))
}
}<file_sep>import { differenceInSeconds } from "date-fns";
const MAX_CHARS = 240
const RAND_MIN = 1
const RAND_MAX = 1000
const MAX_TIME_SECONDS = 3600
const CHAR_MODIFIER = 0.2
const TIME_MODIFIER = 0.3
const RAND_MODIFIER = 0.5
export function pointsCalculator(
text: string,
timeStarted: Date,
timeEnded: Date,
ranGenerator: (min: number, max: number) => number = random) {
const charLength = text.length
const timeTakenSeconds = differenceInSeconds(timeEnded, timeStarted)
const randomAttr = ranGenerator(RAND_MIN, RAND_MAX)
const charPercent = (charLength > MAX_CHARS ? 1 : (charLength / MAX_CHARS)) * CHAR_MODIFIER
const timeTakenSecondsPercent = (timeTakenSeconds > MAX_TIME_SECONDS ? 1 : (timeTakenSeconds / MAX_TIME_SECONDS)) * TIME_MODIFIER
const randomPercent = (randomAttr / RAND_MAX) * RAND_MODIFIER
const total = (charPercent + randomPercent + timeTakenSecondsPercent) * 100
return Math.round(total)
}
export function random(min: number,max: number) {
return Math.floor(Math.random()*(max-min+1)+min);
}<file_sep>import { TodoAction, TodoListActions, setTodo, TodoListState } from "../todos/todoList";
import { Dispatch, Store } from "redux";
import { AsyncStorage } from "react-native";
export const STORE_KEY = '@Citii:state'
export function storageMiddleware(store: Store) {
return (next: Dispatch) => {
return (action: TodoAction) => {
const result = next(action)
switch (action.type) {
case TodoListActions.ADD:
case TodoListActions.COMPLETE:
case TodoListActions.REMOVE:
// Don't wait for the store to respond, just write and ignore the errors
const state = store.getState()
AsyncStorage.setItem(STORE_KEY, JSON.stringify(state))
break
default:
break
}
return result
}
}
}
export function getStateFromStore() {
return async (dispatch: Dispatch) => {
// Todo: handle errors and loading gracefully
try {
const stateString = await AsyncStorage.getItem(STORE_KEY)
if (!stateString) {
return
}
const state = JSON.parse(stateString) as TodoListState | undefined
if (state) {
dispatch(setTodo(state))
}
} catch (error) {
console.log(error)
}
}
}<file_sep>import { addSeconds } from "date-fns";
import { pointsCalculator } from "../pointsCalculator";
describe('pointsCalculator tests', () => {
const timeStarted = new Date()
it('should work with proper attributes', () => {
const text = 'hello world'
const timeEnded = addSeconds(timeStarted, 30)
const randomGen = () => 400
const expected = 21
const actual = pointsCalculator(text, timeStarted, timeEnded, randomGen)
expect(actual).toBe(expected)
})
it('should work and return zero for no properties', () => {
const text = ''
const randomGen = () => 1
const expected = 0
const actual = pointsCalculator(text, timeStarted, timeStarted, randomGen)
expect(actual).toBe(expected)
})
it('should work and return 100 for everything maxed out', () => {
const text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu'
const timeEnded = addSeconds(timeStarted, 3600)
const randomGen = () => 1000
const expected = 100
const actual = pointsCalculator(text, timeStarted, timeEnded, randomGen)
expect(actual).toBe(expected)
})
it('should work and return 100 even if the values are over the max', () => {
const text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pellentesque eu'
const timeEnded = addSeconds(timeStarted, 459493453487)
const randomGen = () => 1000
const expected = 100
const actual = pointsCalculator(text, timeStarted, timeEnded, randomGen)
expect(actual).toBe(expected)
})
})
|
0904b99e4ccb409715592f30508ec3400ff53e59
|
[
"TypeScript"
] | 7
|
TypeScript
|
awaseem/citii
|
227f8048c37a6c4e4a286a96b1580888ea9391d6
|
dff8e19ab363a8bedb8d1b7502d6b9c2965d9bcc
|
refs/heads/master
|
<repo_name>Smootherist/evaluate<file_sep>/ReadMe.txt
根据给出的qrels文本和各.eval文件,依次根据P@10、R@50、MAP、nDCG@10、nDCG@20来评估IR系统。<file_sep>/f10_output_eval.py
import numpy
def output(p_10, r_50, R_p, ap_value, ndcg_10, ndcg_20):
all_score = open('All.eval', 'w')
all_score.write(' \tP@10\tR@50\tr-Precision\tAP\tnCCG@10\tnDCG@20')
# Out put 1st file
file_num = 0
s = open('S1.eval', 'w')
s.write(' \tP@10\tR@50\tr-Precision\tAP\tnCCG@10\tnDCG@20\n')
mean_list = [[], [], [], [], [], []]
for i in range(len(p_10[file_num])):
if i % 2 == 1:
s.write('%s' % p_10[file_num][i-1][0])
s.write('\t%s' % round(p_10[file_num][i][0], 3))
s.write('\t%s' % round(r_50[file_num][i][0], 3))
s.write('\t%s' % round(R_p[file_num][i][0],3))
s.write('\t%s' % round(ap_value[file_num][i][0], 3))
s.write('\t%s' % round(ndcg_10[file_num][i][0], 3))
s.write('\t%s\n' % round(ndcg_20[file_num][i][0], 3))
mean_list[0].append(p_10[file_num][i][0])
mean_list[1].append(r_50[file_num][i][0])
mean_list[2].append(R_p[file_num][i][0])
mean_list[3].append(ap_value[file_num][i][0])
mean_list[4].append(ndcg_10[file_num][i][0])
mean_list[5].append(ndcg_20[file_num][i][0])
all_score.write('\nS1\t')
s.write('mean\t')
for i in range(len(mean_list)):
s.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
all_score.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
s.close()
# Out put 2nd file
file_num += 1
s = open('S2.eval', 'w')
s.write(' \tP@10\tR@50\tr-Precision\tAP\tnCCG@10\tnDCG@20\n')
mean_list = [[], [], [], [], [], []]
for i in range(len(p_10[file_num])):
if i % 2 == 1:
s.write('%s' % p_10[file_num][i - 1][0])
s.write('\t%s' % round(p_10[file_num][i][0], 3))
s.write('\t%s' % round(r_50[file_num][i][0], 3))
s.write('\t%s' % round(R_p[file_num][i][0], 3))
s.write('\t%s' % round(ap_value[file_num][i][0], 3))
s.write('\t%s' % round(ndcg_10[file_num][i][0], 3))
s.write('\t%s\n' % round(ndcg_20[file_num][i][0], 3))
mean_list[0].append(p_10[file_num][i][0])
mean_list[1].append(r_50[file_num][i][0])
mean_list[2].append(R_p[file_num][i][0])
mean_list[3].append(ap_value[file_num][i][0])
mean_list[4].append(ndcg_10[file_num][i][0])
mean_list[5].append(ndcg_20[file_num][i][0])
all_score.write('\nS2\t')
s.write('mean\t')
for i in range(len(mean_list)):
s.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
all_score.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
s.close()
# Out put 3rd file
file_num += 1
s = open('S3.eval', 'w')
s.write(' \tP@10\tR@50\tr-Precision\tAP\tnCCG@10\tnDCG@20\n')
mean_list = [[], [], [], [], [], []]
for i in range(len(p_10[file_num])):
if i % 2 == 1:
s.write('%s' % p_10[file_num][i - 1][0])
s.write('\t%s' % round(p_10[file_num][i][0], 3))
s.write('\t%s' % round(r_50[file_num][i][0], 3))
s.write('\t%s' % round(R_p[file_num][i][0], 3))
s.write('\t%s' % round(ap_value[file_num][i][0], 3))
s.write('\t%s' % round(ndcg_10[file_num][i][0], 3))
s.write('\t%s\n' % round(ndcg_20[file_num][i][0], 3))
mean_list[0].append(p_10[file_num][i][0])
mean_list[1].append(r_50[file_num][i][0])
mean_list[2].append(R_p[file_num][i][0])
mean_list[3].append(ap_value[file_num][i][0])
mean_list[4].append(ndcg_10[file_num][i][0])
mean_list[5].append(ndcg_20[file_num][i][0])
all_score.write('\nS3\t')
s.write('mean\t')
for i in range(len(mean_list)):
s.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
all_score.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
s.close()
# Out put 4th file
file_num += 1
s = open('S4.eval', 'w')
s.write(' \tP@10\tR@50\tr-Precision\tAP\tnCCG@10\tnDCG@20\n')
mean_list = [[], [], [], [], [], []]
for i in range(len(p_10[file_num])):
if i % 2 == 1:
s.write('%s' % p_10[file_num][i - 1][0])
s.write('\t%s' % round(p_10[file_num][i][0], 3))
s.write('\t%s' % round(r_50[file_num][i][0], 3))
s.write('\t%s' % round(R_p[file_num][i][0], 3))
s.write('\t%s' % round(ap_value[file_num][i][0], 3))
s.write('\t%s' % round(ndcg_10[file_num][i][0], 3))
s.write('\t%s\n' % round(ndcg_20[file_num][i][0], 3))
mean_list[0].append(p_10[file_num][i][0])
mean_list[1].append(r_50[file_num][i][0])
mean_list[2].append(R_p[file_num][i][0])
mean_list[3].append(ap_value[file_num][i][0])
mean_list[4].append(ndcg_10[file_num][i][0])
mean_list[5].append(ndcg_20[file_num][i][0])
all_score.write('\nS4\t')
s.write('mean\t')
for i in range(len(mean_list)):
s.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
all_score.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
s.close()
# Out put 5th file
file_num += 1
s = open('S5.eval', 'w')
s.write(' \tP@10\tR@50\tr-Precision\tAP\tnCCG@10\tnDCG@20\n')
mean_list = [[], [], [], [], [], []]
for i in range(len(p_10[file_num])):
if i % 2 == 1:
s.write('%s' % p_10[file_num][i - 1][0])
s.write('\t%s' % round(p_10[file_num][i][0], 3))
s.write('\t%s' % round(r_50[file_num][i][0], 3))
s.write('\t%s' % round(R_p[file_num][i][0], 3))
s.write('\t%s' % round(ap_value[file_num][i][0], 3))
s.write('\t%s' % round(ndcg_10[file_num][i][0], 3))
s.write('\t%s\n' % round(ndcg_20[file_num][i][0], 3))
mean_list[0].append(p_10[file_num][i][0])
mean_list[1].append(r_50[file_num][i][0])
mean_list[2].append(R_p[file_num][i][0])
mean_list[3].append(ap_value[file_num][i][0])
mean_list[4].append(ndcg_10[file_num][i][0])
mean_list[5].append(ndcg_20[file_num][i][0])
all_score.write('\nS5\t')
s.write('mean\t')
for i in range(len(mean_list)):
s.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
all_score.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
s.close()
# Out put 6th file
file_num += 1
s = open('S6.eval', 'w')
s.write(' \tP@10\tR@50\tr-Precision\tAP\tnCCG@10\tnDCG@20\n')
mean_list = [[], [], [], [], [], []]
for i in range(len(p_10[file_num])):
if i % 2 == 1:
s.write('%s' % p_10[file_num][i - 1][0])
s.write('\t%s' % round(p_10[file_num][i][0], 3))
s.write('\t%s' % round(r_50[file_num][i][0], 3))
s.write('\t%s' % round(R_p[file_num][i][0], 3))
s.write('\t%s' % round(ap_value[file_num][i][0], 3))
s.write('\t%s' % round(ndcg_10[file_num][i][0], 3))
s.write('\t%s\n' % round(ndcg_20[file_num][i][0], 3))
mean_list[0].append(p_10[file_num][i][0])
mean_list[1].append(r_50[file_num][i][0])
mean_list[2].append(R_p[file_num][i][0])
mean_list[3].append(ap_value[file_num][i][0])
mean_list[4].append(ndcg_10[file_num][i][0])
mean_list[5].append(ndcg_20[file_num][i][0])
all_score.write('\nS6\t')
s.write('mean\t')
for i in range(len(mean_list)):
s.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
all_score.write('%s\t' % round(numpy.mean(mean_list[i]), 3))
s.close()
all_score.close()<file_sep>/f3_combine_s1tos6_result.py
import f2_import_result
def combine(qrels_list, relevant_num):
'''
If the value of "relevant_num" is "r", the function will use r-precision
Extract top relevant_num of the retrieved documents from S[1-6].results documents and put them into a list.
'''
combined_result = [i for i in range(6)]
combined_result[0] = f2_import_result.load("S1.results", relevant_num, qrels_list)
combined_result[1] = f2_import_result.load("S2.results", relevant_num, qrels_list)
combined_result[2] = f2_import_result.load("S3.results", relevant_num, qrels_list)
combined_result[3] = f2_import_result.load("S4.results", relevant_num, qrels_list)
combined_result[4] = f2_import_result.load("S5.results", relevant_num, qrels_list)
combined_result[5] = f2_import_result.load("S6.results", relevant_num, qrels_list)
return combined_result<file_sep>/f5_recall.py
def r_value(qrels_list, ret_list):
r_value_list_combine = []
for result in ret_list:
r_value_list = []
for i in range(len(result)):
for j in range(len(qrels_list)):
if result[i] == qrels_list[j] and i % 4 == 0 and j % 2 == 0:
all_rel_doc_num = len(qrels_list[j+1])
rel_doc_num = 0
r_value_list.append(result[i])
for ret in result[i + 1]:
for rel_list in qrels_list[j + 1]:
if ret == rel_list[0]:
rel_doc_num += 1
r_value_list.append([rel_doc_num / all_rel_doc_num])
r_value_list_combine.append(r_value_list)
return r_value_list_combine<file_sep>/f7_ndcg.py
import f8_dcg
import f9_idcg
def ndcg(qrels_list, ret_list):
dcg = f8_dcg.dcg(qrels_list, ret_list)
idcg = f9_idcg.idcg(qrels_list, ret_list)
ndcg_combine = []
for index in range(len(dcg)):
ndcg_list_4_each_query = []
for index01 in range(len(dcg[index])):
if index01 % 2 == 0:
ndcg_list_4_each_query.append(dcg[index][index01])
if index01 % 2 == 1:
ndcg_list_4_each_query.append([dcg[index][index01][0]/idcg[index][index01][0]])
ndcg_combine.append(ndcg_list_4_each_query)
return ndcg_combine<file_sep>/f4_precision.py
def p_value(qrels_list, ret_list):
'''
Return the list with multiple sub list.
Each sub list contains the precision value for s[1-6].results respectively.
The format of whole list is [[sub list 01], [sub list 02], ...... ]
The format of sub list is [[query01], [precision01], [query02], [precision02], ...... ]
'''
p_value_list_combine = []
for result in ret_list:
p_value_list = []
for i in range(len(result)):
for j in range(len(qrels_list)):
if result[i] == qrels_list[j] and i%4 == 0 and j%2 == 0:
ret_doc_num = len(result[i+1])
rel_doc_num = 0
p_value_list.append(result[i])
for ret in result[i+1]:
for rel_list in qrels_list[j+1]:
if ret == rel_list[0]:
rel_doc_num += 1
p_value_list.append([rel_doc_num/ret_doc_num])
p_value_list_combine.append(p_value_list)
return p_value_list_combine
#
#
#
#
# for i in range(len(result)):
#
# if i % 4 == 0:
# relevant_doc = 0
# p_value_list.append(result[i])
# elif i % 4 == 1:
# retrieved_doc = len(result[i])
#
#
#
#
#
#
#
#
# for doc_id_ret in result[i]:
# for j in range(len(qrels_list)):
# if j % 2 == 1:
# for doc_id_qrels in qrels_list[int(i/4)*2+1]:
# if doc_id_qrels[0] == doc_id_ret:
# relevant_doc += 1
# p_value_list.append([relevant_doc / retrieved_doc])
#
# p_value_list_combine.append(p_value_list)
#
# return p_value_list_combine
<file_sep>/f2_import_result.py
def load(filename, k_value, qrels_list):
'''
If the value of k_value is "r", the function will use the number of relevant document as k value for each query.
If the value of k_value is "all", the function will contain all the retrieved documents.
Return format: list
[[query01], [doc_id01, doc_id02, ...], [doc_rank01, doc_rank02, ...], [doc_p01, doc_p02, ...], [query02], [doc_id01, ...], ...]
'''
result = []
file = open(filename, 'r')
identical_variable = 1
query_num = []
if k_value == "r":
index = 1
doc_length = len(qrels_list[index])
for line in file.readlines():
if identical_variable == 1:
doc_id, doc_p, doc_rank = [], [], []
query_num = line.strip().split(' ')[0]
result.append([query_num])
doc_id.append(line.strip().split(' ')[2])
doc_rank.append(line.strip().split(' ')[3])
doc_p.append(line.strip().split(' ')[4])
identical_variable +=1
elif query_num != line.strip().split(' ')[0]:
if k_value == "r":
index += 2
doc_length = len(qrels_list[index])
result.append(doc_id)
result.append(doc_rank)
result.append(doc_p)
doc_id, doc_p, doc_rank = [], [], []
query_num = line.strip().split(' ')[0]
result.append([query_num])
doc_id.append(line.strip().split(' ')[2])
doc_rank.append(line.strip().split(' ')[3])
doc_p.append(line.strip().split(' ')[4])
elif query_num == line.strip().split(' ')[0]:
if k_value != "all" and k_value != "r":
if len(doc_id) >= k_value:
continue
if k_value == "r":
if len(doc_id) >= doc_length:
continue
doc_id.append(line.strip().split(' ')[2])
doc_rank.append(line.strip().split(' ')[3])
doc_p.append(line.strip().split(' ')[4])
result.append(doc_id)
result.append(doc_rank)
result.append(doc_p)
file.close()
return result
<file_sep>/f6_ap.py
def ap(qrels_list, ret_list):
'''
This function will return AP value for each query in s[1-6].results files respectively.
The format of return list is [sublist01, sublist02, ......], where sublist_n is [[query01], [AP01], [query02], [AP02], ...... ]
'''
ap_list_all = []
for result in ret_list:
ap_list_4_each_file = []
for i in range(len(qrels_list)):
for j in range(len(result)):
if qrels_list[i] == result[j] and i%2 == 0 and j%4 == 0:
ap_list_4_each_file.append(qrels_list[i])
ap_sum, ap_n =0, 1
for doc_id_ret in range(len(result[j+1])):
for doc_id_rel in range(len(qrels_list[i+1])):
if result[j+1][doc_id_ret] == qrels_list[i+1][doc_id_rel][0]:
ap_sum += ap_n / int(result[j+2][doc_id_ret])
ap_n += 1
ap_list_4_each_file.append([ap_sum/len(qrels_list[i + 1])])
ap_list_all.append(ap_list_4_each_file)
return ap_list_all<file_sep>/f9_idcg.py
import numpy
def idcg(qrels_list, ret_list):
idcg_list_combine = []
for result in ret_list:
idcg_list_4_each_file = []
for i in range(len(result)):
for j in range(len(qrels_list)):
if result[i] == qrels_list[j] and i % 4 == 0 and j % 2 == 0:
idcg_list_4_each_file.append(result[i])
for rel_id in range(len(qrels_list[j + 1])):
if rel_id < len(result[i + 1]):
if rel_id == 0:
idcg_value_4_each_query = qrels_list[j+1][rel_id][1]
if rel_id > 0:
idcg_value_4_each_query += qrels_list[j+1][rel_id][1]/numpy.log2(rel_id + 1)
idcg_list_4_each_file.append([idcg_value_4_each_query])
idcg_list_combine.append(idcg_list_4_each_file)
return idcg_list_combine<file_sep>/f1_import_qrels.py
def load(filename):
qrels = []
file = open(filename, 'r')
for line in file.readlines():
line = line.strip()
query_num = line.split(':')[0]
qrels.append([query_num])
query_rel = line.split(':')[1].strip().split(' ')
list_for_tuples_elements = []
for tuples in query_rel:
if tuples != '':
doc_id = tuples.strip('()').split(',')[0]
rel_value = int(tuples.strip('()').split(',')[1])
list_for_tuples_elements.append([doc_id, rel_value])
qrels.append(list_for_tuples_elements)
file.close()
return qrels
<file_sep>/f8_dcg.py
import numpy
def dcg(qrels_list, ret_list):
dcg_list_combine = []
for result in ret_list:
dcg_list_4_each_file = []
for i in range(len(result)):
for j in range(len(qrels_list)):
if result[i] == qrels_list[j] and i%4 == 0 and j%2 == 0:
dcg_list_4_each_file.append(result[i])
for ret_id in range(len(result[i+1])):
if ret_id == 0:
dcg_value_4_each_query = 0
for rel_id in range(len(qrels_list[j + 1])):
if result[i+1][ret_id] == qrels_list[j+1][rel_id][0]:
dcg_value_4_each_query = qrels_list[j+1][rel_id][1]
if ret_id > 0:
for rel_id in range(len(qrels_list[j + 1])):
if result[i+1][ret_id] == qrels_list[j+1][rel_id][0]:
dcg_value_4_each_query += qrels_list[j+1][rel_id][1]/numpy.log2(ret_id+1)
dcg_list_4_each_file.append([dcg_value_4_each_query])
dcg_list_combine.append(dcg_list_4_each_file)
return dcg_list_combine<file_sep>/CW02_MAIN.py
import numpy
import f1_import_qrels
import f3_combine_s1tos6_result
import f4_precision
import f5_recall
import f6_ap
import f7_ndcg
import f10_output_eval
qrels = f1_import_qrels.load("qrels.txt")
# Calculate the P@10
result_10 = f3_combine_s1tos6_result.combine(qrels, 10)
result_10_p = f4_precision.p_value(qrels, result_10)
# Calculate the R@50
result_50 = f3_combine_s1tos6_result.combine(qrels, 50)
result_50_r = f5_recall.r_value(qrels, result_50)
# Calculate the r-precision
result_R = f3_combine_s1tos6_result.combine(qrels, "r")
result_R_p = f4_precision.p_value(qrels, result_R)
# Calculate the AP
result_ap = f3_combine_s1tos6_result.combine(qrels, "all")
result_ap_value = f6_ap.ap(qrels, result_ap)
# Calculate the nDCG@10
result_10_ndcg = f7_ndcg.ndcg(qrels, result_10)
# Calculate the nDCG@20
result_20 = f3_combine_s1tos6_result.combine(qrels, 20)
result_20_ndcg = f7_ndcg.ndcg(qrels, result_20)
# Out put eval file
f10_output_eval.output(result_10_p, result_50_r, result_R_p, result_ap_value, result_10_ndcg, result_20_ndcg)
|
f424ac93023a152a12494d4936c7b925b26006c0
|
[
"Python",
"Text"
] | 12
|
Text
|
Smootherist/evaluate
|
6d6219b09342f50c6d60e0a56ab73b23032cfbd4
|
a274485d6f4f3875962516ea594c9e3f4fad8489
|
refs/heads/main
|
<repo_name>dobis32/vue-shopping-app<file_sep>/tests/unit/items.spec.ts
import { mount, shallowMount } from '@vue/test-utils'
import Items from '@/components/Items.vue'
import Item from '../../src/store/models/state.model.item';
describe('Items.vue', () => {
let getters: any;
let $store: any;
let wrapper: any;
let dispatch: any;
let state: any;
let testItems = [new Item('TestItemA', 5.00, 'TestCategory1'), new Item('TestItemB', 5.00, 'TestCategory2')];
let testActiveItem = testItems[0];
beforeEach(() => {
dispatch = jest.fn();
getters = {
getItemsByActiveCategory: jest.fn(),
getActiveItem: jest.fn()
}
state = {
items: testItems,
activeItem: testItems[0]
}
$store = {
state,
getters,
dispatch
};
wrapper = mount(Items, {
props: {
items: testItems,
activeItem: testActiveItem
},
global: {
mocks: {
$store
}
}
});
});
// DOM
it('should have an element w class "listed-item" for each item rendered to the DOM', () => {
expect(wrapper.findAll('.listed-item').length).toEqual(testItems.length);
});
it('should have a corresponding item name rendered in each .listed-item element', () => {
const i0 = testItems[0];
const i1 = testItems[1];
const rendered = wrapper.findAll('.listed-item');
expect(rendered[0].text()).toEqual(i0.getItemName());
expect(rendered[1].text()).toEqual(i1.getItemName());
});
it('should call the selectItem method when an item rendered on the DOM is clicked', () => {
let n = 0;
wrapper.vm.selectItem = jest.fn();
wrapper.findAll('.listed-item')[n].trigger('click');
expect(wrapper.vm.selectItem).toHaveBeenCalledWith(testItems[n]);
});
it('should render the item name of each .listed-item element', () => {
let item0 = testItems[0];
let item1 = testItems[1];
expect(wrapper.findAll('.listed-item')[0].text()).toEqual(item0.getItemName());
expect(wrapper.findAll('.listed-item')[1].text()).toEqual(item1.getItemName());
});
// Props
it('should have a prop for the items array', () => {
expect(wrapper.vm.items).toBeDefined();
expect(wrapper.vm.items).toEqual(testItems);
});
it('should have a prop for the active item', () => {
expect(wrapper.vm.activeItem).toBeDefined();
expect(wrapper.vm.activeItem).toEqual(testActiveItem);
});
// Methods
it('should have a method for selecting an item and making it the active-item', () => {
let item = testItems[0];
wrapper.vm.selectItem(item);
expect(typeof wrapper.vm.selectItem).toEqual('function');
expect(dispatch).toHaveBeenCalledWith('setActiveItem', item);
expect(dispatch).toHaveBeenCalledWith('setActiveModal', 'selectedItemModal');
expect(dispatch).toHaveBeenCalledWith('openModal');
});
});
<file_sep>/tests/unit/listedCartItem.spec.ts
import { mount, shallowMount, flushPromises } from '@vue/test-utils'
import ListedCartItem from '@/components/ListedCartItem.vue'
import Item from '../../src/store/models/state.model.item';
describe('ListedCartItem.vue', () => {
let getters: any;
let $store: any;
let wrapper: any;
let dispatch: any;
let state: any;
let testData: any;
let testEditBool: boolean;
const testItem = new Item('test_item', 4.20, 'foobar');
beforeEach(() => {
dispatch = jest.fn();
getters = {}
state = {
cart: [ new Item('Apple', 1.00, 'Fruits'), new Item('Carrot', 1.00, 'Vegetable') ]
}
$store = {
state,
getters,
dispatch
};
testData = { quantity: 2, item: testItem };
testEditBool = true;
wrapper = mount(ListedCartItem, {
props: {
data: testData,
edit: testEditBool
},
global: {
mocks: {
$store
}
}
});
flushPromises();
});
// DOM
it('should have the item quantity rendered to the DOM', () => {
expect(wrapper.find('#item-quantity').exists()).toBeTruthy();
expect(wrapper.find('#item-quantity').text()).toEqual(testData.quantity.toString())
});
it('should have the item name rendered to the DOM', () => {
expect(wrapper.find('#item-name').exists()).toBeTruthy();
expect(wrapper.find('#item-name').text()).toEqual(testData.item.getItemName());
});
it('should have buttons to adjust item quantity rendered to the DOM if the edit prop is true', () => {
expect(wrapper.vm.edit).toEqual(true);
expect(wrapper.find('#controls').exists()).toEqual(true);
expect(wrapper.find('#increase-item').exists()).toEqual(true);
expect(wrapper.find('#increase-item').element.tagName).toEqual('BUTTON');
expect(wrapper.find('#decrease-item').exists()).toEqual(true);
expect(wrapper.find('#decrease-item').element.tagName).toEqual('BUTTON');
});
it('should not have buttons to increase item quantity rendered to the DOM if the edit prop is false', () => {
wrapper = mount(ListedCartItem, {
props: {
data: { quantity: 2, item: testItem },
edit: false
}
});
expect(wrapper.vm.edit).toEqual(false);
expect(wrapper.find('#controls').exists()).toEqual(false);
expect(wrapper.find('#increase-item').exists()).toEqual(false);
expect(wrapper.find('#decrease-item').exists()).toEqual(false);
});
it('should call the "increaseCartItem" method when the increase item button is clicked', () => {
wrapper.vm.increaseCartItem = jest.fn();
wrapper.find('#increase-item').trigger('click');
expect(wrapper.find('#increase-item').exists()).toEqual(true);
});
it('should call the "decreaseCartItem" method when the decrease item button is clicked', () => {
wrapper.vm.decreaseCartItem = jest.fn();
wrapper.find('#decrease-item').trigger('click');
expect(wrapper.find('#decrease-item').exists()).toEqual(true);
});
// Methods
it('should have a function to get increase the cart quantity of the current item', () => {
wrapper.vm.increaseCartItem(testItem);
expect(typeof wrapper.vm.increaseCartItem).toEqual('function');
expect(dispatch).toHaveBeenCalledWith('increaseCartItem', testItem);
});
it('should have a function to get decrease the cart quantity of the current item', () => {
wrapper.vm.decreaseCartItem(testItem);
expect(typeof wrapper.vm.decreaseCartItem).toEqual('function');
expect(dispatch).toHaveBeenCalledWith('decreaseCartItem', testItem);
});
// Props
it('should have a prop for item data', () => {
expect(wrapper.vm.data).toBeDefined();
expect(wrapper.vm.data).toEqual(testData);
});
it('should have a prop that determines if the item is editable', () => {
expect(wrapper.vm.edit).toBeDefined();
expect(wrapper.vm.edit).toEqual(testEditBool);
});
});
<file_sep>/src/store/models/state.model.store.ts
import Item from './state.model.item'
export interface CoreStore {
activeCategory: string,
activeItem: Item,
activeModal: string,
modalState: boolean,
items: Array<Item>,
cart: Array<Item>
}<file_sep>/tests/unit/categories.spec.ts
import { mount, shallowMount } from '@vue/test-utils'
import Categories from '@/components/Categories.vue'
import Item from '../../src/store/models/state.model.item';
describe('Categories.vue', () => {
let $store: any;
let wrapper: any;
let dispatch: any;
let state: any;
const testItems = [ new Item('Apple', 1.00, 'Fruits'), new Item('Carrot', 1.00, 'Vegetable') ];
const testCategories = testItems.map((i: Item) => i.getItemCategory());
const activeCategory = testCategories[0];
beforeEach(() => {
dispatch = jest.fn();
state = {
activeCategory: testItems[0].getItemCategory(),
cart: testItems
}
$store = {
state,
dispatch,
};
wrapper = shallowMount(Categories, {
props: {
categories: testCategories,
activeCategory
},
global: {
mocks: {
$store
}
}
});
});
// DOM
it('should have a way to set the active category to "All"', () => {
let allOption = wrapper.find('#all');
allOption.trigger('click');
expect(dispatch).toHaveBeenCalledWith('setActiveCategory', 'All');
expect(allOption.text()).toEqual('All');
});
it('should render the category string of each item category rendered in each .listed-category element', () => {
let item1 = testItems[0];
let item2 = testItems[1];
let listedCategories = wrapper.findAll('.listed-category');
expect(listedCategories[1].text()).toEqual(item1.getItemCategory());
expect(listedCategories[2].text()).toEqual(item2.getItemCategory());
});
it('should call the "setActiveCetegory" method with the corresponding cateogry according to which DOM element was selected', () => {
wrapper.vm.setActiveCategory = jest.fn(wrapper.vm.setActiveCategory);
const els = wrapper.findAll('.listed-category');
els[0].trigger('click');
expect(wrapper.vm.setActiveCategory).toHaveBeenLastCalledWith(els[0].text());
els[1].trigger('click');
expect(wrapper.vm.setActiveCategory).toHaveBeenLastCalledWith(els[1].text());
els[2].trigger('click');
expect(wrapper.vm.setActiveCategory).toHaveBeenLastCalledWith(els[2].text());
});
it('should an element w the "active" corresponding to the active-category', () => {
expect(wrapper.find('.active').text()).toEqual(activeCategory);
});
it('should have an "All" category listing', () => {
expect(wrapper.find('#all').exists()).toEqual(true);
expect(wrapper.findAll('.listed-category').length).toEqual(testCategories.length + 1);
});
it('should have an "All" category listing, even when no other item category exists', () => {
wrapper = mount(Categories, {
props: {
categories: []
},
global: {
mocks: {
$store
}
}
});
expect(wrapper.find('#all').exists()).toEqual(true);
expect(wrapper.findAll('.listed-category').length).toEqual(1);
});
it('should have the "active" class applied to the corresponding .listed-category element', () => {
let listedCategory = wrapper.findAll('.listed-category')[1]
expect(listedCategory.classes().find((c: string) => c == 'active'));
expect(listedCategory.text()).toEqual(activeCategory);
});
// Props
it('should have a prop for the available categories array', () => {
expect(wrapper.vm.categories).toBeDefined();
expect(wrapper.vm.categories).toEqual(testCategories);
});
it('should have a prop for the active category', () => {
expect(wrapper.vm.activeCategory).toBeDefined();
expect(wrapper.vm.activeCategory).toEqual(activeCategory);
});
// Methods
it('should have a function to set the active category', () => {
const category = 'foo'
wrapper.vm.setActiveCategory(category);
expect(typeof wrapper.vm.setActiveCategory).toEqual('function');
expect(dispatch).toHaveBeenCalledWith('setActiveCategory', category)
});
it('should have a function to discern if a given category is the same as another category (the active category)', () => {
const activeCategory = 'foobar';
const otherCategory = 'something';
expect(typeof wrapper.vm.isActiveCategory).toEqual('function');
expect(wrapper.vm.isActiveCategory(otherCategory, activeCategory)).toBeFalsy();
expect(wrapper.vm.isActiveCategory(activeCategory, activeCategory)).toBeTruthy();
});
});
<file_sep>/src/store/index.ts
import { createStore } from 'vuex'
import Item from './models/state.model.item';
import Cart from './models/state.model.cart';
import Mutations from './src/mutations';
import Actions from './src/actions';
import Getters from './src/getters';
import {CoreStore} from './models/state.model.store'
// let items = ;
// let cart = new Array<Item>();
export default createStore({
state: {
activeCategory: 'All',
activeItem: new Item('', 0, ''),
activeModal: '',
modalState: false,
items: new Array<Item>(),
cart: new Array<Item>()
} as CoreStore,
mutations: { // cannot be async
...Mutations
},
actions: { // can by async
...Actions
},
getters: {
...Getters
},
modules: {
}
})
<file_sep>/src/store/models/state.model.cart.ts
import Item from './state.model.item';
export default class Cart {
private items: Array<Item>
constructor(items: Array<any>) {
this.items = items;
}
getCartItems(): Array<Item> {
return this.items;
}
setCartItems(items: Array<Item>) {
this.items = items;
}
}<file_sep>/tests/unit/cart.spec.ts
import { mount, shallowMount } from '@vue/test-utils'
import Cart from '@/components/Cart.vue'
import ListedCartItem from '@/components/ListedCartItem.vue'
import Item from '../../src/store/models/state.model.item';
describe('Cart.vue', () => {
let getters: any;
let $store: any;
let wrapper: any;
let dispatch: any;
const testCart = [ new Item('Apple', 1.00, 'Fruits'), new Item('Carrot', 1.00, 'Vegetable') ];
beforeEach(() => {
dispatch = jest.fn();
$store = {
state: {
testCart
},
dispatch
};
wrapper = shallowMount(Cart, {
props: {
cartItems: testCart
},
global: {
components: {
ListedCartItem
},
mocks: {
$store
}
}
});
});
// DOM
it('should have an element in the DOM that triggers the "editCart" method on click', () => {
wrapper.vm.editCart = jest.fn();
wrapper.find('#edit-cart').trigger('click');
expect(wrapper.vm.editCart).toHaveBeenCalled();
});
it('should have a .listed-cart-item element for each cart item rendered to the DOM', () => {
expect(wrapper.findAllComponents(ListedCartItem).length).toEqual(testCart.length);
});
// Props
it('should have a prop for the items in the cart', () => {
expect(wrapper.vm.cartItems).toBeDefined();
expect(wrapper.vm.cartItems).toEqual(testCart);
});
// Methods
it('should have a method that sets the active modal to "editCartModal" and also opens the modal', () => {
wrapper.vm.editCart();
expect(typeof wrapper.vm.editCart).toEqual('function');
expect(dispatch).toHaveBeenCalledWith('setActiveModal', 'editCartModal');
expect(dispatch).toHaveBeenCalledWith('openModal');
});
});
<file_sep>/src/store/src/mutations.ts
import Item from '../models/state.model.item';
export default {
addItemToCart: (state: any, item: Item) => {
state.cart.push(item);
},
removeItemFromCart: (state: any, itemToRemove: Item) => {
const filtered = state.items.filter((i: Item) => i == itemToRemove);
state.cart = filtered;
},
setActiveCategory: (state: any, activeCategory: string) => {
state.activeCategory = activeCategory;
},
setActiveModal: (state: any, modal: string) => {
state.activeModal = modal;
},
setModalState: (state: any, active: boolean) => {
state.modalState = active;
},
setActiveItem: (state: any, item: Item) => {
state.activeItem = item;
},
initItems: (state: any, items: Array<Item>) => {
state.items = items;
},
updateCart: (state: any, cart: Array<Item>) => {
state.cart = [...cart];
}
}<file_sep>/src/store/src/actions.ts
import Item from '../models/state.model.item';
export default {
addItemToCart: (context: any, item: Item) => {
context.commit('addItemToCart', item);
},
removeItemFromCart: (context: any, itemToRemove: Item) => {
context.commit('removeItemFromCart', itemToRemove);
},
setActiveCategory: (context: any, category: string) => {
context.commit('setActiveCategory', category);
},
setActiveItem: (context: any, item: Item) => {
context.commit('setActiveItem', item);
},
setActiveModal: (context: any, modal: string) => {
context.commit('setActiveModal', modal);
},
closeModal: (context: any) => {
context.commit('setModalState', false);
},
openModal: (context: any) => {
context.commit('setModalState', true);
},
resetActiveItem: (context: any) => {
context.commit('setActiveItem', new Item('', 0, ''));
},
initItems: (context: any, items: Array<Item>) => {
context.commit('initItems', items);
},
increaseCartItem: (context: any, item: Item) => {
context.commit('addItemToCart', item);
},
decreaseCartItem: (context: any, itemToRemove: Item) => {
const updatedCart = [] as Array<Item>;
const indexToRemove = context.state.cart.indexOf(itemToRemove);
if(indexToRemove > -1) {
context.state.cart.forEach((i: Item, index: number) => {
if(index != indexToRemove) updatedCart.push(i);
});
context.commit('updateCart', updatedCart);
}
}
}<file_sep>/src/store/models/state.model.item.ts
export default class Item {
private name: string;
private price: number;
private category: string;
constructor(name: string, price: number, category: string) {
this.name = name;
this.category = category
this.price = price;
}
getItemName(): string {
return this.name;
}
setItemName(name: string) {
this.name = name;
}
getItemPrice(): number {
return this.price;
}
setItemPrice(n: number) {
this.price = n;
}
getItemCategory(): string {
return this.category;
}
setItemCategory(category: string) {
this.category = category;
}
}<file_sep>/tests/unit/editCartMdal.spec.ts
import { mount, shallowMount, flushPromises } from '@vue/test-utils';
import EditCartModal from '@/components/modal-cards/EditCartModal.vue';
import ListedCartItem from '../../src/components/ListedCartItem.vue';
import Item from '../../src/store/models/state.model.item';
describe('EditCartModal.vue', () => {
let getters: any;
let $store: any;
let wrapper: any;
let dispatch: any;
const cartItems = [new Item('Apple', 1.00, 'Fruits'), new Item('Carrot', 0.80, 'Vegetable')];
const cartIsEmpty = false;
const stopPropagation = jest.fn((e : Event) => { e.stopPropagation() });
const cartTotal = cartItems.map((i: Item) => i.getItemPrice()).reduce((t, v) => t += v);
beforeEach(() => {
dispatch = jest.fn();
$store = {
state: {
},
dispatch
};
wrapper = shallowMount(EditCartModal, {
data: () => {
return { editable: true }
},
props: {
cartItems,
cartIsEmpty,
cartTotal
},
global: {
mocks: {
$store
},
provide: {
stopPropagation
}
}
});
flushPromises();
});
// DOM
it('should call the provided/injected "stopPropagation" function when the modal card is clicked', () => {
wrapper.find('#modal-card').trigger('click');
expect(stopPropagation).toHaveBeenCalled();
});
it('should render a message stating that the cart is empty, if the cart is empty', () => {
const isEmpty = true;
const wrapperEmptyCart = mount(EditCartModal, {
props: {
cartItems,
cartIsEmpty: isEmpty,
cartTotal
},
global: {
mocks: {
$store
},
provide: {
stopPropagation
}
}
});
const msg = wrapperEmptyCart.find('#empty-cart-message')
expect(wrapperEmptyCart.vm.cartIsEmpty)
expect(msg.exists()).toEqual(true);
expect(msg.text()).toEqual('Your cart is empty!');
});
it('should render the items list to the DOM, if the cart is not empty', () => {
expect(wrapper.vm.cartIsEmpty).toEqual(false);
expect(wrapper.find('#item-list').exists()).toEqual(true);
});
it('should have a ListedCartItem for each item in the cart', () => {
expect(wrapper.findAllComponents(ListedCartItem).length).toEqual(cartItems.length);
});
it('should have the cart total rendered to the DOM, if the cart is not empty', () => {
const el = wrapper.find('#cart-total');
expect(el.exists()).toEqual(true);
expect(el.text()).toEqual(`$${cartTotal.toFixed(2)}`);
});
// Methods
it('should have a function for stopping event propagation', () => {
const e = new Event('foo');
e.stopPropagation = jest.fn(e.stopPropagation);
wrapper.vm.stopPropagation(e);
expect(typeof wrapper.vm.stopPropagation).toEqual('function');
expect(e.stopPropagation).toHaveBeenCalled();
});
// Props
it('should have a prop for the items in the cart', () => {
expect(wrapper.vm.cartItems).toBeDefined();
expect(wrapper.vm.cartItems).toEqual(cartItems);
});
it('should have a prop for determining if the cart is empty', () => {
expect(wrapper.vm.cartIsEmpty).toBeDefined();
expect(wrapper.vm.cartIsEmpty).toEqual(cartIsEmpty);
});
it('should have a prop for the cart total', () => {
expect(wrapper.vm.cartTotal).toBeDefined();
expect(wrapper.vm.cartTotal).toEqual(cartTotal);
});
});
<file_sep>/tests/unit/selectedItemModal.spec.ts
import { mount, shallowMount, flushPromises } from '@vue/test-utils';
import SelectedItemModal from '@/components/modal-cards/SelectedItemModal.vue';
import Item from '../../src/store/models/state.model.item';
describe('SelectedItemModal.vue', () => {
let getters: any;
let $store: any;
let wrapper: any;
let dispatch: any;
const activeItem = new Item('Apple', 1.00, 'Fruits');
const activeItemInCart = true;
const quantityOfActiveItemInCart = 666;
const stopPropagation = jest.fn((e : Event) => { e.stopPropagation() });
beforeEach(() => {
dispatch = jest.fn();
$store = {
state: {
},
dispatch
};
wrapper = mount(SelectedItemModal, {
props: {
activeItem,
activeItemInCart,
quantityOfActiveItemInCart
},
global: {
mocks: {
$store
},
provide: {
stopPropagation
}
}
});
flushPromises();
});
// DOM
it('should call the provided/injected "stopPropagation" function when the modal card is clicked', () => {
wrapper.find('#modal-card').trigger('click');
expect(stopPropagation).toHaveBeenCalled();
});
it('should have the name of the active item rendered to the DOM', () => {
expect(wrapper.find('#item-name').text()).toEqual(activeItem.getItemName());
});
it('should have the price of the active item rendered to the DOM', () => {
expect(wrapper.find('#item-price').text()).toEqual(`Price: $${activeItem.getItemPrice().toFixed(2)}`);
});
it('should have the category of the active item rendered to the DOM', () => {
expect(wrapper.find('#item-category').text()).toEqual(`Category: ${activeItem.getItemCategory()}`);
});
it('should have a button to add the active item to the cart', () => {
const btn = wrapper.find('#add-to-cart')
expect(btn.exists()).toEqual(true);
expect(btn.element.tagName).toEqual('BUTTON');
});
it('should call the appropriate function when the add-to-cart button is clicked', () => {
wrapper.vm.addItemToCart = jest.fn(wrapper.vm.addItemToCart);
wrapper.find('#add-to-cart').trigger('click');
expect(wrapper.vm.addItemToCart).toHaveBeenCalled();
});
it('should render the quantity of active item in the cart', () => {
const el = wrapper.find('#quantity-in-cart')
expect(wrapper.vm.activeItemInCart).toEqual(true);
expect(el.exists()).toEqual(true);
expect(el.text()).toEqual(`Quantity in cart: ${quantityOfActiveItemInCart}`)
});
it('should not render the quantity of active item in the cart, if the active item does not exist in the cart', () => {
const wrapperItemNotInCart = mount(SelectedItemModal, {
props: {
activeItem,
activeItemInCart: false,
quantityOfActiveItemInCart
},
global: {
mocks: {
$store
},
provide: {
stopPropagation
}
}
});
expect(wrapperItemNotInCart.find('#quantity-in-cart').exists()).toEqual(false);
});
// Methods
it('should have a function for adding an item to the cart', () => {
const item = new Item('foo', 420, 'bar');
wrapper.vm.addItemToCart(item);
expect(wrapper.vm.addItemToCart).toBeDefined();
expect(typeof wrapper.vm.addItemToCart).toEqual('function');
expect(dispatch).toHaveBeenCalledWith('addItemToCart', item);
});
it('should have a function for stopping event propagation', () => {
const e = new Event('foo');
e.stopPropagation = jest.fn(e.stopPropagation);
wrapper.vm.stopPropagation(e);
expect(typeof wrapper.vm.stopPropagation).toEqual('function');
expect(e.stopPropagation).toHaveBeenCalled();
});
// Props
it('should have a prop for the active item', () => {
expect(wrapper.vm.activeItem).toBeDefined();
});
it('should have a prop for the active item in the cart', () => {
expect(wrapper.vm.activeItemInCart).toBeDefined();
});
it('should have a prop for the quantify of the active item in the cart', () => {
expect(wrapper.vm.quantityOfActiveItemInCart).toBeDefined();
});
});
<file_sep>/tests/unit/modal.spec.ts
import { mount, shallowMount, flushPromises } from '@vue/test-utils';
import Modal from '@/components/Modal.vue';
import Item from '../../src/store/models/state.model.item';
import EditCartModal from '../../src/components/modal-cards/editCartModal.vue';
describe('Modal.vue', () => {
let getters: any;
let $store: any;
let wrapper: any;
let dispatch: any;
const cart = [ new Item('Apple', 1.00, 'Fruits'), new Item('Carrot', 1.00, 'Vegetable') ];
const activeItem = cart[0];
const itemInCart = cart.find((i: Item) => i == activeItem) ? true : false;
const quantityInCart = cart.map((i: Item) => i == activeItem ? <number> 1 : <number> 0).reduce((t, v) => t += v);
const total = 666;
const empty = false;
const modalIsActive = true;
const modalName = 'editCartModal';
beforeEach(() => {
dispatch = jest.fn();
getters = {
getModalState: jest.fn(() => { return false }),
getActiveModal: jest.fn(),
getActiveItem: jest.fn(() => { return activeItem }),
getCartItems: jest.fn(() => { return cart }),
getCartTotal: jest.fn(() => { return total }),
activeItemInCart: jest.fn(() => { return true }),
cartIsEmpty: jest.fn(() => { return empty }),
quantityOfActiveItemInCart: jest.fn(() => { return quantityInCart })
};
$store = {
state: {
cart
},
getters,
dispatch
};
wrapper = shallowMount(Modal, {
props: {
activeState: modalIsActive,
activeModal: modalName
},
global: {
mocks: {
$store
},
provide: {
stopPropagation: (e : Event) => { e.stopPropagation() }
}
}
});
flushPromises();
});
// Computed
it('should have a function to get cart items from the store', () => {
const cartItems = wrapper.vm.cartItems();
expect(typeof wrapper.vm.cartItems).toEqual('function');
expect(cartItems).toEqual(cart);
expect(getters.getCartItems).toHaveBeenCalled();
});
it('should have a function to get the cart total from the store', () => {
const cartTotal = wrapper.vm.cartTotal();
expect(typeof wrapper.vm.cartTotal).toEqual('function');
expect(cartTotal).toEqual(total);
expect(getters.getCartTotal).toHaveBeenCalled();
});
it('should have a function to determine if the cart is empty or not, according to the store', () => {
const isEmpty = wrapper.vm.cartIsEmpty();
expect(typeof wrapper.vm.cartIsEmpty).toEqual('function');
expect(isEmpty).toEqual(empty);
expect(getters.cartIsEmpty).toHaveBeenCalled();
});
it('should have a function to get the active item from the store', () => {
const item = wrapper.vm.activeItem();
expect(typeof wrapper.vm.activeItem).toEqual('function');
expect(item).toEqual(activeItem);
expect(getters.getActiveItem).toHaveBeenCalled();
});
it('should have a function to determine if the active item is in the cart, according to the store', () => {
const inCart = wrapper.vm.activeItemInCart();
expect(typeof wrapper.vm.activeItemInCart).toEqual('function');
expect(inCart).toEqual(itemInCart);
expect(getters.activeItemInCart).toHaveBeenCalled();
});
it('should have have a function to dtermine how many of the active item are in the cart, according to the store', () => {
const quantity = wrapper.vm.quantityOfActiveItemInCart();
expect(typeof wrapper.vm.quantityOfActiveItemInCart).toEqual('function');
expect(quantity).toEqual(quantityInCart);
expect(getters.quantityOfActiveItemInCart).toHaveBeenCalled();
});
//DOM
it('should close the modal when the modal wrapper is clicked', () => {
wrapper.vm.closeModal = jest.fn(wrapper.vm.closeModal);
wrapper.find('#modal-wrapper').trigger('click');
expect(wrapper.vm.closeModal).toHaveBeenCalled();
});
it('should render the modal wrapper if the activeModal prop is', () => {
expect(wrapper.find('#modal-wrapper').exists()).toEqual(true);
});
it('should not render the modal wrapper if the activeModal prop is false', () => {
const active = false;
const wrapperNotActive = shallowMount(Modal, {
props: {
activeState: active,
activeModal: modalName
},
global: {
mocks: {
$store
}
}
});
expect(wrapper.find('#modal-wrapper').exists()).toEqual(true);
expect(wrapper.vm.activeState).toEqual(true);
expect(wrapperNotActive.find('#modal-wrapper').exists()).toEqual(false);
expect(wrapperNotActive.vm.activeState).toEqual(false);
});
it('should render the EditCartModal if the active modal is "editCartModal"', () => {
const modal = 'editCartModal';
const wrapperWithTargetModal = shallowMount(Modal, {
props: {
activeState: modalIsActive,
activeModal: modal
},
global: {
mocks: {
$store
}
}
});
expect(wrapper.find('#edit-cart-modal').exists()).toEqual(true);
expect(wrapperWithTargetModal.vm.activeModal).toEqual(modal);
expect(wrapperWithTargetModal.find('#edit-cart-modal').exists()).toEqual(true);
});
it('should render the SelectedItemModal if the active modal is "selectedItemModal"', () => {
const modal = 'selectedItemModal';
const wrapperWithTargetModal = shallowMount(Modal, {
props: {
activeState: modalIsActive,
activeModal: modal
},
global: {
provide: {
stopPropagation: (e: Event) => { e.stopPropagation()}
},
mocks: {
$store
}
}
});
expect(wrapper.find('#selected-item-modal').exists()).toEqual(false);
expect(wrapperWithTargetModal.vm.activeModal).toEqual(modal);
expect(wrapperWithTargetModal.find('#selected-item-modal').exists()).toEqual(true);
});
// Props
it('should have a prop for the modal active-state', () => {
expect(wrapper.vm.activeState).toBeDefined();
expect(wrapper.vm.activeState).toEqual(modalIsActive);
});
it('should have a prop for the name of the active modal', () => {
expect(wrapper.vm.activeModal).toEqual(modalName);
});
// Methods
it('should have a method for closing and reseting the current modal', () => {
wrapper.vm.closeModal();
expect(typeof wrapper.vm.closeModal).toEqual('function');
expect(dispatch).toHaveBeenCalledWith('resetActiveItem');
expect(dispatch).toHaveBeenCalledWith('closeModal');
});
});
<file_sep>/src/store/src/getters.ts
import Item from '../models/state.model.item';
export default {
getItemCategories: (state: any) => {
return state.items
.map((i: Item) => i.getItemCategory())
.filter((value: Item, index: number, self: Array<Item>) => {
return self.indexOf(value) === index;
})
},
getItemsByActiveCategory: (state: any) => {
const activeCategory = state.activeCategory;
if(activeCategory && activeCategory != 'All') return state.items.filter((i: Item) => i.getItemCategory() == activeCategory);
else return state.items;
},
getActiveModal: (state: any) => {
return state.activeModal;
},
getModalState: (state: any) => {
return state.modalState;
},
getActiveItem: (state: any) => {
return state.activeItem;
},
quantityOfActiveItemInCart: (state: any) => {
let count = 0;
const activeItem = state.activeItem;
state.cart.forEach((i: Item) => {
if(activeItem == i) count++;
})
return count;
},
activeItemInCart: (state: any) => {
return state.cart.find((i: Item) => i == state.activeItem) ? true : false;
},
getCartItems: (state: any) => {
const cartInventory = {} as any;
state.cart.forEach((i: Item) => {
const itemName = i.getItemName()
if (cartInventory[itemName]) {
cartInventory[itemName].quantity++;
} else {
cartInventory[itemName] = { quantity: 1, item: i};
}
});
return cartInventory;
},
cartIsEmpty: (state: any) => {
return state.cart.length ? false : true;
},
getCartTotal: (state: any) => {
if (state.cart.length) return state.cart.map((i: Item) => i.getItemPrice()).reduce((accumulator: number, price: number) => accumulator + price);
else return 0;
}
}
|
f61d27a807a670a169ec14a435e9f6383c25bf90
|
[
"TypeScript"
] | 14
|
TypeScript
|
dobis32/vue-shopping-app
|
32479833644ac5274213ad3ac436ae0e2595e1d7
|
5a9985dfe20c1b47f6610918b383aa3e21ba97ac
|
refs/heads/master
|
<file_sep>local utils = require "utils"
local M = {}
-- 检查胡
function M.check_hu(cards)
-- 找出能做将的牌
local eye_tbl = {}
M._find_eye(cards, eye_tbl, 1, 9)
M._find_eye(cards, eye_tbl, 10, 18)
M._find_eye(cards, eye_tbl, 19, 27)
local hu = false
for i,_ in pairs(eye_tbl) do
repeat
cards[i] = cards[i] - 2
if not M._check_color(cards, 1, 9) then
break
end
if not M._check_color(cards, 10, 18) then
break
end
if not M._check_color(cards, 19, 27) then
break
end
hu = true
until(true)
if hu then
return true
end
cards[i] = cards[i] + 2
end
return hu
end
function M._find_eye(cards, eye_tbl, from, to)
local key = 0
local t = {}
for i=from,to do
local c = cards[i]
if c > 0 then
key = key * 10 + c
if c >= 2 then
t[i] = true
end
end
if c == 0 or i == to then
if (key%3) == 2 then
for k,_ in pairs(t) do
eye_tbl[k] = true
end
end
if key > 0 and next(t) then
t = {}
end
end
end
end
-- 检查单一花色
function M._check_color(cards, min, max)
local t = {}
for i=min,max do
table.insert(t, cards[i])
end
for i=min,max do
local n
if t[i] == 1 or t[i] == 4 then
n = 1
elseif t[i] == 2 then
n = 2
end
if n then
if i + 2 > max or t[i+1] < n or t[i+2] < n then
return false
end
t[i] = t[i] - n
t[i+1] = t[i+1] - n
t[i+2] = t[i+2] - n
end
end
return true
end
return M
|
641a98da9fe5941b94c09bfdf8e289190ba47a84
|
[
"Lua"
] | 1
|
Lua
|
yinjun322/qipai
|
bbb276a0e23b425fbb2cea6481be0a1ef4b0ad6c
|
2e1c407ead42689dbd3c191aded8eab61d7d0b52
|
refs/heads/master
|
<repo_name>yuni5/PinBoll<file_sep>/Assets/ScoreScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreScript : MonoBehaviour {
//得点を表示するテキスト
private GameObject PointText;
private GameObject ScoreText;
//得点の合計を表示するテキスト
static int TotalPoint;
// Use this for initialization
void Start () {
this.PointText = GameObject.Find("PointText");
this.ScoreText = GameObject.Find("ScoreText");
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision other) {
if (other.gameObject.tag == "SmallStarTag") {
this.PointText.GetComponent<Text> ().text = "point:+5";
ScoreScript.TotalPoint += 5;
this.ScoreText.GetComponent<Text> ().text = "Score:" + TotalPoint;
} else if (other.gameObject.tag == "LargeStarTag") {
this.PointText.GetComponent<Text> ().text = "point:+20";
ScoreScript.TotalPoint += 20;
this.ScoreText.GetComponent<Text> ().text = "Score:" + TotalPoint;
}else if(other.gameObject.tag == "SmallCloudTag") {
this.PointText.GetComponent<Text> ().text = "point:+10";
ScoreScript.TotalPoint += 10;
this.ScoreText.GetComponent<Text> ().text = "Score:" + TotalPoint;
}else if(other.gameObject.tag == "LargeCloudTag") {
this.PointText.GetComponent<Text> ().text = "point:+15";
ScoreScript.TotalPoint += 15;
this.ScoreText.GetComponent<Text> ().text = "Score:" + TotalPoint;
}
}
}
<file_sep>/Assets/TouchFripperController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchFripperController : MonoBehaviour {
private float width = Screen.width;
// タッチした場合の座標
public float startPos;
private HingeJoint myHingeJoint;
private float defaultAngle = 20;
private float flickAngle = -20;
void Start () {
this.myHingeJoint = GetComponent<HingeJoint> ();
SetAngle (this.defaultAngle);
}
void Update () {
if (Input.touchCount > 0) {
for(int i = 0; i < Input.touchCount; i++ ){
//タッチしている指の数(0は1本目、1は2本目)
// for文を使って本数を合わせる
Touch touch = Input.GetTouch(i);
// タッチしたx軸の位置
startPos = touch.position.x;
// タップすること(touch.phas)タップしたタイミングを設定(TouchPhase.BeganとTouchPhase.Stationary)
if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Stationary ) {
if (startPos < width/2 && tag == "LeftFripperTag") {
SetAngle (this.flickAngle);
}else if (startPos > width/2 && tag == "RightFripperTag") {
SetAngle (this.flickAngle);
}else if (startPos < width/2 &&startPos > width/2 &&tag == "LeftFripperTag"&&tag == "RightFripperTag") {
SetAngle (this.flickAngle);
}
// TouchPhase.Endedは画面から指が離れた時
}else if(touch.phase == TouchPhase.Ended){
SetAngle (this.defaultAngle);
}
}
}
}
public void SetAngle(float angle){
JointSpring jointspr = this.myHingeJoint.spring;
jointspr.targetPosition = angle;
this.myHingeJoint.spring = jointspr;
}
}
|
a994e46b2a40f0bdaed53b00bc2a79645cd400c3
|
[
"C#"
] | 2
|
C#
|
yuni5/PinBoll
|
e6a3bffee4d789b93f0b83ddb3a8f1bd5ae02a6f
|
38b0a4188a3e548da8c8ac03462d31c431a1b3a7
|
refs/heads/master
|
<repo_name>russianidiot/npmjs-open.sh.cli<file_sep>/README.md
<!--
README generated with readmemako.py (github.com/russianidiot/readme-mako.py) and .README dotfiles (github.com/russianidiot-dotfiles/.README)
-->
[]()
[](https://pypi.python.org/pypi/npmjs-open)
[](https://www.npmjs.com/package/npmjs-open)
[](https://drone.io/github.com/russianidiot/npmjs-open.sh.cli)
[](https://scrutinizer-ci.com/g/russianidiot/npmjs-open.sh.cli/)
[](https://semaphoreci.com/russianidiot/npmjs-open-sh-cli)
[](https://app.shippable.com/projects/5713e9382a8192902e1cfb92/status/)
[](https://travis-ci.org/russianidiot/npmjs-open.sh.cli)
[](https://app.wercker.com/russianidiot/npmjs-open.sh.cli/)
<p align="center">
<b>open node package page (npmjs.com/package/pkgname) in default browser</b>
</p>
#### Install
`[sudo] pip install npmjs-open`
`[sudo] sudo npm install -g npmjs-open`
#### Usage
```bash
# npmjs-open --help
usage: npmjs-open
```
#### Example
```bash
$ cd path/to/repo
$ npmjs-open
+ open https://www.npmjs.com/package/pkgname
```
Feedback
[](https://github.com/russianidiot/npmjs-open.sh.cli/issues)
[](https://gitter.im/russianidiot/npmjs-open.sh.cli)
[](https://github.com/russianidiot)
<file_sep>/description.txt
open node package page (npmjs.com/package/pkgname) in default browser<file_sep>/.README/pypi.python.org/README.rst
.. README generated with readmemako.py (github.com/russianidiot/readme-mako.py) and .README dotfiles (github.com/russianidiot-dotfiles/.README)
Install
```````
:code:`[sudo] pip install npmjs-open`
Usage
`````
.. code:: bash
# npmjs-open --help
usage: npmjs-open
Example
```````
.. code:: bash
$ cd path/to/repo
$ npmjs-open
+ open https://www.npmjs.com/package/pkgname
Feedback |github_issues| |gitter| |github_follow|
.. |github_issues| image:: https://img.shields.io/github/issues/russianidiot/npmjs-open.sh.cli.svg
:target: https://github.com/russianidiot/npmjs-open.sh.cli/issues
.. |github_follow| image:: https://img.shields.io/github/followers/russianidiot.svg?style=social&label=Follow
:target: https://github.com/russianidiot
.. |gitter| image:: https://badges.gitter.im/russianidiot/npmjs-open.sh.cli.svg
:target: https://gitter.im/russianidiot/npmjs-open.sh.cli
<file_sep>/.README/nodejs.com/README.md
<!--
README generated with readmemako.py (github.com/russianidiot/readme-mako.py) and .README dotfiles (github.com/russianidiot-dotfiles/.README)
-->
<p align="center">
<b>open node package page (npmjs.com/package/pkgname) in default browser</b>
</p>
#### Install
`[sudo] pip install npmjs-open`
`[sudo] sudo npm install -g npmjs-open`
#### Usage
```bash
# npmjs-open --help
usage: npmjs-open
```
#### Example
```bash
$ cd path/to/repo
$ npmjs-open
+ open https://www.npmjs.com/package/pkgname
```
Feedback
[](https://github.com/russianidiot/npmjs-open.sh.cli/issues)
[](https://gitter.im/russianidiot/npmjs-open.sh.cli)
[](https://github.com/russianidiot)
<file_sep>/bin/npmjs-open
#!/usr/bin/env bash
{ set +x; } 2>/dev/null
usage="usage: ${BASH_SOURCE[0]##*/}"
[[ $1 == "--help" ]] && {
echo "$usage"
[[ $1 == "--help" ]]; exit # exit 0 if --help
}
[[ $OSTYPE != *"darwin"* ]] && echo "OS X only" && exit 0
! [ -e package.json ] && echo "ERROR: ./package.json NOT EXISTS" && exit 1
name="$(node -e "console.log(require('./package.json').name);")" || exit
url="https://www.npmjs.com/package/$name"
( set -x; open "$url" )
|
b9607c71b164e72dad7954c24a9935a56581ebc4
|
[
"Markdown",
"Text",
"reStructuredText",
"Shell"
] | 5
|
Markdown
|
russianidiot/npmjs-open.sh.cli
|
7f3102990bc73eb57cfc7a0ee755919be17837a2
|
175594eb0de540d5fb85d583b349a259aa03c557
|
refs/heads/master
|
<repo_name>Richard-Seaman/FinalProject-Arduino<file_sep>/Wireless_Sensor_Node.ino
// Date: 03-07-2018
// Author: <NAME>
// Student Number: 17119111
// project: Sensors & Sockets
// This is the Arduino sketch for the wireless sensor node
// It utilises the xbee-arduino library by <NAME>
// The XBee Series 1 transmitter example was used as a basis for this sketch
// The example was accessed on 03/07/2018 at the followinf link:
// https://github.com/andrewrapp/xbee-arduino/blob/master/examples/Series1_Tx/Series1_Tx.pde
// NB: SHIELD MUST BE IN UART TO WORK!!!
#include <XBee.h>
#include <dht.h>
XBee xbee = XBee();
dht DHT;
// Create a payload to send with the frame
// Only need to send a single byte for temperature and another for humidty
// Range of 0-255 is acceptable
uint8_t payload[2] = {0, 0}; // {humidity, temperature}
// Configure the transmission request and response
// 16-bit addressing (Note: coordinator 16-bit Source Address = 1234)
Tx16Request tx = Tx16Request(0x1234, payload, sizeof(payload));
TxStatusResponse txStatus = TxStatusResponse();
// LED pins
// LEDs are used as indicators for status / error / success
int statusLed = 11;
int errorLed = 12;
int successLed = 10;
// DHT sensor pin
// (blue type used)
#define DHT11_PIN 7
// Simple function to flash an LED at the given pin, a given number of times and duration
// (unchanged from Andrew Rapp's function)
void flashLed(int pin, int times, int wait) {
for (int i = 0; i < times; i++) {
digitalWrite(pin, HIGH);
delay(wait);
digitalWrite(pin, LOW);
if (i + 1 < times) {
delay(wait);
}
}
}
// Do the initial setup for the sketch
void setup() {
pinMode(statusLed, OUTPUT);
pinMode(errorLed, OUTPUT);
pinMode(successLed, OUTPUT);
Serial.begin(9600);
xbee.setSerial(Serial);
Serial.println("Setup completed.");
}
// The continuous loop which begins after the setup
void loop() {
// Read the humidity and temperature
int chk = DHT.read11(DHT11_PIN);
int h = DHT.humidity;
int t = DHT.temperature;
// And print them out
Serial.print("Temperature = ");
Serial.println(t);
Serial.print("Humidity = ");
Serial.println(h);
// Make sure they're okay before continuing
if (!isnan(t) && !isnan(h)) {
// convert humidity into a byte and assign to payload
payload[0] = (char) h;
//Serial.print("Humidity Payload: ");
//Serial.println(payload[0]);
// and temperature
payload[1] = (char) t;
//Serial.print("Temperature Payload: ");
//Serial.println(payload[1]);
//Serial.println("");
Serial.println("Transmitting...");
xbee.send(tx);
// flash TX indicator
flashLed(statusLed, 1, 100);
// after sending a tx request, we expect a status response
// wait up to 5 seconds for the status response
if (xbee.readPacket(5000)) {
// got a response!
Serial.println("Got a response!");
// should be a znet tx status
if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {
xbee.getResponse().getTxStatusResponse(txStatus);
// get the delivery status, the fifth byte
if (txStatus.getStatus() == SUCCESS) {
// success. time to celebrate
flashLed(successLed, 5, 50);
} else {
// the remote XBee did not receive our packet. is it powered on?
flashLed(errorLed, 3, 500);
}
}
} else if (xbee.getResponse().isError()) {
Serial.println("Error reading packet. Error code: ");
Serial.println(xbee.getResponse().getErrorCode());
} else {
// local XBee did not provide a timely TX Status Response.
// Radio is not configured properly or connected
Serial.println("local XBee did not provide a timely TX Status Response");
// Flash the error LED
flashLed(errorLed, 2, 50);
}
}
// Delay the loop
delay(900000);
}
|
783ce3f35d671847287089dfeab257bec0e6b2a0
|
[
"C++"
] | 1
|
C++
|
Richard-Seaman/FinalProject-Arduino
|
e9eebca82ea316c2d935e898dc3655d79fafd5d6
|
f1926876cdf9b7cb2c1297905130ea87ab645437
|
refs/heads/master
|
<repo_name>amvinnu/processing-cluster<file_sep>/hadoop/hadoop-worker/files/default_cmd
#!/bin/bash
source /root/hadoop_files/configure_hadoop.sh
IP=$(ip -o -4 addr list eth0 | perl -n -e 'if (m{inet\s([\d\.]+)\/\d+\s}xms) { print $1 }')
echo "WORKER_IP=$IP"
echo "preparing Hadoop"
if [ -z "$MASTER_HOST" ]; then
echo "Defining MASTER_HOST is mandatory !"
exit 1
fi
prepare_hadoop $MASTER_HOST
echo "starting Hadoop Worker services"
service hadoop-hdfs-datanode start
service hadoop-yarn-nodemanager start
echo "starting sshd"
/usr/sbin/sshd
sleep 5
echo "starting Hadoop Worker"
cp /root/hadoop_worker_files/run_hadoop_worker.sh /
chmod a+rx /run_hadoop_worker.sh
/run_hadoop_worker.sh
<file_sep>/hadoop/hadoop-base/hadoop-files/configure_hadoop.sh
#!/bin/bash
hadoop_files=( "/root/hadoop_files/core-site.xml" "/root/hadoop_files/hdfs-site.xml" "/root/hadoop_files/mapred-site.xml" "/root/hadoop_files/yarn-site.xml" "/root/hadoop_files/capacity-scheduler.xml" )
function create_hadoop_directories() {
echo "creating hadoop directories"
mkdir /data/namenode
mkdir /data/datanode
chown hdfs:hadoop /data/namenode
chown hdfs:hadoop /data/datanode
mkdir -p /data/yarn/local
mkdir -p /data/yarn/logs
chown -R yarn:hadoop /data/yarn
}
function deploy_hadoop_files() {
for i in "${hadoop_files[@]}";
do
filename=$(basename $i);
cp $i /etc/hadoop/conf/$filename;
done
}
function configure_hadoop() {
sed -i s/__MASTER__/$1/ /etc/hadoop/conf/core-site.xml
sed -i s/__MASTER__/$1/ /etc/hadoop/conf/yarn-site.xml
sed -i s/__MASTER__/$1/ /etc/hadoop/conf/mapred-site.xml
echo "export JAVA_HOME=/usr/java/default" >> /etc/profile
}
function prepare_hadoop() {
create_hadoop_directories
deploy_hadoop_files
configure_hadoop $1
}
<file_sep>/hadoop/hadoop-master/files/run_hadoop_master.sh
#!/bin/bash
while [ 1 ];
do
tail /var/log/hadoop-hdfs-namenode/*.log
sleep 1
done
<file_sep>/kafka/Dockerfile
#
# Kafka Dockerfile
#
# based on https://github.com/wurstmeister/kafka-docker
#
# Pull base image.
FROM base
RUN curl http://apache.mirrors.lucidnetworks.net/kafka/0.8.2.0/kafka_2.10-0.8.2.0.tgz -o /tmp/kafka_2.10-0.8.2.0.tgz
RUN tar xfz /tmp/kafka_2.10-0.8.2.0.tgz -C /opt
ENV KAFKA_ADVERTISED_PORT=9092
EXPOSE 9092
VOLUME ["/kafka"]
ENV KAFKA_HOME /opt/kafka_2.10-0.8.2.0
ADD start-kafka.sh /usr/bin/start-kafka.sh
ADD broker-list.sh /usr/bin/broker-list.sh
COPY log4j.properties /opt/kafka_2.10-0.8.2.0/config/log4j.properties
CMD start-kafka.sh
<file_sep>/hadoop/hadoop-master/Dockerfile
# Based on
# https://github.com/amplab/docker-scripts.git
FROM hadoop-base
# Hadoop
RUN yum install -y hadoop-hdfs-namenode hadoop-yarn-resourcemanager hadoop-mapreduce-historyserver spark-history-server
# Zookeeper
RUN yum install -y zookeeper-server
RUN service zookeeper-server init
# HDFS ports
EXPOSE 50070 50470 9000 50075 50475 50010 50020 50090
# YARN ports
EXPOSE 8088 8031 8032 8033 50060
# ZK ports
EXPOSE 2181 2888 3888
ADD files /root/hadoop_master_files
RUN chmod +x /root/hadoop_master_files/default_cmd
ENTRYPOINT ["/root/hadoop_master_files/default_cmd"]
<file_sep>/hadoop/hadoop-worker/Dockerfile
# Based on
# https://github.com/amplab/docker-scripts.git
FROM hadoop-base
# Hadoop
RUN yum install -y hadoop-hdfs-datanode hadoop-yarn-nodemanager
# HDFS ports
EXPOSE 50070 50470 9000 50075 50475 50010 50020 50090
# YARN ports
EXPOSE 8088 8031 8032 8033 50060
ADD files /root/hadoop_worker_files
ENTRYPOINT ["/root/hadoop_worker_files/default_cmd"]
<file_sep>/run_all.sh
#! /bin/bash
cwd=`cd "$(dirname "$0")" && pwd`
source $cwd/env.sh
$cwd/stop_all.sh
export EXTRA_FLAGS=""
function addOrReplaceHost() {
local container_name="$1"
local fqhn="$2"
local ip=`docker inspect $container_name | grep -i ipaddress | awk -F'"' '{print $4}'`
echo "container_name=${container_name}, fqhn=${fqhn}, ip=${ip}"
grep -q $container_name /etc/hosts && sed -i "s/^.* $container_name .*$/$ip $container_name $fqhn/" /etc/hosts || echo $ip $container_name $fqhn >> /etc/hosts
}
if [ -f /etc/redhat-release ]
then
EXTRA_FLAGS="--privileged"
fi
# is typically 172.17.42.1
DOCKER_BRIDGE_ADDR=$(ifconfig | grep -A1 docker0 | grep "inet addr" | awk -F':' '{print $2}' | awk '{print $1}')
echo "Starting skydns"
docker run $EXTRA_FLAGS -d -p $DOCKER_BRIDGE_ADDR:53:53/udp --name skydns crosbymichael/skydns -nameserver 8.8.8.8:53 -domain $DOMAIN
echo "Starting skydock"
docker run $EXTRA_FLAGS -d -v /var/run/docker.sock:/docker.sock --name skydock crosbymichael/skydock -ttl 30 -environment $ENVRN -s /docker.sock -domain $DOMAIN -name skydns
echo "Starting Master ...."
docker run $EXTRA_FLAGS -h $HDP_MASTER -d --name master --dns $DOCKER_BRIDGE_ADDR -e MASTER_HOST=$HDP_MASTER ${NAMESPACE}hadoop-master
addOrReplaceHost master $HDP_MASTER
echo "Waiting for Master to come up ...."
sleep 30
IFS=',' read -a hdpworkers <<< "$hadoop_worker_list"
for hdp_worker in ${hdpworkers[@]}; do
IFS='.' read -a hdp_worker_parts <<< "$hdp_worker"
hdp_worker_name=${hdp_worker_parts[0]}
echo "Starting $hdp_worker_name"
docker run $EXTRA_FLAGS -h $hdp_worker -d --name $hdp_worker_name --dns $DOCKER_BRIDGE_ADDR -e MASTER_HOST=$HDP_MASTER ${NAMESPACE}hadoop-worker
addOrReplaceHost $hdp_worker_name $hdp_worker
echo "Waiting for Worker to come up ...."
sleep 10
done
echo "Starting Client ...."
docker run $EXTRA_FLAGS -h $CLIENT -d --name client --dns $DOCKER_BRIDGE_ADDR -e MASTER_HOST=$HDP_MASTER ${NAMESPACE}hadoop-client
addOrReplaceHost client $CLIENT
echo "Waiting for Client to come up ...."
sleep 30
IFS=',' read -a kafkaservers <<< "$kafka_list"
for kafkas in ${kafkaservers[@]}; do
IFS=':' read -a kafkacomponents <<< "$kafkas"
brokerid=${kafkacomponents[0]}
kafkahost=${kafkacomponents[1]}
IFS='.' read -a kafkaparts <<< "$kafkahost"
kafkaname=${kafkaparts[0]}
echo "Starting $kafkaname"
docker run $EXTRA_FLAGS -h $kafkahost -d --name $kafkaname --dns $DOCKER_BRIDGE_ADDR -e KAFKA_ZOOKEEPER_CONNECT=$zk_connect -e KAFKA_BROKER_ID=$brokerid -e KAFKA_HOST_NAME=$kafkahost ${NAMESPACE}kafka
addOrReplaceHost $kafkaname $kafkahost
echo "Waiting for $kafkaname to come up"
sleep 10
done
echo "Starting Kafka web console ...."
docker run $EXTRA_FLAGS -d --dns $DOCKER_BRIDGE_ADDR -h $KAFKA_CONSOLE --name kafka-console hwestphal/kafka-web-console
addOrReplaceHost kafka-console $KAFKA_CONSOLE
echo "Waiting for Kafka web console to come up ...."
sleep 10
echo "Done"
<file_sep>/hadoop/hadoop-client/files/run_hadoop_client.sh
#!/bin/bash
service oozie start
while [ 1 ];
do
tail /var/log/oozie/*.log
sleep 1
done
<file_sep>/stop_all.sh
#! /bin/bash
cwd=`cd "$(dirname "$0")" && pwd`
source $cwd/env.sh
echo "Stopping any running docker containers"
function stopAndRemove() {
local container_name="$1"
docker ps | grep -q $container_name && docker stop $container_name
docker ps -a | grep -q $container_name && docker rm -v $container_name
}
IFS=',' read -a kafkaservers <<< "$kafka_list"
for kafkas in ${kafkaservers[@]}; do
IFS=':' read -a kafkacomponents <<< "$kafkas"
brokerid=${kafkacomponents[0]}
kafkahost=${kafkacomponents[1]}
IFS='.' read -a kafkaparts <<< "$kafkahost"
kafkaname=${kafkaparts[0]}
echo "Stopping $kafkaname"
stopAndRemove $kafkaname
done
IFS=',' read -a hdpworkers <<< "$hadoop_worker_list"
for hdp_worker in ${hdpworkers[@]}; do
IFS='.' read -a hdp_worker_parts <<< "$hdp_worker"
hdp_worker_name=${hdp_worker_parts[0]}
echo "Stopping $hdp_worker_name"
stopAndRemove $hdp_worker_name
done
stopAndRemove kafka-console
stopAndRemove client
stopAndRemove master
stopAndRemove skydock
stopAndRemove skydns
echo "Done stopping containers"
<file_sep>/hadoop/hadoop-client/files/default_cmd
#!/bin/bash
source /root/hadoop_files/configure_hadoop.sh
IP=$(ip -o -4 addr list eth0 | perl -n -e 'if (m{inet\s([\d\.]+)\/\d+\s}xms) { print $1 }')
echo "CLIENT_IP=$IP"
echo "preparing Hadoop"
if [ -z "$MASTER_HOST" ]; then
echo "Defining MASTER_HOST is mandatory !"
exit 1
fi
cp /root/hadoop_client_files/oozie-site.xml /etc/oozie/conf
prepare_hadoop $MASTER_HOST
echo "starting sshd"
/usr/sbin/sshd
sleep 5
echo "configuring oozie"
su - hdfs -c "hadoop fs -mkdir -p /user/oozie"
su - hdfs -c "hadoop fs -chmod 775 /user"
su - hdfs -c "hadoop fs -chown oozie:hadoop /user/oozie"
su - hdfs -c "hadoop fs -ls /user/oozie" | grep -q /user/oozie/share || /usr/bin/oozie-setup sharelib create -fs hdfs://$MASTER_HOST:9000 -locallib /usr/lib/oozie/oozie-sharelib-yarn.tar.gz
echo "starting Hadoop Client"
cp /root/hadoop_client_files/run_hadoop_client.sh /
chmod a+rx /run_hadoop_client.sh
/run_hadoop_client.sh
<file_sep>/hadoop/hadoop-base/Dockerfile
# Based on
# https://github.com/amplab/docker-scripts.git
FROM base
# Setup a volume for data
VOLUME ["/data"]
# Setup CDH repo
RUN curl http://archive.cloudera.com/cdh5/redhat/6/x86_64/cdh/cloudera-cdh5.repo -o /etc/yum.repos.d/cloudera-cdh5.repo
RUN sed -i "s|cdh/5/|cdh/5.3.1/|" /etc/yum.repos.d/cloudera-cdh5.repo
# Hadoop
RUN yum install -y hadoop-mapreduce hadoop-0.20-mapreduce hadoop-client
# Docker messes up /etc/hosts and adds two entries for 127.0.0.1
# we try to recover from that by giving /etc/resolv.conf and therefore
# the nameserver priority
RUN sed -i s/"files dns"/"dns files"/ /etc/nsswitch.conf
ADD hadoop-files /root/hadoop_files
RUN chmod +x /root/hadoop_files/*.sh
<file_sep>/hadoop/hadoop-worker/files/run_hadoop_worker.sh
#!/bin/bash
while [ 1 ];
do
tail /var/log/hadoop-hdfs-datanode/*.log
sleep 1
done
<file_sep>/build_all.sh
#! /bin/bash
cwd=`cd "$(dirname "$0")" && pwd`
source $cwd/env.sh
$cwd/clean_all.sh
set -e
EXTN=".amv"
function cleanup {
echo "Reverting Dockerfile mods.."
for f in `find $cwd -name Dockerfile$EXTN -not -path $cwd/base/*`
do
mv $f $(dirname $f)/Dockerfile
done
echo "Done reverting mods."
}
trap cleanup EXIT
for f in `find $cwd -name Dockerfile -not -path $cwd/base/*`
do
echo "Modifying file : "$f
ESC_NAMESPACE=$(echo $NAMESPACE | sed -e 's#/#\\/#g')
sed -i$EXTN "/FROM *${ESC_NAMESPACE}/b; s/FROM */FROM ${ESC_NAMESPACE}/" $f
done
docker images | grep -q skydns || docker pull crosbymichael/skydns
docker images | grep -q skydock || docker pull crosbymichael/skydock
docker images | grep -q kafka-web-console || docker pull hwestphal/kafka-web-console
docker build -t ${NAMESPACE}base base
docker build -t ${NAMESPACE}hadoop-base hadoop/hadoop-base
docker build -t ${NAMESPACE}hadoop-worker hadoop/hadoop-worker
docker build -t ${NAMESPACE}hadoop-master hadoop/hadoop-master
docker build -t ${NAMESPACE}hadoop-client hadoop/hadoop-client
docker build -t ${NAMESPACE}kafka kafka
<file_sep>/base/Dockerfile
#
# Base Dockerfile that defines OS and JDK alongwith their versions
#
FROM centos:6.6
ENV OS_VERSION 6.6
RUN yum -y update
RUN yum install -y curl git tar sudo openssh-server openssh-clients rsync
# passwordless ssh
RUN ssh-keygen -q -N "" -t dsa -f /etc/ssh/ssh_host_dsa_key
RUN ssh-keygen -q -N "" -t rsa -f /etc/ssh/ssh_host_rsa_key
RUN ssh-keygen -q -N "" -t rsa -f /root/.ssh/id_rsa
RUN cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys
# java
RUN curl -LO 'http://download.oracle.com/otn-pub/java/jdk/7u71-b14/jdk-7u71-linux-x64.rpm' -H 'Cookie: oraclelicense=accept-securebackup-cookie'
RUN rpm -i jdk-7u71-linux-x64.rpm
RUN rm jdk-7u71-linux-x64.rpm
ENV JAVA_HOME /usr/java/default
ENV PATH $PATH:$JAVA_HOME/bin
# /etc/hosts is read-only in docker, hack to work around this
# from http://jasonincode.com/customizing-hosts-file-in-docker/
# RUN cp /etc/hosts /tmp/hosts
# RUN mkdir -p -- /lib-override && cp /lib64/libnss_files.so.2 /lib-override
# RUN sed -i 's:/etc/hosts:/tmp/hosts:g' /lib-override/libnss_files.so.2
# ENV LD_LIBRARY_PATH /lib-override
<file_sep>/README.md
# processing-cluster
A collection of docker scripts to initialize a cluster of docker containers including hadoop, spark, kafka and oozie
# Quickstart:
1. Build images (change namespace etc. settings in env.sh)
./build_all.sh
2. Run
./run_all.sh
3. Stop containers
./stop_all.sh
4. Cleanup and remove all images
./clean_all.sh
<file_sep>/env.sh
#! /bin/bash
#export NAMESPACE=""
export NAMESPACE="amvinnu/"
export DOMAIN=test.corp
export ENVRN=dev
export HDP_MASTER=master.hadoop-master.$ENVRN.$DOMAIN
export HDP_WORKER_1=worker-1.hadoop-worker.$ENVRN.$DOMAIN
export HDP_WORKER_2=worker-2.hadoop-worker.$ENVRN.$DOMAIN
export hadoop_worker_list="$HDP_WORKER_1,$HDP_WORKER_2"
export KAFKA_1=kafka-1.kafka.$ENVRN.$DOMAIN
export KAFKA_2=kafka-2.kafka.$ENVRN.$DOMAIN
export kafka_list="1:$KAFKA_1,2:$KAFKA_2"
export zk_connect="$HDP_MASTER:2181"
export KAFKA_CONSOLE=kafka-console.kafka-web-console.$ENVRN.$DOMAIN
export CLIENT=client.hadoop-client.$ENVRN.$DOMAIN
<file_sep>/hadoop/hadoop-master/files/default_cmd
#!/bin/bash
set -x
echo "starting to configure"
env
source /root/hadoop_files/configure_hadoop.sh
IP=$(ip -o -4 addr list eth0 | perl -n -e 'if (m{inet\s([\d\.]+)\/\d+\s}xms) { print $1 }')
echo "MASTER_IP=$IP"
echo "preparing Hadoop"
if [ -z "$MASTER_HOST" ]; then
echo "Defining MASTER_HOST is mandatory !"
exit 1
fi
prepare_hadoop $MASTER_HOST
echo "starting Hadoop Master services"
su - hdfs -c "/usr/bin/hdfs namenode -format"
service hadoop-hdfs-namenode start
su - hdfs -c "hadoop fs -chown hdfs:hadoop /"
su - hdfs -c "hadoop fs -chmod 775 /"
su - hdfs -c "hadoop fs -mkdir /tmp"
su - hdfs -c "hadoop fs -chown mapred:hadoop /tmp"
service hadoop-yarn-resourcemanager start
service hadoop-mapreduce-historyserver start
service zookeeper-server start
su - hdfs -c "hadoop fs -mkdir -p hdfs:///user/spark/applicationHistory"
su - hdfs -c "hadoop fs -chmod 775 /user"
su - hdfs -c "hadoop fs -chown -R spark:spark /user/spark"
service spark-history-server start
echo "starting sshd"
/usr/sbin/sshd
sleep 5
echo "starting Hadoop Master"
cp /root/hadoop_master_files/run_hadoop_master.sh /
chmod a+rx /run_hadoop_master.sh
/run_hadoop_master.sh
<file_sep>/clean_all.sh
#! /bin/bash
cwd=`cd "$(dirname "$0")" && pwd`
source $cwd/env.sh
$cwd/stop_all.sh
echo "Removing docker images"
function cleanImage() {
local container_name="$1"
docker images | grep -q ${NAMESPACE}$container_name && docker rmi ${NAMESPACE}$container_name
}
cleanImage kafka
cleanImage hadoop-client
cleanImage hadoop-worker
cleanImage hadoop-master
cleanImage hadoop-base
cleanImage base
echo "Done removing docker images"
<file_sep>/hadoop/hadoop-client/Dockerfile
# Spark
FROM hadoop-base
# Install some tools required for the setup script
RUN yum install -y epel-release
RUN yum install -y sshpass
RUN yum install -y tomcat
# Install Spark
RUN yum install -y spark-core spark-python
# Oozie
RUN yum install -y oozie unzip
RUN curl -o /var/lib/oozie/ext-2.2.zip http://dev.sencha.com/deploy/ext-2.2.zip
RUN [ ! -d /var/lib/oozie/ext-2.2 ] && cd /var/lib/oozie && unzip ext-2.2.zip && chown -R oozie:oozie /var/lib/oozie/ext-2.2
# OOZIE ports
EXPOSE 11000
ADD files /root/hadoop_client_files
ENTRYPOINT ["/root/hadoop_client_files/default_cmd"]
|
f2a121f30a97fecd4b6108775346173691d9f023
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 19
|
Shell
|
amvinnu/processing-cluster
|
dff7734ca0eed4af4ca1762347145f993ed558bf
|
ba3bb33e8650888a65d4faed497b9fd232764093
|
refs/heads/master
|
<file_sep>package com.user.service.appservice.service;
import com.user.service.dbservice.domain.UserExp;
import java.util.List;
/**
* APP服务
*/
public interface UserExpService {
/**
* 新增一条记录
*
* @param exp 记录
* @return
*/
int create(UserExp exp);
/**
* 查询用户对应的所有记录
*
* @param userid
* @return
*/
List<UserExp> queryByUserID(String userid);
}
<file_sep>package com.user.view;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
public class LockView extends JDialog {
private JLabel passLb;
private JPasswordField passtxt;
private JButton login;
private boolean loginresult;
public LockView(JFrame p) {
super(p, true);
init();
initDlgParams();
}
private void initDlgParams() {
this.setTitle("登录");
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
this.setSize(240, 80);
this.setResizable(false);
this.setLocationRelativeTo(this.getParent());
passtxt.requestFocus();
repaint();
}
private void init() {
passLb = new JLabel("密码:");
passtxt = new JPasswordField();
passtxt.setPreferredSize(new Dimension(100, 26));
passtxt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
login();
}
});
login = new JButton("登录");
login.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
login();
}
});
Container con = this.getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
con.add(passLb);
con.add(passtxt);
con.add(login);
}
private void login() {
char[] pass = new char[6];
for (int i = 0; i < 6; i++) {
pass[i] = (char) (49 + i);
}
char[] password = passtxt.getPassword();
boolean canlogin = Arrays.equals(pass, password);
if (canlogin) {
loginresult = true;
dispose();
} else {
JOptionPane.showMessageDialog(this, "密码错误!", "提示"
, JOptionPane.WARNING_MESSAGE);
}
}
public boolean getLoginresult() {
return loginresult;
}
public static void main(String[] args) {
new LockView(new JFrame()).setVisible(true);
}
}
<file_sep>package com.magicg.practice.velocity;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.junit.Test;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
public class VelocityTest {
@Test
public void testit() {
//初始化velocityengine
VelocityEngine engine = new VelocityEngine();
/**
* 参考默认属性配置:org/apache/velocity/runtime/defaults/velocity.properties
*resource.loader = file
*file.resource.loader.description = Velocity File Resource Loader
*file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
*file.resource.loader.path = .
*file.resource.loader.cache = false
*file.resource.loader.modificationCheckInterval = 2
*/
//资源加载类型:classpath
engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
engine.setProperty("classpath.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
engine.init();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = simpleDateFormat.format(System.currentTimeMillis());
/**
* 获取vm文件
*/
Template template = engine.getTemplate("Service.vm", "UTF-8");
/**
* 初始化context,保存要渲染至vm的属性对象
*/
VelocityContext context = new VelocityContext();
context.put("package_name", "com.magicg");
context.put("model", "CreateUserService");
context.put("ctime", date);
context.put("author", "MagicG");
System.out.println(context.getCurrentResource());
System.out.println(context.getCurrentTemplateName());
for (String key : context.getKeys()) {
System.out.println(key);
}
//输出目标
StringWriter sw = new StringWriter();
//begin renderer
template.merge(context, sw);
System.out.println(sw);
}
}
<file_sep>package com.user.practice.ehcache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
//@Service
@Component
public class NameOper {
private long timestamp = System.currentTimeMillis();
public NameOper() {
}
@Cacheable(value = "name_cache")
public long getTimestamp() {
System.out.println("gettimestamp called");
return timestamp;
}
}
<file_sep>package com.magicg.practice.spring.cache;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertNotNull;
@ContextConfiguration(locations = "classpath*:spring/*.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountService2Test {
@Autowired
private AccountService2 accountService2;
@Test
public void testInject() {
assertNotNull(accountService2);
}
@Test
public void testGetAccountByName() {
System.out.println("first query...");
accountService2.getAccountByName("accountName");
System.out.println("second query...");
accountService2.getAccountByName("accountName");
System.out.println("first query...");
accountService2.getAccountByName("accountName2");
System.out.println("second query...");
accountService2.getAccountByName("accountName2");
}
}<file_sep>package com.user.view;
import com.user.model.BalanceOperation;
import com.user.service.BeanService;
import com.user.service.appservice.service.UserExpService;
import com.user.service.appservice.service.UserService;
import com.user.service.dbservice.domain.User;
import com.user.service.dbservice.domain.UserExp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.util.UUID;
public class CreateUserView extends JDialog {
private JLabel nameLb;
private JTextField nameTxt;
private JLabel phoneLb;
private JTextField phoneTxt;
private JLabel commentLb;
private JTextField commentTxt;
private JLabel balanceLb;
private JTextField balanceTxt;
private JButton okbtn;
private boolean result = false;
public CreateUserView(JFrame p) {
super(p, true);
init();
}
private void init() {
nameLb = new JLabel("姓名");
nameTxt = new JTextField();
nameTxt.setPreferredSize(new Dimension(100, 26));
phoneLb = new JLabel("手机号:");
phoneTxt = new JTextField();
phoneTxt.setPreferredSize(new Dimension(100, 26));
commentLb = new JLabel("备注:");
commentTxt = new JTextField();
commentTxt.setPreferredSize(new Dimension(100, 26));
balanceLb = new JLabel("充值金额:");
balanceTxt = new JTextField();
balanceTxt.setPreferredSize(new Dimension(100, 26));
okbtn = new JButton("确定");
okbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
createUser();
}
});
Container con = getContentPane();
con.setLayout(new GridLayout(5, 2));
con.add(nameLb);
con.add(nameTxt);
con.add(phoneLb);
con.add(phoneTxt);
con.add(commentLb);
con.add(commentTxt);
con.add(balanceLb);
con.add(balanceTxt);
con.add(new JLabel());
con.add(okbtn);
pack();
this.setResizable(false);
this.setTitle("注册");
this.setLocationRelativeTo(getParent());
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
private void createUser() {
String name = nameTxt.getText();
if (name == null || name.isEmpty()) {
JOptionPane.showMessageDialog(this, "用户名不能为空!", "提示"
, JOptionPane.WARNING_MESSAGE);
return;
}
String phoneno = phoneTxt.getText();
phoneno = null == phoneno ? "" : phoneno;
if (!phoneno.isEmpty()) {
try {
Long.parseLong(phoneno);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "手机号格式错误!", "提示"
, JOptionPane.WARNING_MESSAGE);
return;
}
}
String comment = commentTxt.getText();
String balance = balanceTxt.getText();
if (balance == null || balance.isEmpty()) {
balance = "0.0";
}
double value = 0.0;
try {
value = Double.parseDouble(balance);
if (value < 0.0) {
JOptionPane.showMessageDialog(this, "充值金额错误!", "提示"
, JOptionPane.WARNING_MESSAGE);
return;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "充值金额错误!", "提示"
, JOptionPane.WARNING_MESSAGE);
return;
}
User user = new User();
user.setUserID(UUID.randomUUID().toString());
user.setUserName(name);
user.setBalance(value);
user.setPhoneNo(phoneno);
user.setRegDate(new Date(System.currentTimeMillis()));
user.setComment(comment);
UserService userService = BeanService.getService(UserService.class);
try {
userService.createUser(user);
//记录
UserExp exp = new UserExp();
exp.setCurrentBalance(user.getBalance());
exp.setExpDate(new Date(System.currentTimeMillis()));
exp.setExpID(UUID.randomUUID().toString());
exp.setExpValue(value);
exp.setUserID(user.getUserID());
exp.setOperation(BalanceOperation.ADD);
UserExpService userExpService = BeanService.getService(UserExpService.class);
try {
userExpService.create(exp);
} catch (Exception ee) {
ee.printStackTrace();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "提示"
, JOptionPane.WARNING_MESSAGE);
return;
}
result = true;
dispose();
}
public boolean getResult() {
return result;
}
public static void main(String[] args) {
new CreateUserView(new JFrame()).setVisible(true);
}
}
<file_sep>package com.magicg.practice.spring.cache;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(locations = "classpath*:spring/*.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountService1Test {
@Autowired()
private AccountService1 accountService1;
@Test
public void testGetAccountByName() {
accountService1.getAccountByName("accountName");
accountService1.getAccountByName("accountName");
accountService1.reload();
System.out.println(("after reload ...."));
accountService1.getAccountByName("accountName");
accountService1.getAccountByName("accountName");
}
}
<file_sep>package com.user.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanService {
private static ApplicationContext ctx;
static {
try {
//String[] cfgs = {"spring/spring_appservice.xml", "spring/spring_dbservice.xml"};
/**
* 使用通配符方式,模块将springcfg放置到固定目录下。
*/
String cfgs = "classpath*:spring/*.xml";
ctx = new ClassPathXmlApplicationContext(cfgs);
} catch (Exception e) {
e.printStackTrace();
}
}
public static <T> T getService(String id) {
return (T) ctx.getBean(id);
}
public static <T> T getService(Class<T> clz) {
return ctx.getBean(clz);
}
public static void main(String[] args) {
}
}
<file_sep>package com.user.view;
import com.user.service.BeanService;
import com.user.service.appservice.service.UserService;
import com.user.service.dbservice.domain.User;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.util.List;
import java.util.UUID;
import java.util.Vector;
public class MainFrame extends JFrame {
private JTable tableView;
private DefaultTableModel dataModel;
private JLabel status;
private JScrollPane jScrollPane;
private boolean isLocked = true;
public MainFrame() {
super("会员管理");
init();
}
private void init() {
createMenu();
createTable();
createStatus();
initFrameParams();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
lockSystem();
getData();
}
});
SwingUtilities.updateComponentTreeUI(this);
}
private void initFrameParams() {
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit()
.getScreenSize();
Rectangle bounds = new Rectangle(screenSize);
Insets insets = Toolkit.getDefaultToolkit()
.getScreenInsets(this.getGraphicsConfiguration());
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= insets.left + insets.right;
bounds.height -= insets.top + insets.bottom;
this.setBounds(bounds);
}
private void createStatus() {
status = new JLabel();
getContentPane().add(status, BorderLayout.SOUTH);
}
////TEST
private User buildUser() {
User user = new User();
user.setUserID(UUID.randomUUID().toString());
user.setUserName("用户名--" + System.currentTimeMillis());
user.setRegDate(new Date(System.currentTimeMillis()));
user.setPhoneNo("" + System.currentTimeMillis());
user.setBalance(Math.random() * 50);
user.setComment("月落乌啼霜满天");
return user;
}
private void getData() {
if (isLocked) {
return;
}
clearTableData();
//get data
clearStatus();
addUsers(getAllUsers());
}
private void addUsers(List<User> users) {
Vector dataVector = dataModel.getDataVector();
for (User user : users) {
Vector row = new Vector();
row.add(user);
row.add(user.getPhoneNo());
row.add(user.getRegDate());
row.add(user.getBalance());
row.add(user.getComment());
dataVector.add(row);
}
dataModel.fireTableDataChanged();
}
private List<User> getAllUsers() {
UserService userService = BeanService.getService(UserService.class);
return userService.queryAll();
}
private void clearStatus() {
status.setText("");
}
private void clearTableData() {
tableView.getSelectionModel().clearSelection();
dataModel.getDataVector().clear();
dataModel.fireTableDataChanged();
}
private void createMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu userMenu = new JMenu("用户");
JMenuItem addUser = new JMenuItem("注册");
addUser.addActionListener(new CreateAction());
JMenuItem findUser = new JMenuItem("查找");
findUser.addActionListener(new FindUserAction());
JMenuItem delUser = new JMenuItem("删除");
delUser.addActionListener(new DelUserAction());
userMenu.add(addUser);
userMenu.add(findUser);
userMenu.add(delUser);
menuBar.add(userMenu);
JMenu balanceMenu = new JMenu("金额");
JMenuItem addbalance = new JMenuItem("充值");
addbalance.addActionListener(new AddBalanceAction());
JMenuItem debalance = new JMenuItem("消费");
debalance.addActionListener(new DeBalanceAction());
balanceMenu.add(addbalance);
balanceMenu.add(debalance);
JMenuItem showrecords = new JMenuItem("消费记录");
showrecords.addActionListener(new ShowRecordsAction());
balanceMenu.add(showrecords);
menuBar.add(balanceMenu);
JMenu opMenu = new JMenu("操作");
JMenuItem locksys = new JMenuItem("锁定");
locksys.addActionListener(new LockSystemAction());
JMenuItem exitsys = new JMenuItem("退出");
exitsys.addActionListener(new ExitSystemAction());
opMenu.add(locksys);
opMenu.add(exitsys);
menuBar.add(opMenu);
this.setJMenuBar(menuBar);
}
public void createTable() {
// final
final String[] names = {
"姓名",
"手机号",
"注册日期",
"余额",
"备注"
};
dataModel = new DefaultTableModel(names, 0);
// Create the table
tableView = new JTable(dataModel) {
public boolean isCellEditable(int row, int col) {
return false;
}
};
// TableRowSorter sorter = new TableRowSorter(dataModel);
// tableView.setRowSorter(sorter);
dataModel.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
updateStatus();
}
});
tableView.getTableHeader().setReorderingAllowed(false);
tableView.setRowHeight(25);
tableView.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jScrollPane = new JScrollPane(tableView);
this.getContentPane().add(jScrollPane, BorderLayout.CENTER);
}
private void updateStatus() {
status.setText("总数:" + dataModel.getRowCount());
}
public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
new MainFrame().setVisible(true);
}
private class CreateAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
CreateUserView cv = new CreateUserView(MainFrame.this);
cv.setVisible(true);
if (cv.getResult()) {
getData();
}
}
}
private class FindUserAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
findUser();
}
}
private void findUser() {
FindView findView = new FindView(this);
findView.setVisible(true);
String namecondition = findView.getNameCondition();
if (namecondition == null || namecondition.isEmpty()) {
getData();
} else {
UserService userService = BeanService.getService(UserService.class);
List<User> users = userService.queryByName(namecondition);
clearTableData();
//get data
clearStatus();
addUsers(users);
}
}
private class AddBalanceAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int selectedRow = tableView.getSelectedRow();
if (-1 == selectedRow) {
JOptionPane.showMessageDialog(MainFrame.this, "请选择要充值的用户!", "提示"
, JOptionPane.WARNING_MESSAGE);
return;
}
User user = (User) tableView.getValueAt(selectedRow, 0);
AddBalanceView addBalanceView = new AddBalanceView(MainFrame.this, user);
addBalanceView.setVisible(true);
getData();
tableView.getSelectionModel().addSelectionInterval(selectedRow, selectedRow);
}
}
private class DeBalanceAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int selectedRow = tableView.getSelectedRow();
if (-1 == selectedRow) {
JOptionPane.showMessageDialog(MainFrame.this, "请选择要操作的用户!", "提示"
, JOptionPane.WARNING_MESSAGE);
return;
}
User user = (User) tableView.getValueAt(selectedRow, 0);
DeBalanceView deBalanceView = new DeBalanceView(MainFrame.this, user);
deBalanceView.setVisible(true);
getData();
tableView.getSelectionModel().addSelectionInterval(selectedRow, selectedRow);
}
}
private class LockSystemAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
lockSystem();
getData();
}
}
private void lockSystem() {
isLocked = true;
clearTableData();
clearStatus();
LockView lockView = new LockView(this);
lockView.setVisible(true);
if (lockView.getLoginresult()) {
isLocked = false;
}
//TODO refresh table data
getData();
}
private class ExitSystemAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private class ShowRecordsAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int selectedRow = tableView.getSelectedRow();
if (-1 == selectedRow) {
JOptionPane.showMessageDialog(MainFrame.this, "请选择要操作的用户!", "提示"
, JOptionPane.WARNING_MESSAGE);
return;
}
User user = (User) tableView.getValueAt(selectedRow, 0);
new RecordView(MainFrame.this, user).setVisible(true);
}
}
private class DelUserAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int selectedRow = tableView.getSelectedRow();
if (-1 == selectedRow) {
JOptionPane.showMessageDialog(MainFrame.this, "请选择要删除的用户!", "提示"
, JOptionPane.WARNING_MESSAGE);
return;
}
User user = (User) tableView.getValueAt(selectedRow, 0);
UserService userService = BeanService.getService(UserService.class);
userService.deleteUser(user.getUserID());
getData();
}
}
}
<file_sep>package com.magicg.practice.spring.cache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class AccountService2 {
// 使用了一个缓存名叫 accountCache
@Cacheable(value = "accountCache", key = "#accountName")
public Account getAccountByName(String accountName) {
// 方法内部实现不考虑缓存逻辑,直接实现业务
System.out.println("real querying account... " + accountName);
Optional<Account> accountOptional = getFromDB(accountName);
if (!accountOptional.isPresent()) {
throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));
}
return accountOptional.get();
}
private Optional<Account> getFromDB(String accountName) {
System.out.println("real querying db... " + accountName);
//Todo query data from database
return Optional.ofNullable(new Account(accountName));
}
}
<file_sep>
### 技术选型
#### 后端技术:
技术 | 名称 | 官网| S
----|------|----|----
Spring Framework | 容器 | [http://projects.spring.io/spring-framework/](http://projects.spring.io/spring-framework/) | S
SpringMVC | MVC框架 | [http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc)
Apache Shiro | 安全框架 | [http://shiro.apache.org/](http://shiro.apache.org/)
Spring session | 分布式Session管理 | [http://projects.spring.io/spring-session/](http://projects.spring.io/spring-session/)
MyBatis | ORM框架 | [http://www.mybatis.org/mybatis-3/zh/index.html](http://www.mybatis.org/mybatis-3/zh/index.html) | S
MyBatis Generator | 代码生成 | [http://www.mybatis.org/generator/index.html](http://www.mybatis.org/generator/index.html)
PageHelper | MyBatis物理分页插件 | [http://git.oschina.net/free/Mybatis_PageHelper](http://git.oschina.net/free/Mybatis_PageHelper)
Druid | 数据库连接池 | [https://github.com/alibaba/druid](https://github.com/alibaba/druid)
FluentValidator | 校验框架 | [https://github.com/neoremind/fluent-validator](https://github.com/neoremind/fluent-validator)
Thymeleaf | 模板引擎 | [http://www.thymeleaf.org/](http://www.thymeleaf.org/)
Velocity | 模板引擎 | [http://velocity.apache.org/](http://velocity.apache.org/) | S
ZooKeeper | 分布式协调服务 | [http://zookeeper.apache.org/](http://zookeeper.apache.org/)
Dubbo | 分布式服务框架 | [http://dubbo.io/](http://dubbo.io/)
TBSchedule & elastic-job | 分布式调度框架 | [https://github.com/dangdangdotcom/elastic-job](https://github.com/dangdangdotcom/elastic-job)
Redis | 分布式缓存数据库 | [https://redis.io/](https://redis.io/)
Solr & Elasticsearch | 分布式全文搜索引擎 | [http://lucene.apache.org/solr/](http://lucene.apache.org/solr/) [https://www.elastic.co/](https://www.elastic.co/)
Quartz | 作业调度框架 | [http://www.quartz-scheduler.org/](http://www.quartz-scheduler.org/)
Ehcache | 进程内缓存框架 | [http://www.ehcache.org/](http://www.ehcache.org/) | S
ActiveMQ | 消息队列 | [http://activemq.apache.org/](http://activemq.apache.org/)
JStorm | 实时流式计算框架 | [http://jstorm.io/](http://jstorm.io/)
FastDFS | 分布式文件系统 | [https://github.com/happyfish100/fastdfs](https://github.com/happyfish100/fastdfs)
Log4J | 日志组件 | [http://logging.apache.org/log4j/1.2/](http://logging.apache.org/log4j/1.2/) | S
Swagger2 | 接口测试框架 | [http://swagger.io/](http://swagger.io/)
sequence | 分布式高效ID生产 | [http://git.oschina.net/yu120/sequence](http://git.oschina.net/yu120/sequence)
AliOSS & Qiniu & QcloudCOS | 云存储 | [https://www.aliyun.com/product/oss/](https://www.aliyun.com/product/oss/) [http://www.qiniu.com/](http://www.qiniu.com/) [https://www.qcloud.com/product/cos](https://www.qcloud.com/product/cos)
Protobuf & json | 数据序列化 | [https://github.com/google/protobuf](https://github.com/google/protobuf)
Jenkins | 持续集成工具 | [https://jenkins.io/index.html](https://jenkins.io/index.html)
Maven | 项目构建管理 | [http://maven.apache.org/](http://maven.apache.org/) | S
Netty-socketio | 实时推送 | [https://github.com/mrniko/netty-socketio](https://github.com/mrniko/netty-socketio)
#### 前端技术:
技术 | 名称 | 官网
----|------|----
jQuery | 函式库 | [http://jquery.com/](http://jquery.com/)
Bootstrap | 前端框架 | [http://getbootstrap.com/](http://getbootstrap.com/)
Bootstrap-table | Bootstrap数据表格 | [http://bootstrap-table.wenzhixin.net.cn/](http://bootstrap-table.wenzhixin.net.cn/)
Font-awesome | 字体图标 | [http://fontawesome.io/](http://fontawesome.io/)
material-design-iconic-font | 字体图标 | [https://github.com/zavoloklom/material-design-iconic-font](https://github.com/zavoloklom/material-design-iconic-font)
Waves | 点击效果插件 | [https://github.com/fians/Waves](https://github.com/fians/Waves)
zTree | 树插件 | [http://www.treejs.cn/v3/](http://www.treejs.cn/v3/)
Select2 | 选择框插件 | [https://github.com/select2/select2](https://github.com/select2/select2)
jquery-confirm | 弹出窗口插件 | [https://github.com/craftpip/jquery-confirm](https://github.com/craftpip/jquery-confirm)
jQuery EasyUI | 基于jQuery的UI插件集合体 | [http://www.jeasyui.com](http://www.jeasyui.com)
React | 界面构建框架 | [https://github.com/facebook/react](https://github.com/facebook/react)
Editor.md | Markdown编辑器 | [https://github.com/pandao/editor.md](https://github.com/pandao/editor.md)
zhengAdmin | 后台管理系统模板 | [https://github.com/shuzheng/zhengAdmin](https://github.com/shuzheng/zhengAdmin)
autoMail | 邮箱地址自动补全插件 | [https://github.com/shuzheng/autoMail](https://github.com/shuzheng/autoMail)
zheng.jprogress.js | 加载进度条插件 | [https://github.com/shuzheng/zheng.jprogress.js](https://github.com/shuzheng/zheng.jprogress.js)
zheng.jtotop.js | 返回顶部插件 | [https://github.com/shuzheng/zheng.jtotop.js](https://github.com/shuzheng/zheng.jtotop.js)
socket.io.js | SocketIO插件 | [https://socket.io/](https://socket.io/)
#### 开发工具:
- MySql: 数据库
- jetty: 开发服务器
- Tomcat: 应用服务器
- SVN|Git: 版本管理
- Nginx: 反向代理服务器
- Varnish: HTTP加速器
- IntelliJ IDEA: 开发IDE
- PowerDesigner: 建模工具
- Navicat for MySQL: 数据库客户端
#### 开发环境:
- Jdk7+
- Mysql5.5+
- Redis
- Zookeeper
- ActiveMQ
- Dubbo-admin
- Dubbo-monitor
### 工具安装
环境搭建和系统部署文档(作者:小兵,QQ群共享提供下载)
### 资源下载
- JDK7 [http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html](http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html "JDK7")
- Maven [http://maven.apache.org/download.cgi](http://maven.apache.org/download.cgi "Maven")
- Redis [https://redis.io/download](https://redis.io/download "Redis")
- ActiveMQ [http://activemq.apache.org/download-archives.html](http://activemq.apache.org/download-archives.html "ActiveMQ")
- ZooKeeper [http://www.apache.org/dyn/closer.cgi/zookeeper/](http://www.apache.org/dyn/closer.cgi/zookeeper/ "ZooKeeper")
- Dubbo [http://dubbo.io/Download-zh.htm](http://dubbo.io/Download-zh.htm "Dubbo")
- Elastic Stack [https://www.elastic.co/downloads](https://www.elastic.co/downloads "Elastic Stack")
- Nginx [http://nginx.org/en/download.html](http://nginx.org/en/download.html "Nginx")
- Jenkins [http://updates.jenkins-ci.org/download/war/](http://updates.jenkins-ci.org/download/war/ "Jenkins")
- dubbo-admin-2.5.3 [http://download.csdn.net/detail/shuzheng5201314/9733652](http://download.csdn.net/detail/shuzheng5201314/9733652 "dubbo-admin-2.5.3")
- dubbo-admin-2.5.4-SNAPSHOT-jdk8 [http://download.csdn.net/detail/shuzheng5201314/9733657](http://download.csdn.net/detail/shuzheng5201314/9733657 "dubbo-admin-2.5.4-SNAPSHOT-jdk8")
- 更多资源请加QQ群
### 优秀文章和博客
- [创业互联网公司如何搭建自己的技术框架](http://shuzheng5201314.iteye.com/blog/2330151 "创业互联网公司如何搭建自己的技术框架")
- [微服务实战](https://segmentfault.com/a/1190000004634172 "微服务实战")
- [单点登录原理与简单实现](http://shuzheng5201314.iteye.com/blog/2343910 "单点登录原理与简单实现")
- [ITeye论坛关于权限控制的讨论](http://www.iteye.com/magazines/82 "ITeye论坛关于权限控制的讨论")
- [RBAC新解:基于资源的权限管理(Resource-Based Access Control)](http://globeeip.iteye.com/blog/1236167 "RBAC新解:基于资源的权限管理(Resource-Based Access Control)")
- [网站架构经验随笔](http://jinnianshilongnian.iteye.com/blog/2289904 "网站架构经验随笔")
- [支付系统架构](http://shuzheng5201314.iteye.com/blog/2355431 "支付系统架构")
- [Spring整合JMS](http://elim.iteye.com/blog/1893038 "Spring整合JMS")
- [跟我学Shiro目录贴](http://jinnianshilongnian.iteye.com/blog/2018398 "跟我学Shiro目录贴")
- [跟我学SpringMVC目录汇总贴](http://jinnianshilongnian.iteye.com/blog/1752171 "跟我学SpringMVC目录汇总贴")
- [跟我学spring3 目录贴](http://jinnianshilongnian.iteye.com/blog/1482071 "跟我学spring3 目录贴")
- [跟我学OpenResty(Nginx+Lua)开发目录贴](http://jinnianshilongnian.iteye.com/blog/2190344 "跟我学OpenResty(Nginx+Lua)开发目录贴")
- [Redis中文网](http://www.redis.net.cn/ "Redis中文网")
- [读懂Redis并配置主从集群及高可用部署](http://mp.weixin.qq.com/s?__biz=MzIxNTYzOTQ0Ng==&mid=2247483668&idx=1&sn=cd31574877d38cf7ff9c047b86c9bf23&chksm=979475eda0e3fcfb6b5006bcd19c5a838eca9e369252847dbdf97820bf418201dd75c1dadda3&mpshare=1&scene=23&srcid=0117KUiiITwi2ETRan16xRVg#rd "读懂Redis并配置主从集群及高可用部署")
- [Redis哨兵-实现Redis高可用](http://redis.majunwei.com/topics/sentinel.html "Redis哨兵-实现Redis高可用")
- [ELK(ElasticSearch, Logstash, Kibana)搭建实时日志分析平台](http://www.open-open.com/lib/view/open1451801542042.html "ELK(ElasticSearch, Logstash, Kibana)搭建实时日志分析平台")
- [Nginx基本功能极速入门](http://xxgblog.com/2015/05/17/nginx-start/ "Nginx基本功能极速入门")
- [mybatis-genarator 自定义插件](https://my.oschina.net/alexgaoyh/blog/702791 "mybatis-genarator 自定义插件")
- [Elasticsearch权威指南(中文版)](https://es.xiaoleilu.com/510_Deployment/20_hardware.html "Elasticsearch权威指南(中文版)")
- [springMVC对简单对象、Set、List、Map的数据绑定和常见问题.](http://blog.csdn.net/z_dendy/article/details/12648641 "springMVC对简单对象、Set、List、Map的数据绑定和常见问题.")
- [如何细粒度地控制你的MyBatis二级缓存](http://blog.csdn.net/luanlouis/article/details/41800511 "如何细粒度地控制你的MyBatis二级缓存")
- [Git 在团队中的最佳实践--如何正确使用Git Flow](hhttps://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow "Git 在团队中的最佳实践--如何正确使用Git Flow")
- [做个男人,做个成熟的男人,做个有城府的男人](http://shuzheng5201314.iteye.com/blog/1387820 "做个男人,做个成熟的男人,做个有城府的男人")
### 在线小工具
- [在线Cron表达式生成器](http://cron.qqe2.com/ "在线Cron表达式生成器")
- [在线工具 - 程序员的工具箱](http://tool.lu/ "在线工具 - 程序员的工具箱")
### 在线文档
- [JDK7英文文档](http://tool.oschina.net/apidocs/apidoc?api=jdk_7u4 "JDK7英文文档")
- [Spring4.x文档](http://spring.oschina.mopaas.com/ "Spring4.x文档")
- [Mybatis3官网](http://www.mybatis.org/mybatis-3/zh/index.html "Mybatis3官网")
- [Dubbo官网](http://dubbo.io/ "Dubbo官网")
- [Nginx中文文档](http://tool.oschina.net/apidocs/apidoc?api=nginx-zh "Nginx中文文档")
- [Freemarker在线手册](http://freemarker.foofun.cn/ "Freemarker在线中文手册")
- [Velocity在线手册](http://velocity.apache.org/engine/devel/developer-guide.html "Velocity在线手册")
- [Bootstrap在线手册](http://www.bootcss.com/ "Bootstrap在线手册")
- [Git官网中文文档](https://git-scm.com/book/zh/v2 "Git官网中文文档")
- [Thymeleaf](http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html "Thymeleaf")
<file_sep>package com.user.service.dbservice.service;
import com.user.service.dbservice.domain.UserExp;
import com.user.service.dbservice.mapper.UserExpMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Objects;
/**
*
*/
@Repository("pluserexpservice")
public class DefaultPLUserExpService implements PLUserExpService {
@Autowired
private SqlSessionFactory sessionFactory;
public DefaultPLUserExpService() {
// this.sessionFactory = SqlSessionFactoryHolder.getSessionFactory();
}
/**
* 新增一条记录
*
* @param exp 记录
* @return
*/
@Override
public int create(UserExp exp) {
if (expInvalid(exp)) {
return 0;
}
try (SqlSession session = sessionFactory.openSession(true)) {
UserExpMapper mapper = session.getMapper(UserExpMapper.class);
return mapper.create(exp);
} catch (Exception e) {
return 0;
}
}
private boolean expInvalid(UserExp exp) {
if (Objects.isNull(exp)) {
return true;
}
if (Objects.isNull(exp.getExpID()) || exp.getExpID().isEmpty()) {
return true;
}
if (Objects.isNull(exp.getUserID()) || exp.getUserID().isEmpty()) {
return true;
}
return Objects.isNull(exp.getExpDate());
}
/**
* 批量创建
*
* @param exps
* @return
*/
// @Override
// public int create(Collection<UserExp> exps) {
// return 0;
// }
/**
* 查询用户对应的所有记录
*
* @param userid
* @return
*/
@Override
public List<UserExp> queryByUserID(String userid) {
try (SqlSession session = sessionFactory.openSession(true)) {
UserExpMapper mapper = session.getMapper(UserExpMapper.class);
return mapper.queryByUser(userid);
}
}
/**
* 查询一条记录数据
*
* @param expid
* @return
*/
// @Override
// public UserExp queryByExpID(String expid) {
// try (SqlSession session = sessionFactory.openSession(true)) {
// UserExpMapper mapper = session.getMapper(UserExpMapper.class);
//
// return mapper.queryByExpID(expid);
// }
// }
/**
* 查询库中所有的记录
*
* @return
*/
@Override
public List<UserExp> queryAll() {
try (SqlSession session = sessionFactory.openSession(true)) {
UserExpMapper mapper = session.getMapper(UserExpMapper.class);
return mapper.queryAll();
}
}
/**
* 删除一条记录
*
* @param expID
* @return
*/
@Override
public int delete(String expID) {
try (SqlSession session = sessionFactory.openSession(true)) {
UserExpMapper mapper = session.getMapper(UserExpMapper.class);
return mapper.delete(expID);
}
}
/**
* 删除用户的消费记录
*
* @param userID
* @return
*/
// @Override
// public int deleteByUserID(String userID) {
// try (SqlSession session = sessionFactory.openSession(true)) {
// UserExpMapper mapper = session.getMapper(UserExpMapper.class);
//
// return mapper.deleteByUser(userID);
// }
// }
public final void setSessionFactory(SqlSessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
<file_sep>jdbc.driverClassName = org.sqlite.JDBC
jdbc.url = jdbc:sqlite::resource:data/test.db
jdbc.username =
jdbc.password =<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>serverparent</artifactId>
<groupId>com.user</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>dbservice</artifactId>
<name>user.dbservice</name>
<url>https://mgmdd.github.io/comuser/</url>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.user</groupId>
<artifactId>common</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
</dependencies>
<build>
<!--此处使用错误,通过resource来直接执行拷贝动作
导致执行单元测试时找不到 data/test.db,
修改为通过resource plugin执行拷贝动作
look issue #1
-->
<!--<resources>-->
<!--<resource>-->
<!--<directory>src/main/resources</directory>-->
<!--<excludes>-->
<!--<exclude>-->
<!--data/**-->
<!--</exclude>-->
<!--</excludes>-->
<!--</resource>-->
<!--<resource>-->
<!--<directory>src/main/resources</directory>-->
<!--<targetPath>${project.basedir}/../../user.distribution/src/main</targetPath>-->
<!--<includes>-->
<!--<include>-->
<!--data/**-->
<!--</include>-->
<!--</includes>-->
<!--</resource>-->
<!--</resources>-->
<plugins>
<!--<plugin>-->
<!--<artifactId>maven-jar-plugin</artifactId>-->
<!--<executions>-->
<!--<execution>-->
<!--<id>jar-it</id>-->
<!--<phase>package</phase>-->
<!--<goals>-->
<!--<goal>jar</goal>-->
<!--</goals>-->
<!--<configuration>-->
<!--<includes>-->
<!--<include>-->
<!--**-->
<!--</include>-->
<!--</includes>-->
<!--<excludes>-->
<!--data/**-->
<!--</excludes>-->
<!--</configuration>-->
<!--</execution>-->
<!--</executions>-->
<!--</plugin>-->
<!--<plugin>-->
<!--<artifactId>maven-jar-plugin</artifactId>-->
<!--<version>3.0.2</version>-->
<!--<executions>-->
<!--<execution>-->
<!--<id>default-jar</id>-->
<!--<phase>package</phase>-->
<!--<goals>-->
<!--<goal>jar</goal>-->
<!--</goals>-->
<!--<configuration>-->
<!--<archive>-->
<!--<addMavenDescriptor>false</addMavenDescriptor>-->
<!--</archive>-->
<!--<excludes>-->
<!--<exclude>-->
<!--data/**-->
<!--</exclude>-->
<!--</excludes>-->
<!--</configuration>-->
<!--</execution>-->
<!--</executions>-->
<!--<configuration>-->
<!--<archive>-->
<!--<addMavenDescriptor>false</addMavenDescriptor>-->
<!--</archive>-->
<!--</configuration>-->
<!--</plugin>-->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<!--<execution>-->
<!--<id>default-resources</id>-->
<!--<phase>process-resources</phase>-->
<!--<goals>-->
<!--<goal>resources</goal>-->
<!--</goals>-->
<!--<configuration>-->
<!--<resources>-->
<!--<resource>-->
<!--<directory>src/main/resources</directory>-->
<!--<include>**</include>-->
<!--<exclude>data/**</exclude>-->
<!--</resource>-->
<!--</resources>-->
<!--</configuration>-->
<!--</execution>-->
<execution>
<id>copy-db</id>
<phase>compile</phase>
<goals>
<goal>
copy-resources
</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>
data/**
</include>
</includes>
</resource>
</resources>
<outputDirectory>${project.basedir}/../../distribution/src/main</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<file_sep>package com.user.view;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FindView extends JDialog {
private JLabel nameLb;
private JTextField nameTxt;
private JButton find;
private String findname;
public FindView(JFrame p) {
super(p, true);
init();
initDlgParams();
}
private void initDlgParams() {
this.setTitle("查找");
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setSize(240, 80);
this.setResizable(false);
this.setLocationRelativeTo(this.getParent());
}
private void init() {
nameLb = new JLabel("姓名:");
nameTxt = new JTextField();
nameTxt.setPreferredSize(new Dimension(100, 26));
nameTxt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
finduser();
}
});
find = new JButton("查找");
find.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
finduser();
}
});
Container con = this.getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
con.add(nameLb);
con.add(nameTxt);
con.add(find);
}
private void finduser() {
findname = nameTxt.getText();
dispose();
}
public String getNameCondition() {
return findname;
}
public static void main(String[] args) {
new FindView(new JFrame()).setVisible(true);
}
}
<file_sep>package com.user.view;
import com.user.model.BalanceOperation;
import com.user.service.BeanService;
import com.user.service.appservice.service.UserExpService;
import com.user.service.dbservice.domain.User;
import com.user.service.dbservice.domain.UserExp;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;
public class RecordView extends JDialog {
private JLabel name;
private JLabel status;
private User user;
public RecordView(JFrame p, User user) {
super(p, true);
this.user = user;
init();
setSize(800, 500);
setTitle("消费记录);");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(true);
setLocationRelativeTo(getParent());
}
private void init() {
name = new JLabel();
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
name.setText("姓名:" + user.getUserName() + " , 查询时间: " + sf.format(new Date()));
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(name, BorderLayout.NORTH);
status = new JLabel();
this.getContentPane().add(status, BorderLayout.SOUTH);
createTable();
}
private void createTable() {
// final
final String[] names = {
"操作日期",
"操作类型",
"金额",
"操作后余额"
};
DefaultTableModel dataModel = new DefaultTableModel(names, 0);
// Create the table
JTable tableView = new JTable(dataModel) {
public boolean isCellEditable(int row, int col) {
return false;
}
};
//
tableView.getTableHeader().setReorderingAllowed(false);
tableView.setRowHeight(25);
tableView.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane jScrollPane = new JScrollPane(tableView);
this.getContentPane().add(jScrollPane, BorderLayout.CENTER);
UserExpService userExpService = BeanService.getService(UserExpService.class);
List<UserExp> userExps = userExpService.queryByUserID(user.getUserID());
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Vector dataVector = dataModel.getDataVector();
for (UserExp userExp : userExps) {
Vector v = new Vector();
v.add(sf.format(userExp.getExpDate()));
int op = userExp.getOperation();
if (BalanceOperation.ADD == op) {
v.add("充值");
} else {
v.add("消费");
}
v.add(userExp.getExpValue());
v.add(userExp.getCurrentBalance());
dataVector.add(v);
}
status.setText("总数:" + dataVector.size());
dataModel.fireTableDataChanged();
}
}
<file_sep>package com.user.service.appservice.service;
import com.user.service.dbservice.domain.User;
import com.user.service.dbservice.service.DefaultPLUserService;
import com.user.service.dbservice.service.PLUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("userservice")
public class DefaultUserService implements UserService {
@Autowired
private PLUserService plUserService;
/**
* 查询所有的用户信息
*
* @return
*/
@Override
public List<User> queryAll() {
return plUserService.queryAll();
}
/**
* 通过用户名模糊查找用户
*
* @param condition
* @return
*/
@Override
public List<User> queryByName(String condition) {
return plUserService.queryByName(condition);
}
/**
* 查询用户信息
* 查询用户信息
*
* @param userid 用户id
* @return
*/
@Override
public User queryUserByID(String userid) {
return plUserService.queryUserByID(userid);
}
/**
* 总的用户数
*
* @return
*/
@Override
public int countUsers() {
return plUserService.countUsers();
}
/**
* 创建用户
*
* @param user 用户信息
* @return
*/
@Override
public int createUser(User user) {
return plUserService.createUser(user);
}
/**
* 删除用户
*
* @param usid 用户ID
* @return
*/
@Override
public int deleteUser(String usid) {
return plUserService.deleteUser(usid);
}
/**
* 更新余额
*
* @param userid 用户ID
* @param newBalance 最新余额
* @return
*/
@Override
public int updateBalance(String userid, double newBalance) {
return plUserService.updateBalance(userid, newBalance);
}
public void setPlUserService(DefaultPLUserService plUserService) {
this.plUserService = plUserService;
}
}
<file_sep>package com.user.service.dbservice.service;
import com.user.service.dbservice.domain.UserExp;
import java.util.List;
/**
* 消费记录服务
*/
public interface PLUserExpService {
/**
* 新增一条记录
*
* @param exp 记录
* @return
*/
int create(UserExp exp);
/**
* 批量创建
*
* @param exps
* @return
*/
// int create(Collection<UserExp> exps);
/**
* 查询用户对应的所有记录
*
* @param userid
* @return
*/
List<UserExp> queryByUserID(String userid);
/**
* 查询一条记录数据
* @param expid
* @return
*/
// UserExp queryByExpID(String expid);
/**
* @param user
* @return
*/
// default List<UserExp> queryByUser(User user) {
// if (Objects.isNull(user)) {
// return new ArrayList<>(0);
// }
// return queryByUserID(user.getUserID());
// }
/**
* 查询库中所有的记录
*
* @return
*/
List<UserExp> queryAll();
/**
* 删除一条记录
*
* @param expID
* @return
*/
int delete(String expID);
// default int delete(UserExp userExp) {
// if (Objects.isNull(userExp)) {
// return 0;
// }
//
// return delete(userExp.getExpID());
// }
/**
* 删除用户的消费记录
*
* @param userID
* @return
*/
// int deleteByUserID(String userID);
// default int deleteByUser(User user) {
// if (Objects.isNull(user)) {
// return 0;
// }
// return deleteByUserID(user.getUserID());
// }
}
<file_sep>package com.user.service.dbservice.domain;
public class UserCondition {
private String namecondition;
public UserCondition() {
}
public String getNamecondition() {
return namecondition;
}
public void setNamecondition(String namecondition) {
this.namecondition = namecondition;
}
}
<file_sep>定义 <cache:annotation-driven/>,cache-manager= 指明使用的cachemgr,默认:cacheManager
在spring定义CacheManager实例bean。
spring自动识别使用了Cachable等标注的方法。
通过动态AOP进行缓存处理。
spring cache定义了一种缓存的抽象,可以由其他组件实现cache、cachemgr的具体实现
例如:EHCache、JCache等
org.springframework.cache.Cache
org.springframework.cache.CacheManager
#### @Cacheable
#### @CachePut
#### @CacheEvict
##@@@@SEE
https://www.cnblogs.com/yudar/p/4809345.html
https://www.cnblogs.com/fashflying/p/6908028.html
<file_sep>package com.user.service;
import org.junit.Test;
public class BeanServiceTest {
@Test
public void getService() {
// BeanService.getService(UserService.class)
}
}<file_sep>package com.user.service.dbservice.service;
import com.user.service.dbservice.domain.User;
import java.util.List;
/**
* 提供用户操作的服务接口
*/
public interface PLUserService {
/**
* 查询所有的用户信息
*
* @return
*/
List<User> queryAll();
/**
* 通过用户名模糊查找用户
*
* @param condition
* @return
*/
List<User> queryByName(String condition);
/**
* 查询用户信息
* 查询用户信息
*
* @param userid 用户id
* @return
*/
User queryUserByID(String userid);
/**
* 总的用户数
*
* @return
*/
int countUsers();
/**
* 创建用户
*
* @param user 用户信息
* @return
*/
int createUser(User user);
/**
* 删除用户
*
* @param usid 用户ID
* @return
*/
int deleteUser(String usid);
/**
* 更新余额
*
* @param userid 用户ID
* @param newBalance 最新余额
* @return
*/
int updateBalance(String userid, double newBalance);
/**
* 更新用户备注
*
* @param user 用户信息
* @return
*/
// int updateComment(User user);
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.user</groupId>
<artifactId>userroot</artifactId>
<packaging>pom</packaging>
<version>1.0</version>
<url>https://mgmdd.github.io/comuser/</url>
<modules>
<module>distribution</module>
<module>common</module>
<module>serverparent</module>
<module>logservice</module>
<module>appparent</module>
<module>view</module>
<module>practice</module>
</modules>
<name>user.root</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--编译的源代码级别、目标代码级别-->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>4.3.20.RELEASE</spring.version>
</properties>
<inceptionYear>2018</inceptionYear>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>mgmdd</id>
<name>MagicG</name>
<email><EMAIL></email>
<roles>
<role>Owner</role>
<role>Founder</role>
<role>Committer</role>
</roles>
</developer>
<developer>
<id>pangdachong</id>
<name>MagicG2</name>
<email><EMAIL></email>
<roles>
<role>Committer</role>
</roles>
</developer>
</developers>
<issueManagement>
<system>GitHub Issue Management</system>
<url>https://github.com/mgmdd/comuser/issues</url>
</issueManagement>
<!--统一管理项目的版本号,确保应用的各个项目的依赖和版本一致-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.8.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.user</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.user</groupId>
<artifactId>logservice</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.user</groupId>
<artifactId>appservice</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.user</groupId>
<artifactId>dbservice</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.user</groupId>
<artifactId>distribution</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.user</groupId>
<artifactId>appmodel</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.user</groupId>
<artifactId>view</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--<dependency>-->
<!--<groupId>org.apache.logging.log4j</groupId>-->
<!--<artifactId>log4j-api</artifactId>-->
<!--<version>2.11.1</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.apache.logging.log4j</groupId>-->
<!--<artifactId>log4j-core</artifactId>-->
<!--<version>2.11.1</version>-->
<!--</dependency>-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.apache.logging.log4j</groupId>-->
<!--<artifactId>log4j-api</artifactId>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.apache.logging.log4j</groupId>-->
<!--<artifactId>log4j-core</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<!--<executions>-->
<!--<execution>-->
<!--<phase>-->
<!--package-->
<!--</phase>-->
<!--<goals>-->
<!--<goal>-->
<!--jar-no-fork-->
<!--</goal>-->
<!--</goals>-->
<!--</execution>-->
<!--</executions>-->
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<filesets>
<fileset>
<directory>${project.basedir}</directory>
<includes>
<include>
var/**
</include>
</includes>
</fileset>
</filesets>
</configuration>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<!--jar文件中不生成META-INF/maven目录及文件-->
<addMavenDescriptor>false</addMavenDescriptor>
<!--<manifest>-->
<!--<mainClass>com.user.view.MainFrame</mainClass>-->
<!--</manifest>-->
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>compile1.8</id>
<activation>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</profile>
</profiles>
</project>
<file_sep>#验证项目。
##1、2018-10-20 初始化,支持Sqlite、mybatis,单一工程
##2、2018-10-25 拆分为maven工程,解决编译问题
##3、2018-10-27 使用assembly plugin
##4、2018-10-28 引入Spring bean
##5、2018-11-3 SqlSessionFactory由Spring接管
##6、补充log能力,引入commons-logging,log4j
##7、TODO 引入Spring AOP
##8、TODO 引入commons包<file_sep>package com.user.service.dbservice.mapper;
import com.user.service.dbservice.domain.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 用户mapper
*/
public interface UserMapper {
/**
* 查询所有的用户信息
*
* @return
*/
List<User> queryAll();
/**
* 通过用户名模糊查找用户
*
* @param namecondtion
* @return
*/
List<User> queryByName(@Param("namecondition") String namecondtion);
/**
* 查询用户信息
*
* @param userid 用户id
* @return
*/
User queryByID(@Param("userid") String userid);
/**
* 创建用户
*
* @param user 用户信息
* @return
*/
int createUser(User user);
/**
* 删除用户
*
* @param usid 用户ID
* @return
*/
int deleteUser(@Param("userid") String usid);
/**
* 更新余额
*
* @param userid 用户ID
* @param newbalance 更新后的余额
* @return
*/
int updateBalance(@Param("userid") String userid, @Param("newbalance") double newbalance);
/**
* 更新用户备注
*
* @param user 用户信息
* @return
*/
// int updateComment(User user);
/**
* 计算行数
*
* @return 行数
*/
int count();
}
|
469abd95b0e846d5b9e9e507bfa56b5747927b0e
|
[
"Markdown",
"Java",
"Maven POM",
"INI"
] | 25
|
Java
|
mgmdd/comuser
|
9a301db7f4beac3cb4cdbb4d0c9d676319317271
|
595226c37f3b0d13fe3177bdedef62dadb1a93b9
|
refs/heads/master
|
<file_sep>package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.daoImpl.CategoryDaoImpl;
import com.daoImpl.UserDaoImpl;
import com.model.Category;
import com.model.User;
@Controller
public class indexController
{
@RequestMapping("/")
public String index()
{
return "index";
}
@RequestMapping("/DAPhome")
public String indexDAP()
{
return "DAPhome";
}
@RequestMapping("/js")
public String js()
{
return "jumpstart";
}
/*@RequestMapping("/")
public String indexhome()
{
return "index";
}
*/
@RequestMapping("/index")
public String indexPage()
{
return "index";
}
@RequestMapping(value="/register", method=RequestMethod.GET)
public ModelAndView goToRegister()
{
ModelAndView mv = new ModelAndView();
mv.addObject("user", new User());
mv.setViewName("register");
return mv;
}
@Autowired
UserDaoImpl userDaoImpl;
@RequestMapping(value="/saveregister", method=RequestMethod.POST)
public ModelAndView saveUser(@ModelAttribute("user")User user, BindingResult res)
{
ModelAndView mv = new ModelAndView();
user.setRole("ROLE_USER");
userDaoImpl.insertUser(user);
mv.setViewName("index");
return mv;
}
@RequestMapping("/admin/adding")
public String addPage()
{
return "admin";
}
@Autowired
CategoryDaoImpl categoryDaoImpl;
@RequestMapping(value="/admin/saveCat", method=RequestMethod.POST)
public ModelAndView saveCat(@RequestParam("cid")int cid, @RequestParam("cname")String cname)
{
ModelAndView mv = new ModelAndView();
Category c = new Category();
c.setCid(cid);
c.setCname(cname);
categoryDaoImpl.insertCategory(c);
mv.setViewName("redirect:/admin/adding");
return mv;
}
}
<file_sep>package com.dao;
import java.util.List;
import com.model.Category;
import com.model.Supplier;
public interface SupplierDao
{
public void insertSupplier(Supplier supplier);
public List<Supplier> retreive();
public Supplier findById(int sid);
public void deleteSupplier(int sid);
}
|
69a5f117d9c4974f58e0008ef97ef60441f6db49
|
[
"Java"
] | 2
|
Java
|
SUSHIL2905/MyOnlineShoppinNew
|
a25d9cca8c9eed041a361a62154097ccca81bf2f
|
3cc9cbee6168f3de8395454f8a579c8eed8c716c
|
refs/heads/main
|
<repo_name>DimpalAgrawal/caucus<file_sep>/INSTALLATION.MD
# Steps for setting up the project locally
1. Clone the caucus Repository
```sh
git clone https://github.com/Rishabh-malhotraa/caucus.git
```
2. Create a new file .env and copy contents of `.env.example` file to the `.env` file
```sh
touch .env
```
3. Clone the caucus-server from github
```sh
git clone https://github.com/Rishabh-malhotraa/caucus-server.git
```
4. Create the .env file as mentioned in the [readme file](https://github.com/Rishabh-malhotraa/caucus-server#prerequisites)
If you want the oauth to work locally you need to get your own client key and client secret from the oauth provider(check the readme file), you can also skip this step if you dont want to enable oauth and just login to room using login as guest feature
5. Start the react front end by moving opening bash in the client folder and running the following commmand
``` sh
npm run start
```
**Run the CRDT SERVER**
_inside the caucus repository run the following bash command_
``` sh
npx y-websocket-server
```
6. Start the nodejs backend using by running the following code in the server folder6
``` sh
npm run dev
```
7. I recommend opening a workspace on your favorite editor with the server and client folder openend.
If you have any difficulty in setting up the project locally let me know by opening an [issue](https://github.com/Rishabh-malhotraa/caucus/issues) on github, or contacting me on discord.
<file_sep>/src/setupProxy.ts
import { createProxyMiddleware } from "http-proxy-middleware";
function Proxy(app: any) {
app.use(
"/",
createProxyMiddleware({
target: process.env.REACT_APP_SERVER_URL,
changeOrigin: true,
})
);
}
export default Proxy;
<file_sep>/src/component/Editor/CodeMirrorImports.ts
// Lamguage Highlight
import "codemirror/mode/clike/clike";
import "codemirror/mode/python/python";
import "codemirror/mode/javascript/javascript";
import "codemirror/mode/go/go";
import "codemirror/mode/rust/rust";
import "codemirror/mode/ruby/ruby";
import "codemirror/mode/php/php";
import "codemirror/mode/haskell/haskell";
// Addons
import "codemirror/addon/edit/closebrackets";
import "codemirror/addon/edit/closetag";
import "codemirror/addon/hint/show-hint";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/addon/hint/javascript-hint";
import "codemirror/addon/hint/anyword-hint";
import "codemirror/addon/fold/foldcode";
import "codemirror/addon/fold/foldgutter";
import "codemirror/addon/fold/brace-fold";
import "codemirror/addon/fold/comment-fold";
import "codemirror/addon/fold/foldgutter.css";
// Keybinds
import "codemirror/keymap/sublime";
import "codemirror/keymap/vim";
import "codemirror/keymap/emacs";
// Themes
import "codemirror/lib/codemirror.css";
import "codemirror/theme/3024-night.css";
import "codemirror/theme/dracula.css";
import "codemirror/theme/monokai.css";
import "codemirror/theme/material-palenight.css";
import "codemirror/theme/material-darker.css";
import "codemirror/theme/neat.css";
import "codemirror/theme/eclipse.css";
<file_sep>/src/component/TextChat/ChatMessage-styles.ts
import { Theme } from "@material-ui/core/styles";
const styles = ({ palette, spacing }: Theme) => {
const radius = spacing(2.5);
const size = spacing(4);
const rightBgColor = palette.primary.main;
// if you want the same as facebook messenger, use this color '#09f'
return {
avatar: {
width: size,
height: size,
},
leftRow: {
textAlign: "left",
},
rightRow: {
textAlign: "right",
},
msg: {
padding: spacing(1, 2),
borderRadius: 4,
marginBottom: 4,
display: "inline-block",
wordBreak: "break-word",
fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',
fontSize: "14px",
},
left: {
borderTopRightRadius: radius,
borderBottomRightRadius: radius,
backgroundColor: "dimgrey",
},
right: {
borderTopLeftRadius: radius,
borderBottomLeftRadius: radius,
backgroundColor: rightBgColor,
color: palette.common.white,
},
leftFirst: {
borderTopLeftRadius: radius,
},
leftLast: {
borderBottomLeftRadius: radius,
},
rightFirst: {
borderTopRightRadius: radius,
},
rightLast: {
borderBottomRightRadius: radius,
},
};
};
export default styles;
<file_sep>/src/config.keys.ts
export const SERVER_URL = process.env.REACT_APP_SERVER_URL || "http://localhost:5000";
export const CLIENT_URL = process.env.REACT_APP_CLIENT_URL || "http://localhost:3000";
export const CDRT_SERVER = process.env.REACT_APP_CRDT_SERVER || "ws://localhost:1234";
export const PUBLIC_ROOM = ["public-room1", "public-room2", "public-room3", "public-room4", "public-room5"];
export const IS_DISABLED = process.env.REACT_APP_NETLIFY == "false" ? false : true;
<file_sep>/src/types.d.ts
import React from "react";
export interface UserInfoType {
isLoggedIn: boolean;
name?: string;
image_link?: string;
cookies?: string;
}
export interface OAUTH_TABLE {
id: number;
user_id: string;
name: string;
image_link: string;
create_time: string;
oauth_provider: string;
access_token: string;
refresh_token?: string;
}
export interface OauthResponse {
isLoggedIn: boolean;
message: string;
user?: OAUTH_TABLE;
cookies?: string;
}
export interface GuestNameContextTypes {
guestName: string;
guestLoginClick: boolean;
handleGuestNameChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
isGuestNameClick: (
e: React.MouseEvent<HTMLButtonElement, MouseEvent> | React.KeyboardEvent<HTMLInputElement>
) => void;
}
export interface SettingsContextType {
language: string;
fontSize: number;
theme: string;
keybinds: string;
handleLanguageChange: (value: string, id: string, broadcast: boolean) => void;
handleThemeChange: (value: string) => void;
handleKeybindsChange: (value: string) => void;
handleFontSizeChange: (value: number) => void;
}
export interface CodeExecutionInfoType {
value: number;
loading: boolean;
inputText: string;
outputData: {
output: string;
memory: number;
cpuTime: number;
};
setValue: (value: number) => void;
setLoading: (isLoading: boolean) => void;
setInputText: (text: string) => void;
setOutputData: (record: Record<string | any>) => void;
}
export interface RoomIDContextTypes {
roomID: string;
setRoomID: (id: string) => void;
}
export interface UserContextTypes {
user: UserInfoType | undefined;
saveUserInfo: (data: OauthResponse, isLoggedIn: boolean) => void;
logoutUserInfo: () => void;
}
export interface StateInterface {
appData: {
guestName: string;
AdminUser: UserInfoType;
UserList: UserInfoType[];
isLoggedIn: boolean;
};
}
// SS -> short 😜
export interface UserInfoSS {
name: string;
image_link: string;
roomID: string;
}
export interface LabelType {
name: string;
color: string;
description?: string;
}
export interface QuestionListResponse {
question_id: number;
question_title: string;
difficulty: string;
}
export interface QuestionDataSS {
question_data: any;
companies: string[];
tags: string[];
}
export interface ScrappedDataType {
htmlString: string;
hostname: "codeforces.com" | "atcoder.jp";
}
export interface TabsContextTypes {
tabIndex: number;
showScrapped: boolean;
questionData: QuestionDataSS;
scrappedData: ScrappedDataType;
filterResponseData: (data: Record<string, any>, id: string) => void;
onTabsChange: (value: number) => void;
handleScrappedData: (value: ScrappedDataType, id: string, broadcast: boolean) => void;
onQuestionDataChange: (value: QuestionDataSS) => void;
}
<file_sep>/devlog.md
# Devlogs
## 7th October (Patch 2.0.2)
- Caucus is taking part in the hacktoberfest 21, and I am grateful for all the contributions made by the community so far.
## 18th June (Patch 2.0.1)
- Fixed the `ws` URL for the signaling server.
- Disabled Twitter Login because Twitter Oauth is not working for some reason 😑
## 17th June (Patch 2.0)
- Removed bulky Monaco editor and convergence with code-mirror and YJS
- Using WEBRTC Protocol (which does not scale well compared to a central server but maintaining a server on Heroku is a pain in the neck)
- Added Vim and Emacs Keybinds
- Fixed the Bug where the language change did not sync issue [#26](https://github.com/Rishabh-malhotraa/caucus/issues/26)
- Fixed the code duplication issue 🥳🎉
- Fixed the cursor jump issue on deletion
- CLoses [#17](https://github.com/Rishabh-malhotraa/caucus/issues/17) [#13](https://github.com/Rishabh-malhotraa/caucus/issues/13) [#10](https://github.com/Rishabh-malhotraa/caucus/issues/10) (autocomplete only for javascript) [#7](https://github.com/Rishabh-malhotraa/caucus/issues/7) [#6](https://github.com/Rishabh-malhotraa/caucus/issues/6)
## 16th June (Major Changes Coming)
- I have decided to move from convergence to yjs, which is better maintained
- Changing editor from Monaco to code-mirror
- Vim support
- Better Supported by YJS (better adapter with better awareness)
- Autocompletion support with LSP
- More themes
## 12th JUNE (Roadmap)
- We hit 150 ⭐ 🥳🥳🎉.
- Convergence is causing me a lot of issues, especially when you delete something in Monaco; your cursor changes line, which is really really annoying, and I am thinking of switching to yjs with a bit better cursor management support like convergence and moving from POSTGRESQL to SQLite.
- Maybe I'll do these changes tomorrow, maybe I'll do these changes in a few days, 🤞
## 14th April (UPDATES)
- Added stargazers chart in the readme. The GSOC application period is over, so now I look forward to improving Caucus a bit, but then I feel most of my time would be dedicated to practicing LeetCode Questions, plus I have some tests coming up this week.
## 7th April (UPDATES)
- We have reached 125 stars on Github YAY 🎉️🎉️🎉️
## 26th March 2021 (SSL Certificate Updates)
- Thanks to Harrison, I was able to deploy the convergence-deployment file, which had the Nginx configuration and SSL certificate to Digital Ocean, but I still feel there are some wholes in the deployment, as I wasn't able to login to the console of convergence; nonetheless, I have an HTTPS convergence-omnibus hosted on digital ocean.
## 24th March 2021 (UPDATES)
- Caucus reached 100+ stars on Github YAY! It also has 500+ registered users, 3500 visits on GitHub repo & view, and 12000+ website visits.
- The main priority for me is to get the SSL certificate for the docker container, which is soo annoying man I cannot tell you, DevOps is a different beast in itself D:
- I am stopping development on Caucus for the time being and focusing on GSOC, most likely Navidrome else Accord or maybe Zulip.
## 22nd March 2021 (PATCH 1.02.01)
- I have had such a bad experience hosting my app on Heroku, I'm either moving to GCP or digital ocean because I cannot take this trash anymore, plus for that, I need to change the database server from PostgreSQL to MongoDB because I get like 512 MB on MongoDB cloud, now I understand why architecture design and planning for the project is so important, I hate rewriting code D:
## 18th March 2021 (PATCH 1.02)
- Added Support for natively displaying atcoder or codeforces questions (using Axios and cheerio for scraping since they don't have a public API that sends the data). Also incorporated sockets, so all the users in the rooms have same problem opened.
## 17th March 2021 (PATCH 1.01)
- fixed the sync issue; previously, if another person entered a room in which another person was already typing, the new user did not get all the text which the user once typed. Now the texts get synced when the user enters the room HURRAY 🎉🥳
<file_sep>/src/service/socket.ts
import io from "socket.io-client";
import { SERVER_URL } from "config.keys";
export const socket = io(SERVER_URL);
<file_sep>/README.md
<!-- PROJECT SHIELDS -->
[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![MIT License][license-shield]][license-url]
[![LinkedIn][linkedin-shield]][linkedin-url]
[![All Contributors][all-contributors-shield]](#contributors-)
<!-- PROJECT LOGO -->
<br />
<p align="center">
<a href="https://caucus-app.herokuapp.com/">
<img src="images/logo.png" alt="Logo" width="256" height="256">
</a>
<strong>
<h3 align="center" >caucus</h3>
</strong>
<p align="center">
A Real Time Collaborative Editor with an embedded compiler
<br />
<a href="https://github.com/Rishabh-malhotraa/caucus/tree/main/src"><strong>Explore the project »</strong></a>
<br />
<br />
<a href="https://caucus-app.herokuapp.com/">View Demo</a>
·
<a href="https://github.com/Rishabh-malhotraa/caucus/issues">Report Bug</a>
·
<a href="https://github.com/Rishabh-malhotraa/caucus/issues">Request Feature</a>
</p>
</p>
<!-- TABLE OF CONTENTS -->
<details open="open">
<summary>Table of Contents</summary>
<ol>
<li>
<a href="#about-the-project">About The Project</a>
<ul>
<li><a href="#built-with">Built With</a></li>
</ul>
</li>
<li>
<a href="#getting-started">Getting Started</a>
<ul>
<li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#installation">Installation</a></li>
</ul>
</li>
<li><a href="#roadmap">Roadmap</a></li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#license">License</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#acknowledgements">Acknowledgements</a></li>
</ol>
</details>
## 📣 Latest Announcements
🆕 5-10-2021: We now have a discussions form, if you want any new feature to be implemented you can [discuss here](https://github.com/Rishabh-malhotraa/caucus/discussions/50)
🆕 28-09-2021: Caucus is participating in Hacktoberfest 2021 🥳
## About The Project
### Demonstration
[![Product Demonstation][product-demo]](https://caucus-app.herokuapp.com/)
<br/>
### Collaborative Code Editor
[![Product Name Screen Shot][product-screenshoti]](https://caucus-app.herokuapp.com/)
| Login Page | Navigate Rooms Page |
| :------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------: |
| [![Product Name Screen Shot][product-screenshotii]](https://caucus-app.herokuapp.com/) | [![Product Name Screen Shot][product-screenshotiii]](https://caucus-app.herokuapp.com/) |
<br />
### Built With
- [React](https://reactjs.org/docs/getting-started.html)
- [Material UI](https://material-ui.com/getting-started/installation/)
- [yjs](https://yjs.dev/)
Written in TypeScript ♥
## Getting Started
Follow the instructions to set up the project on your local machine.
### Prerequisites
This is an example of how to list things you need to use the software and how to install them.
- npm
```sh
npm install npm@latest -g
```
### Installation
1. Clone the repo
```sh
git clone https://github.com/Rishabh-malhotraa/caucus.git
```
2. Install NPM packages
```sh
npm install
```
3. Start the react server
```sh
npm run start
```
## Roadmap
See the [open issues](https://github.com/Rishabh-malhotraa/caucus/issues) for a list of proposed features (and known issues).
### Things To do
- [x] Initial Login Page
- [x] Database hookup with login from oAuth
- [x] Chat Application
- [x] Video Chat Application (the main chunk of work)
- [x] Collaborative Editing (the main chunk of work)
- [x] Resizable Panes
- [x] Code Running (Easy need to just hookup with an api)
- [x] Database with all the leetcode question and sorted based on tags.
- [x] IMP: Sync code using localstorage or sockets when a new person joins in the room, with defaultvalue prop on the monaco editor instance.
- [x] Add SSL certificate to the docker container, andd get rid of the current bootleg shenanigans D: (LetsEncrypt or Cloudflare)
- [x] Add codeforce problem using webscraping thingy
- [x] Add Vim Keybinds
- [x] Add intellisense using Language Server Protocol for atleast C++ and JAVA
- [x] Make a public api to fetch questions, based on scrapped data
- [ ] Add a full-screen Zen Mode
- [ ] Change Hosting from Heroku to GCP or Digital Ocean
- [ ] Change Heroku PSQL DB to either ~~MongoDB or Firebase~~ SQLITE.
- [ ] Add Autoformatting keybind.
- [ ] ~~Fix the number of users in the room.~~
- [ ] ~~REACH: Add video call functionality (using WEBRTC or something propieteary like Twilo proprietary)~~
- [ ] ~~Add ability to add different tabs on the editor instance just like that on VSCODE~~
- [ ] ~~Integrate the random quote thingy on loading screen from forticodes API~~
- [ ] ~~Fix why the loader gets frozen on intial render -\_-~~
## Contributing
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
Refer to this [article](https://medium.com/swlh/guide-to-git-a-practical-approach-27926a1ff564?sk=b54ca413a142c275f5d2901d0384a0db) if you have any difficulty in making a pull request
## License
Distributed under the MIT License. See [`LICENSE`][license-url] for more information.
---
## Contact
<NAME> - [@rish_bishhh](https://twitter.com/rish_bishhh) - <EMAIL>
Discord : rishabh.malhotra#4193
Project Link: [https://caucus-app.herokuapp.com/](https://caucus-app.herokuapp.com/)
---
## Stargazers over time
[](https://starchart.cc/rishabh-malhotraa/caucus)
---
## Acknowledgements
- [Heroku](https://www.heroku.com/)
- [Azure](https://azure.microsoft.com/en-us/)
- [notistack](https://www.npmjs.com/package/notistack/)
- [axios](https://www.npmjs.com/package/axios)
- [dog-names](https://www.npmjs.com/package/dog-names)
- [Best-README-Template](https://github.com/othneildrew/Best-README-Template)
- [MIT License](https://opensource.org/licenses/MIT)
- [SVG Backgrounds](https://www.svgbackgrounds.com/)
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[all-contributors-shield]: https://img.shields.io/badge/all_contributors-8-orange.svg?style=for-the-badge
[contributors-shield]: https://img.shields.io/github/contributors/Rishabh-malhotraa/caucus.svg?style=for-the-badge
[contributors-url]: https://github.com/Rishabh-malhotraa/caucus/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/Rishabh-malhotraa/caucus.svg?style=for-the-badge
[forks-url]: https://github.com/Rishabh-malhotraa/caucus/network/members
[stars-shield]: https://img.shields.io/github/stars/Rishabh-malhotraa/caucus.svg?style=for-the-badge
[stars-url]: https://github.com/Rishabh-malhotraa/caucus/stargazers
[issues-shield]: https://img.shields.io/github/issues/Rishabh-malhotraa/caucus.svg?style=for-the-badge
[issues-url]: https://github.com/Rishabh-malhotraa/caucus/issues
[license-shield]: https://img.shields.io/github/license/Rishabh-malhotraa/caucus.svg?style=for-the-badge
[license-url]: https://github.com/Rishabh-malhotraa/caucus/blob/main/LICENSE.txt
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555
[linkedin-url]: https://www.linkedin.com/in/rishabh-malhotra-4536a418b
[product-demo]: images/caucus-demonstation.gif
[product-screenshoti]: images/code-editor.png
[product-screenshotii]: images/login-page.png
[product-screenshotiii]: images/navigation-page.png
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://rishabh-malhotraa.github.io/Rishabh-Portfolio-main/"><img src="https://avatars.githubusercontent.com/u/54576074?v=4?s=140" width="140px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="#infra-Rishabh-malhotraa" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/Rishabh-malhotraa/caucus/commits?author=Rishabh-malhotraa" title="Code">💻</a> <a href="#design-Rishabh-malhotraa" title="Design">🎨</a></td>
<td align="center"><a href="https://github.com/MarufSharifi"><img src="https://avatars.githubusercontent.com/u/59383482?v=4?s=140" width="140px;" alt=""/><br /><sub><b>Maruf</b></sub></a><br /><a href="#infra-MarufSharifi" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/Rishabh-malhotraa/caucus/commits?author=MarufSharifi" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/swikars1"><img src="https://avatars.githubusercontent.com/u/20171676?v=4?s=140" width="140px;" alt=""/><br /><sub><b>Swikar Sharma</b></sub></a><br /><a href="https://github.com/Rishabh-malhotraa/caucus/commits?author=swikars1" title="Documentation">📖</a></td>
<td align="center"><a href="https://www.linkedin.com/in/iamdevvalecha/"><img src="https://avatars.githubusercontent.com/u/71969867?v=4?s=140" width="140px;" alt=""/><br /><sub><b>Dev Valecha</b></sub></a><br /><a href="#talk-iamdevvalecha" title="Talks">📢</a></td>
<td align="center"><a href="https://github.com/HarrisonMayotte"><img src="https://avatars.githubusercontent.com/u/48367813?v=4?s=140" width="140px;" alt=""/><br /><sub><b>Harrison Mayotte</b></sub></a><br /><a href="#infra-HarrisonMayotte" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/Rishabh-malhotraa/caucus/pulls?q=is%3Apr+reviewed-by%3AHarrisonMayotte" title="Reviewed Pull Requests">👀</a></td>
</tr>
<tr>
<td align="center"><a href="https://bit.ly/adityaarya1"><img src="https://avatars.githubusercontent.com/u/52771727?v=4?s=140" width="140px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="#design-Aditya9111" title="Design">🎨</a></td>
<td align="center"><a href="https://github.com/mthakur7"><img src="https://avatars.githubusercontent.com/u/89182004?v=4?s=140" width="140px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="#design-mthakur7" title="Design">🎨</a></td>
<td align="center"><a href="https://apexweb.me"><img src="https://avatars.githubusercontent.com/u/68195580?v=4?s=140" width="140px;" alt=""/><br /><sub><b>Apex Web</b></sub></a><br /><a href="#design-chirag3003" title="Design">🎨</a></td>
<td align="center"><a href="https://github.com/GaganpreetKaurKalsi"><img src="https://avatars.githubusercontent.com/u/54144759?v=4?s=140" width="140px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/Rishabh-malhotraa/caucus/commits?author=GaganpreetKaurKalsi" title="Code">💻</a> <a href="#design-GaganpreetKaurKalsi" title="Design">🎨</a></td>
<td align="center"><a href="https://pavankalyan-codes.github.io/"><img src="https://avatars.githubusercontent.com/u/35896290?v=4?s=140" width="140px;" alt=""/><br /><sub><b>Pavan kalyan C</b></sub></a><br /><a href="https://github.com/Rishabh-malhotraa/caucus/commits?author=pavankalyan-codes" title="Code">💻</a></td>
</tr>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
<file_sep>/.env.example
REACT_APP_CLIENT_URL = https://localhost:3000
REACT_APP_SERVER_URL = https://localhost:5000
REACT_APP_CDRT_SERVER1 = ws://localhost:1234
REACT_APP_NETLIFY = false
<file_sep>/src/service/getRandomAvatar.ts
const getRandomColor = () => {
const avatar = [
"https://i.pinimg.com/originals/57/47/06/57470642bba41d1b079cb9926117fe6e.jpg", // goku
"https://i.pinimg.com/236x/b6/d9/58/b6d9586cb24fdd802dd70d0c6b17f2b0.jpg", // jerry 1
"https://i.pinimg.com/236x/9d/aa/e2/9daae24f4ca34cfecb368d0590930934.jpg", // jerry2
"https://i1.sndcdn.com/avatars-000406450287-rukoyr-t500x500.jpg", // squirtle
"https://i.pinimg.com/originals/97/9e/a3/979ea3e13fe19f047f1918c640531edf.jpg", // pikachu
"https://i.pinimg.com/originals/6a/b8/ed/6ab8ed1a70bd7c744c7fda2fd0803b18.jpg", // winneh
"https://i.pinimg.com/originals/5a/6e/49/5a6e498e40b1dcd9e0fef062db163e93.jpg", // tigor
"https://i.pinimg.com/564x/1d/fc/27/1dfc278c0f56a18c98ada502916ee70b.jpg", // stich
"https://avatars.githubusercontent.com/u/47313528?v=4", // github avatar
"https://i1.sndcdn.com/avatars-000542389239-i206kr-t500x500.jpg", // doge
];
return avatar[Math.floor(Math.random() * avatar.length)];
};
export default getRandomColor;
|
97f5b3466bcbd0407d2d6bd7694d530d664f74cd
|
[
"Markdown",
"TypeScript",
"Shell"
] | 11
|
Markdown
|
DimpalAgrawal/caucus
|
cab28b73d78acb982ad4db0f91eb699ebd7a3853
|
262acdd694cc45496f2661f593aaf94829bbc9a6
|
refs/heads/master
|
<file_sep>cmake_minimum_required(VERSION 2.8.4)
project(ResultProcessor CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wpedantic -Wall -Wextra -Wconversion")
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Weverything -Wno-weak-vtables -Wno-missing-noreturn -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-shadow -Wno-old-style-cast -Wno-missing-prototypes -Wno-padded")
endif()
set(SOURCE_FILES
result-processor.cpp
)
add_executable(result-processor ${SOURCE_FILES})
<file_sep>#pragma once
#include <iostream>
#include "util/Arguments.h"
#include "model/RelationGenerator.h"
#include "util/Experiments.h"
inline Relation getRelation(Arguments& arguments, RelationGenerator::SeedType seed)
{
std::string type = arguments.getCurrentArgAndSkipIt("relation source type (--file, --uniform, --exp)");
Relation result;
if (arguments.isSwitchPresent("--reset-seed"))
seed = 23423;
if (type == "--file")
{
auto filename = arguments.getCurrentArgAndSkipIt("file name");
std::cout << "loading from file " << filename << std::flush;
result = RelationGenerator::loadFromClosedIntervalFile(filename);
}
else
if (type == "--basf")
{
auto filename = arguments.getCurrentArgAndSkipIt("file name");
std::cout << "loading from BASF file " << filename << std::flush;
result = RelationGenerator::loadFromBASFFile(filename);
}
else
if (type == "--dasa")
{
auto filename = arguments.getCurrentArgAndSkipIt("file name");
std::cout << "loading from DASA file " << filename << std::flush;
result = RelationGenerator::loadFromDASATemperatureFile(filename);
}
else
if (type == "--uni")
{
auto count = arguments.getCurrentArgAsDoubleAndSkipIt("tuple count");
auto max = arguments.getCurrentArgAsDoubleAndSkipIt("max tuple length");
std::cout << "generating " << count << " uniform tuples with max length " << max << std::flush;
result = RelationGenerator::generateUniform(size_t(count), 1, Timestamp(max), 1, Timestamp(1e6), seed);
}
else
if (type == "--exp")
{
auto count = arguments.getCurrentArgAsDoubleAndSkipIt("tuple count");
auto max = arguments.getCurrentArgAsDoubleAndSkipIt("--uni max tuple length analog");
auto avg = max / 2;
std::cout << "generating " << count << " exp tuples with avg length " << avg << std::flush;
result = RelationGenerator::generateExponential(size_t(count), 1/avg, 1, Timestamp(1e6), seed);
}
else
arguments.error("Unknown relation source ", type);
std::cout << ", n = " << result.size() << std::flush;
std::cout << std::endl;
return result;
}
inline Experiments getExperimentsAndPopulateRelations(Arguments& arguments, Relation& R, Relation& S)
{
if (!arguments.empty())
{
Timer timer;
std::cout << "Relation R: ";
R = getRelation(arguments, 564564);
std::cout << "Relation G: ";
S = getRelation(arguments, 345);
std::cout << "Loading done in ";
timer.stopAndPrint();
std::cout << " s" << std::endl;
}
else
{
// R = RelationGenerator::generateUniform((unsigned) 1e5, 1, (unsigned) 6e2, 1, (unsigned) 1e9, 1232398);
// S = RelationGenerator::generateUniform((unsigned) 1e4, 1, (unsigned) 1e2, 1, (unsigned) 1e9, 345);
// R = RelationGenerator::generateExponential(100'000, 1e-4, 1, 1'000'000, 1232398);
// S = RelationGenerator::generateExponential(100'000, 1e-4, 1, 1'000'000, 345);
R = RelationGenerator::generateUniform(1200000, 1, 3, 10, 3000, 5904595);
S = RelationGenerator::generateUniform( 30000, 1, 3, 10, 3000, 58534);
// R = RelationGenerator::generateUniform(12, 1, 3, 10, 30, 5904595);
// S = RelationGenerator::generateUniform( 3, 1, 3, 10, 30, 58534);
}
// std::unordered_set<Timestamp> ts;
// for (const auto& r : R)
// {
// ts.insert(r.start);
// ts.insert(r.end);
// }
// std::cout << "Distinct: " << ts.size() << std::endl;
auto disabledExperiments = arguments.getCurrentArgAndSkipIt("comma-separated list of disabled tests");
return Experiments(disabledExperiments);
}
struct Workload
{
Timestamp& accum;
#ifdef COUNTERS
mutable unsigned long long count = 0;
#endif
void operator()(const Tuple& r, const Tuple& s) const noexcept
{
#ifdef COUNTERS
count++;
#endif
accum += r.start + s.end;
}
};
<file_sep>#include <gtest/gtest.h>
#include <model/RelationGenerator.h>
#include "algorithms/Joins.h"
#include "algorithms/JoinsInlined.h"
using testing::Test;
static Relation R;
static Relation S;
static Index indexR;
static Index indexS;
static Timestamp result;
static auto consumer = [] (const Tuple& r, const Tuple& s)
{
result += r.start + s.end;
};
class JoinsInlined : public Test
{
protected:
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
static void SetUpTestCase()
#pragma clang diagnostic pop
{
R = RelationGenerator::generateUniform(1000, 1, 100, 1, 10000, 453565455);
S = RelationGenerator::generateUniform(1000, 1, 100, 1, 10000, 585);
indexR.buildFor(R);
indexS.buildFor(S);
R.setIndex(indexR);
S.setIndex(indexS);
}
// virtual void TearDown()
// {
// result = 0;
// }
};
TEST_F(JoinsInlined, before)
{
for (Timestamp delta = 0; delta < 10; delta++)
{
result = 0;
beforeJoin(R, S, delta, consumer);
auto inlinedResult = beforeJoinInlined(R, S, delta);
EXPECT_EQ(result, inlinedResult);
}
}
<file_sep>#include <gtest/gtest.h>
#include "model/Interval.h"
TEST(Interval, Basic)
{
EXPECT_TRUE ( Interval(3, 8).overlaps(Interval(3, 8)) );
EXPECT_TRUE ( Interval(1, 4).overlaps(Interval(3, 8)) );
EXPECT_FALSE( Interval(1, 3).overlaps(Interval(3, 8)) );
EXPECT_TRUE ( Interval(7, 10).overlaps(Interval(3, 8)) );
EXPECT_FALSE( Interval(8, 10).overlaps(Interval(3, 8)) );
EXPECT_TRUE ( Interval(3, 8).overlaps(Interval(3, 8)) );
EXPECT_TRUE ( Interval(3, 8).overlaps(Interval(1, 4)) );
EXPECT_FALSE( Interval(3, 8).overlaps(Interval(1, 3)) );
EXPECT_TRUE ( Interval(3, 8).overlaps(Interval(7, 10)) );
EXPECT_FALSE( Interval(3, 8).overlaps(Interval(8, 10)) );
EXPECT_TRUE ( Interval(3, 10) < Interval(4, 6) );
EXPECT_FALSE( Interval(4, 10) < Interval(4, 6) );
EXPECT_FALSE( Interval(5, 10) < Interval(4, 6) );
EXPECT_TRUE ( Interval(1, 4).covers(Interval(1, 4)) );
EXPECT_TRUE ( Interval(1, 4).covers(Interval(2, 4)) );
EXPECT_TRUE ( Interval(1, 4).covers(Interval(1, 3)) );
EXPECT_FALSE( Interval(1, 4).covers(Interval(0, 4)) );
EXPECT_FALSE( Interval(1, 4).covers(Interval(1, 5)) );
EXPECT_FALSE( Interval(1, 4).covers(Interval(0, 5)) );
}
<file_sep>cmake_minimum_required(VERSION 2.4)
include_directories(.)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -march=native")
add_executable(iseql
Main.cpp
model/Interval.h
model/RelationGenerator.h
model/Tuple.h
model/Relation.h
model/Endpoint.h
model/Index.h
algorithms/IEJoin.h
algorithms/Iterators.h
algorithms/Joins0.h
algorithms/Joins1.h
algorithms/Joins2.h
algorithms/Joins.h
algorithms/JoinsInlined.h
algorithms/LMJoin0.h
algorithms/LMJoins.h
util/Arguments.h
util/Experiments.h
util/String.h
util/Timer.h
MainBefore.h
MainCommon.h
MainLatency.h
MainJoins.h
containers/GaplessHashMap.h
containers/GaplessList.h
containers/Util.h
util/Aggregates.h)
<file_sep>#pragma once
#include <algorithm>
#include <containers/GaplessList.h>
#include "model/Relation.h"
//#define LM_VERBOSE
#ifdef COUNTERS
static unsigned long long lmCounterBeforeSelection = 0;
static unsigned long long lmCounterAfterSelection = 0;
static unsigned long long lmCounterActiveCountX = 0;
static unsigned long long lmCounterActiveCountY = 0;
static unsigned long long lmCounterActiveCountTimes = 0;
static size_t lmCounterActiveMaxX = 0;
static size_t lmCounterActiveMaxY = 0;
static size_t lmCounterActiveMax = 0;
#endif
template <typename ShouldReadX,
typename ShouldReadY,
typename CanCleanupX,
typename CanCleanupY,
typename CheckingConsumer>
void leungMuntzJoin2(const Relation& X,
const Relation& Y,
const ShouldReadX& shouldReadX,
const ShouldReadY& shouldReadY,
const CanCleanupX& canCleanupX,
const CanCleanupY& canCleanupY,
const CheckingConsumer& checkingConsumer) noexcept
{
auto tauX = 1 + static_cast<Timestamp>(( (X[X.size() - 1].start - X[0].start) / static_cast<double>(X.size() - 1) )) ;
auto tauY = 1 + static_cast<Timestamp>(( (Y[Y.size() - 1].start - Y[0].start) / static_cast<double>(Y.size() - 1) )) ;
// auto tauX = 1 + static_cast<Timestamp>(round( (X[X.size() - 1].start - X[0].start) / static_cast<double>(X.size() - 1) )) ;
// auto tauY = 1 + static_cast<Timestamp>(round( (Y[Y.size() - 1].start - Y[0].start) / static_cast<double>(Y.size() - 1) )) ;
GaplessList<Tuple> workspaceY;
GaplessList<Tuple> workspaceX;
// static int a = 0;
// static int b = 0;
auto bufferX = X.begin();
auto bufferY = Y.begin();
bool shouldReadYNextIteration = false;
#ifdef LM_VERBOSE
std::cout << std::endl;
#endif
for (;;)
{
/* READING AND JOINING */
if (shouldReadYNextIteration)
{
#ifdef LM_VERBOSE
std::cout << " Reading Y " << *bufferY << std::endl;
#endif
for (const auto& x : workspaceX)
{
checkingConsumer(x, *bufferY);
}
workspaceY.insert(*bufferY);
// ++bufferY;
}
else
{
#ifdef LM_VERBOSE
std::cout << " Reading X " << *bufferX << std::endl;
#endif
for (const auto& y : workspaceY)
{
checkingConsumer(*bufferX, y);
}
workspaceX.insert(*bufferX);
// ++bufferX;
}
/* CLEANUP */
unsigned potentialPruneX = 0;
unsigned potentialPruneY = 0;
{
auto x = workspaceX.begin();
while (x != workspaceX.end())
{
if (canCleanupX(*x, bufferY->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase X " << *x << std::endl;
#endif
workspaceX.erase(x);
}
else
{
if (canCleanupX(*x, bufferY->start + tauY))
potentialPruneX++;
++x;
}
}
}
{
auto y = workspaceY.begin();
while (y != workspaceY.end())
{
if (canCleanupY(*y, bufferX->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase Y " << *y << std::endl;
#endif
workspaceY.erase(y);
}
else
{
if (canCleanupY(*y, bufferX->start + tauX))
potentialPruneY++;
++y;
}
}
}
if (shouldReadYNextIteration)
++bufferY;
else
++bufferX;
/* DECIDING */
if (bufferX == X.end())
{
if (workspaceX.empty() || bufferY == Y.end())
{
// std::cout << a << ' ' << b << std::endl;
return;
}
shouldReadYNextIteration = true;
}
else
if (bufferY == Y.end())
{
if (workspaceY.empty())
{
// std::cout << a << ' ' << b << std::endl;
return;
}
shouldReadYNextIteration = false;
}
else
if (shouldReadX(*bufferX, *bufferY))
{
shouldReadYNextIteration = false;
}
else
if (shouldReadY(*bufferX, *bufferY))
{
shouldReadYNextIteration = true;
}
else
{
#ifdef LM_VERBOSE
std::cout << "POTENTIAL PRUNE X " << potentialPruneX << " and Y " << potentialPruneY << std::endl;
#endif
// if (potentialPruneX == potentialPruneY)
// shouldReadYNextIteration = !shouldReadYNextIteration;
// else
shouldReadYNextIteration = potentialPruneX > potentialPruneY;
}
#ifdef COUNTERS
lmCounterActiveCountX += workspaceX.size();
lmCounterActiveCountY += workspaceY.size();
lmCounterActiveCountTimes++;
lmCounterActiveMaxX = std::max(lmCounterActiveMaxX, workspaceX.size());
lmCounterActiveMaxY = std::max(lmCounterActiveMaxY, workspaceY.size());
lmCounterActiveMax = std::max(lmCounterActiveMax, workspaceX.size() + workspaceY.size());
#endif
}
}
template <typename ShouldReadX,
typename ShouldReadY,
typename CanCleanupX,
typename CanCleanupY,
typename CheckingConsumer>
void leungMuntzJoin3(const Relation& X,
const Relation& Y,
const ShouldReadX& shouldReadX,
const ShouldReadY& shouldReadY,
const CanCleanupX& canCleanupX,
const CanCleanupY& canCleanupY,
const CheckingConsumer& checkingConsumer) noexcept
{
auto tauX = 1 + static_cast<Timestamp>(( (X[X.size() - 1].start - X[0].start) / static_cast<double>(X.size() - 1) )) ;
auto tauY = 1 + static_cast<Timestamp>(( (Y[Y.size() - 1].start - Y[0].start) / static_cast<double>(Y.size() - 1) )) ;
// auto tauX = 1 + static_cast<Timestamp>(round( (X[X.size() - 1].start - X[0].start) / static_cast<double>(X.size() - 1) )) ;
// auto tauY = 1 + static_cast<Timestamp>(round( (Y[Y.size() - 1].start - Y[0].start) / static_cast<double>(Y.size() - 1) )) ;
GaplessList<Tuple> workspaceY;
GaplessList<Tuple> workspaceX;
// static int a = 0;
// static int b = 0;
auto bufferX = X.begin();
auto bufferY = Y.begin();
bool shouldReadYNextIteration = false;
#ifdef LM_VERBOSE
std::cout << std::endl;
#endif
for (;;)
{
unsigned potentialPruneX = 0;
unsigned potentialPruneY = 0;
if (shouldReadYNextIteration)
{
#ifdef LM_VERBOSE
std::cout << " Reading Y " << *bufferY << std::endl;
#endif
auto x = workspaceX.begin();
while (x != workspaceX.end())
{
checkingConsumer(*x, *bufferY);
if (canCleanupX(*x, bufferY->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase X " << *x << std::endl;
#endif
workspaceX.erase(x);
}
else
{
if (canCleanupX(*x, bufferY->start + tauY))
potentialPruneX++;
++x;
}
}
workspaceY.insert(*bufferY);
++bufferY;
// We could just check for the new tuple, but we anyway have to estimate the potentialPruneY
auto y = workspaceY.begin();
while (y != workspaceY.end())
{
if (canCleanupY(*y, bufferX->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase Y " << *y << std::endl;
#endif
workspaceY.erase(y);
}
else
{
if (canCleanupY(*y, bufferX->start + tauX))
potentialPruneY++;
++y;
}
}
}
else
{
#ifdef LM_VERBOSE
std::cout << " Reading X " << *bufferX << std::endl;
#endif
auto y = workspaceY.begin();
while (y != workspaceY.end())
{
checkingConsumer(*bufferX, *y);
if (canCleanupY(*y, bufferX->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase Y " << *y << std::endl;
#endif
workspaceY.erase(y);
}
else
{
if (canCleanupY(*y, bufferX->start + tauX))
potentialPruneY++;
++y;
}
}
workspaceX.insert(*bufferX);
++bufferX;
auto x = workspaceX.begin();
while (x != workspaceX.end())
{
if (canCleanupX(*x, bufferY->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase X " << *x << std::endl;
#endif
workspaceX.erase(x);
}
else
{
if (canCleanupX(*x, bufferY->start + tauY))
potentialPruneX++;
++x;
}
}
}
/* DECIDING */
if (bufferX == X.end())
{
if (workspaceX.empty() || bufferY == Y.end())
{
// std::cout << a << ' ' << b << std::endl;
return;
}
shouldReadYNextIteration = true;
}
else
if (bufferY == Y.end())
{
if (workspaceY.empty())
{
// std::cout << a << ' ' << b << std::endl;
return;
}
shouldReadYNextIteration = false;
}
else
if (shouldReadX(*bufferX, *bufferY))
{
shouldReadYNextIteration = false;
}
else
if (shouldReadY(*bufferX, *bufferY))
{
shouldReadYNextIteration = true;
}
else
{
#ifdef LM_VERBOSE
std::cout << "POTENTIAL PRUNE X " << potentialPruneX << " and Y " << potentialPruneY << std::endl;
#endif
// if (potentialPruneX == potentialPruneY)
// shouldReadYNextIteration = !shouldReadYNextIteration;
// else
shouldReadYNextIteration = potentialPruneX > potentialPruneY;
}
#ifdef COUNTERS
lmCounterActiveCountX += workspaceX.size();
lmCounterActiveCountY += workspaceY.size();
lmCounterActiveCountTimes++;
lmCounterActiveMaxX = std::max(lmCounterActiveMaxX, workspaceX.size());
lmCounterActiveMaxY = std::max(lmCounterActiveMaxY, workspaceY.size());
lmCounterActiveMax = std::max(lmCounterActiveMax, workspaceX.size() + workspaceY.size());
#endif
}
}
template <typename ShouldReadX,
typename ShouldReadY,
typename CanCleanupX,
typename CanCleanupY,
typename CheckingConsumer>
void leungMuntzJoin4(const Relation& X,
const Relation& Y,
const ShouldReadX& shouldReadX,
const ShouldReadY& shouldReadY,
const CanCleanupX& canCleanupX,
const CanCleanupY& canCleanupY,
const CheckingConsumer& checkingConsumer) noexcept
{
auto tauX = 1 + static_cast<Timestamp>(( (X[X.size() - 1].start - X[0].start) / static_cast<double>(X.size() - 1) )) ;
auto tauY = 1 + static_cast<Timestamp>(( (Y[Y.size() - 1].start - Y[0].start) / static_cast<double>(Y.size() - 1) )) ;
// auto tauX = 1 + static_cast<Timestamp>(round( (X[X.size() - 1].start - X[0].start) / static_cast<double>(X.size() - 1) )) ;
// auto tauY = 1 + static_cast<Timestamp>(round( (Y[Y.size() - 1].start - Y[0].start) / static_cast<double>(Y.size() - 1) )) ;
GaplessList<Tuple> workspaceY;
GaplessList<Tuple> workspaceX;
// static int a = 0;
// static int b = 0;
auto bufferX = X.begin();
auto bufferY = Y.begin();
bool shouldReadYNextIteration = false;
unsigned potentialPruneX = 0;
unsigned potentialPruneY = 0;
#ifdef LM_VERBOSE
std::cout << std::endl;
#endif
for (;;)
{
if (shouldReadYNextIteration)
{
#ifdef LM_VERBOSE
std::cout << " Reading Y " << *bufferY << std::endl;
#endif
potentialPruneX = 0;
auto x = workspaceX.begin();
while (x != workspaceX.end())
{
checkingConsumer(*x, *bufferY);
if (canCleanupX(*x, bufferY->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase X " << *x << std::endl;
#endif
workspaceX.erase(x);
}
else
{
if (canCleanupX(*x, bufferY->start + tauY))
potentialPruneX++;
++x;
}
}
if (!canCleanupY(*bufferY, bufferX->start))
{
workspaceY.insert(*bufferY);
if (canCleanupY(*bufferY, bufferX->start + tauX))
potentialPruneY++;
}
++bufferY;
}
else
{
#ifdef LM_VERBOSE
std::cout << " Reading X " << *bufferX << std::endl;
#endif
potentialPruneY = 0;
auto y = workspaceY.begin();
while (y != workspaceY.end())
{
checkingConsumer(*bufferX, *y);
if (canCleanupY(*y, bufferX->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase Y " << *y << std::endl;
#endif
workspaceY.erase(y);
}
else
{
if (canCleanupY(*y, bufferX->start + tauX))
potentialPruneY++;
++y;
}
}
if (!canCleanupX(*bufferX, bufferY->start))
{
workspaceX.insert(*bufferX);
if (canCleanupX(*bufferX, bufferY->start + tauY))
potentialPruneX++;
}
++bufferX;
}
/* DECIDING */
if (bufferX == X.end())
{
if (workspaceX.empty() || bufferY == Y.end())
{
// std::cout << a << ' ' << b << std::endl;
return;
}
shouldReadYNextIteration = true;
}
else
if (bufferY == Y.end())
{
if (workspaceY.empty())
{
// std::cout << a << ' ' << b << std::endl;
return;
}
shouldReadYNextIteration = false;
}
else
if (shouldReadX(*bufferX, *bufferY))
{
shouldReadYNextIteration = false;
}
else
if (shouldReadY(*bufferX, *bufferY))
{
shouldReadYNextIteration = true;
}
else
{
#ifdef LM_VERBOSE
std::cout << "POTENTIAL PRUNE X " << potentialPruneX << " and Y " << potentialPruneY << std::endl;
#endif
// if (potentialPruneX == potentialPruneY)
// shouldReadYNextIteration = !shouldReadYNextIteration;
// else
shouldReadYNextIteration = potentialPruneX > potentialPruneY;
}
#ifdef COUNTERS
lmCounterActiveCountX += workspaceX.size();
lmCounterActiveCountY += workspaceY.size();
lmCounterActiveCountTimes++;
lmCounterActiveMaxX = std::max(lmCounterActiveMaxX, workspaceX.size());
lmCounterActiveMaxY = std::max(lmCounterActiveMaxY, workspaceY.size());
lmCounterActiveMax = std::max(lmCounterActiveMax, workspaceX.size() + workspaceY.size());
#endif
}
}
template <typename ShouldReadX,
typename ShouldReadY,
typename CanCleanupX,
typename CanCleanupY,
typename CheckingConsumer>
void leungMuntzJoin5(const Relation& X,
const Relation& Y,
const ShouldReadX& shouldReadX,
const ShouldReadY& shouldReadY,
const CanCleanupX& canCleanupX,
const CanCleanupY& canCleanupY,
const CheckingConsumer& checkingConsumer) noexcept
{
auto tauX = 1 + static_cast<Timestamp>(( (X[X.size() - 1].start - X[0].start) / static_cast<double>(X.size() - 1) )) ;
auto tauY = 1 + static_cast<Timestamp>(( (Y[Y.size() - 1].start - Y[0].start) / static_cast<double>(Y.size() - 1) )) ;
// auto tauX = 1 + static_cast<Timestamp>(round( (X[X.size() - 1].start - X[0].start) / static_cast<double>(X.size() - 1) )) ;
// auto tauY = 1 + static_cast<Timestamp>(round( (Y[Y.size() - 1].start - Y[0].start) / static_cast<double>(Y.size() - 1) )) ;
GaplessList<Tuple> workspaceY;
GaplessList<Tuple> workspaceX;
// static int a = 0;
// static int b = 0;
auto bufferX = X.begin();
auto bufferY = Y.begin();
bool shouldReadYNextIteration = false;
#ifdef LM_VERBOSE
std::cout << std::endl;
#endif
for (;;)
{
#ifdef LM_VERBOSE
if (shouldReadYNextIteration)
std::cout << " Reading Y " << *bufferY << std::endl;
else
std::cout << " Reading X " << *bufferX << std::endl;
#endif
unsigned potentialPruneX = 0;
unsigned potentialPruneY = 0;
{
auto x = workspaceX.begin();
while (x != workspaceX.end())
{
if (shouldReadYNextIteration)
checkingConsumer(*x, *bufferY);
if (canCleanupX(*x, bufferY->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase X " << *x << std::endl;
#endif
workspaceX.erase(x);
}
else
{
if (canCleanupX(*x, bufferY->start + tauY))
potentialPruneX++;
++x;
}
}
}
{
auto y = workspaceY.begin();
while (y != workspaceY.end())
{
if (!shouldReadYNextIteration)
checkingConsumer(*bufferX, *y);
if (canCleanupY(*y, bufferX->start))
{
#ifdef LM_VERBOSE
std::cout << " Erase Y " << *y << std::endl;
#endif
workspaceY.erase(y);
}
else
{
if (canCleanupY(*y, bufferX->start + tauX))
potentialPruneY++;
++y;
}
}
}
if (shouldReadYNextIteration)
{
workspaceY.insert(*bufferY);
++bufferY;
}
else
{
workspaceX.insert(*bufferX);
++bufferX;
}
/* DECIDING */
if (bufferX == X.end())
{
if (workspaceX.empty() || bufferY == Y.end())
{
// std::cout << a << ' ' << b << std::endl;
return;
}
shouldReadYNextIteration = true;
}
else
if (bufferY == Y.end())
{
if (workspaceY.empty())
{
// std::cout << a << ' ' << b << std::endl;
return;
}
shouldReadYNextIteration = false;
}
else
if (shouldReadX(*bufferX, *bufferY))
{
shouldReadYNextIteration = false;
}
else
if (shouldReadY(*bufferX, *bufferY))
{
shouldReadYNextIteration = true;
}
else
{
#ifdef LM_VERBOSE
std::cout << "POTENTIAL PRUNE X " << potentialPruneX << " and Y " << potentialPruneY << std::endl;
#endif
// if (potentialPruneX == potentialPruneY)
// shouldReadYNextIteration = !shouldReadYNextIteration;
// else
shouldReadYNextIteration = potentialPruneX > potentialPruneY;
}
#ifdef COUNTERS
lmCounterActiveCountX += workspaceX.size();
lmCounterActiveCountY += workspaceY.size();
lmCounterActiveCountTimes++;
lmCounterActiveMaxX = std::max(lmCounterActiveMaxX, workspaceX.size());
lmCounterActiveMaxY = std::max(lmCounterActiveMaxY, workspaceY.size());
lmCounterActiveMax = std::max(lmCounterActiveMax, workspaceX.size() + workspaceY.size());
#endif
}
}
<file_sep>#!/bin/bash
DATA_DIR=~/data
SCRIPT_DIR=`dirname "$0"`
BUILD_DIR=""
EXE=""
BUILD_DIR_SOURCE="../.."
switchToRelease()
{
BUILD_DIR="target/release"
EXE="$BUILD_DIR/src/iseql"
}
switchToCounters()
{
BUILD_DIR="target/counters"
EXE="$BUILD_DIR/src/iseql"
}
switchToEBI()
{
BUILD_DIR="target/ebi"
EXE="$BUILD_DIR/src/iseql"
}
switchToRelease
<file_sep>#pragma once
#include <iostream>
#include <unordered_map>
#include "model/RelationGenerator.h"
#include "util/Experiments.h"
#include "util/Arguments.h"
#include "util/Aggregates.h"
#include "algorithms/Joins.h"
#include "MainCommon.h"
static void stats(Experiments& experiments, const Relation& relation, const std::string& name)
{
Aggregate<Timestamp> aggregate;
for (const auto& tuple : relation)
{
aggregate.add(tuple.getLength());
}
experiments.addExperimentResult(name + "-avg-len", aggregate.getAvg());
experiments.addExperimentResult(name + "-max-len", aggregate.max);
}
static void tupleEffectiveEnds(Relation& relation)
{
GaplessHashMap<TID, Timestamp> active(4096);
for (const auto& endpoint : relation.getIndex())
{
auto tid = endpoint.getTID();
auto& tuple = relation[tid];
if (endpoint.isStart())
{
active.insert(tid, tuple.end);
// std::cout << &tuple - &relation[0] << std::endl;
auto effectiveEnd = std::max_element(active.begin(), active.end());
tuple.id = *effectiveEnd;
}
else
{
active.erase(tid);
}
}
}
inline void mainLatency(Arguments& arguments)
{
Relation R, S;
auto experiments = getExperimentsAndPopulateRelations(arguments, R, S);
Index indexR{R}, indexS{S};
R.setIndex(indexR);
S.setIndex(indexS);
stats(experiments, R, "r");
stats(experiments, S, "s");
Aggregate<Timestamp> latencies1;
Aggregate<Timestamp> latencies2;
tupleEffectiveEnds(R);
tupleEffectiveEnds(S);
reverseDuringStrictJoin(R, S, [&] (const Tuple& r, const Tuple& s)
{
latencies1.add(r.end - s.end);
auto realEnd = std::max(r.id, s.id);
latencies2.add(realEnd - s.end);
});
experiments.addExperimentResult("latency-1-avg", latencies1.getAvg());
experiments.addExperimentResult("latency-1-max", latencies1.max);
experiments.addExperimentResult("latency-2-avg", latencies2.getAvg());
experiments.addExperimentResult("latency-2-max", latencies2.max);
}
<file_sep>#pragma once
#include <list>
#include <iostream>
#include <string>
#include <map>
#include <memory>
#include <string>
#include <iomanip>
#include <functional>
#include <cstring>
#include <vector>
#include <algorithm>
#include "util/Timer.h"
#include "util/String.h"
class Experiments
{
struct Experiment
{
const std::string name;
const std::string dependency;
const std::function<void()> code;
double seconds;
bool wasExecuted = false;
std::vector<unsigned long long> measurements;
Experiment(const std::string& name, const std::string& dependency)
:
name(name), dependency(dependency)
{
}
Experiment(const std::string& name, const std::string& dependency, const std::function<void()>& code)
:
name(name), dependency(dependency), code(code)
{
}
bool operator == (const std::string& name)
{
return this->name == name;
}
};
private:
std::vector<Experiment> experiments;
std::vector<std::string> disabledExperiments;
std::vector<const char*> measurementNames;
public:
Experiments(const char* disabledExperiments)
:
disabledExperiments(split(disabledExperiments, ','))
{
experiments.reserve(64);
std::cout << "Experiment Seconds Result" << std::endl;
std::cout << "-------------------- ---------- --------------------" << std::endl;
}
Experiments() : Experiments("") { }
Experiments(Experiments&&) = default;
~Experiments()
{
print();
}
void prepare(const char* name, const char* dependency, const std::function<void()>& code)
{
experiments.emplace_back(name, dependency, code);
}
size_t divideBy = 0;
template<typename Function>
void experiment(const std::string& name, const std::string& dependency, const Function& code)
{
experiments.emplace_back(name, dependency);
auto& experiment = experiments.back();
executeExperiment(experiment, code);
}
private:
template<typename Function>
void executeExperiment(Experiment& experiment, const Function& code)
{
using namespace std;
experiment.wasExecuted = isMeasurementEnabled(experiment.name);
if (experiment.wasExecuted)
resolveDependency(experiment.dependency);
cout << setw(20) << left << experiment.name << flush;
int width = 10;
int precision = 3;
if (experiment.wasExecuted)
{
if (experiment.code)
{
Timer timer;
experiment.code();
experiment.seconds = timer.stop();
cout << ' ' << setw(width) << right << fixed << setprecision(precision) << experiment.seconds;
cout << endl;
}
else
{
Timer timer;
const auto result = code();
experiment.seconds = timer.stop();
cout << ' ' << setw(width) << right << fixed << setprecision(precision) << experiment.seconds;
cout << ' ' << left << result << endl;
}
}
else
{
cout << ' ' << right << setw(width) << "skipped" << endl;
}
}
void resolveDependency(const std::string& name)
{
if (name.empty())
return;
auto& experiment = operator[](name);
if (experiment.wasExecuted)
return;
executeExperiment(experiment, [] { return 0; });
}
public:
void addExperimentResult(const std::string& name, double seconds)
{
experiments.emplace_back(name, "");
auto& experiment = experiments.back();
experiment.wasExecuted = true;
experiment.seconds = seconds;
}
Experiment& operator[](const std::string& name)
{
return *std::find(experiments.begin(), experiments.end(), name);
}
void print()
{
using namespace std;
int width = 13;
cout << "-----BEGIN RESULTS-----" << endl;
cout << left;
for (auto& experiment : experiments)
{
cout << setw(width) << experiment.name << ' ';
if (!experiment.measurements.empty())
{
for (const auto& name : measurementNames)
cout << setw(width) << (std::string(experiment.name) + '-' + name) << ' ';
}
}
cout << endl;
cout.unsetf(ios::floatfield);
// cout << defaultfloat;
for (auto& experiment : experiments)
{
if (experiment.wasExecuted)
{
cout << setw(width) << setprecision(6) << experiment.seconds << ' ';
if (!experiment.measurements.empty())
{
for (auto value : experiment.measurements)
cout << setw(width) << setprecision(6) << double(value) / double(divideBy) << ' ';
}
}
else
cout << setw(width) << left << "nan" << ' ';
}
cout << endl;
cout << "-----END RESULTS-----" << endl;
}
private:
bool isMeasurementEnabled(const std::string& name)
{
for (const auto& disabledExperiment : disabledExperiments)
{
if (disabledExperiment == name)
return false;
}
return true;
}
};
<file_sep>#pragma once
#include <cstdint>
#include <vector>
#include "Util.h"
template<typename T>
class GaplessList
{
private:
std::vector<T> elements;
public:
using iterator = typename std::vector<T>::iterator;
// using const_iterator = std::vector<T>::const_iterator;
public:
GaplessList()
{
}
GaplessList(size_t capacity)
{
elements.reserve(capacity);
}
void insert(const T& element)
{
elements.push_back(element);
}
void erase(iterator it)
{
auto last = elements.end() - 1;
if (it != last)
*it = *last;
elements.erase(last);
}
iterator begin() noexcept
{
return elements.begin();
}
iterator end() noexcept
{
return elements.end();
}
bool empty() const noexcept
{
return elements.empty();
}
size_t size() const noexcept
{
return elements.size();
}
};
<file_sep>#pragma once
#include <iostream>
class Arguments
{
private:
const char** argv;
size_t index = 1;
private:
const char* getCurrentArgOrNull()
{
return argv[index];
}
void skipCurrentArg()
{
index++;
}
public:
Arguments(const char* argv[]) : argv(argv)
{
}
bool isSwitchPresent(const char* switchName)
{
if (getCurrentArgOrNull() != nullptr && getCurrentArgOrNull() == std::string(switchName))
{
skipCurrentArg();
return true;
}
else
return false;
}
const char* getCurrentArgAndSkipIt(const char* description)
{
auto arg = getCurrentArgOrNull();
if (!arg)
error("Expected command-line argument: ", description);
index++;
return arg;
}
double getCurrentArgAsDoubleAndSkipIt(const char* description)
{
return strtod(getCurrentArgAndSkipIt(description), nullptr);
}
bool empty()
{
return argv[index] == nullptr;
}
[[noreturn]] void error(const char* reason, const std::string& reason2)
{
error(reason, reason2.c_str());
}
[[noreturn]] void error(const char* reason, const char* reason2)
{
std::cerr << reason << reason2 << std::endl;
exit(1);
}
};
<file_sep>#pragma once
#include "Iterators.h"
#include "containers/GaplessHashMap.h"
#ifdef COUNTERS
static unsigned long long myCounterBeforeSelection = 0;
static unsigned long long myCounterAfterSelection = 0;
static unsigned long long myCounterActiveCount = 0;
static unsigned long long myCounterActiveCountTimes = 0;
static size_t myCounterActiveMax = 0;
#endif
#ifndef EBI
template <typename IteratorR, typename IteratorS, typename Compare, typename Consumer>
void joinByS(const Relation& R, const Relation& S, IteratorR itR, IteratorS itS, Compare comp, const Consumer& consumer)
{
GaplessHashMap<TID, Tuple> activeR(32);
for (;;)
{
if (comp(itR.getEndpoint(), itS.getEndpoint()))
{
const Endpoint& endpointR = itR.getEndpoint();
TID tid = endpointR.getTID();
if (endpointR.isStart())
activeR.insert(tid, R[tid]);
else
activeR.erase(tid);
#ifdef COUNTERS
myCounterActiveCount += activeR.size();
myCounterActiveCountTimes++;
myCounterActiveMax = std::max(myCounterActiveMax, activeR.size());
#endif
itR.moveToNextEndpoint();
if (itR.isFinished())
break;
}
else
{
Tuple buffer[32];
auto bufferBegin = std::begin(buffer);
auto bufferEnd = std::end(buffer);
auto bufferNext = bufferBegin;
do
{
*bufferNext = S[itS.getEndpoint().getTID()];
++bufferNext;
itS.moveToNextEndpoint();
}
while (!itS.isFinished() && !comp(itR.getEndpoint(), itS.getEndpoint()) && bufferNext != bufferEnd);
switch (bufferNext - bufferBegin)
{
case 1:
for (const auto& r : activeR)
{
consumer(r, buffer[0]);
}
break;
case 2:
for (const auto& r : activeR)
{
consumer(r, buffer[0]);
consumer(r, buffer[1]);
}
break;
case 3:
for (const auto& r : activeR)
{
consumer(r, buffer[0]);
consumer(r, buffer[1]);
consumer(r, buffer[2]);
}
break;
case 4:
for (const auto& r : activeR)
{
consumer(r, buffer[0]);
consumer(r, buffer[1]);
consumer(r, buffer[2]);
consumer(r, buffer[3]);
}
break;
default:
for (const auto& r : activeR)
{
for (auto s = bufferBegin; s != bufferNext; ++s)
{
consumer(r, *s);
}
}
}
if (itS.isFinished())
break;
}
}
}
#else
template <typename IteratorR, typename IteratorS, typename Compare, typename Consumer>
void joinByS(const Relation& R, const Relation& S, IteratorR itR, IteratorS itS, Compare comp, const Consumer& consumer)
{
GaplessHashMap<TID, Tuple> activeR(32);
for (;;)
{
if (comp(itR.getEndpoint(), itS.getEndpoint()))
{
const Endpoint& endpointR = itR.getEndpoint();
TID tid = endpointR.getTID();
if (endpointR.isStart())
activeR.insert(tid, R[tid]);
else
activeR.erase(tid);
itR.moveToNextEndpoint();
if (itR.isFinished())
break;
}
else
{
const Tuple& s = S[itS.getEndpoint().getTID()];
for (const auto& r : activeR)
consumer(r, s);
itS.moveToNextEndpoint();
if (itS.isFinished())
break;
}
}
}
#endif
<file_sep>#pragma once
#include <limits>
#include <cassert>
#include <ostream>
#include <utility>
#include <algorithm>
using Timestamp = int;
class Interval
{
public:
Timestamp start; // inclusive
Timestamp end; // exclusive
public:
Interval() noexcept {}
Interval(Timestamp start, Timestamp end) noexcept
:
start(start),
end(end)
{
assert(start < end);
}
bool operator < (const Interval& rhs) const noexcept
{
return start < rhs.start;
}
bool overlaps(const Interval& other) const noexcept
{
return start < other.end && other.start < end;
}
bool covers(const Interval& other) const noexcept
{
return start <= other.start && end >= other.end;
}
Timestamp getLength() const noexcept
{
return end - start;
}
friend void swap(Interval& a, Interval& b) noexcept
{
using std::swap;
swap(a.start, b.start);
swap(a.end , b.end );
}
friend std::ostream& operator << (std::ostream &out, const Interval& self)
{
return out << '[' << self.start << ',' << self.end << ')';
}
};
<file_sep>cmake_minimum_required(VERSION 2.8.2)
# https://github.com/google/googletest/tree/master/googletest
project(googletest-download NONE)
include(ExternalProject)
ExternalProject_Add(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.8.0
# GIT_CONFIG advice.detachedHead=false
SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src"
BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
UPDATE_COMMAND ""
)
<file_sep>#pragma once
#include <limits>
#include "Joins2.h"
constexpr Timestamp UNBOUND = std::numeric_limits<Timestamp>::max();
template<typename Consumer>
inline auto makeReversingConsumer(const Consumer& consumer) noexcept
{
return [&consumer] (const Tuple& s, const Tuple& r) noexcept
{
consumer(r, s);
};
}
template <typename Consumer>
void startPrecedingJoin(const Relation& R, const Relation& S, Timestamp delta, const Consumer& consumer) noexcept
{
startPrecedingJoin(R, S, [delta, &consumer] (const Tuple& r, const Tuple& s)
{
if (s.start - r.start <= delta)
consumer(r, s);
});
}
template <typename Consumer>
void reverseStartPrecedingJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
startPrecedingJoin(S, R, makeReversingConsumer(consumer));
}
template <typename Consumer>
void reverseStartPrecedingStrictJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
startPrecedingStrictJoin(S, R, makeReversingConsumer(consumer));
}
template <typename Consumer>
void endFollowingJoin(const Relation& R, const Relation& S, Timestamp epsilon, const Consumer& consumer) noexcept
{
endFollowingJoin(R, S, [epsilon, &consumer] (const Tuple& r, const Tuple& s)
{
if (r.end - s.end <= epsilon)
consumer(r, s);
});
}
template <typename Consumer>
void reverseEndFollowingJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
endFollowingJoin(S, R, makeReversingConsumer(consumer));
}
template <typename Consumer>
void reverseEndFollowingStrictJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
endFollowingStrictJoin(S, R, makeReversingConsumer(consumer));
}
template <typename Consumer>
void leftOverlapJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
startPrecedingJoin(R, S, [&consumer] (const Tuple& r, const Tuple& s)
{
if (r.end <= s.end)
consumer(r, s);
});
}
template <typename Consumer>
void leftOverlapStrictJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
startPrecedingStrictJoin(R, S, [&consumer] (const Tuple& r, const Tuple& s)
{
#ifdef COUNTERS
myCounterBeforeSelection++;
#endif
if (r.end < s.end)
{
#ifdef COUNTERS
myCounterAfterSelection++;
#endif
consumer(r, s);
}
});
}
template <typename Consumer>
void leftOverlapJoin(const Relation& R, const Relation& S, Timestamp delta, Timestamp epsilon, const Consumer& consumer) noexcept
{
leftOverlapJoin(R, S, [delta, epsilon, &consumer] (const Tuple& r, const Tuple& s)
{
if (s.start - r.start <= delta && s.end - r.end <= epsilon)
consumer(r, s);
});
}
template <typename Consumer>
void rightOverlapJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
leftOverlapJoin(S, R, makeReversingConsumer(consumer));
}
template <typename Consumer>
void rightOverlapJoin(const Relation& R, const Relation& S, Timestamp delta, Timestamp epsilon, const Consumer& consumer) noexcept
{
leftOverlapJoin(S, R, delta, epsilon, makeReversingConsumer(consumer));
}
template <typename Consumer>
void duringJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
reverseStartPrecedingJoin(R, S, [&consumer] (const Tuple& r, const Tuple& s)
{
if (r.end <= s.end)
consumer(r, s);
});
}
template <typename Consumer>
void reverseDuringStrictJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
startPrecedingStrictJoin(R, S, [&consumer] (const Tuple& r, const Tuple& s)
{
#ifdef COUNTERS
myCounterBeforeSelection++;
#endif
if (s.end < r.end)
{
#ifdef COUNTERS
myCounterAfterSelection++;
#endif
consumer(r, s);
}
});
}
template <typename Consumer>
void duringJoin(const Relation& R, const Relation& S, Timestamp delta, Timestamp epsilon, const Consumer& consumer) noexcept
{
duringJoin(R, S, [delta, epsilon, &consumer] (const Tuple& r, const Tuple& s)
{
if (r.start - s.start <= delta && s.end - r.end <= epsilon)
consumer(r, s);
});
}
template <typename Consumer>
void reverseDuringJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
duringJoin(S, R, makeReversingConsumer(consumer));
}
template <typename Consumer>
void reverseDuringJoin(const Relation& R, const Relation& S, Timestamp delta, Timestamp epsilon, const Consumer& consumer) noexcept
{
duringJoin(S, R, delta, epsilon, makeReversingConsumer(consumer));
}
template <typename Consumer>
void afterJoin(const Relation& R, const Relation& S, Timestamp delta, const Consumer& consumer) noexcept
{
beforeJoin(S, R, delta, makeReversingConsumer(consumer));
}
<file_sep>#pragma once
#include <cstdint>
#include <algorithm>
#include "Util.h"
template<typename K, typename V>
class GaplessHashMap
{
private:
class Reference
{
private:
typedef uint32_t value_type;
static constexpr value_type tableFlag = ~(~value_type(0) >> 1);
private:
value_type value;
Reference(value_type value) noexcept
:
value(value)
{
}
public:
static Reference forTable(size_t position) noexcept
{
return static_cast<value_type>(position) | tableFlag;
}
static Reference forNodes(size_t position) noexcept
{
return static_cast<value_type>(position);
}
inline bool isTableReference() const noexcept
{
return (value & tableFlag) != 0;
}
inline size_t getTablePosition() const noexcept
{
return value & ~tableFlag;
}
inline size_t getNodesPosition() const noexcept
{
return value;
}
inline operator bool() const noexcept
{
return value != 0;
}
};
template <typename T>
class BaseOneDynamicArray
{
T* array;
T* arrayEnd;
public:
BaseOneDynamicArray(size_t capacity) noexcept
:
array(array_malloc<T>(capacity) - 1),
arrayEnd(begin())
{
}
virtual ~BaseOneDynamicArray() noexcept
{
std::free(begin());
}
T* insert() noexcept
{
auto result = arrayEnd;
++arrayEnd;
return result;
}
void insert(const T& value) noexcept
{
*insert() = value;
}
void erase(Reference reference) noexcept
{
T* element = &operator[](reference);
arrayEnd--;
if (element != arrayEnd)
*element = *arrayEnd;
}
Reference referenceOf(const T* element) const noexcept
{
return Reference::forNodes(static_cast<size_t>(element - array));
}
T& operator[](Reference reference) noexcept
{
return array[reference.getNodesPosition()];
}
T* begin() const noexcept
{
return array + 1;
}
T* end() const noexcept
{
return arrayEnd;
}
size_t size() const noexcept
{
return static_cast<size_t>(end() - begin());
}
void resize(size_t capacity)
{
size_t saveSize = size();
array = array_realloc(begin(), capacity) - 1;
arrayEnd = begin() + saveSize;
}
};
class HashTable
{
Reference* table;
size_t mask;
public:
HashTable(size_t size) noexcept
:
table(array_calloc<Reference>(size)),
mask(size - 1)
{
}
friend void swap(HashTable& table1, HashTable& table2)
{
std::swap(table1.table, table2.table);
std::swap(table1.mask, table2.mask);
}
~HashTable() noexcept
{
std::free(table);
}
inline size_t size() const noexcept
{
return mask + 1;
}
Reference referenceOf(const Reference* bucket) const noexcept
{
return Reference::forTable(static_cast<size_t>(bucket - table));
}
Reference* bucketFor(K key) noexcept
{
size_t position = static_cast<size_t>(key) & mask;
return table + position;
}
Reference& operator[](Reference reference) noexcept
{
return table[reference.getTablePosition()];
}
};
struct Node
{
Reference prev, next;
K key;
};
private:
size_t capacity;
HashTable table;
BaseOneDynamicArray<Node> nodes;
BaseOneDynamicArray<V> values;
public:
using value_type = V;
using const_iterator = const V*;
public:
GaplessHashMap(size_t capacity) noexcept
:
capacity(capacity),
table(next_power_of_two(capacity)),
nodes (capacity),
values(capacity)
{
}
void insert(K key, const V& value) noexcept
{
if (values.size() == capacity)
grow();
values.insert(value);
Node* node = nodes.insert();
node->key = key;
insertNodeIntoBucket(table, node);
}
void erase(K key) noexcept
{
Reference reference = *table.bucketFor(key);
Node* node = &nodes[reference];
// Find the node
while (node->key != key)
{
reference = node->next;
node = &nodes[reference];
}
// Remove the node from the bucket
Reference prev = node->prev;
Reference next = node->next;
if (prev.isTableReference())
table[prev] = next;
else
nodes[prev].next = next;
if (next)
nodes[next].prev = prev;
// Remove the node and the value from storage arrays
values.erase(reference);
nodes.erase(reference);
if (node != nodes.end()) // node now points to a different, moved node
{
prev = node->prev;
next = node->next;
if (prev.isTableReference())
table[prev] = reference;
else
nodes[prev].next = reference;
if (next)
nodes[next].prev = reference;
}
}
size_t size() const noexcept
{
return values.size();
}
const_iterator begin() const noexcept
{
return values.begin();
}
const_iterator end() const noexcept
{
return values.end();
}
private:
void grow() noexcept
{
constexpr size_t factor = 4;
capacity *= factor;
nodes.resize(capacity);
values.resize(capacity);
HashTable table2(table.size() * factor);
for (Node& node : nodes)
{
insertNodeIntoBucket(table2, &node);
}
swap(table, table2);
}
void insertNodeIntoBucket(HashTable& table, Node* node) noexcept
{
Reference* bucket = table.bucketFor(node->key);
node->prev = table.referenceOf(bucket);
node->next = *bucket;
if (node->next)
nodes[node->next].prev = nodes.referenceOf(node);
*bucket = nodes.referenceOf(node);
}
};
<file_sep>#pragma once
#include <iostream>
#include <memory>
#include "util/Arguments.h"
#include "util/Experiments.h"
#include "util/Timer.h"
#include "model/RelationGenerator.h"
#include "MainCommon.h"
#include "algorithms/IEJoin.h"
#include "algorithms/Joins.h"
#include "algorithms/LMJoins.h"
typedef void join_algorithm_t(const Relation&, const Relation&, const Workload&);
inline void compareDanilaAndLM(const Relation& R, const Relation& S, Experiments& experiments,
join_algorithm_t* danila, join_algorithm_t* lm)
{
experiments.experiment("danila", "index", [&]
{
Timestamp accum = 0;
danila(R, S, Workload{accum});
return accum;
});
experiments.experiment("lm", "sort", [&]
{
Timestamp accum = 0;
Workload workload{accum};
lm(R, S, workload);
#ifdef COUNTERS
experiments.addExperimentResult("z", static_cast<double>(workload.count));
#endif
return accum;
});
}
template <typename IEJoin>
void testIEJoin(const Relation& R, const Relation& S, Experiments& experiments)
{
std::unique_ptr<IEJoin> ieJoin;
experiments.prepare("ie-index", "", [&]
{
ieJoin = std::make_unique<IEJoin>(R, S);
});
experiments.experiment("ie", "ie-index", [&]
{
Timestamp accum = 0;
ieJoin->join(Workload{accum});
return accum;
});
}
inline void mainJoins(const std::string& command, Arguments& arguments)
{
Relation R, S;
auto experiments = getExperimentsAndPopulateRelations(arguments, R, S);
experiments.prepare("sort", "", [&]
{
R.sort();
S.sort();
});
Index indexR{}, indexS{};
experiments.prepare("index", "sort", [&]
{
indexR.buildFor(R);
indexS.buildFor(S);
});
R.setIndex(indexR);
S.setIndex(indexS);
if (command == "reverse-during")
{
compareDanilaAndLM(R, S, experiments, &reverseDuringStrictJoin, &leungMuntzReverseDuringStrictJoin);
testIEJoin<IEJoinReverseDuringStrict>(R, S, experiments);
}
else
if (command == "start-preceding")
{
compareDanilaAndLM(R, S, experiments, &startPrecedingStrictJoin, &leungMuntzStartPrecedingStrictJoin);
testIEJoin<IEJoinStartPrecedingStrict>(R, S, experiments);
}
else
if (command == "left-overlap")
{
compareDanilaAndLM(R, S, experiments, &leftOverlapStrictJoin, &leungMuntzLeftOverlapStrictJoin);
}
else
arguments.error("Invalid command ", command);
#ifdef COUNTERS
experiments.addExperimentResult("lm-sel", (double) lmCounterAfterSelection / (double) lmCounterBeforeSelection);
// experiments.addExperimentResult("lm-x-avg", (double) lmCounterActiveCountX / lmCounterActiveCountTimes);
// experiments.addExperimentResult("lm-y-avg", (double) lmCounterActiveCountY / lmCounterActiveCountTimes);
experiments.addExperimentResult("lm-avg", (double) (lmCounterActiveCountX + lmCounterActiveCountY) / (double) lmCounterActiveCountTimes);
// experiments.addExperimentResult("lm-x-max", lmCounterActiveMaxX);
// experiments.addExperimentResult("lm-y-max", lmCounterActiveMaxY);
experiments.addExperimentResult("lm-max", (double) lmCounterActiveMax);
experiments.addExperimentResult("my-sel", myCounterBeforeSelection ? (double) myCounterAfterSelection / (double) myCounterBeforeSelection : 1);
experiments.addExperimentResult("my-avg", (double) myCounterActiveCount / (double) myCounterActiveCountTimes);
experiments.addExperimentResult("my-max", (double) myCounterActiveMax);
experiments.addExperimentResult("lm-comp", (double) (lmComparisonCount + lmCounterBeforeSelection * 2));
experiments.addExperimentResult("my-comp", (double) myCounterBeforeSelection);
#endif
}
<file_sep>#pragma once
#include "model/Index.h"
class Iterator
{
private:
Index::const_iterator it;
Index::const_iterator end;
public:
Iterator(const Index& index) noexcept
:
it(index.begin()),
end(index.end())
{
}
void moveToNextEndpoint() noexcept
{
++it;
}
bool isFinished() const noexcept
{
return it == end;
}
const Endpoint& getEndpoint() const noexcept
{
return *it;
}
};
template <typename Iterator>
class FilteringIterator
{
private:
Iterator iterator;
Endpoint::Type type;
bool isWrongType() const noexcept
{
return getEndpoint().getType() != type;
}
public:
FilteringIterator(Iterator iterator, Endpoint::Type type) noexcept
:
iterator(iterator),
type(type)
{
while (isWrongType())
this->iterator.moveToNextEndpoint();
}
void moveToNextEndpoint() noexcept
{
do
{
iterator.moveToNextEndpoint();
}
while (!isFinished() && isWrongType());
}
bool isFinished() const noexcept
{
return iterator.isFinished();
}
const Endpoint& getEndpoint() const noexcept
{
return iterator.getEndpoint();
}
};
template <typename Iterator>
class ShiftingIterator
{
private:
Iterator iterator;
Timestamp shiftArgument;
public:
ShiftingIterator(Iterator iterator, Timestamp delta) noexcept
:
iterator(iterator),
shiftArgument(Endpoint::calculateShiftArgument(delta))
{
}
ShiftingIterator(Iterator iterator, Timestamp delta, Endpoint::Type fromType, Endpoint::Type toType) noexcept
:
iterator(iterator),
shiftArgument(Endpoint::calculateShiftArgument(delta, fromType, toType))
{
}
void moveToNextEndpoint() noexcept
{
iterator.moveToNextEndpoint();
}
bool isFinished() const noexcept
{
return iterator.isFinished();
}
Endpoint getEndpoint() const noexcept
{
return iterator.getEndpoint().shiftedBy(shiftArgument);
}
};
template <typename Iterator1, typename Iterator2>
class MergingIterator
{
private:
Iterator1 iterator1; // finishes always before the second iterator
Iterator2 iterator2;
Endpoint endpoint;
public:
MergingIterator(Iterator1 iterator1, Iterator2 iterator2) noexcept
:
iterator1(iterator1),
iterator2(iterator2)
{
assert(iterator1.getEndpoint() < iterator2.getEndpoint());
moveToNextEndpoint();
}
void moveToNextEndpoint() noexcept
{
auto endpoint1 = iterator1.getEndpoint();
auto endpoint2 = iterator2.getEndpoint();
if (!iterator1.isFinished() && endpoint1 < endpoint2)
{
endpoint = endpoint1;
iterator1.moveToNextEndpoint();
}
else
{
endpoint = endpoint2;
iterator2.moveToNextEndpoint();
}
}
bool isFinished() const noexcept
{
return iterator2.isFinished();
}
const Endpoint& getEndpoint() const noexcept
{
return endpoint;
}
};
template <typename Iterator>
FilteringIterator<Iterator> makeFilteringIterator(Iterator iterator, Endpoint::Type type) noexcept
{
return FilteringIterator<Iterator>(iterator, type);
}
static inline FilteringIterator<Iterator> makeFilteringIterator(const Index& index, Endpoint::Type type) noexcept
{
return makeFilteringIterator(Iterator(index), type);
}
template <typename Iterator>
ShiftingIterator<Iterator> makeShiftingIterator(Iterator iterator, int delta) noexcept
{
return ShiftingIterator<Iterator>(iterator, delta);
}
template <typename Iterator>
ShiftingIterator<Iterator> makeShiftingIterator(Iterator iterator, int delta, Endpoint::Type fromType, Endpoint::Type toType) noexcept
{
return ShiftingIterator<Iterator>(iterator, delta, fromType, toType);
}
template <typename Iterator1, typename Iterator2>
MergingIterator<Iterator1, Iterator2> makeMergingIterator(Iterator1 iterator1, Iterator2 iterator2) noexcept
{
return MergingIterator<Iterator1, Iterator2>(iterator1, iterator2);
}
<file_sep>#!/bin/bash
set -e
source ./common.inc.sh
if [ ! "$1" ]
then
echo "ARGUMENTS: <experiment suite name>"
exit 1
fi
RESULTS_DIR="$SCRIPT_DIR/results/$1"
mkdir -p "$RESULTS_DIR"
DISABLED_EXPERIMENTS='ie'
disableLongExperiments()
{
local DATA=`cat "$1" | grep -B 2 -- '-----END RESULTS-----' | head -n 2`
local experiments=(`echo "$DATA" | head -n 1`)
local values=(`echo "$DATA" | tail -n 1`)
for i in `seq 0 $((${#experiments[*]} - 1))`
do
local experiment="${experiments[$i]}"
local time="${values[$i]}"
if [ "$time" != 'nan' ] && (( $(bc -l <<< "${time/e/E} > 20000") ))
then
echo "Disabling experiment $experiment due to the running time of $time s in $1"
DISABLED_EXPERIMENTS="$DISABLED_EXPERIMENTS,$experiment"
fi
done
}
experiment()
{
NAME="$1"
RESULT_FILE="$RESULTS_DIR/$NAME.txt"
if [ ! -f "$RESULT_FILE" ]
then
#echo "Skipping because $RESULT_FILE exists"
# else
echo '---------------------------------------------------------------------------------------'
echo experiment "${@}"
echo '---------------------------------------------------------------------------------------'
"$EXE" "${@:2}" | tee "$RESULTS_DIR/current.txt"
mv "$RESULTS_DIR/current.txt" "$RESULT_FILE"
fi
disableLongExperiments "$RESULT_FILE"
}
experiment latency-ie-flight latency --file "$DATA_DIR/FLIGHTS_DATA_TABLE.txt" --file "$DATA_DIR/FLIGHTS_DATA_TABLE.txt" -
experiment latency-ie-inc latency --file "$DATA_DIR/incumbent-norm.txt" --file "$DATA_DIR/incumbent-norm.txt" -
experiment latency-ie-wi latency --file "$DATA_DIR/webkit-norm.txt" --file "$DATA_DIR/incumbent-norm.txt" -
experiment latency-ie-bi latency --file "$DATA_DIR/big_table-norm.txt" --file "$DATA_DIR/incumbent-norm.txt" -
experiment latency-ie-web latency --file "$DATA_DIR/webkit-norm.txt" --file "$DATA_DIR/webkit-norm.txt" -
experiment latency-ie-big latency --file "$DATA_DIR/big_table-norm.txt" --file "$DATA_DIR/big_table-norm.txt" -
experiment latency-ie-basf latency --basf "$DATA_DIR/basf_nono.import" --basf "$DATA_DIR/basf_nono.import" -
EXPERIMENTS_PREFIX=""
experiments()
{
experiment "$EXPERIMENTS_PREFIX$1"-reverse-during reverse-during "${@:2}"
experiment "$EXPERIMENTS_PREFIX$1"-start-preceding start-preceding "${@:2}"
experiment "$EXPERIMENTS_PREFIX$1"-left-overlap left-overlap "${@:2}"
}
exp-suite()
{
DISABLED_EXPERIMENTS='ie'
for c in 1e3 3.16e3 1e4 3.16e4 1e5 3.16e5 1e6 3.16e6 1e7 3.16e7 1e8 # 3.16e8 1e9
do
# for l in 1e1 1e2 1e3 1e4 1e5 1e6
for l in 1e2 1e4 1e6
do
# if [[ "$c" == "3.16e6" && ("$l" == "1e6") ]]
# then
# continue
# fi
if [[ "$c" == "1e7" && ("$l" == "1e6") ]]
then
continue
fi
if [[ "$c" == "3.16e7" && ("$l" == "1e5" || "$l" == "1e6") ]]
then
continue
fi
if [[ "$c" == "1e8" && ("$l" == "1e4" || "$l" == "1e5" || "$l" == "1e6") ]]
then
continue
fi
if [[ "$c" == "3.16e8" && ("$l" == "1e3" || "$l" == "1e4" || "$l" == "1e5" || "$l" == "1e6") ]]
then
continue
fi
experiments "exp-$c-$l" --exp $c $l --exp $c $l ie
done
done
}
rw-suite()
{
DISABLED_EXPERIMENTS='ie'
experiments rw-flight --file "$DATA_DIR/FLIGHTS_DATA_TABLE.txt" --file "$DATA_DIR/FLIGHTS_DATA_TABLE.txt" ie
experiments rw-inc --file "$DATA_DIR/incumbent-norm.txt" --file "$DATA_DIR/incumbent-norm.txt" ie
experiments rw-wi --file "$DATA_DIR/webkit-norm.txt" --file "$DATA_DIR/incumbent-norm.txt" ie
experiments rw-bi --file "$DATA_DIR/big_table-norm.txt" --file "$DATA_DIR/incumbent-norm.txt" ie
experiments rw-web --file "$DATA_DIR/webkit-norm.txt" --file "$DATA_DIR/webkit-norm.txt" ie
experiments rw-big --file "$DATA_DIR/big_table-norm.txt" --file "$DATA_DIR/big_table-norm.txt" ie
experiments rw-basf --basf "$DATA_DIR/basf_nono.import" --basf "$DATA_DIR/basf_nono.import" ie
}
exp-suite
rw-suite
switchToCounters
EXPERIMENTS_PREFIX="counters-"
rw-suite
switchToEBI
EXPERIMENTS_PREFIX="ebi-"
rw-suite
<file_sep>#pragma once
#include "LMJoin0.h"
//#define leungMuntzJoin leungMuntzJoin2
//#define leungMuntzJoin leungMuntzJoin4
#define leungMuntzJoin leungMuntzJoin5
//#define leungMuntzJoin leungMuntzJoin3
#ifdef COUNTERS
static unsigned long long lmComparisonCount = 0;
#endif
template <typename Consumer>
void leungMuntzStartPrecedingBaseJoin(const Relation& X, const Relation& Y, Consumer&& consumer) noexcept
{
leungMuntzJoin(X, Y,
[] (const Tuple& , const Tuple& ) { return false; },
[] (const Tuple& bufferX, const Tuple& bufferY) { return bufferY.start < bufferX.start; },
[] (const Tuple& x, Timestamp startY)
{
#ifdef COUNTERS
lmComparisonCount++;
#endif
return x.end < startY;
},
[] (const Tuple& y, Timestamp startX)
{
#ifdef COUNTERS
lmComparisonCount++;
#endif
return y.start < startX;
},
consumer
);
}
template <typename Consumer>
void leungMuntzReverseDuringStrictJoin(const Relation& X, const Relation& Y, Consumer&& consumer) noexcept
{
leungMuntzStartPrecedingBaseJoin(
X,
Y,
[&consumer] (const Tuple& x, const Tuple& y)
{
#ifdef COUNTERS
lmCounterBeforeSelection++;
#endif
if (x.start < y.start && y.end < x.end)
{
#ifdef COUNTERS
lmCounterAfterSelection++;
#endif
consumer(x, y);
}
}
);
}
template <typename Consumer>
void leungMuntzStartPrecedingStrictJoin(const Relation& X, const Relation& Y, Consumer&& consumer) noexcept
{
leungMuntzStartPrecedingBaseJoin(
X,
Y,
[&consumer] (const Tuple& x, const Tuple& y)
{
#ifdef COUNTERS
lmCounterBeforeSelection++;
#endif
if (x.start < y.start && y.start < x.end)
{
#ifdef COUNTERS
lmCounterAfterSelection++;
#endif
consumer(x, y);
}
}
);
}
template <typename Consumer>
void leungMuntzLeftOverlapStrictJoin(const Relation& X, const Relation& Y, Consumer&& consumer) noexcept
{
leungMuntzStartPrecedingBaseJoin(
X,
Y,
[&consumer] (const Tuple& x, const Tuple& y)
{
#ifdef COUNTERS
lmCounterBeforeSelection++;
#endif
if (x.start < y.start && y.start < x.end && x.end < y.end)
{
#ifdef COUNTERS
lmCounterAfterSelection++;
#endif
consumer(x, y);
}
}
);
}
<file_sep>#pragma once
#include <vector>
#include <algorithm>
#include "model/Endpoint.h"
#include "model/Relation.h"
class Index : public std::vector<Endpoint>
{
private:
size_t maxOverlappingTupleCount;
public:
Index()
{
}
using std::vector<Endpoint>::const_iterator; // Until CLion fixes bug
Index(const Relation& r)
{
buildFor(r);
}
void buildFor(const Relation& r)
{
reserve(r.size() * 2);
for (size_t i = 0; i < r.size(); i++)
{
emplace_back(r[i].start, Endpoint::Type::START, i);
emplace_back(r[i].end, Endpoint::Type::END, i);
}
std::sort(begin(), end());
calcMaxOverlappingTupleCount();
}
size_t getMaxOverlappingTupleCount() const
{
return maxOverlappingTupleCount;
}
private:
void calcMaxOverlappingTupleCount() noexcept
{
size_t overlappingTupleCount = 0;
size_t maxOverlappingTupleCount = 0;
for (const auto& endpoint : *this)
{
if (endpoint.isStart())
{
overlappingTupleCount++;
maxOverlappingTupleCount = std::max(maxOverlappingTupleCount, overlappingTupleCount);
}
else
overlappingTupleCount--;
}
this->maxOverlappingTupleCount = maxOverlappingTupleCount;
}
};
<file_sep>#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "containers/GaplessHashMap.h"
using testing::UnorderedElementsAre;
TEST(GaplessHashMap, Basic)
{
GaplessHashMap<int, int> map(10);
EXPECT_THAT(map, UnorderedElementsAre());
map.insert(0, 10);
EXPECT_THAT(map, UnorderedElementsAre(10));
map.insert(1, 11);
map.insert(2, 12);
map.insert(5, 15);
EXPECT_THAT(map, UnorderedElementsAre(10, 11, 12, 15));
map.erase(1);
map.erase(5);
EXPECT_THAT(map, UnorderedElementsAre(10, 12));
map.erase(0);
map.erase(2);
EXPECT_THAT(map, UnorderedElementsAre());
map.insert(1, 21);
map.insert(2, 22);
map.insert(5, 25);
EXPECT_THAT(map, UnorderedElementsAre(21, 22, 25));
}
TEST(GaplessHashMap, Grow)
{
GaplessHashMap<int, int> map(2); // hash table size 4
map.insert(0x01, 0x01);
map.insert(0x02, 0x02);
EXPECT_THAT(map, UnorderedElementsAre(0x01, 0x02));
map.insert(0x11, 0x11);
EXPECT_THAT(map, UnorderedElementsAre(0x01, 0x02, 0x11));
}
<file_sep>#pragma once
#include <limits>
#include <algorithm>
template <typename T>
struct Aggregate
{
static_assert(sizeof(long double) >= 10, "long double should be bigger than double");
T max = std::numeric_limits<T>::min();
T min = std::numeric_limits<T>::max();
unsigned long long count = 0;
long double sum = 0;
void add(T value)
{
max = std::max(max, value);
min = std::min(min, value);
sum += (long double) value;
count++;
}
double getAvg()
{
return static_cast<double>(sum / count);
}
};
<file_sep>#pragma once
#include <iostream>
#include <model/RelationGenerator.h>
#include "util/Experiments.h"
#include "algorithms/JoinsInlined.h"
#include "algorithms/Joins.h"
template <typename Code>
static void timer(Code code)
{
Timer timer;
auto result = code();
timer.stop();
std::cout << result << "\t" << timer.getElapsedTimeInSeconds() << std::endl;
}
static void mainBefore(Arguments& arguments)
{
auto R = RelationGenerator::generateUniform(1'000'000, 1, 19, 1, 100'000, 123123);
auto S = RelationGenerator::generateUniform(1'000'000, 1, 19, 1, 100'000, 123);
Index indexR(R);
Index indexS(S);
R.setIndex(indexR);
S.setIndex(indexS);
std::string implementation = arguments.getCurrentArgAndSkipIt("Implementation (normal or inlined)");
bool isInlined = implementation == "inlined";
for (size_t i = 1; i < 20; i++)
{
std::cout << i << '\t';
if (isInlined)
{
timer([&]
{
return beforeJoinInlined(R, S, 3);
});
}
else
{
timer([&]
{
Timestamp result = 0;
beforeJoin(R, S, 3, [&] (const Tuple& r, const Tuple& s) noexcept
{
result += r.start + s.end;
});
return result;
});
}
}
}
<file_sep>#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
using std::string;
using std::ifstream;
using std::ofstream;
using std::ios_base;
using std::setw;
using std::flush;
using std::left;
using std::exception;
using std::cerr;
using std::endl;
using std::cout;
using std::vector;
static const char* result_dir;
static const char* output_dir;
static const char* prefix = "";
//unsigned ceil_div(unsigned a, unsigned b)
//{
// return (a + b - 1) / b;
//}
auto get_header_and_result_lines(const string& filename)
{
cout << "Reading file " << filename << flush;
ifstream in(string(result_dir) + '/' + filename);
if (!in)
{
cout << " Not found" << endl;
return make_pair(string(), string());
}
else
cout << endl;
string line;
while (getline(in, line) && line != "-----BEGIN RESULTS-----") { /* do nothing */ }
string header;
getline(in, header);
string result;
getline(in, result);
return make_pair(header, result);
}
class Task
{
public:
string dataset;
string filename;
};
void generate_data_file(string output_file_name, const vector<Task>& tasks)
{
output_file_name = prefix + output_file_name;
cout << "Writing file " << output_file_name << endl;
ofstream out;
out.exceptions(ios_base::failbit | ios_base::badbit);
out.open(string(output_dir) + '/' + output_file_name);
string global_header;
out << "dataset ";
for (auto task : tasks)
{
string header;
string result;
tie(header, result) = get_header_and_result_lines(prefix + task.filename);
if (result.empty())
continue;
if (global_header.empty())
{
global_header = header;
out << header << '\n';
}
if (header != global_header)
{
cout << "Invalid header\n"
<< "Expected: " << global_header << '\n'
<< "Received: " << header << endl;
}
out << setw(10) << left << task.dataset << ' ' << result << '\n';
}
}
void vary_cardinality(const string& output_file_name,
const string& result_file_prefix,
const string& result_file_suffix)
{
generate_data_file(output_file_name,
{
{"1.00e3", result_file_prefix + "1e3" + result_file_suffix},
{"3.16e3", result_file_prefix + "3.16e3" + result_file_suffix},
{"1.00e4", result_file_prefix + "1e4" + result_file_suffix},
{"3.16e4", result_file_prefix + "3.16e4" + result_file_suffix},
{"1.00e5", result_file_prefix + "1e5" + result_file_suffix},
{"3.16e5", result_file_prefix + "3.16e5" + result_file_suffix},
{"1.00e6", result_file_prefix + "1e6" + result_file_suffix},
{"3.16e6", result_file_prefix + "3.16e6" + result_file_suffix},
{"1.00e7", result_file_prefix + "1e7" + result_file_suffix},
{"3.16e7", result_file_prefix + "3.16e7" + result_file_suffix},
{"1.00e8", result_file_prefix + "1e8" + result_file_suffix},
{"3.16e8", result_file_prefix + "3.16e8" + result_file_suffix},
{"1.00e9", result_file_prefix + "1e9" + result_file_suffix},
});
}
void vary_cardinality_and_operator(const string& output_file_name, const string& result_file_middle)
{
vary_cardinality("exp-reverse-during-" + output_file_name, "exp-", "-" + result_file_middle + "-reverse-during.txt");
vary_cardinality("exp-start-preceding-" + output_file_name, "exp-", "-" + result_file_middle + "-start-preceding.txt");
vary_cardinality("exp-left-overlap-" + output_file_name, "exp-", "-" + result_file_middle + "-left-overlap.txt");
}
void vary_rw_dataset(const string& output_file_name,
const string& result_file_prefix,
const string& result_file_suffix)
{
generate_data_file(output_file_name,
{
{"flight", result_file_prefix + "flight" + result_file_suffix},
{"inc", result_file_prefix + "inc" + result_file_suffix},
{"web", result_file_prefix + "web" + result_file_suffix},
{"basf", result_file_prefix + "basf" + result_file_suffix},
{"feed", result_file_prefix + "big" + result_file_suffix},
// {"dasa", result_file_prefix + "dasa" + result_file_suffix},
{"wi", result_file_prefix + "wi" + result_file_suffix},
{"fi", result_file_prefix + "bi" + result_file_suffix},
});
}
void rwSuite()
{
vary_rw_dataset("rw-reverse-during.txt", "rw-", "-reverse-during.txt");
vary_rw_dataset("rw-start-preceding.txt", "rw-", "-start-preceding.txt");
vary_rw_dataset("rw-left-overlap.txt", "rw-", "-left-overlap.txt");
}
void expSuite()
{
vary_cardinality_and_operator("w1e2.txt", "1e2");
vary_cardinality_and_operator("w1e4.txt", "1e4");
vary_cardinality_and_operator("w1e6.txt", "1e6");
}
void main__()
{
output_dir = "../iseql-article/data";
// result_dir = "results/dacha4";
// expSuite();
// return;
result_dir = "results/dacha1";
expSuite();
rwSuite();
generate_data_file("latency.txt",
{
{"flight", "latency-ie-flight.txt"},
{"inc", "latency-ie-inc.txt" },
{"web", "latency-ie-web.txt" },
{"basf", "latency-ie-basf.txt" },
{"feed", "latency-ie-big.txt" },
{"wi", "latency-ie-wi.txt" },
{"fi", "latency-ie-bi.txt" },
});
prefix = "counters-";
rwSuite();
prefix = "ebi-";
rwSuite();
}
int main()
{
try
{
main__();
}
catch (const exception& e)
{
cerr << "Exception: " << e.what() << endl;
return EXIT_FAILURE;
}
catch (...)
{
cerr << "Unknown exception occurred" << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<file_sep>#!/bin/bash
set -e
source ./common.inc.sh
build()
(
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"
cmake -DCMAKE_BUILD_TYPE=Release "$BUILD_DIR_SOURCE" "$@"
make -j 4 iseql
)
switchToRelease
build
switchToCounters
build -DCOUNTERS=ON
switchToEBI
build -DEBI=ON
<file_sep>#pragma once
#include "model/Interval.h"
class Tuple : public Interval
{
public:
int id;
// char data[32 - 12];
public:
Tuple() noexcept {}
Tuple(Timestamp start, Timestamp end) noexcept
:
Interval(start, end)
{
}
Tuple(Timestamp start, Timestamp end, int id) noexcept
:
Interval(start, end),
id(id)
{
}
friend std::ostream& operator << (std::ostream &out, const Tuple& tuple)
{
return out << static_cast<const Interval&>(tuple) << ' ' << tuple.id;
}
int getId() const noexcept
{
return id;
}
};
<file_sep>#pragma once
#include <iostream>
#include "model/Index.h"
#include "model/Relation.h"
#include "containers/GaplessHashMap.h"
//void afterJoin(const Relation& R, const Relation& S, Timestamp delta, const Consumer& consumer) noexcept
//{
// beforeJoin(S, R, delta, makeReversingConsumer(consumer));
//}
static Timestamp beforeJoinInlined(const Relation& R, const Relation& S, Timestamp delta)
{
Timestamp result = 0;
GaplessHashMap<TID, Tuple> activeR(1024);
// std::unordered_map<TID, Tuple> activeR;
const auto& indexR = R.getIndex();
const auto& indexS = S.getIndex();
const auto indexREnd = indexR.end();
const auto indexSEnd = indexS.end();
auto itR1 = indexR.begin();
auto itR2 = indexR.begin();
auto itS = indexS.begin();
const auto itR1Shift = Endpoint::calculateShiftArgument(0, Endpoint::Type::END, Endpoint::Type::START);
const auto itR2Shift = Endpoint::calculateShiftArgument(delta + 1);
while (itR1->isStart())
++itR1;
Endpoint endpointR = itR1->shiftedBy(itR1Shift);
do
++itR1;
while (itR1->isStart());
while (itR2->isStart())
++itR2;
while (itS->isEnd()) // useless, because any index starts with a 'start' endpoint
++itS;
for (;;)
{
if (endpointR <= *itS)
{
TID tid = endpointR.getTID();
if (endpointR.isStart())
activeR.insert(tid, R[tid]);
else
activeR.erase(tid);
auto endpointR1 = itR1->shiftedBy(itR1Shift);
auto endpointR2 = itR2->shiftedBy(itR2Shift);
if (itR1 != indexREnd && endpointR1 < endpointR2)
{
endpointR = endpointR1;
do
++itR1;
while (itR1 != indexREnd && itR1->isStart());
}
else
{
endpointR = endpointR2;
do
++itR2;
while (itR2 != indexREnd && itR2->isStart());
}
if (itR2 == indexREnd)
break;
}
else
{
const Tuple& s = S[itS->getTID()];
for (const auto& r : activeR)
{
// std::cout << "Result " << r.second << " " << s << std::endl;
result += r.start + s.end;
}
do
++itS;
while (itS != indexSEnd && itS->isEnd());
if (itS == indexSEnd)
break;
}
}
return result;
}
<file_sep>#pragma once
#include <string>
#include <sstream>
#include <vector>
static void split(const std::string& s, char delimiter, std::vector<std::string>& result)
{
std::istringstream ss(s);
size_t i = 0;
while (i < result.size() && std::getline(ss, result[i], delimiter))
i++;
if (i < result.size())
{
result.resize(i);
return;
}
if (ss.eof())
return;
std::string item;
while (std::getline(ss, item, delimiter))
result.emplace_back(std::move(item));
}
inline static std::vector<std::string> split(const std::string& s, char delimiter)
{
std::vector<std::string> result;
split(s, delimiter, result);
return result;
}
<file_sep>add_subdirectory(lib/googletest)
include_directories(../src)
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-global-constructors")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-weak-vtables")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-exit-time-destructors")
endif()
if(COMMAND cmake_policy)
cmake_policy(SET CMP0003 NEW)
endif(COMMAND cmake_policy)
enable_testing()
add_executable(tests
model/IntervalTest.cpp
algorithms/IEJoinTest.cpp
algorithms/JoinsTest.cpp
algorithms/JoinsTest.cpp
algorithms/JoinsInlinedTest.cpp
algorithms/JoinsComparison.cpp
containers/GaplessHashMapTest.cpp
../src/model/RelationGenerator.h)
target_link_libraries(tests gmock_main)
add_test(NAME tests COMMAND tests)
<file_sep>#include <set>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "algorithms/IEJoin.h"
using testing::Pair;
using testing::UnorderedElementsAre;
static Relation R = {
{140, 1009, 1},
{100, 1012, 2},
{ 90, 1005, 3},
};
static Relation S = {
{100, 1006, 1},
{140, 1011, 2},
{ 80, 1010, 3},
{ 90, 1005, 4},
};
TEST(IEJoinTests, ArticleExample)
{
IEJoinOperator2<GetIntervalStart, Operator::Less, GetIntervalStart,
GetIntervalEnd, Operator::Greater, GetIntervalEnd> join{R, S};
std::vector<std::pair<int, int>> result;
join.join([&] (const Tuple& r, const Tuple& s)
{
result.emplace_back(r.getId(), s.getId());
// std::cout << r.getId() << ' ' << s.getId() << std::endl;
});
EXPECT_THAT(result, UnorderedElementsAre(
Pair(2, 2)
));
}
<file_sep>#pragma once
#include <iostream>
#include <fstream>
#include <random>
#include "model/Relation.h"
#include "util/String.h"
class RelationGenerator
{
private:
typedef std::minstd_rand RandomEngine;
public:
typedef RandomEngine::result_type SeedType;
static Relation generateUniform(size_t n, Timestamp durationMin, Timestamp durationMax, Timestamp domainMin, Timestamp domainMax, SeedType seed = RandomEngine::default_seed)
{
Relation result;
result.reserve(n);
assert(durationMin >= 1);
assert(durationMin <= durationMax);
assert(durationMax <= domainMax - domainMin + 1);
assert(domainMin <= domainMax);
typedef std::uniform_int_distribution<Timestamp> Distribution;
RandomEngine generator(seed);
for (size_t i = 0; i < n; i++)
{
Timestamp duration = Distribution{durationMin, durationMax}(generator);
Timestamp begin = Distribution{domainMin, domainMax - duration + 1}(generator);
Timestamp end = begin + duration;
result.emplace_back(begin, end, i);
}
return result;
}
// template <typename OffsetDistribution, typename DurationDistribution>
// static Relation generate(size_t n, OffsetDistribution& offsetDistribution,
// DurationDistribution& durationDistribution, SeedType seed = RandomEngine::default_seed)
// {
// Relation result;
// result.reserve(n);
//
// RandomEngine generator(seed);
//
// for (size_t i = 0; i < n; i++)
// {
// Timestamp duration = durationDistribution(generator);
// Timestamp begin = offsetDistribution(generator);
// Timestamp end = begin + duration;
// result.emplace_back(begin, end);
// }
//
// return result;
// }
static Relation generateExponential(size_t n, double lambda, Timestamp domainMin, Timestamp domainMax, SeedType seed = RandomEngine::default_seed)
{
Relation result;
result.reserve(n);
assert(domainMin <= domainMax);
std::exponential_distribution<double> lengthDistribution(lambda);
typedef std::uniform_int_distribution<Timestamp> OffsetDistribution;
RandomEngine generator(seed);
// Tuple::Value uCharPayload = 0;
for (size_t i = 0; i < n; i++)
{
double length;
do
{
length = lengthDistribution(generator);
}
while (length >= domainMax - domainMin + 1); // length in [0, domainWidth)
Timestamp beginAndEndDifference = (Timestamp) length;
Timestamp begin = OffsetDistribution{domainMin, domainMax - beginAndEndDifference}(generator);
Timestamp end = begin + beginAndEndDifference;
result.emplace_back(begin, end + 1, i);
// result.back().setValue(uCharPayload);
// ++uCharPayload;
}
return result;
}
static Relation loadFromClosedIntervalFile(const char* filename)
{
std::ifstream in(filename);
if (!in)
{
std::cerr << "Cannot open file " << filename << std::endl;
exit(1);
}
Relation result;
Timestamp start, end;
// Tuple::Value uCharPayload = 0;
while (in >> start >> end)
{
assert(start <= end);
result.emplace_back(start, end + 1);
// result.back().setValue(uCharPayload);
// ++uCharPayload;
}
return result;
}
static Relation loadFromDASATemperatureFile(const char* filename)
{
std::ifstream in(filename);
if (!in)
{
std::cerr << "Cannot open file " << filename << std::endl;
exit(1);
}
Relation result;
Timestamp start, end;
double value;
while (in >> start >> end >> value)
{
assert(start <= end);
int intValue = (int) ((value + 100) * 1000);
result.emplace_back(start, end, intValue);
}
return result;
}
// echo 'copy (select EXTRACT(EPOCH FROM measured_at)::INT,
// EXTRACT(EPOCH FROM measured_at)::INT + 300, measured_value from measurements
// where active and value_type_id = 1 order by measured_at) to stdout' | psql > asd.txt
// static Relation loadFrom
static Relation loadFromBASFFile(const char* filename)
{
std::ifstream in(filename);
if (!in)
{
std::cerr << "Cannot open file " << filename << std::endl;
exit(1);
}
int columnCount;
in >> columnCount;
for (int i = 0; i < columnCount; i++) // skip header
{
std::string s;
in >> s >> s;
}
Relation result;
std::string line;
std::vector<std::string> fields;
while (true)
{
in >> line;
if (line[0] == '-')
break;
split(line, '|', fields);
auto start = std::stoi(fields.at(1));
auto end = std::stoi(fields.at(2)) + 1;
auto value = std::stoi(fields.at(5)); // nolines
result.emplace_back(start, end, value);
}
return result;
}
};
<file_sep>#pragma once
#include <cstdlib>
#include <cstdio>
template<typename T>
void check_malloc_result(T* result, size_t size = 1) noexcept
{
if (!result)
{
std::fprintf(stderr, "Failed to allocate %zu object(s) of size %zu\n", size, sizeof(T));
std::abort();
}
}
template<typename T>
T* array_calloc(size_t size) noexcept
{
auto result = static_cast<T*>(std::calloc(size, sizeof(T)));
check_malloc_result(result, size);
return result;
}
template<typename T>
T* array_malloc(size_t size) noexcept
{
auto result = static_cast<T*>(std::malloc(size * sizeof(T)));
check_malloc_result(result, size);
return result;
}
template<typename T>
T* array_realloc(T* array, size_t size) noexcept
{
auto result = static_cast<T*>(std::realloc(array, size * sizeof(T)));
check_malloc_result(result, size);
return result;
}
template <typename T>
T next_power_of_two(T x)
{
T result = 2;
while (result < x)
result <<= 1;
return result;
}
//template <typename T>
//T ceil_div(T a, T b)
//{
// static_assert(std::is_unsigned<T>::value, "ceil_div works only with unsigned types");
// return (a + b - 1) / b;
//}
<file_sep>#include <set>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "algorithms/IEJoin.h"
#include "algorithms/Joins.h"
#include "algorithms/LMJoins.h"
using testing::Test;
using testing::Pair;
using testing::UnorderedElementsAre;
static Relation R = {
{1, 6, 1},
{1, 11, 2},
{7, 12, 3},
{9, 11, 4},
};
static Relation S = {
{2, 3, 1},
{3, 13, 2},
{4, 6, 3},
{5, 7, 4},
{8, 10, 5},
};
static Index indexR(R);
static Index indexS(S);
static std::set<std::pair<int, int>> result;
static auto consumer = [] (const Tuple& r, const Tuple& s)
{
result.emplace(r.getId(), s.getId());
};
class Joins : public Test
{
protected:
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
static void SetUpTestCase()
{
R.setIndex(indexR);
S.setIndex(indexS);
}
#pragma clang diagnostic pop
virtual void TearDown()
{
// for (const auto& item : result)
// std::cout << item.first << ' ' << item.second << std::endl;
result.clear();
}
};
TEST_F(Joins, startPreceding)
{
startPrecedingJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(1, 2),
Pair(1, 3),
Pair(1, 4),
Pair(2, 1),
Pair(2, 2),
Pair(2, 3),
Pair(2, 4),
Pair(2, 5),
Pair(3, 5)
));
}
TEST_F(Joins, startPrecedingStrict)
{
startPrecedingStrictJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(1, 2),
Pair(1, 3),
Pair(1, 4),
Pair(2, 1),
Pair(2, 2),
Pair(2, 3),
Pair(2, 4),
Pair(2, 5),
Pair(3, 5)
));
}
TEST_F(Joins, startPrecedingStrictIE)
{
ieJoinStartPrecedingStrictJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(1, 2),
Pair(1, 3),
Pair(1, 4),
Pair(2, 1),
Pair(2, 2),
Pair(2, 3),
Pair(2, 4),
Pair(2, 5),
Pair(3, 5)
));
}
TEST_F(Joins, reverseStartPreceding)
{
reverseStartPrecedingJoin(S, R, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(2, 1),
Pair(3, 1),
Pair(4, 1),
Pair(1, 2),
Pair(2, 2),
Pair(3, 2),
Pair(4, 2),
Pair(5, 2),
Pair(5, 3)
));
}
TEST_F(Joins, startPrecedingWithDelta)
{
startPrecedingJoin(R, S, 1, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(2, 1),
Pair(3, 5)
));
}
TEST_F(Joins, endFollowing)
{
endFollowingJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(1, 3),
Pair(2, 1),
Pair(2, 3),
Pair(2, 4),
Pair(2, 5),
Pair(3, 5),
Pair(4, 5)
));
}
TEST_F(Joins, endFollowingStrict)
{
endFollowingStrictJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(2, 1),
Pair(2, 3),
Pair(2, 4),
Pair(2, 5),
Pair(3, 5),
Pair(4, 5)
));
}
TEST_F(Joins, reverseEndFollowing)
{
reverseEndFollowingJoin(S, R, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(3, 1),
Pair(1, 2),
Pair(3, 2),
Pair(4, 2),
Pair(5, 2),
Pair(5, 3),
Pair(5, 4)
));
}
TEST_F(Joins, endFollowingWithEpsilon)
{
endFollowingJoin(R, S, 1, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 3),
Pair(2, 5),
Pair(4, 5)
));
}
TEST_F(Joins, leftOverlap)
{
leftOverlapJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 2),
Pair(1, 3),
Pair(1, 4),
Pair(2, 2)
));
}
TEST_F(Joins, leftOverlapStrict)
{
leftOverlapStrictJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 2),
Pair(1, 4),
Pair(2, 2)
));
}
TEST_F(Joins, leftOverlapWithDelta)
{
leftOverlapJoin(R, S, 2, UNBOUND, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 2),
Pair(2, 2)
));
}
TEST_F(Joins, rightOverlap)
{
rightOverlapJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(4, 5)
));
}
TEST_F(Joins, rightOverlapWithEpsilon)
{
rightOverlapJoin(R, S, UNBOUND, 0, consumer);
EXPECT_THAT(result, UnorderedElementsAre());
}
TEST_F(Joins, during)
{
duringJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(3, 2),
Pair(4, 2)
));
}
TEST_F(Joins, duringWithDelta)
{
duringJoin(R, S, 4, UNBOUND, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(3, 2)
));
}
TEST_F(Joins, reverseDuring)
{
reverseDuringJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(1, 3),
Pair(2, 1),
Pair(2, 3),
Pair(2, 4),
Pair(2, 5),
Pair(3, 5)
));
}
TEST_F(Joins, reverseDuringStrict)
{
reverseDuringStrictJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(2, 1),
Pair(2, 3),
Pair(2, 4),
Pair(2, 5),
Pair(3, 5)
));
}
TEST_F(Joins, reverseDuringStrictLM)
{
leungMuntzReverseDuringStrictJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(2, 1),
Pair(2, 3),
Pair(2, 4),
Pair(2, 5),
Pair(3, 5)
));
}
TEST_F(Joins, reverseDuringStrictIE)
{
ieJoinReverseDuringStrictJoin(R, S, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(2, 1),
Pair(2, 3),
Pair(2, 4),
Pair(2, 5),
Pair(3, 5)
));
}
TEST_F(Joins, reverseDuringWithDeltaAndEpsilon)
{
reverseDuringJoin(R, S, 4, 3, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 1),
Pair(1, 3),
Pair(3, 5)
));
}
TEST_F(Joins, before)
{
beforeJoin(R, S, 2, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(1, 5)
));
}
TEST_F(Joins, after)
{
afterJoin(R, S, 1, consumer);
EXPECT_THAT(result, UnorderedElementsAre(
Pair(3, 3),
Pair(3, 4)
));
}
<file_sep>#include <gtest/gtest.h>
#include <model/RelationGenerator.h>
#include "algorithms/IEJoin.h"
#include "algorithms/Joins.h"
#include "algorithms/LMJoins.h"
#include "util/Timer.h"
using testing::Test;
static Relation R;
static Relation S;
static Index indexR;
static Index indexS;
static Timestamp result;
static auto consumer = [] (const Tuple& r, const Tuple& s)
{
result += r.start + s.end;
};
class JoinsComparison : public Test
{
protected:
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
static void SetUpTestCase()
{
R = RelationGenerator::generateUniform(3'000, 1, 1000, 1, 10'000, 5904595);
S = RelationGenerator::generateUniform(3'000, 1, 1000, 1, 10'000, 58534);
R.sort();
S.sort();
indexR.buildFor(R);
indexS.buildFor(S);
R.setIndex(indexR);
S.setIndex(indexS);
}
#pragma clang diagnostic pop
};
TEST_F(JoinsComparison, reverseDuringStrict)
{
Timer t;
// result = 0;
// for (const auto& r : R)
// {
// for (const auto& s : S)
// {
// if (r.start < s.start && s.end < r.end)
// consumer(r, s);
// }
// }
// auto naiveResult = result;
// t.stopAndPrint();
// std::cout << " " << result << "\n";
result = 0;
reverseDuringStrictJoin(R, S, consumer);
auto normalResult = result;
t.stopAndPrint();
std::cout << " " << result << "\n";
t.start();
result = 0;
leungMuntzReverseDuringStrictJoin(R, S, consumer);
auto lmResult = result;
t.stopAndPrint();
std::cout << " " << result << "\n";
t.start();
result = 0;
ieJoinReverseDuringStrictJoin(R, S, consumer);
auto ieResult = result;
t.stopAndPrint();
std::cout << " " << result << "\n";
EXPECT_EQ(normalResult, lmResult);
EXPECT_EQ(normalResult, ieResult);
}
TEST_F(JoinsComparison, startPrecedingStrict)
{
Timer t;
result = 0;
startPrecedingStrictJoin(R, S, consumer);
auto normalResult = result;
t.stopAndPrint();
std::cout << " " << result << "\n";
t.start();
result = 0;
leungMuntzStartPrecedingStrictJoin(R, S, consumer);
auto lmResult = result;
t.stopAndPrint();
std::cout << " " << result << "\n";
t.start();
result = 0;
ieJoinStartPrecedingStrictJoin(R, S, consumer);
auto ieResult = result;
t.stopAndPrint();
std::cout << " " << result << "\n";
EXPECT_EQ(normalResult, lmResult);
EXPECT_EQ(normalResult, ieResult);
}
TEST_F(JoinsComparison, leftOverlapStrict)
{
Timer t;
result = 0;
leftOverlapStrictJoin(R, S, consumer);
auto normalResult = result;
t.stopAndPrint();
std::cout << " " << result << "\n";
t.start();
result = 0;
leungMuntzLeftOverlapStrictJoin(R, S, consumer);
auto lmResult = result;
t.stopAndPrint();
std::cout << " " << result << "\n";
EXPECT_EQ(normalResult, lmResult);
}
<file_sep>cmake_minimum_required(VERSION 2.4)
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
endif (POLICY CMP0048)
project(iseql-cpp CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")
#set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -D_LIBCPP_DEBUG=0 -D_LIBCPP_DEBUG2=0")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wpedantic -Wall -Wextra -Wconversion -Wdisabled-optimization")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-pragmas")
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Weverything")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-date-time")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-shadow")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-c++98-compat")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-c++98-compat-pedantic")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-old-style-cast")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-float-equal")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-padded")
endif()
OPTION(COUNTERS "Enable algorithm performance counters" OFF)
if (COUNTERS)
message("## Enabling counters ##")
add_definitions(-DCOUNTERS)
endif()
OPTION(EBI "Enable EBI algorithm instead of LEBI" OFF)
if (EBI)
message("## Enabling EBI ##")
add_definitions(-DEBI)
endif()
add_subdirectory(src)
add_subdirectory(test)
add_subdirectory(result-processor)
SET(MY_REMOTE_LOCATION im:iseql-cpp)
SET(IL_REMOTE_LOCATION im:iseql-il)
add_custom_target(upload-to-ironmaiden
COMMAND rsync -aPvz
--exclude='.*' --exclude=results --exclude=target
${CMAKE_CURRENT_SOURCE_DIR}/
${MY_REMOTE_LOCATION})
add_custom_target(upload-to-ironlady
COMMAND rsync -aPvz
--exclude='.*' --exclude=results --exclude=target
${CMAKE_CURRENT_SOURCE_DIR}/
${IL_REMOTE_LOCATION})
add_custom_target(downloads-results-from-ironmaiden
COMMAND rsync -aPvzL
--exclude='.*'
${MY_REMOTE_LOCATION}/results/
${CMAKE_CURRENT_SOURCE_DIR}/results)
<file_sep>#pragma once
#include <chrono>
#include <iostream>
#include <iomanip>
class Timer
{
private:
using Clock = std::chrono::high_resolution_clock;
Clock::time_point start_time, stop_time;
public:
Timer()
{
start();
}
void start()
{
start_time = Clock::now();
}
double getElapsedTimeInSeconds()
{
return std::chrono::duration<double>(stop_time - start_time).count();
}
double stop()
{
stop_time = Clock::now();
return getElapsedTimeInSeconds();
}
void print()
{
std::cout << std::fixed << std::setprecision(3) << getElapsedTimeInSeconds();
}
double stopAndPrint()
{
auto result = stop();
print();
return result;
}
};
<file_sep>#pragma once
#include "Joins1.h"
template <typename Consumer>
void startPrecedingJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
joinBySStart(R, S, Iterator(R.getIndex()), consumer);
}
template <typename Consumer>
void startPrecedingStrictJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
joinBySStartStrict(R, S, Iterator(R.getIndex()), consumer);
}
template <typename Consumer>
void endFollowingJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
joinBySEnd(R, S, Iterator(R.getIndex()), consumer);
}
template <typename Consumer>
void endFollowingStrictJoin(const Relation& R, const Relation& S, const Consumer& consumer) noexcept
{
joinBySEndStrict(R, S, Iterator(R.getIndex()), consumer);
}
template <typename Consumer>
void beforeJoin(const Relation& R, const Relation& S, Timestamp delta, const Consumer& consumer) noexcept
{
constexpr auto START = Endpoint::Type::START;
constexpr auto END = Endpoint::Type::END;
assert(delta >= 0);
const Index& index = R.getIndex();
joinBySStart(
R,
S,
makeMergingIterator(
makeShiftingIterator(makeFilteringIterator(index, END), 0, END, START), // r.end -> r.start
makeShiftingIterator(makeFilteringIterator(index, END), delta + 1) // r.end + delta + 1 -> r.end
),
consumer
);
}
<file_sep>#pragma once
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <tuple>
#include <cstddef>
#include "model/Relation.h"
enum class Operator { Greater, GreaterOrEquals, Less, LessOrEquals };
struct GetIntervalStart
{
Timestamp operator () (const Interval& interval) const noexcept
{
return interval.start;
}
};
struct GetIntervalEnd
{
Timestamp operator () (const Interval& interval) const noexcept
{
return interval.end;
}
};
class BitVector
{
public:
static constexpr size_t END = std::numeric_limits<size_t>::max();
private:
std::vector<bool> bits;
public:
BitVector(size_t size)
:
bits(size)
{
}
void setBit(size_t i) noexcept
{
bits[i] = true;
}
size_t findFirstBitInRange(size_t offsetBegin, size_t offsetEnd) noexcept
{
auto begin = bits.begin() + static_cast<ptrdiff_t>(offsetBegin);
auto end = bits.begin() + static_cast<ptrdiff_t>(offsetEnd);
auto pos = std::find(begin, end, true);
if (pos == end)
return END;
else
return static_cast<size_t>(std::distance(bits.begin(), pos));
}
size_t size() const noexcept
{
return bits.size();
}
};
class IndexedBitVector
{
private:
static constexpr size_t CHUNK_SIZE = 1024;
BitVector bits;
BitVector index;
size_t maxIndexPos = 0;
public:
IndexedBitVector(size_t size)
:
bits(size),
index((size + CHUNK_SIZE - 1) / CHUNK_SIZE)
{
}
void setBit(size_t i) noexcept
{
bits.setBit(i);
auto indexPos = i / CHUNK_SIZE;
index.setBit(indexPos);
maxIndexPos = std::max(maxIndexPos, indexPos);
}
size_t findFirstBitStartingAt(size_t offsetBegin) noexcept
{
auto indexBegin = offsetBegin / CHUNK_SIZE;
if (indexBegin > maxIndexPos)
return BitVector::END;
auto indexPos = index.findFirstBitInRange(indexBegin, maxIndexPos + 1);
if (indexPos == BitVector::END)
return BitVector::END;
auto offsetChunkBegin = indexPos * CHUNK_SIZE;
offsetBegin = std::max(offsetBegin, offsetChunkBegin);
auto offsetEnd = std::min(bits.size(), offsetChunkBegin + CHUNK_SIZE);
auto result = bits.findFirstBitInRange(offsetBegin, offsetEnd);
if (result == BitVector::END && offsetEnd != bits.size())
return findFirstBitStartingAt(offsetEnd);
else
return result;
}
};
/**
* The IEJoin algorithm described in the article (<NAME>at et al. Fast and scalable
* inequality joins. VLDB journal, 2017) is incorrect. First of all, there is a typo in
* line 17: it should be size(L2') or size(L1') or simply n, not size(L2). But that's
* not the main problem. It contains more principal bugs. It marks marks those tuples suitable
* for reporting for which the first condition is ‘<=’ when ‘<’ is used at the operator.
* And it does not support relations with non-distinct attributes. Is magically works
* for the example data, but fails for other data.
*
* This is a fixed version that only supports ‘<’ as the first and ‘>’ as the second operator.
*/
template <typename GetRA1, Operator op1, typename GetSA1,
typename GetRA2, Operator op2, typename GetSA2>
class IEJoinOperator2
{
private:
static_assert(op1 == Operator::Less && op2 == Operator::Greater,
"This implementation only supports ‘<’ as the first and ‘>’ as the second operator.");
struct Element
{
Timestamp value;
int id;
Tuple tuple;
Element(Timestamp value, bool isOuter, int id, const Tuple& tuple)
:
value(value),
id(isOuter ? id : -id),
tuple(tuple)
{
}
bool isOuter() const noexcept
{
return id > 0;
}
bool isInner() const noexcept
{
return id < 0;
}
};
using Elements = std::vector<Element>;
using Indices = std::vector<unsigned>;
Elements L1;
Elements L2;
Indices P;
IndexedBitVector B;
public:
IEJoinOperator2(const Relation& R, const Relation& S)
:
B(R.size() + S.size())
{
relationsToElements<GetRA1, GetSA1>(R, S, L1);
relationsToElements<GetRA2, GetSA2>(R, S, L2);
std::sort(L1.begin(), L1.end(), [] (const Element& lhs, const Element& rhs) noexcept
{
return std::make_tuple(lhs.value, lhs.isOuter()) < std::make_tuple(rhs.value, rhs.isOuter());
});
std::sort(L2.begin(), L2.end(), [] (const Element& lhs, const Element& rhs) noexcept
{
return std::make_tuple(lhs.value, lhs.isInner()) < std::make_tuple(rhs.value, rhs.isInner());
});
computePermutations(L2, L1, P);
}
template <typename Consumer>
void join(Consumer&& consumer)
{
for (size_t i2 = 0; i2 < L2.size(); i2++)
{
if (!L2[i2].isOuter())
continue;
for (size_t j2 = 0; j2 < i2; j2++)
{
if (!L2[j2].isInner())
continue;
B.setBit(P[j2]);
}
auto i1 = static_cast<size_t>(P[i2]);
for (;;)
{
i1 = B.findFirstBitStartingAt(i1 + 1);
if (i1 == BitVector::END)
break;
consumer(L2[i2].tuple, L1[i1].tuple);
}
}
}
private:
template <typename GetRValue, typename GetSValue>
static void relationsToElements(const Relation& R, const Relation& S, std::vector<Element>& result)
{
GetRValue getRValue;
GetSValue getSValue;
result.reserve(R.size() + S.size());
for (size_t i = 0; i < R.size(); i++)
{
const auto& tuple = R[i];
result.push_back(Element{getRValue(tuple), true, (int) i + 1, tuple});
}
for (size_t i = 0; i < S.size(); i++)
{
const auto& tuple = S[i];
result.push_back(Element{getSValue(tuple), false, (int) i + 1, tuple});
}
}
static void computePermutations(const Elements& from, const Elements& to, Indices& result)
{
auto n = from.size();
std::unordered_map<int, unsigned> map;
map.reserve(n);
for (size_t i = 0; i < n; i++)
{
map.emplace(to[i].id, (unsigned) i);
}
result.reserve(n);
for (const Element& item : from)
{
result.push_back(map[item.id]);
}
}
};
using IEJoinStartPrecedingStrict = IEJoinOperator2<
GetIntervalStart, Operator::Less, GetIntervalStart,
GetIntervalEnd, Operator::Greater, GetIntervalStart>;
using IEJoinReverseDuringStrict = IEJoinOperator2<
GetIntervalStart, Operator::Less, GetIntervalStart,
GetIntervalEnd, Operator::Greater, GetIntervalEnd>;
template <typename Consumer>
void ieJoinStartPrecedingStrictJoin(const Relation& R, const Relation& S, Consumer&& consumer) noexcept
{
IEJoinStartPrecedingStrict(R, S).join(consumer);
}
template <typename Consumer>
void ieJoinReverseDuringStrictJoin(const Relation& R, const Relation& S, Consumer&& consumer) noexcept
{
IEJoinReverseDuringStrict(R, S).join(consumer);
}
<file_sep>#pragma once
#include <ostream>
#include <algorithm>
#include "model/Tuple.h"
typedef unsigned TID;
class Endpoint
{
public:
enum class Type : Timestamp {END = 0, START = 1};
private:
Timestamp timestampAndType;
TID tid;
public:
Endpoint() { }
Endpoint(Timestamp timestampAndType, TID tid)
:
timestampAndType(timestampAndType),
tid(tid)
{
}
public:
Endpoint(Timestamp timestamp, Type type, TID tid) noexcept
:
timestampAndType(timestamp << 1 | static_cast<Timestamp>(type)),
tid(tid)
{
assert(getTimestamp() == timestamp);
assert(getType() == type);
}
TID getTID() const noexcept
{
return tid;
}
Timestamp getTimestamp() const noexcept
{
return timestampAndType >> 1;
}
Type getType() const noexcept
{
return static_cast<Type>(timestampAndType & 1);
}
bool operator < (const Endpoint& rhs) const noexcept
{
return timestampAndType < rhs.timestampAndType;
}
bool operator <= (const Endpoint& rhs) const noexcept
{
return timestampAndType <= rhs.timestampAndType;
}
bool isStart() const noexcept
{
return !isEnd();
}
bool isEnd() const noexcept
{
return getType() == Type::END;
}
static constexpr Timestamp calculateShiftArgument(Timestamp delta)
{
return delta << 1;
}
static constexpr Timestamp calculateShiftArgument(Timestamp delta, Type fromType, Type toType)
{
return calculateShiftArgument(delta) + static_cast<Timestamp>(toType) - static_cast<Timestamp>(fromType);
}
Endpoint shiftedBy(Timestamp shiftArgument) const noexcept
{
return Endpoint(timestampAndType + shiftArgument, tid);
}
friend void swap(Endpoint& a, Endpoint& b) noexcept
{
using std::swap;
swap(a.timestampAndType, b.timestampAndType);
swap(a.tid, b.tid);
}
friend std::ostream& operator << (std::ostream &out, const Endpoint& endpoint)
{
return out << '@' << endpoint.getTimestamp() << (endpoint.isStart() ? 'S' : 'E') << endpoint.getTID() + 1;
}
};
<file_sep>#pragma once
#include <functional>
#include "Joins0.h"
template <typename IteratorR, typename Consumer>
void joinBySStart(const Relation& R, const Relation& S, IteratorR itR, const Consumer& consumer) noexcept
{
joinByS(R, S, itR, makeFilteringIterator(S.getIndex(), Endpoint::Type::START), std::less_equal<>(), consumer);
}
template <typename IteratorR, typename Consumer>
void joinBySStartStrict(const Relation& R, const Relation& S, IteratorR itR, const Consumer& consumer) noexcept
{
joinByS(R, S, itR, makeFilteringIterator(S.getIndex(), Endpoint::Type::START), std::less<>(), consumer);
}
template <typename IteratorR, typename Consumer>
void joinBySEnd(const Relation& R, const Relation& S, IteratorR itR, const Consumer& consumer) noexcept
{
joinByS(R, S, itR, makeFilteringIterator(S.getIndex(), Endpoint::Type::END), std::less<>(), consumer);
}
template <typename IteratorR, typename Consumer>
void joinBySEndStrict(const Relation& R, const Relation& S, IteratorR itR, const Consumer& consumer) noexcept
{
joinByS(R, S, itR, makeFilteringIterator(S.getIndex(), Endpoint::Type::END), std::less_equal<>(), consumer);
}
<file_sep>#include <iostream>
#include "util/Arguments.h"
#include "algorithms/Joins.h"
#include "MainBefore.h"
#include "MainLatency.h"
#include "MainJoins.h"
int main(int /*argc*/, const char* argv[])
{
std::cout << "ISEQL ";
std::cout << sizeof(size_t) * 8 << "-bit ";
std::cout << "Compiled on " __DATE__ " " __TIME__ " ";
std::cout << "Tuple size " << sizeof(Tuple) << " bytes";
#ifdef NDEBUG
std::cout << " Release";
#else
std::cout << " Debug";
#endif
#ifdef COUNTERS
std::cout << " COUNTERS";
#endif
std::cout << std::endl;
Arguments arguments{argv};
std::string command = arguments.getCurrentArgAndSkipIt("Command");
if (command == "before")
mainBefore(arguments);
else if (command == "latency")
mainLatency(arguments);
else
mainJoins(command, arguments);
// Relation R = {
// {1, 5, 1},
// {1, 10, 2},
// {7, 11, 3},
// {9, 10, 4},
// };
// Relation S = {
// {2, 2, 1},
// {3, 12, 2},
// {4, 5, 3},
// {5, 6, 4},
// {8, 9, 5},
// };
//
// Index indexR; indexR.buildFor(R);
// Index indexS; indexS.buildFor(S);
//
// R.setIndex(indexR);
// S.setIndex(indexS);
//
//
// startPrecedingJoin(R, S, [] (const Tuple& r, const Tuple& s)
// {
// std::cout << r << s << std::endl;
// });
}
<file_sep>#pragma once
#include <vector>
#include "model/Tuple.h"
class Index;
class Relation : public std::vector<Tuple>
{
private:
const Index* index;
public:
Relation() { }
Relation(std::initializer_list<Tuple> list)
:
vector(list)
{
}
void setIndex(const Index& index) noexcept
{
this->index = &index;
}
const Index& getIndex() const noexcept
{
return *this->index;
}
void sort()
{
std::sort(begin(), end());
}
};
|
d6c692adf2686d7c630f2a500c43b402ce953f38
|
[
"CMake",
"C++",
"Shell"
] | 43
|
CMake
|
danilcha/iseql-cpp
|
0fdb58e2cc52a16ede0ebec841e8930f728ede70
|
3aaca7837de922e0908a2f7eda1178799436f995
|
refs/heads/main
|
<file_sep># compvision_testing
This is a little project to test Microsoft's computer vision API functionality
https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/
<file_sep>from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
from array import array
import os
from PIL import Image
import sys
import time
'''
Authenticate
Authenticates your credentials and creates a client.
'''
# <snippet_vars>
subscription_key = "<KEY>"
endpoint = "https://pcs-compvision-test-001.cognitiveservices.azure.com/"
# </snippet_vars>
# <snippet_client>
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
# </snippet_client>
'''
END - Authenticate
'''
# local_image_url = "C:\Users\Derek.Johanson\Documents\development\OCR\id.jpg"
'''
Batch Read File, recognize handwritten text - remote
This example will extract handwritten text in an image, then print results, line by line.
This API call can also recognize handwriting (not shown).
'''
print("===== Batch Read File - remote =====")
# Get an image with handwritten text
remote_image_handw_text_url = r"https://i.pinimg.com/236x/76/6b/be/766bbeed4408251e73c52a1b8ab74ca9.jpg"
# Call API with URL and raw response (allows you to get the operation location)
recognize_handw_results = computervision_client.read(remote_image_handw_text_url, raw=True)
# Get the operation location (URL with an ID at the end) from the response
operation_location_remote = recognize_handw_results.headers["Operation-Location"]
# Grab the ID from the URL
operation_id = operation_location_remote.split("/")[-1]
# Call the "GET" API and wait for it to retrieve the results
while True:
get_handw_text_results = computervision_client.get_read_result(operation_id)
if get_handw_text_results.status not in ['notStarted', 'running']:
break
time.sleep(1)
# Print the detected text, line by line
if get_handw_text_results.status == OperationStatusCodes.succeeded:
for text_result in get_handw_text_results.analyze_result.read_results:
for line in text_result.lines:
print(line.text)
print(line.bounding_box)
print()
|
a04d936a5c5366cb4f9140e7dfe3cfee54e328de
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
jzaq16/compvision_testing
|
6223448fabcfc6ef8ea0f4ceb50da0f95df743f7
|
ac27609c3f134ad282957c5e2c62f81636af0699
|
refs/heads/master
|
<file_sep>import React from 'react';
import AppHeader from './AppHeader';
import { BrowserRouter, Route, Link } from "react-router-dom";
import Idea from './Idea';
import IdeaForm from './IdeaForm';
import update from 'immutability-helper';
import Notification from './Notification';
import Login from './Login';
export default (props) => {
return (
<BroswerRouter>
<div>
<Route path="/" compoenent={AppHeader}/>
<Route path="/login" compoenent={Login} />
</div>
</BrowserRouter>
)
}<file_sep>class User < ApplicationRecord
# Include default devise modules.
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
include DeviseTokenAuth::Concerns::User
<<<<<<< HEAD
has_many :boards
has_many :ideas
=======
has_many :ideas
>>>>>>> refs/remotes/origin/master
end
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import { GithubPicker } from 'react-color';
class Color extends React.Component {
state = {
color: 'lightyellow',
};
handleChangeComplete = (color) => {
if (this.props.selected) {
console.log('this.selected.changeBackground ', this.props.selected);
this.props.selected.changeBackground(color.hex);
}
this.setState({ background: color.hex});
this.props.handleUnselect();
};
render() {
return (
<div hidden={this.props.selected === null ? true : false}>
<GithubPicker
color={ this.state.color}
onChangeComplete={ this.handleChangeComplete }
/>
</div>
);
}
}
export default Color<file_sep>class ApplicationController < ActionController::API
<<<<<<< HEAD
include DeviseTokenAuth::Concerns::SetUserByToken
=======
>>>>>>> e4c4851... added connector
end
<file_sep>class Idea < ApplicationRecord
<<<<<<< HEAD
belongs_to :users , optional: true
<<<<<<< HEAD
=======
>>>>>>> refs/remotes/origin/master
=======
>>>>>>> e4c4851... added connector
end
<file_sep>import React, { Component } from 'react';
import './App.css';
<<<<<<< HEAD
import AppHeader from './components/AppHeader'
import IdeasContainer from './components/IdeasContainer'
import { BrowserRouter, Route } from "react-router-dom";
import Login from './components/Login';
import Signup from './components/Signup';
import Board from './components/Board' ;
=======
import IdeasContainer from './components/IdeasContainer'
>>>>>>> e4c4851... added connector
class App extends Component {
render() {
return (
<<<<<<< HEAD
<BrowserRouter>
<div className="App">
<Route path="/" component={AppHeader}/>
<header className="App-header">
<h1> Idea Board </h1>
</header>
<Route path="/login" component={Login} />
<Route exact path="/" component={IdeasContainer} />
</div>
</BrowserRouter>
=======
<div className="App">
<header className="App-header">
<h1> Idea Board </h1>
</header>
<IdeasContainer/>
</div>
>>>>>>> e4c4851... added connector
);
}
}
export default App;
<file_sep>class V1::SessionsController < ApplicationController
def create
user = User.where(email: params[:email]).first
if user && user.authenticate(params[:session][:password])
json user.as_json(only: [:email, :authentication_token]), status: :created
else
head(:unauthorized)
end
end
def destroy
end
end <file_sep>module Api::V1
class IdeasController < ApplicationController
<<<<<<< HEAD
before_action :authenticate_user!
def index
if !user_signed_in?
redirect_to @authenticate_user
else
@ideas = current_user.ideas.order("created_at DESC")
render json: @ideas
end
end
def create
@idea = current_user.ideas.new(idea_params)
if @idea.save
render json: @idea
else
render json: @idea.errors, status: :unprocessable_entity
end
end
def update
@idea = current_user.ideas.find(params[:id])
@idea.update_attributes(idea_params)
render json: @idea
end
def destroy
@idea = current_user.ideas.find(params[:id])
if @idea.destroy
head :no_content, status: :ok
else
render json: @ideas.errors, status: :unprocessable_entity
end
end
private
def idea_params
<<<<<<< HEAD
params.require(:idea).permit(:title, :body, :color)
=======
params.require(:idea).permit(:title, :body)
>>>>>>> refs/remotes/origin/master
end
end
=======
def index
@ideas = Idea.all
render json: @ideas
end
end
>>>>>>> e4c4851... added connector
end
<file_sep>import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class BoardTitle extends Component {
state = {
title: "DEFAULT TITLE",
editMode: false
}
changeTitle = (e) => {
this.setState({[e.target.name]: e.target.value})
}
editTitle = () => {
this.setState({
editMode: !this.state.editMode
})
}
unFocus = (e) => {
console.log(e.target.value);
this.setState({
title: e.target.value,
editMode: false
})
}
render(){
return(
<div>
{
this.state.editMode ?
<input defaultValue={this.state.title} onBlur={this.unFocus} style={{width:"100%", height:"30px", fontSize:"30px"}} onClick={this.changeTitle} />
:
<h1 onClick={this.editTitle}>{this.state.title}</h1>
}
</div>
);
}
}
export default BoardTitle<file_sep>ideas = Idea.create(
[
{
title: "Work on this shit",
body: "Made of chocolate"
},
{
title: "A twitter clinent idea",
body: "Only for repwadawdwad"
},
{
title: "wdawdwdwad",
body: "wdawdwadawd"
},
{
title: "dwadwadw",
body: "dawdwadawd"
}
])<file_sep>Rails.application.routes.draw do
<<<<<<< HEAD
mount_devise_token_auth_for 'User', at: 'auth'
mount ActionCable.server => '/cable'
#devise_for :users
namespace :api do
namespace :v1 do
resources :ideas
# resources :sessions, only: [:create, :destroy]
=======
namespace :api do
namespace :v1 do
resources :ideas
>>>>>>> e4c4851... added connector
end
end
end
<file_sep>class AddBoardToUsers < ActiveRecord::Migration[5.2]
def change
add_reference :users, :board , foreign_key: true
end
end
|
757adf4f82c86bfa7f82511018c1657b17e8d09b
|
[
"JavaScript",
"Ruby"
] | 12
|
JavaScript
|
Jesontheg6/real-time-ideaboard
|
84dc6920df6be468519fea28b8671aa214e6c4ef
|
cd955ca0770dbbbf66d6c5da96d5155eb26755fa
|
refs/heads/master
|
<repo_name>AmandaJField/ionicShoppingList<file_sep>/shoppingList/src/pages/list/list.service.ts
import { Injectable } from '@angular/core';
import { List } from './list.object';
import { Item } from '../item/item.object';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
/**
* This service is used to hold all list data manipulation
*/
@Injectable()
export class ListService {
lists: FirebaseListObservable<any[]>;
items: any;
list: any;
tempList: List;
tempItem: Item;
constructor(public af: AngularFire){
this.lists = this.af.database.list('/lists');
}
//List CRUD
public getLists():FirebaseListObservable<any[]>{
return this.lists
}
public addList(name, items){
this.tempList = {name: name, items: items};
this.lists.push(this.tempList)
.then( newList => {
console.log(newList);
}, error => {
console.log(error);
});
}
public updateList(list, name, items){
this.tempList = {name: name, items: items};
this.lists.update(list.$key, this.tempList);
}
public deleteList(list):void{
this.af.database.object('/lists/'+list.$key).remove();
}
//Item CRUD
public getItems(list){
return this.af.database.object('/lists/'+list.$key+'/items')
}
public deleteItem(list, item){
console.log(list.indexOf(item));
// this.af.database.object('/lists/'+list.$key+'/items/'+item.$key).remove();
}
}<file_sep>/shoppingList/src/pages/item/item.component.ts
import { Component } from '@angular/core';
import {Platform, NavController, NavParams} from 'ionic-angular';
import { ListService } from '../list/list.service';
/*
This component is used to represent the display of all todos generated by all my todos
*/
@Component({
selector: 'item',
templateUrl: 'item.html'
})
export class ItemComponent {
items: any;
list: any;
listName: String;
item: String;
amount: String;
constructor(platform: Platform, public navCtrl: NavController, public listSrv: ListService, navParams: NavParams) {
this.list = navParams.get("list")
Object.keys(this.list).length === 0 ? this.items = [] : listSrv.getItems(this.list).subscribe(items => {
items.length > 0 ? this.items = items : this.items = []
})
this.listName = this.list.name;
}
addItem(){
let newItem = {item: this.item, amount: this.amount}
if(newItem.item !== null && newItem.amount !== null) {
this.items.push(newItem);
this.item = null;
this.amount = null;
}else{
console.log('Item incomplete');
}
}
deleteItem(item){
this.items.splice(this.items.indexOf(item),1)
}
save(){
this.list.$key ? this.listSrv.updateList(this.list, this.listName, this.items) : this.listSrv.addList(this.listName, this.items)
this.navigate();
}
navigate(){
this.navCtrl.pop()
}
}
<file_sep>/shoppingList/src/pages/list/list.component.ts
import { Component } from '@angular/core';
import {Platform, NavController} from 'ionic-angular';
import { ItemList } from '../itemList/itemList'
import { ListService } from './list.service'
import { FirebaseListObservable } from 'angularfire2';
/*
This component is used to represent the display of all todos generated by all my todos
*/
@Component({
selector: 'list',
templateUrl: 'list.html'
})
export class ListComponent {
lists: FirebaseListObservable<any[]>;
constructor(platform: Platform, public navCtrl: NavController, public listSrv: ListService) {
this.lists = listSrv.getLists();
}
delete(list){
this.listSrv.deleteList(list);
}
navigate(data){
this.navCtrl.push(ItemList, {list: data});
}
}
<file_sep>/shoppingList/src/pages/list/list.object.ts
export class List{
name: String;
items: Array<any>;
}<file_sep>/shoppingList/src/pages/item/item.object.ts
export class Item{
item: String;
amount: Number;
}<file_sep>/shoppingList/src/app/app.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { ShoppingList } from '../pages/shoppingList/shoppingList';
import { ListComponent } from '../pages/list/list.component';
import { ListService } from '../pages/list/list.service';
import { ItemList } from '../pages/itemList/itemList';
import { ItemComponent } from '../pages/item/item.component';
// Import the AF2 Module
import { AngularFireModule } from 'angularfire2';
// AF2 Settings
const config = {
apiKey: "<KEY>",
authDomain: "shoppinglist-43762.firebaseapp.com",
databaseURL: "https://shoppinglist-43762.firebaseio.com",
storageBucket: "shoppinglist-43762.appspot.com",
messagingSenderId: "914989121787"
};
AngularFireModule.initializeApp(config);
@NgModule({
declarations: [
MyApp,
ShoppingList,
ItemList,
ListComponent,
ItemComponent
],
imports: [
IonicModule.forRoot(MyApp),
AngularFireModule.initializeApp(config)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
ShoppingList,
ItemList,
ListComponent,
ItemComponent
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, ListService]
})
export class AppModule {}
<file_sep>/shoppingList/src/pages/itemList/itemList.ts
import { Component } from '@angular/core';
import { Platform,NavController, NavParams } from 'ionic-angular';
@Component({
selector: 'itemList',
templateUrl: 'itemList.html'
})
export class ItemList {
items: any;
constructor(platform: Platform, public navCtrl: NavController, public navParams: NavParams) {
}
}
<file_sep>/shoppingList/src/pages/shoppingList/shoppingList.ts
import { Component } from '@angular/core';
import { Platform, NavController, NavParams } from 'ionic-angular';
@Component({
selector: 'shoppingList',
templateUrl: 'shoppingList.html'
})
export class ShoppingList {
constructor(platform: Platform, public navCtrl: NavController, public navParams: NavParams) {
}
}
|
1d102a33c04714849de913b45fb08b71b98e4445
|
[
"TypeScript"
] | 8
|
TypeScript
|
AmandaJField/ionicShoppingList
|
8e36627cd2f280a4d3305f57bf1267df4ca7da91
|
f4077d8729ab2dbcf0123d32bed25712468741bc
|
refs/heads/master
|
<repo_name>ether1991/water<file_sep>/day副本.js
require([
"dojox/data/CsvStore"],
function(CsvStore){
var dataStore = new CsvStore({url: "data/day.csv"}); //csv数据文件
var processData = function(items, arg){
//items.reverse(); //将csv存储数据倒序排列
//currentData = [];
data1 = [];
data2 = [];
data3 = [];
rdata = [];
rdata1 = [];
dates = [];
var item;
for(var i = 0; i < items.length; i++){
// Reduce data size
item = {};
//var value = dataStore.getValue(items[i], "data1");
//item.data1 = parseFloat(value);
//value = dataStore.getValue(items[i], "data2");
//item.data2 = parseFloat(value);
value = dataStore.getValue(items[i], "yuce");
item.data3 = parseFloat(value);
//解决曲线连接到0的问题
if(i<=2){
value=null;
item.rdata = parseFloat(value);
alert("hahahah");
}else{
value = dataStore.getValue(items[i], "shiji");
item.rdata = parseFloat(value);
}
value = dataStore.getValue(items[i], "lishi");
item.rdata1 = parseFloat(value);
value = dataStore.getValue(items[i], "dates");
item.dates = value;
data1.push(item.data1);
data2.push(item.data2);
data3.push(item.data3);
rdata.push(item.rdata);
rdata1.push(item.rdata1);
dates.push(item.dates);
}
chart1.addSeries("预测",data3,{plot:"volumePlot",stroke:{color:"#f7a357"}});//图中最下边的线,对应data3
//chart1.addSeries("历史",rdata1,{plot:"volumePlot",stroke: {color: "red"}});
chart1.addSeries("实际",rdata, {plot:"volumePlot",stroke: {color: "blue"}});//图中最上边的线,对应rdata
//添加网格图
chart1.addPlot("default", { type: Grid,
hStripes: true,
vStripes: false,
hFill: "white",
vFill: "white" });
resize();//适应屏幕
chart1.render();//开始渲染
var legend1 = new dojox.charting.widget.Legend({chart: chart1}, "legend1");
//var legend = new dojox.charting.widget.Legend({ chart1: chart1 }, "legend");
};
dataStore.fetch({onComplete: processData}); //读取数据
});
<file_sep>/README.md
# water
采用DOJO的api来完成图表的展示,包括柱状图和折线图,可以对图表进行拉伸缩放等等操作,
data文件夹存放需要展示的数据,csv格式,
js文件是对应的加载数据的文件,相应名称的html文件负责前端展示
<file_sep>/src.js
var customClaroTheme, timeLabelFunction;
var data1;
var data2;
var data3;
var rdata;
var rdata1;
var dates;
require([
"dojo/ready",
"dojo/sniff", // ua sniffing
"dojo/on",
"dojo/dom", // byId
"dojo/dom-style",
"dojo/_base/fx",
"dojo/topic",
"dojo/fx/easing",
"dojox/mobile",
"dojox/mobile/compat",
"dojox/mobile/View",
"dojox/mobile/RoundRect",
"dojox/mobile/Button",
"dojox/mobile/parser",
"dojox/charting/widget/Chart",
"dojox/charting/Theme",
"dojox/charting/axis2d/Default",
"dojox/charting/plot2d/Columns",
"dojox/charting/plot2d/Areas",
"dojox/charting/plot2d/StackedAreas",
"dojox/charting/plot2d/Lines",
"dojox/charting/plot2d/Grid",
"dojox/data/CsvStore",
"dijit/registry",
"dojo/has!touch?dojox/charting/action2d/TouchZoomAndPan:dojox/charting/action2d/MouseZoomAndPan",
"dojo/has!touch?dojox/charting/action2d/TouchIndicator:dojox/charting/action2d/MouseIndicator",
// Load the Legend widget class
"dojox/charting/widget/Legend",
"dojox/charting/widget/SelectableLegend"],
function(ready, has, on, dom, domStyle, fx,easing, topic, mobile, compat, View, RoundRect, Button, parser,
Chart, Theme, Default, Columns, StackedAreas,Areas,Lines, Grid, CsvStore, registry, ZoomAndPan, Indicator,Legend,SelectableLegend){
var pHeight = 0;
//resize函数主要解决屏幕适配问题
var resize = function(){
var view2 = dom.byId("view2");
if(view2.style.visibility == "hidden" || view2.style.display == "none"){
return;
}
var wsize = mobile.getScreenSize();
// needed for IE, because was overriden to 0 at some point
if(has("ie")){
dom.byId("stockChart").style.width = "100%";
}else{
// on Android, the window size is changing a bit when scrolling!
// ignore those resize
if(wsize.h > pHeight - 64 && wsize.h < pHeight + 64){
return;
}
}
pHeight = wsize.h;
var box = { h: wsize.w > wsize.h ? wsize.h - 92 : wsize.h - 196 };
registry.byId("stockChart").resize(box);
};
/* var googStore = new CsvStore({url: "resources/data/goog_prices.csv"});
var yahooStore = new CsvStore({url: "resources/data/yahoo_prices.csv"});
var msftStore = new CsvStore({url: "resources/data/msft_prices.csv"});
var selectedStore = googStore; */
//var currentData;
//var dataFreq = 4;
//showChartView函数:显示图表,添加数据
var showChartView = function(){
//selectedStore.fetch({onComplete: processData});
var chart1 = registry.byId("stockChart").chart;
var dataStore = new CsvStore({url: "data/data1.csv"}); //csv数据文件
var processData = function(items, arg){
//items.reverse(); //将csv存储数据倒序排列
//currentData = [];
data1 = [];
data2 = [];
data3 = [];
data4 = [];
data5 = [];
data6 = [];
data7 = [];
data8 = [];
data9 = [];
data10 = [];
data11 = [];
data12 = [];
data13 = [];
date=[];
var item;
for(var i = 0; i < items.length; i++){
// Reduce data size
item = {};
var value = dataStore.getValue(items[i], "data1");
item.data1 = parseFloat(value);
value = dataStore.getValue(items[i], "data2");
item.data2 = parseFloat(value);
value = dataStore.getValue(items[i], "data3");
item.data3 = parseFloat(value);
value = dataStore.getValue(items[i], "data4");
item.data4 = parseFloat(value);
value = dataStore.getValue(items[i], "data5");
item.data5 = parseFloat(value);
value = dataStore.getValue(items[i], "data6");
item.data6 = parseFloat(value);
value = dataStore.getValue(items[i], "data7");
item.data7 = parseFloat(value);
value = dataStore.getValue(items[i], "data8");
item.data8 = parseFloat(value);
value = dataStore.getValue(items[i], "data9");
item.data9 = parseFloat(value);
value = dataStore.getValue(items[i], "data10");
item.data10 = parseFloat(value);
value = dataStore.getValue(items[i], "data11");
item.data11 = parseFloat(value);
value = dataStore.getValue(items[i], "data12");
item.data12 = parseFloat(value);
value = dataStore.getValue(items[i], "data13");
item.data13 = parseFloat(value);
value = dataStore.getValue(items[i], "date");
item.date = parseFloat(value);
data1.push(item.data1);
data2.push(item.data2);
data3.push(item.data3);
data4.push(item.data4);
data5.push(item.data5);
data6.push(item.data6);
data7.push(item.data7);
data8.push(item.data8);
data9.push(item.data9);
data10.push(item.data10);
data11.push(item.data11);
data12.push(item.data12);
data13.push(item.data13);
date.push(item.date);
}
chart1.addSeries("0.05",data1, {plot:"volumePlot", stroke: {color: "rgb(156,198,240)"}});
chart1.addSeries("0.10",data2, {plot:"volumePlot", stroke: {color: "rgb(156,18,240)"}});
chart1.addSeries("0.25",data3, {plot:"volumePlot", stroke: {color: "red"}});
chart1.addSeries("0.40",data4, {plot:"volumePlot",stroke: {color: "blue"}});
chart1.addSeries("0.55",data5,{plot:"volumePlot",stroke:{color:"#f7a357"}});
chart1.addSeries("0.70",data6, {plot:"volumePlot", stroke: {color: "rgb(156,198,240)"}});
chart1.addSeries("0.85",data7, {plot:"volumePlot", stroke: {color: "rgb(156,98,40)"}});
chart1.addSeries("1.00",data8, {plot:"volumePlot",stroke: {color: "red"}});
chart1.addSeries("1.15",data9, {plot:"volumePlot",stroke: {color: "blue"}});
chart1.addSeries("1.30",data10,{plot:"volumePlot",stroke:{color:"#f7a357"}});
chart1.addSeries("1.45",data11, {plot:"volumePlot", stroke: {color: "rgb(156,198,240)"}});
chart1.addSeries("1.60",data12, {plot:"volumePlot", stroke: {color: "rgb(156,19,20)"}});
chart1.addSeries("1.75",data13, {plot:"volumePlot",stroke: {color: "red"}});
chart1.addSeries("date",date, {plot:"volumePlot",stroke: {color: "blue"}});
//chart1.addSeries("data5",data3,{plot:"volumePlot",stroke:{color:"#f7a357"}});
//添加网格图
chart1.addPlot("default", { type: Grid,
hStripes: true,
vStripes: false,
hFill: "white",
vFill: "white" });
resize();//适应屏幕
chart1.render();//开始渲染
var legend1 = new dojox.charting.widget.Legend({chart: chart1}, "legend1"); //加图例
};
dataStore.fetch({onComplete: processData}); //读取数据
};
//hideChartView:隐藏部分数据
var hideChartView = function(){
var chart1 = registry.byId("stockChart").chart;
chart1.removeSeries("data1");
chart1.removeSeries("data2");
chart1.removeSeries("data3");
//chart1.removeSeries("VolumeSeries");
chart1.render();
};
//timeLabelFunction:实现横轴时间根据缩放而变化
timeLabelFunction = function(v){
var idx = parseInt(v);
var dtime;
dtime = date[idx]; //
return dtime;
}
var interactionMode = null;
var interactor1;
var interactor2;
/*
var indicatorFillFunc = function(v1, v2){
if(v2){
return v2.y>v1.y?"green":"red";
}else{
return "#ff9000";
}
};
*/
//indicatorFillFunc:在表头上,根据不同位置显示不同数值
var indicatorFillFunc = function(v){
if(v){
dom.byId("date").innerHTML = date[v.x-1];
dom.byId("data1").innerHTML = data1[v.x-1];
dom.byId("data2").innerHTML = data2[v.x-1];
dom.byId("data3").innerHTML = data3[v.x-1];
dom.byId("data4").innerHTML = data4[v.x-1];
dom.byId("data5").innerHTML = data5[v.x-1];
dom.byId("data6").innerHTML = data6[v.x-1];
dom.byId("data7").innerHTML = data7[v.x-1];
dom.byId("data8").innerHTML = data8[v.x-1];
dom.byId("data9").innerHTML = data9[v.x-1];
dom.byId("data10").innerHTML = data10[v.x-1];
dom.byId("data11").innerHTML = data11[v.x-1];
dom.byId("data12").innerHTML = data12[v.x-1];
dom.byId("data13").innerHTML = data13[v.x-1];
//return data3[v.x-1];//参数超过阈值,显示红色
}else{
return "#ff9000";
}
};
//labelFillFunc:在鼠标或手指在屏幕滑动时,在指示线上实时显示水位的范围
var labelFillFunc = function(v){
//str1 = "水位范围: "+data1[v.x-1] + " - " +data2[v.x-1];
// str1=dat3[v.x-1];
//return str1;
};
//switchMode:根据不同需要选择3中不同的模式:1. data indicator:可以在页面拖动,同时会有指示线和相应数据的变化;
//2.zoom&pan:可以鼠标左键单击拖动,选择部分区域放大;3.no interaction:普通图表页面,不允许缩放和拖动
var switchMode = function(){
var label = dom.byId("touchLabel");
label.style.display = "";
domStyle.set(label, "opacity", 0);
fx.fadeIn({node:"touchLabel", duration:1500}).play();
setTimeout(function(){label.style.display = "none";}, 2000);//屏幕适应,每2秒刷新一次
var chart = registry.byId("stockChart").chart;
if(interactionMode == null){
// we were in no interaction let's go to indicator mode
interactionMode = "indicator";
interactor1 = has("touch")?new ZoomAndPan(chart, "default", { axis: "x",
enableScroll: false, enableZoom: true}):
new ZoomAndPan(chart, "default", { axis: "x", enableScroll: false });
interactor2 = has("touch")?new Indicator(chart, "default", {
series: "0.25", dualIndicator: true, font: "normal normal bold 12pt Helvetica",
lineOutline: null, outline: null, markerOutline: null,
fillFunc: indicatorFillFunc,labelFunc : labelFillFunc
}):new Indicator(chart, "default", {
series: "0.25", font: "normal normal bold 12pt Helvetica",
lineOutline: null, outline: null, markerOutline: null,
fillFunc: indicatorFillFunc,labelFunc : labelFillFunc,
});
label.innerHTML = "滑动指示模式";
}else if (interactionMode == "indicator"){
// we were in indicator mode let's go to zoom mode
interactionMode = "zoom";
interactor1.disconnect();
interactor2.disconnect();
interactor1 = has("touch")?new ZoomAndPan(chart, "default", {axis: "x", scaleFactor:2}):
new ZoomAndPan(chart, "default", {axis: "x", scaleFactor:2});
label.innerHTML = "伸缩模式";
}else {
// we were in zoom mode let's go to null
interactionMode = null;
interactor1.disconnect();
label.innerHTML = "图表模式";
}
chart.render();
};
/* var companySelect = function(store, label){
return function(event){
selectedStore = store;
registry.byId("view2head1").set("label", label);
}
}; */
//init:
var init = function(){
var view2 = registry.byId("view2");
//view2.on("BeforeTransitionOut", hideChartView);
//view2.on("AfterTransitionIn", showChartView);
showChartView();//调用showChartView,显示图表
on(dom.byId("indicatorMode"), "click", switchMode);//根据按钮的点击事件,更换不同模式
switchMode();//变换不同的模式
topic.subscribe("/dojox/mobile/resizeAll", resize);
};
//customClaroTheme:设置主题,包括坐标轴的样式,线的颜色,宽度
customClaroTheme = new Theme({
axis:{
stroke: { // the axis itself
color: "rgba(0, 0, 0, 0.5)"
},
tick: { // used as a foundation for all ticks
color: "rgba(0, 0, 0, 0.5)",
fontColor: "rgba(0, 0, 0, 0.5)"
}
},
series: {
outline: null
},
grid: {
majorLine: {
color: "rgba(0, 0, 0, 0.2)"
}
},
indicator: {//指示线相关属性
lineStroke: {width: 1.5, color: "blue"},//这是跟着手指或者鼠标滑动而滑动的纵向指示线
lineOutline: {width: 0.5, color: "white"},
stroke: null,
outline: null,
fontColor: "#ffffff",//指示线上显示水位范围的字体的颜色
markerFill: Theme.generateGradient({type: "radial", space: "shape", r: 100}, "white", "#ff9000"),
markerStroke: {width: 1.5, color: "#ff6000"},//lineStroke指示线上小球的颜色和大小
markerOutline:{width: 0.5, color: "white"}
},
seriesThemes: [ {stroke: "#1a80a8", fill: "#c7e0e9" }, {stroke: "#6d66b9", fill: "#c9c6e4" } ]//可以控制带状区域的颜色,和showChartView配合使用
});
//开始,载入页面,调用init
ready(init);
});
|
c83439d897ac0cf17ad977ca9caa638368ea27aa
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
ether1991/water
|
45ff835b13907716e45ed38e720b39db12143c12
|
d59738d8eb1ff514b822031e3be8001d4cee0bc5
|
refs/heads/master
|
<file_sep>/*
* WelcomeController.java
*
* Copyright (C) 2018 Universidad de Sevilla
*
* The use of this project is hereby constrained to the conditions of the
* TDG Licence, a copy of which you may download from
* http://www.tdg-seville.info/License.html
*/
package controllers;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import security.LoginService;
import security.UserAccount;
import services.*;
@Controller
@RequestMapping("/profile")
public class ProfileController extends AbstractController {
@Autowired
private ActorService actorService;
@Autowired
private AdministratorService administratorService;
@Autowired
private RefereeService refereeService;
@Autowired
private SponsorService sponsorService;
@Autowired
private ReaderService readerService;
@Autowired
private OrganizerService organizerService;
@RequestMapping(value = "/myInformation", method = RequestMethod.GET)
public ModelAndView myInformation() {
final ModelAndView result = new ModelAndView("profile/myInformation");
final Actor user = this.actorService.getActorLogged();
final UserAccount userAccount = LoginService.getPrincipal();
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("ADMIN")) {
Administrator administrador1;
administrador1 = this.administratorService.findOne(user.getId());
Assert.notNull(administrador1);
result.addObject("administrator", administrador1);
}
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("REFEREE")) {
Referee referee;
referee = this.refereeService.findOne(user.getId());
Assert.notNull(referee);
result.addObject("referee", referee);
}
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("SPONSOR")) {
Sponsor sponsor;
sponsor = this.sponsorService.findOne(user.getId());
Assert.notNull(sponsor);
result.addObject("sponsor", sponsor);
}
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("READER")) {
Reader reader;
reader = this.readerService.findOne(user.getId());
Assert.notNull(reader);
result.addObject("reader", reader);
}
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("ORGANIZER")) {
Organizer organizer;
organizer = this.organizerService.findOne(user.getId());
Assert.notNull(organizer);
result.addObject("organizer", organizer);
}
return result;
}
@RequestMapping(value = "/deleteInformation", method = RequestMethod.GET)
public ModelAndView deleteInformation(){
ModelAndView result;
try {
Assert.isTrue(this.actorService.getActorLogged() != null);
this.actorService.deleteInformation();
result = new ModelAndView("redirect:/j_spring_security_logout");
} catch (final Exception e) {
return new ModelAndView("redirect:/");
}
return result;
}
@RequestMapping(value = "/exportJSON", method = RequestMethod.GET)
public ModelAndView exportJSON () {
final ModelAndView result = new ModelAndView("profile/exportJSON");
final Actor user = this.actorService.getActorLogged();
final UserAccount userAccount = LoginService.getPrincipal();
final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("ADMIN")) {
Administrator administrador1;
administrador1 = this.administratorService.findOne(user.getId());
Assert.notNull(administrador1);
final String json = gson.toJson(administrador1);
result.addObject("json", json);
}
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("REFEREE")) {
Referee referee;
referee = this.refereeService.findOne(user.getId());
Assert.notNull(referee);
final String json = gson.toJson(referee);
result.addObject("json", json);
}
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("SPONSOR")) {
Sponsor sponsor;
sponsor = this.sponsorService.findOne(user.getId());
Assert.notNull(sponsor);
final String json = gson.toJson(sponsor);
result.addObject("json", json);
}
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("READER")) {
Reader reader;
reader = this.readerService.findOne(user.getId());
Assert.notNull(reader);
final String json = gson.toJson(reader);
result.addObject("json", json);
}
if (userAccount.getAuthorities().iterator().next().getAuthority().equals("ORGANIZER")) {
Organizer organizer;
organizer = this.organizerService.findOne(user.getId());
Assert.notNull(organizer);
final String json = gson.toJson(organizer);
result.addObject("json", json);
}
return result;
}
@RequestMapping(value="/show", method = RequestMethod.GET)
public ModelAndView show(@RequestParam int actorId){
ModelAndView result;
Actor actor;
try{
actor = this.actorService.findOne(actorId);
result = new ModelAndView("profile/show");
result.addObject("actor", actor);
return result;
} catch(Throwable oops){
result = new ModelAndView("redirect:/");
}
return result;
}
}
<file_sep>transaction.buyer = Comprador
transaction.seller = Vendedor
transaction.moment = Momento de Venta
transaction.book = Libro
transaction.state = Estado
transaction.price = Precio
transaction.sold = Vendido
transaction.onSale = En venta
transaction.delete = Borrar
transaction.createSale = Crear Venta
transaction.createExchange = Crear Intercambio
transaction.save = Guardar
transaction.cancel = Cancelar
transaction.offers = Ofertas
transaction.show = Mostrar
transaction.commit.error = No se puede realizar la operacion
transaction.price.error = No puede estar vacío
transaction.buy = Comprar
complaint.create = Crear queja
transaction.back = Volver
transaction.Offer = Hacer una Oferta
<file_sep>
package service;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import services.RegisterService;
import utilities.AbstractTest;
@ContextConfiguration(locations = {
"classpath:spring/junit.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class RegisterTest extends AbstractTest {
@Autowired
private RegisterService registerService;
/*
* Testing functional requirement : An actor who is authenticated as reader must be able to register in an event
* Positive: A reader register in an event
* Negative: An organizer try register in an event
* Sentence coverage: 95%
* Data coverage: Not applicable
*/
@Test
public void checkInDriver() {
final Object testingData[][] = {
{
"event3", "reader1", null
}, {
"event3", "organizer1", IllegalArgumentException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.checkInTemplate(super.getEntityId((String) testingData[i][0]), (String) testingData[i][1], (Class<?>) testingData[i][2]);
}
private void checkInTemplate(final int eventId, final String user, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(user);
this.registerService.save(eventId);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
/*
* Testing functional requirement : An actor who is authenticated as reader must be able to cancel a register
* Positive: A reader cancel a register
* Negative: An organizer try cancel a register
* Sentence coverage: 100%
* Data coverage: Not applicable
*/
@Test
public void cancelRegisterDriver() {
final Object testingData[][] = {
{
"event1", "register1", "reader1", null
}, {
"event1", "register1", "organizer1", IllegalArgumentException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.cancelRegisterTemplate(super.getEntityId((String) testingData[i][0]), super.getEntityId((String) testingData[i][1]), (String) testingData[i][2], (Class<?>) testingData[i][3]);
}
private void cancelRegisterTemplate(final int eventId, final int registerId, final String user, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(user);
this.registerService.cancel(registerId, eventId);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
}
<file_sep>
package repositories;
import domain.Reader;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ReaderRepository extends JpaRepository<Reader, Integer> {
}
<file_sep>package repositories;
import domain.Finder;
import domain.Transaction;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Collection;
@Repository
public interface FinderRepository extends JpaRepository<Finder, Integer> {
@Query("select t from Transaction t where (t.book.title like %?1% or t.book.author like %?1% " +
"or t.book.publisher like %?1% or t.book.description like %?1%) and t.isFinished=FALSE")
Collection<Transaction> getTransactionsByKeyWord(String keyWord);
@Query("select t from Transaction t where (t.book.languageB like ?1 or t.book.isbn like ?1) and t.isFinished=FALSE")
Collection<Transaction> getTransactionsContainsKeyWord(String keyWord);
@Query("select t from Transaction t join t.book.categories c where (c.nameEs like ?1 or c.nameEn like ?1) " +
"and t.isFinished=FALSE")
Collection<Transaction> getTransactionsByCategory(String category);
@Query("select t from Transaction t where t.book.status like ?1 and t.isFinished=FALSE")
Collection<Transaction> getTransactionsByStatus(String status);
@Query("select f from Finder f join f.transactions t where t.id=?1")
Collection<Finder> findAllByTransaction(int transactionId);
}
<file_sep>transaction.book.title = Titulo
transaction.moment = Fecha
transaction.book.status = Estado
transaction.book.category = Categoria
transaction.price = Precio
transaction.show = Show
finder.update.keyword = Palabra
finder.update.update = Guardar
finder.update.cancel = Cancelar
finder.update.clear = Limpiar
transaction.book.VERYGOOD = MUY BUENO
transaction.book.GOOD = BUENO
transaction.book.BAD = MALO
transaction.book.VERYBAD = MUY MALO<file_sep>comment.moment = Moment
comment.body = Body
comment.author = Author
comment.back = Back
comment.save = Save
comment.cancel = Cancel
comment.commit.error = Can not commit this operation
<file_sep>register.date = Date
register.event.title = Event title
register.delete = Cancel<file_sep>
package domain;
import com.google.gson.annotations.Expose;
import org.hibernate.validator.constraints.*;
import org.hibernate.validator.constraints.SafeHtml.WhiteListType;
import security.UserAccount;
import javax.persistence.*;
import javax.validation.Valid;
import java.util.Collection;
@Entity
@Access(AccessType.PROPERTY)
@Table(indexes = {
@Index(columnList = "isSuspicious, isBanned")
})
public abstract class Actor extends DomainEntity {
@Expose
private String name;
@Expose
private String middleName;
@Expose
private String surname;
@Expose
private String photo;
@Expose
private String email;
@Expose
private String phoneNumber;
@Expose
private String address;
@Expose
private Boolean isSuspicious;
@Expose
private Boolean isBanned;
@Expose
private Double score;
@NotBlank
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getName() {
return this.name;
}
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getMiddleName() {
return this.middleName;
}
@NotBlank
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getSurname() {
return this.surname;
}
@URL
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getPhoto() {
return this.photo;
}
@NotBlank
@Email
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getEmail() {
return this.email;
}
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getPhoneNumber() {
return this.phoneNumber;
}
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getAddress() {
return this.address;
}
public Boolean getIsSuspicious() {
return this.isSuspicious;
}
@Range(min = -1, max = 1)
public Double getScore() {
return this.score;
}
public Boolean getIsBanned() {
return this.isBanned;
}
public void setName(final String name) {
this.name = name;
}
public void setMiddleName(final String middleName) {
this.middleName = middleName;
}
public void setSurname(final String surname) {
this.surname = surname;
}
public void setPhoto(final String photo) {
this.photo = photo;
}
public void setEmail(final String email) {
this.email = email;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setAddress(final String address) {
this.address = address;
}
public void setIsSuspicious(final Boolean isSuspicious) {
this.isSuspicious = isSuspicious;
}
public void setIsBanned(final Boolean isBanned) {
this.isBanned = isBanned;
}
public void setScore(final Double score) {
this.score = score;
}
//Relationships
@Expose
private UserAccount userAccount;
@Expose
private Collection<SocialProfile> socialProfiles;
@Expose
private Collection<MessageBox> boxes;
@Valid
@OneToOne(optional = false, cascade = CascadeType.ALL)
public UserAccount getUserAccount() {
return this.userAccount;
}
@Valid
@OneToMany
public Collection<SocialProfile> getSocialProfiles() {
return this.socialProfiles;
}
@Valid
@OneToMany(cascade = CascadeType.ALL)
public Collection<MessageBox> getBoxes() {
return boxes;
}
public void setUserAccount(final UserAccount userAccount) {
this.userAccount = userAccount;
}
public void setSocialProfiles(final Collection<SocialProfile> socialProfiles) {
this.socialProfiles = socialProfiles;
}
public void setBoxes(Collection<MessageBox> boxes) {
this.boxes = boxes;
}
public MessageBox getMessageBox(final String name) {
final MessageBox result = null;
for (final MessageBox box : this.getBoxes())
if (box.getName().equals(name))
return box;
return result;
}
}
<file_sep>/*
* RegisterAndEditAdministratorTest.java
*
* Copyright (C) 2018 Universidad de Sevilla
*
* The use of this project is hereby constrained to the conditions of the
* TDG Licence, a copy of which you may download from
* http://www.tdg-seville.info/License.html
*/
package service;
import datatype.Url;
import domain.Comment;
import domain.Report;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.validation.DataBinder;
import services.CommentService;
import services.ReportService;
import utilities.AbstractTest;
import javax.transaction.Transactional;
import javax.validation.ValidationException;
import java.util.Collection;
@ContextConfiguration(locations = {
"classpath:spring/junit.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class CommentTest extends AbstractTest {
@Autowired
private CommentService commentService;
//In this test we are testing the requirement 31 and 34(creating comments).
//In the negative cases we are testing that the actors involved in the report can not create a comment if they do not
//submit a body, and it can only be created by the readers involved in the complaint and the referee that has
//self-assigned it
//Sequence coverage: 100%
//Data coverage: 100%
@Test
public void createCommentDriver() {
final Object testingData[][] = {
{
"reader1", "test", "report1", null
},{
"reader2", "test", "report1", null
},{
"referee1", "test", "report1", null
}, {
"reader1", "", "report1", ValidationException.class
}, {
"referee2", "test", "report1", IllegalArgumentException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.createCommentTemplate((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (Class<?>) testingData[i][3]);
}
private void createCommentTemplate(final String username, final String body, final String report, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(username);
final int reportId = super.getEntityId(report);
Comment comment = this.commentService.create();
comment.setBody(body);
final DataBinder binding = new DataBinder(new Comment());
comment = this.commentService.reconstruct(comment, binding.getBindingResult());
this.commentService.save(comment, reportId);
super.unauthenticate();
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
}
<file_sep>package services;
import domain.Actor;
import domain.Configuration;
import domain.Message;
import domain.MessageBox;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.MessageRepository;
import security.LoginService;
import security.UserAccount;
import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
@Service
@Transactional
public class MessageService {
// Manage Repository
@Autowired
private MessageRepository messageRepository;
//Supporting devices
@Autowired
private ConfigurationService configurationService;
@Autowired
private ActorService actorService;
@Autowired
private Validator validator;
// CRUD methods
public Message create() {
final Message result = new Message();
final Calendar calendar = new GregorianCalendar();
final long time = calendar.getTimeInMillis() - 500;
calendar.setTimeInMillis(time);
final Collection<String> tags = new ArrayList<String>();
final Collection<MessageBox> boxes = new ArrayList<MessageBox>();
result.setTags(tags);
result.setMoment(calendar.getTime());
result.setMessageBoxes(boxes);
return result;
}
public Message findOne(final int messageID) {
final Message result = this.messageRepository.findOne(messageID);
Assert.notNull(result);
return result;
}
public Message save(final Message message) {
Assert.notNull(message);
final Message result;
if (message.getId() == 0) {
Assert.notNull(message);
final Actor sender = this.actorService.getActorLogged();
message.setSender(sender);
final Collection<Actor> recipients = message.getRecipients();
Assert.notNull(recipients);
Assert.notEmpty(recipients);
final Boolean spam = this.checkSpam(message);
final String box;
if (spam) {
box = "SPAMBOX";
message.setIsSpam(true);
} else {
box = "INBOX";
message.setIsSpam(false);
}
message.getMessageBoxes().add(sender.getMessageBox("OUTBOX"));
for (final Actor recipient : recipients)
message.getMessageBoxes().add(recipient.getMessageBox(box));
result = this.messageRepository.save(message);
sender.getMessageBox("OUTBOX").addMessage(result);
for (final Actor recipient : recipients)
recipient.getMessageBox(box).addMessage(result);
} else
result = this.messageRepository.save(message);
return result;
}
public Message broadcast(final Message message) {
final Message result;
final Collection<Actor> recipients = message.getRecipients();
Assert.notNull(recipients);
Assert.notEmpty(recipients);
for (final Actor recipient : recipients)
message.getMessageBoxes().add(recipient.getMessageBox("NOTIFICATIONBOX"));
result = this.messageRepository.save(message);
for (final Actor recipient : recipients)
recipient.getMessageBox("NOTIFICATIONBOX").addMessage(result);
return result;
}
public Message notification(final Message message) {
final Message result;
final Collection<Actor> recipients = message.getRecipients();
message.getTags().add("NOTIFICATION");
message.setPriority("HIGH");
for (final Actor recipient : recipients)
message.getMessageBoxes().add(recipient.getMessageBox("NOTIFICATIONBOX"));
result = this.messageRepository.save(message);
for (final Actor recipient : recipients)
recipient.getMessageBox("NOTIFICATIONBOX").addMessage(result);
return result;
}
public void delete(final Message message, final MessageBox srcMessageBox) {
Assert.notNull(message);
final UserAccount userAccount = LoginService.getPrincipal();
Assert.notNull(userAccount);
final Actor actor = this.actorService.findByUsername(userAccount.getUsername());
Assert.isTrue(message.getRecipients().contains(actor) || message.getSender().equals(actor));
if (srcMessageBox.getName().equals("TRASHBOX")) {
for (final MessageBox box : actor.getBoxes())
if (box.getMessages().contains(message)) {
actor.getMessageBox(box.getName()).deleteMessage(message);
message.getMessageBoxes().remove(box);
}
if (message.getMessageBoxes().size() == 0) //&& message.getSender() == null message.getRecipients().size() == 0 &&
this.messageRepository.delete(message);
else
this.messageRepository.save(message);
} else {
Assert.isTrue(srcMessageBox.getMessages().contains(message));
this.moveMessage(message, srcMessageBox, actor.getMessageBox("TRASHBOX"));
}
}
public void deleteAll(final Message m) {
this.messageRepository.delete(m);
}
// Other methods
public Message moveMessage(final Message message, final MessageBox srcMessageBox, final MessageBox destMessageBox) {
Assert.notNull(message);
Assert.notNull(srcMessageBox);
Assert.notNull(destMessageBox);
Assert.notNull(LoginService.getPrincipal());
final Actor actor = this.actorService.findByUsername(LoginService.getPrincipal().getUsername());
Assert.isTrue(actor.getBoxes().contains(srcMessageBox));
Assert.isTrue(actor.getBoxes().contains(destMessageBox));
Assert.isTrue(actor.getMessageBox(srcMessageBox.getName()).getMessages().contains(message));
Assert.isTrue(message.getRecipients().contains(actor) || message.getSender().equals(actor));
Assert.isTrue(message.getMessageBoxes().contains(srcMessageBox));
if (!destMessageBox.getMessages().contains(message)) {
message.getMessageBoxes().remove(srcMessageBox);
message.getMessageBoxes().add(destMessageBox);
srcMessageBox.deleteMessage(message);
destMessageBox.addMessage(message);
} else {
message.getMessageBoxes().remove(srcMessageBox);
srcMessageBox.deleteMessage(message);
}
return this.messageRepository.save(message);
}
public Message copyMessage(final Message message, final MessageBox srcMessageBox, final MessageBox destMessageBox) {
Assert.notNull(message);
Assert.notNull(srcMessageBox);
Assert.notNull(destMessageBox);
Assert.notNull(LoginService.getPrincipal());
final Actor actor = this.actorService.findByUsername(LoginService.getPrincipal().getUsername());
Assert.isTrue(actor.getBoxes().contains(srcMessageBox));
Assert.isTrue(actor.getBoxes().contains(destMessageBox));
Assert.isTrue(actor.getMessageBox(srcMessageBox.getName()).getMessages().contains(message));
Assert.isTrue(!actor.getMessageBox(destMessageBox.getName()).getMessages().contains(message));
Assert.isTrue(message.getRecipients().contains(actor) || message.getSender().equals(actor));
Assert.isTrue(message.getMessageBoxes().contains(srcMessageBox));
message.getMessageBoxes().add(destMessageBox);
destMessageBox.addMessage(message);
return this.messageRepository.save(message);
}
// Aux methods
private Boolean checkSpam(final Message message) {
Boolean spam = false;
final Configuration configuration = this.configurationService.findAll().get(0);
final Collection<String> spamWords = configuration.getSpamWords();
for (final String word : spamWords)
if (message.getSubject().contains(word)) {
spam = true;
break;
}
if (!spam)
for (final String word : spamWords)
if (message.getBody().contains(word)) {
spam = true;
break;
}
return spam;
}
public Collection<Message> findAllByMessageBox(final int messageBoxID) {
final Collection<Message> result = this.messageRepository.findByMessageBox(messageBoxID);
Assert.notNull(result);
return result;
}
public Collection<Message> findAllSentByActor(final int actorID) {
final Collection<Message> result = this.messageRepository.findAllSentByActor(actorID);
Assert.notNull(result);
return result;
}
public Double findSpamRatioByActor(final int actorID) {
Double result = this.messageRepository.findSpamRatioByActor(actorID);
if (result == null)
result = 0.0;
return result;
}
public Message reconstruct(final Message message, final BindingResult binding) {
final Message result;
result = this.create();
result.setSubject(message.getSubject());
result.setPriority(message.getPriority());
result.setBody(message.getBody());
result.setTags(message.getTags());
result.setRecipients(message.getRecipients());
this.validator.validate(result, binding);
if (binding.hasErrors())
throw new ValidationException();
return result;
}
public Collection<Message> findAllReceivedByActor(final int actorID) {
Collection<Message> result = this.messageRepository.findAllReceivedByActor(actorID);
return result;
}
}<file_sep>/*
* AdministratorController.java
*
* Copyright (C) 2018 Universidad de Sevilla
*
* The use of this project is hereby constrained to the conditions of the
* TDG Licence, a copy of which you may download from
* http://www.tdg-seville.info/License.html
*/
package controllers.administrator;
import controllers.AbstractController;
import domain.Actor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import services.*;
import java.util.ArrayList;
import java.util.Collection;
@Controller
@RequestMapping("/administrator")
public class ManageActorsController extends AbstractController {
@Autowired
private ActorService actorService;
@Autowired
private AdministratorService administratorService;
@Autowired
private SponsorService sponsorService;
@Autowired
private OrganizerService organizerService;
@Autowired
private ReaderService readerService;
@RequestMapping(value = "/management", method = RequestMethod.GET)
public ModelAndView actorList() {
ModelAndView result;
result = new ModelAndView("administrator/management");
final Collection<Actor> actorList = new ArrayList<Actor>();
actorList.addAll(this.organizerService.findAll());
actorList.addAll(this.readerService.findAll());
actorList.addAll(this.sponsorService.findAll());
result.addObject("actors", actorList);
result.addObject("requestURI", "administrator/management.do");
return result;
}
@RequestMapping(value = "/management/calculateSpam", method = RequestMethod.GET)
public ModelAndView calculateSpam() {
ModelAndView result;
try {
this.administratorService.computeAllSpam();
result = new ModelAndView("redirect:/administrator/management.do");
} catch (final Throwable oops) {
return new ModelAndView("redirect:/");
}
return result;
}
@RequestMapping(value = "/management/calculateScore", method = RequestMethod.GET)
public ModelAndView calculateScore() {
ModelAndView result;
try {
this.administratorService.computeAllScores();
result = new ModelAndView("redirect:/administrator/management.do");
} catch (final Throwable oops) {
return new ModelAndView("redirect:/");
}
return result;
}
@RequestMapping(value = "/management/deactivateExpiredCreditCards", method = RequestMethod.GET)
public ModelAndView deactivateExpiredCreditCards() {
ModelAndView result;
try {
final Integer deactivateSponsorships = this.administratorService.desactivateExpiredSponsorships();
//result = new ModelAndView("redirect:/administrator/management.do");
final Collection<Actor> actorList = new ArrayList<Actor>();
actorList.addAll(this.organizerService.findAll());
actorList.addAll(this.readerService.findAll());
actorList.addAll(this.sponsorService.findAll());
result = new ModelAndView("administrator/management");
result.addObject("actors", actorList);
result.addObject("requestURI", "administrator/management.do");
result.addObject("deactivateSponsorships", deactivateSponsorships);
} catch (final Throwable oops) {
return new ModelAndView("redirect:/");
}
return result;
}
@RequestMapping(value = "/management/deleteInactiveBooks", method = RequestMethod.GET)
public ModelAndView deleteInactiveBooks() {
ModelAndView result;
try {
final Integer deletedBooks = this.administratorService.deleteInactiveBooks();
//result = new ModelAndView("redirect:/administrator/management.do");
final Collection<Actor> actorList = new ArrayList<Actor>();
actorList.addAll(this.organizerService.findAll());
actorList.addAll(this.readerService.findAll());
actorList.addAll(this.sponsorService.findAll());
result = new ModelAndView("administrator/management");
result.addObject("actors", actorList);
result.addObject("requestURI", "administrator/management.do");
result.addObject("deletedBooks", deletedBooks);
} catch (final Throwable oops) {
return new ModelAndView("redirect:/");
}
return result;
}
@RequestMapping(value = "/management/ban", method = RequestMethod.GET)
public ModelAndView ban(@RequestParam final int actorId) {
ModelAndView result;
try {
final Actor actor = this.actorService.findOne(actorId);
this.administratorService.ban(actor);
result = new ModelAndView("redirect:/administrator/management.do");
} catch (final Throwable oops) {
return new ModelAndView("redirect:/");
}
return result;
}
@RequestMapping(value = "/management/unban", method = RequestMethod.GET)
public ModelAndView unban(@RequestParam final int actorId) {
ModelAndView result;
try {
final Actor actor = this.actorService.findOne(actorId);
this.administratorService.unban(actor);
result = new ModelAndView("redirect:/administrator/management.do");
} catch (final Throwable oops) {
return new ModelAndView("redirect:/");
}
return result;
}
@RequestMapping(value = "/management/showActor", method = RequestMethod.GET)
public ModelAndView showMember(@RequestParam final int actorId) {
ModelAndView result;
result = new ModelAndView("administrator/management/showActor");
try {
final Actor actor = this.actorService.findOne(actorId);
Assert.notNull(actor);
result.addObject("actor", actor);
} catch (final Throwable oops) {
return new ModelAndView("redirect:/");
}
return result;
}
}
<file_sep>transaction.book.title = Title
transaction.book.status = Status
transaction.book.category = Category
transaction.price = Price
transaction.show = Show
finder.update.keyword = Keyword
finder.update.update = Save
finder.update.cancel = Cancel
finder.update.clear = Clear
transaction.book.VERYGOOD = VERY GOOD
transaction.book.GOOD = GOOD
transaction.book.BAD = BAD
transaction.book.VERYBAD = VERY BAD
<file_sep>package domain;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.util.Date;
@Entity
@Access(AccessType.PROPERTY)
public class Register extends DomainEntity {
private Date moment;
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
public Date getMoment() {
return moment;
}
public void setMoment(Date moment) {
this.moment = moment;
}
//Relationships...................................................
private Reader reader;
@ManyToOne(optional = false)
public Reader getReader() {
return reader;
}
public void setReader(Reader reader) {
this.reader = reader;
}
}
<file_sep>register.date = Fecha
register.event.title = Título del evento
register.delete = Cancelar<file_sep>package services;
import domain.Book;
import domain.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.CategoryRepository;
import security.UserAccount;
import javax.transaction.Transactional;
import javax.validation.ValidationException;
import java.util.Collection;
@Service
@Transactional
public class CategoryService {
//Manager repository
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private ActorService actorService;
@Autowired
private Validator validator;
public Category create() {
UserAccount userAccount;
userAccount = this.actorService.getActorLogged().getUserAccount();
Assert.isTrue(userAccount.getAuthorities().iterator().next().getAuthority().equals("ADMIN"));
Category res = new Category();
return res;
}
public Collection<Category> findAll() {
Collection<Category> res;
res = this.categoryRepository.findAll();
Assert.notNull(res);
return res;
}
public Category findOne(int categoryId) {
Category res;
res = this.categoryRepository.findOne(categoryId);
Assert.notNull(res);
return res;
}
public Category save(Category c) {
UserAccount userAccount;
userAccount = this.actorService.getActorLogged().getUserAccount();
Assert.isTrue(userAccount.getAuthorities().iterator().next().getAuthority().equals("ADMIN"));
Assert.notNull(c);
Category res;
res = this.categoryRepository.save(c);
return res;
}
public void delete(Category c) {
UserAccount userAccount;
userAccount = this.actorService.getActorLogged().getUserAccount();
Assert.isTrue(userAccount.getAuthorities().iterator().next().getAuthority().equals("ADMIN"));
Assert.notNull(c);
Assert.isTrue(c.getId() != 0);
Collection<Book> bookWithThisCategory = this.getBooksWithCategoryParam(c);
for (Book b : bookWithThisCategory) {
Collection<Category> categories = b.getCategories();
if (b.getCategories().size() == 1) {
categories.add(this.getDefaultCategory());
}
categories.remove(c);
b.setCategories(categories);
}
this.categoryRepository.delete(c);
}
public Collection<String> getNamesEs() {
return this.categoryRepository.getNamesEs();
}
public Collection<String> getNamesEn() {
return this.categoryRepository.getNamesEn();
}
public Collection<Book> getBooksWithCategoryParam(Category category) {
Collection<Book> res;
res = this.categoryRepository.getBooksWithCategoryParam(category);
return res;
}
public Category getDefaultCategory() {
Category res;
res = this.categoryRepository.getDefaultCategory();
Assert.notNull(res);
return res;
}
public Category reconstruct(Category category, BindingResult binding) {
Category result;
Boolean existsES = false;
Boolean existsEN = false;
if (category.getId() == 0) {
result = this.create();
} else {
result = this.categoryRepository.findOne(category.getId());
}
if (result.getId() == 0) {
existsES = existsES(category);
existsEN = existsEN(category);
} else {
if (!result.equalsES(category))
existsES = existsES(category);
if (!result.equalsEN(category))
existsEN = existsEN(category);
}
result.setNameEn(category.getNameEn());
result.setNameEs(category.getNameEs());
validator.validate(result, binding);
if (existsES)
binding.rejectValue("nameEs", "category.es.duplicated");
if (existsEN)
binding.rejectValue("nameEn", "category.en.duplicated");
if (binding.hasErrors()) {
throw new ValidationException();
}
return result;
}
public Boolean existsES(final Category a) {
Boolean exist = false;
final Collection<Category> categories = this.findAll();
for (final Category b : categories)
if (a.equalsES(b)) {
exist = true;
break;
}
return exist;
}
public Boolean existsEN(final Category a) {
Boolean exist = false;
final Collection<Category> categories = this.findAll();
for (final Category b : categories)
if (a.equalsEN(b)) {
exist = true;
break;
}
return exist;
}
}
<file_sep>package repositories;
import domain.Book;
import domain.Reader;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Collection;
@Repository
public interface BookRepository extends JpaRepository<Book, Integer> {
@Query("select count(t) from Transaction t where t.book.id = ?1")
Integer numTransaction(int bookId);
@Query("select b from Book b where b.reader = ?1 and not exists(select t from Transaction t where t.book = b) and not exists (select o from Offer o where o.book = b)")
Collection<Book> getBooksWithNoTransactionsByReader(Reader r);
@Query("select b from Book b where b.moment < ?1 and not exists(select t from Transaction t where t.book = b) and not exists (select o from Offer o where o.book = b)")
Collection<Book> findAllInactiveBooks(java.sql.Date date);
@Query("select b from Book b where b.reader.id = ?1")
Collection<Book> getBooksByReader(int readerId);
}
<file_sep>package converters;
import domain.Transaction;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
@Component
@Transactional
public class TransactionToStringConverter implements Converter<Transaction, String> {
@Override
public String convert(final Transaction sp) {
String result;
if (sp == null)
result = null;
else
result = String.valueOf(sp.getId());
return result;
}
}
<file_sep>
package services;
import domain.*;
import forms.AdministratorForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.AdministratorRepository;
import security.Authority;
import security.LoginService;
import security.UserAccount;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
@Service
@Transactional
public class AdministratorService {
//Managed Repositories
@Autowired
private AdministratorRepository administratorRepository;
//Supporting services
@Autowired
private ActorService actorService;
@Autowired
private ConfigurationService configurationService;
@Autowired
private MessageBoxService messageBoxService;
@Autowired
private MessageService messageService;
@Autowired
private SponsorService sponsorService;
@Autowired
private ReaderService readerService;
@Autowired
private OrganizerService organizerService;
@Autowired
private SponsorshipService sponsorshipService;
@Autowired
private BookService bookService;
@Autowired
private CategoryService categoryService;
@Autowired
private Validator validator;
public Administrator create() {
final Actor actor = this.actorService.getActorLogged();
Assert.isTrue(actor.getUserAccount().getAuthorities().iterator().next().getAuthority().equals("ADMIN"));
final Authority auth;
final UserAccount userAccount;
final Collection<Authority> authorities;
final Collection<SocialProfile> profiles;
final Collection<MessageBox> boxes;
final Administrator a = new Administrator();
userAccount = new UserAccount();
auth = new Authority();
authorities = new ArrayList<Authority>();
profiles = new ArrayList<SocialProfile>();
boxes = new ArrayList<MessageBox>();
auth.setAuthority(Authority.ADMIN);
authorities.add(auth);
userAccount.setAuthorities(authorities);
a.setUserAccount(userAccount);
a.setIsBanned(false);
a.setIsSuspicious(false);
a.setSocialProfiles(profiles);
a.setBoxes(boxes);
return a;
}
public Collection<Administrator> findAll() {
Collection<Administrator> result;
result = this.administratorRepository.findAll();
return result;
}
public Administrator findOne(final int administratorId) {
Assert.isTrue(administratorId != 0);
Administrator result;
result = this.administratorRepository.findOne(administratorId);
return result;
}
public Administrator save(final Administrator administrator) {
UserAccount userAccount;
userAccount = LoginService.getPrincipal();
Assert.isTrue(userAccount.getAuthorities().iterator().next().getAuthority().equals("ADMIN"));
Assert.notNull(administrator);
Administrator result;
final char[] c = administrator.getPhoneNumber().toCharArray();
if ((!administrator.getPhoneNumber().equals(null) && !administrator.getPhoneNumber().equals("")))
if (c[0] != '+') {
final String i = this.configurationService.findAll().get(0).getCountryCode();
administrator.setPhoneNumber("+" + i + " " + administrator.getPhoneNumber());
}
if (administrator.getId() == 0) {
final Md5PasswordEncoder encoder = new Md5PasswordEncoder();
final String res = encoder.encodePassword(administrator.getUserAccount().getPassword(), null);
administrator.getUserAccount().setPassword(res);
administrator.setBoxes(this.messageBoxService.createSystemMessageBox());
}
result = this.administratorRepository.save(administrator);
return result;
}
public void delete(final Administrator administrator) {
final Actor actor = this.actorService.getActorLogged();
Assert.isTrue(actor.getUserAccount().getAuthorities().iterator().next().getAuthority().equals("ADMIN"));
Assert.notNull(administrator);
Assert.isTrue(actor.getId() != 0);
this.administratorRepository.delete(administrator);
}
public Administrator reconstruct(final Administrator admin, final BindingResult binding) {
Administrator result;
if (admin.getId() == 0) {
this.validator.validate(admin, binding);
result = admin;
} else {
result = this.administratorRepository.findOne(admin.getId());
result.setName(admin.getName());
result.setPhoto(admin.getPhoto());
result.setPhoneNumber(admin.getPhoneNumber());
result.setEmail(admin.getEmail());
result.setAddress(admin.getAddress());
result.setSurname(admin.getSurname());
result.setMiddleName(admin.getMiddleName());
this.validator.validate(admin, binding);
}
return result;
}
//Validador de contraseņas
public Boolean checkPass(final String pass, final String confirmPass) {
Boolean res = false;
if (pass.compareTo(confirmPass) == 0)
res = true;
return res;
}
//Objeto formulario
public Administrator reconstruct(final AdministratorForm admin, final BindingResult binding) {
final Administrator result = this.create();
result.setAddress(admin.getAddress());
result.setEmail(admin.getEmail());
result.setMiddleName(admin.getMiddleName());
result.setId(admin.getId());
result.setName(admin.getName());
result.setPhoneNumber(admin.getPhoneNumber());
result.setPhoto(admin.getPhoto());
result.setSurname(admin.getSurname());
result.getUserAccount().setPassword(<PASSWORD>());
result.getUserAccount().setUsername(admin.getUsername());
result.setVersion(admin.getVersion());
this.validator.validate(result, binding);
return result;
}
public void ban(final Actor actor) {
final Actor principal = this.actorService.getActorLogged();
Assert.isTrue(principal instanceof Administrator);
Assert.isTrue(!actor.getIsBanned());
Assert.isTrue(actor.getIsSuspicious() || actor.getScore() < -0.5);
actor.setIsBanned(true);
this.actorService.save(actor);
}
public void unban(final Actor actor) {
final Actor principal = this.actorService.getActorLogged();
Assert.isTrue(principal instanceof Administrator);
Assert.isTrue(actor.getIsBanned());
actor.setIsBanned(false);
this.actorService.save(actor);
}
public void computeAllScores() {
Collection<Reader> readers;
Collection<Organizer> organizers;
Collection<Sponsor> sponsors;
// Make sure that the principal is an Admin
final Actor principal = this.actorService.getActorLogged();
Assert.isInstanceOf(Administrator.class, principal);
readers = this.readerService.findAll();
for (final Reader reader : readers) {
reader.setScore(this.computeScore(this.messageService.findAllSentByActor(reader.getId())));
this.readerService.updateAdmin(reader);
}
organizers = this.organizerService.findAll();
for (final Organizer organizer : organizers) {
organizer.setScore(this.computeScore(this.messageService.findAllSentByActor(organizer.getId())));
this.organizerService.updateAdmin(organizer);
}
sponsors = this.sponsorService.findAll();
for (final Sponsor sponsor : sponsors) {
sponsor.setScore(this.computeScore(this.messageService.findAllSentByActor(sponsor.getId())));
this.sponsorService.updateAdmin(sponsor);
}
}
private Double computeScore(final Collection<Message> messages) {
final Collection<String> positiveWords = this.configurationService.getConfiguration().getPosWords();
final Collection<String> negativeWords = this.configurationService.getConfiguration().getNegWords();
Double positiveWordsValue = 0.0;
Double negativeWordsValue = 0.0;
for (final Message message : messages) {
final String body = message.getBody();
final String subject = message.getSubject();
for (final String positiveWord : positiveWords) {
if (body.contains(positiveWord)) {
positiveWordsValue += 1.0;
}
}
for (final String negativeWord : negativeWords) {
if (body.contains(negativeWord)) {
negativeWordsValue += 1.0;
}
}
for (final String positiveWord : positiveWords) {
if (subject.contains(positiveWord)) {
positiveWordsValue += 1.0;
}
}
for (final String negativeWord : negativeWords) {
if (subject.contains(negativeWord)) {
negativeWordsValue += 1.0;
}
}
}
// check for NaN values
if (positiveWordsValue + negativeWordsValue == 0)
return 0.0;
else if (positiveWordsValue - negativeWordsValue == 0)
return 0.0;
else
return (positiveWordsValue - negativeWordsValue) / (positiveWordsValue + negativeWordsValue);
}
public void computeAllSpam() {
Collection<Reader> readers;
Collection<Organizer> organizers;
Collection<Sponsor> sponsors;
// Make sure that the principal is an Admin
final Actor principal = this.actorService.getActorLogged();
Assert.isInstanceOf(Administrator.class, principal);
readers = this.readerService.findAll();
for (final Reader reader : readers) {
reader.setIsSuspicious(this.messageService.findSpamRatioByActor(reader.getId()) > .10);
this.readerService.updateAdmin(reader);
}
organizers = this.organizerService.findAll();
for (final Organizer organizer : organizers) {
organizer.setIsSuspicious(this.messageService.findSpamRatioByActor(organizer.getId()) > .10);
this.organizerService.updateAdmin(organizer);
}
sponsors = this.sponsorService.findAll();
for (final Sponsor sponsor : sponsors) {
sponsor.setIsSuspicious(this.messageService.findSpamRatioByActor(sponsor.getId()) > .10);
this.sponsorService.updateAdmin(sponsor);
}
}
public Integer desactivateExpiredSponsorships() {
final Actor principal = this.actorService.getActorLogged();
Assert.isInstanceOf(Administrator.class, principal);
final Collection<Sponsorship> sponsorships = this.sponsorshipService.findAllExpiredCreditCard();
for (final Sponsorship s : sponsorships)
this.sponsorshipService.desactivate(s);
return sponsorships.size();
}
public Integer deleteInactiveBooks() {
final Actor principal = this.actorService.getActorLogged();
Assert.isInstanceOf(Administrator.class, principal);
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -30);
java.sql.Date oneMonthOld = new java.sql.Date(cal.getTimeInMillis());
final Collection<Book> books = this.bookService.findAllInactiveBooks(oneMonthOld);
for (final Book b : books)
this.bookService.deleteAdmin(b);
return books.size();
}
//DASHBOARD
//Q2
public Collection<Organizer> getTop5OrganizersWithMoreEvents(){
List<Organizer> o = (List<Organizer>) this.administratorRepository.getOrganizersWithMoreEvents();
Collection<Organizer> result = new ArrayList<>();
if(o.size()>5){
for(int i=0; i<5; i++){
result.add(o.get(i));
}
} else result = o;
return result;
}
//Q3
public List<Double> getTransactionsPrice(){
List<Double> result = new ArrayList<>();
result.add(this.administratorRepository.getAvgTransactionsPrice());
result.add(this.administratorRepository.getMinTransactionsPrice());
result.add(this.administratorRepository.getMaxTransactionsPrice());
result.add(this.administratorRepository.getStddevTransactionsPrice());
return result;
}
//Q4
public List<Double> getBooksPerReader(){
List<Double> result = new ArrayList<>();
result.add(this.administratorRepository.getAvgBooksPerReader());
result.add(this.administratorRepository.getMinBooksPerReader());
result.add(this.administratorRepository.getMaxBooksPerReader());
result.add(this.administratorRepository.getStddevBooksPerReader());
return result;
}
//Q5
public List<Double> getTransactionsComplaint(){
List<Double> result = new ArrayList<>();
result.add(this.administratorRepository.getAvgNumberTransactionsComplaints());
result.add(this.administratorRepository.getMinNumberTransactionsComplaints());
result.add(this.administratorRepository.getMaxNumberTransactionsComplaints());
result.add(this.administratorRepository.getStddevNumberTransactionsComplaints());
return result;
}
//Q6
public List<Double> getSponsorPerEvent(){
List<Double> result = new ArrayList<>();
result.add(this.administratorRepository.getAvgNumberSponsorsPerEvent());
result.add(this.administratorRepository.getMinNumberSponsorsPerEvent());
result.add(this.administratorRepository.getMaxNumberSponsorsPerEvent());
result.add(this.administratorRepository.getStddevNumberSponsorsPerEvent());
return result;
}
//Q7
public Double getRatioOfActiveVSInnactiveSpons(){
return this.administratorRepository.getRatioOfActiveVSInnactiveSpons();
}
//Q8
public Double getRatioOfFullFinders() {
return this.administratorRepository.getRatioOfFullFinders();
}
//Q9
public Double getRatioOfEmptyFinders() {
return this.administratorRepository.getRatioOfEmptyFinders();
}
//Q10
public Double getRatioOfEmptyVSFullFinders() {
return this.administratorRepository.getRatioOfEmptyVSFullFinders();
}
//Q11
public Double getRatioOfEmptyVSFullTransactionsComplaints(){
return this.administratorRepository.getRatioOfEmptyVSFullTransactionsComplaints();
}
//Q12
public Collection<Reader> getTop5ReadersWithMoreComplaints(){
List<Reader> o = (List<Reader>) this.administratorRepository.getReadersWithMoreComplaints();
Collection<Reader> result = new ArrayList<>();
if(o.size()>5){
result = o.subList(0,5);
} else result = o;
return result;
}
//Q13
public Double getRatioOfSalesVSExchangesByReader() {
return this.administratorRepository.getRatioOfSalesVSExchangesByReader();
}
//Q1
public List<Object> getNumberOfSoldBooksByCategory(String language){
List<Double> result = new ArrayList<Double>();
Collection<Category> categories = this.categoryService.findAll();
List<String> names = new ArrayList<String>();
List<Object> lists = new ArrayList<Object>();
for (Category c: categories){
result.add(this.administratorRepository.getNumberOfSoldBooksByCategory(c));
if(language.equals("es")){
names.add(c.getNameEs());
}else{
names.add(c.getNameEn());
}
}
lists.add(result);
lists.add(names);
return lists;
}
}
<file_sep>package repositories;
import domain.Complaint;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Collection;
@Repository
public interface ComplaintRepository extends JpaRepository<Complaint, Integer> {
@Query("select c from Complaint c where c.referee is null")
Collection<Complaint> getComplaintsWithNoReferee();
@Query("select c from Complaint c where c.referee.id=?1")
Collection<Complaint> getComplaintsByReferee(int refereeId);
@Query("select c from Transaction t join t.complaints c where t.seller.id =?1 or t.buyer.id = ?1")
Collection<Complaint> getComplaintsByReader(int readerId);
}
<file_sep>package service;
import domain.Configuration;
import domain.Finder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import services.ConfigurationService;
import services.FinderService;
import utilities.AbstractTest;
import javax.transaction.Transactional;
import java.util.Collection;
@ContextConfiguration(locations = {
"classpath:spring/junit.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class ConfigurationTest extends AbstractTest {
@Autowired
public ConfigurationService configurationService;
//In this test we are testing the requirement 35.7(creating new positive word).
//In the negative cases we are testing that other user that he isn't admin try to edit it
//Sequence coverage: 100%
//Data coverage: 100%
@Test
public void creatingPositiveWordConfigurationDriver() {
final Object testingData[][] = {
{
"admin1", "configuration1", "word", null
}, {
"reader1", "configuration1", "word", IllegalArgumentException.class
},};
for (int i = 0; i < testingData.length; i++)
this.creatingPositiveWordConfigurationTemplate((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (Class<?>) testingData[i][3]);
}
private void creatingPositiveWordConfigurationTemplate(final String username, final String finder, final String word, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(username);
Configuration configuration1 = this.configurationService.findOne(super.getEntityId(finder));
Collection<String> posWords = configuration1.getPosWords();
posWords.add(word);
configuration1.setPosWords(posWords);
this.configurationService.save(configuration1);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
//In this test we are testing the requirement 35.7(updating/deleting a positive word).
//In the negative cases we are testing that other user that he isn't admin try to edit it
//Sequence coverage: 100%
//Data coverage: 100%
@Test
public void deletingPositiveWordConfigurationDriver() {
final Object testingData[][] = {
{
"admin1", "configuration1", "good", null
}, {
"reader1", "configuration1", "good", IllegalArgumentException.class
},};
for (int i = 0; i < testingData.length; i++)
this.deletingPositiveWordConfigurationTemplate((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (Class<?>) testingData[i][3]);
}
private void deletingPositiveWordConfigurationTemplate(final String username, final String finder, final String word, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(username);
Configuration configuration1 = this.configurationService.findOne(super.getEntityId(finder));
Collection<String> posWords = configuration1.getPosWords();
posWords.remove(word);
configuration1.setPosWords(posWords);
this.configurationService.save(configuration1);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
//In this test we are testing the requirement 35.7(creating new negative word).
//In the negative cases we are testing that other user that he isn't admin try to edit it
//Sequence coverage: 100%
//Data coverage: 100%
@Test
public void creatingNegativeWordConfigurationDriver() {
final Object testingData[][] = {
{
"admin1", "configuration1", "word", null
}, {
"reader1", "configuration1", "word", IllegalArgumentException.class
},};
for (int i = 0; i < testingData.length; i++)
this.creatingNegativeWordConfigurationTemplate((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (Class<?>) testingData[i][3]);
}
private void creatingNegativeWordConfigurationTemplate(final String username, final String finder, final String word, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(username);
Configuration configuration1 = this.configurationService.findOne(super.getEntityId(finder));
Collection<String> negWords = configuration1.getNegWords();
negWords.add(word);
configuration1.setNegWords(negWords);
this.configurationService.save(configuration1);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
//In this test we are testing the requirement 35.7(updating/deleting a negative word).
//In the negative cases we are testing that other user that he isn't admin try to edit it
//Sequence coverage: 100%
//Data coverage: 100%
@Test
public void deletingNegativeWordConfigurationDriver() {
final Object testingData[][] = {
{
"admin1", "configuration1", "bad", null
}, {
"reader1", "configuration1", "bad", IllegalArgumentException.class
},};
for (int i = 0; i < testingData.length; i++)
this.deletingNegativeWordConfigurationTemplate((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (Class<?>) testingData[i][3]);
}
private void deletingNegativeWordConfigurationTemplate(final String username, final String finder, final String word, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(username);
Configuration configuration1 = this.configurationService.findOne(super.getEntityId(finder));
Collection<String> negWords = configuration1.getNegWords();
negWords.remove(word);
configuration1.setNegWords(negWords);
this.configurationService.save(configuration1);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
}
<file_sep>DP2-D05 Acme Library.
The version delivered is in branch named release, if you prefer the version without https you can download the code from branch master.
<file_sep>
package controllers.sponsor;
import controllers.AbstractController;
import domain.Actor;
import domain.Sponsor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import services.ActorService;
import services.SponsorService;
import javax.validation.Valid;
@Controller
@RequestMapping("sponsor/sponsor")
public class EditSponsorController extends AbstractController {
@Autowired
private ActorService actorService;
@Autowired
private SponsorService sponsorService;
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView edit() {
ModelAndView result;
final Actor user = this.actorService.getActorLogged();
final Sponsor a= this.sponsorService.findOne(user.getId());
Assert.notNull(a);
result = this.editModelAndView(a);
return result;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "update")
public ModelAndView update(@Valid Sponsor a, final BindingResult binding) {
ModelAndView result;
if (binding.hasErrors())
result = this.editModelAndView(a);
else
try {
a = this.sponsorService.reconstruct(a, binding);
this.sponsorService.save(a);
result = new ModelAndView("redirect:/profile/myInformation.do");
} catch (final Throwable oops) {
result = this.editModelAndView(a, "actor.commit.error");
}
return result;
}
protected ModelAndView editModelAndView(final Sponsor a) {
ModelAndView result;
result = this.editModelAndView(a, null);
return result;
}
protected ModelAndView editModelAndView(final Sponsor a, final String messageCode) {
ModelAndView result;
result = new ModelAndView("sponsor/sponsor/edit");
result.addObject("sponsor", a);
result.addObject("messageCode", messageCode);
return result;
}
}
<file_sep>package services;
import domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.TransactionRepository;
import javax.validation.ValidationException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
@Transactional
public class TransactionService {
//Managed repository
@Autowired
private TransactionRepository transactionRepository;
//Services
@Autowired
private ActorService actorService;
@Autowired
private ReaderService readerService;
@Autowired
private MessageService messageService;
@Autowired
private ConfigurationService configurationService;
@Autowired
private Validator validator;
public Transaction reconstructSale(Transaction transaction, BindingResult binding){
Transaction result;
if(transaction.getId() == 0){
result = this.create();
result.setTicker(this.tickerGenerator());
result.setIsSale(true);
result.setSeller(this.readerService.findOne(this.actorService.getActorLogged().getId()));
result.setPrice(transaction.getPrice());
result.setBook(transaction.getBook());
}else{
result = this.findOne(transaction.getId());
Assert.isTrue(result.getIsSale() == true && result.getIsFinished() == false);
result.setBuyer(this.readerService.findOne(this.actorService.getActorLogged().getId()));
result.setMoment(new Date());
result.setCreditCard(transaction.getCreditCard());
}
validator.validate(result,binding);
if(transaction.getId() != 0){
final Collection<String> brandNames = this.configurationService.getConfiguration().getBrandName();
if(!brandNames.contains(result.getCreditCard().getBrandName()))
binding.rejectValue("creditCard.brandName", "sponsorship.creditCard.brandName.error");
// (!result.getEvent().getIsFinal())
// binding.rejectValue("event", "sponsorship.event.error.notFinal");
final Date date = new Date();
if(result.getCreditCard().getExpirationYear() != null && result.getCreditCard().getExpirationYear().before(date))
binding.rejectValue("creditCard.expirationYear", "sponsorship.creditCard.expiration.future");
}
if(binding.hasErrors()){
throw new ValidationException();
}
return result;
}
public Transaction create(){
Assert.isTrue(this.actorService.getActorLogged() instanceof Reader);
Transaction transaction = new Transaction();
return transaction;
}
public Transaction findOne(int id){
return this.transactionRepository.findOne(id);
}
public Collection<Transaction> findAll(){
return this.transactionRepository.findAll();
}
public Transaction saveSale(Transaction t){
if(t.getId() == 0){
t.setSeller(this.readerService.findOne(this.actorService.getActorLogged().getId()));
Assert.isTrue(t.getBook().getReader().equals(t.getSeller()));
t.setTicker(tickerGenerator());
t.setIsSale(true);
t.setIsFinished(false);
} else {
t.setIsFinished(true);
final Message message = this.messageService.create();
final Collection<Actor> recipients = new ArrayList<Actor>();
recipients.add(t.getSeller());
message.setRecipients(recipients);
message.setSubject("Your book has been sold. \n Tu libro ha sido vendido.");
message.setBody("Your book: "+t.getBook().getTitle()+" has been sold. \n Tu libro: "+t.getBook().getTitle()+
" ha sido vendido.");
this.messageService.notification(message);
}
Transaction result = this.transactionRepository.save(t);
return result;
}
public Transaction saveExchange(Transaction t){
Assert.isTrue(t.getId() == 0);
Assert.isTrue(t.getBook() != null);
t.setSeller(this.readerService.findOne(this.actorService.getActorLogged().getId()));
t.setTicker(tickerGenerator());
t.setIsSale(false);
t.setIsFinished(false);
Transaction result = this.transactionRepository.save(t);
return result;
}
public void delete(Transaction t){
Assert.isTrue(t.getSeller().equals(this.readerService.findOne(this.actorService.getActorLogged().getId())));
Assert.isTrue(t.getIsFinished() == false);
this.transactionRepository.delete(t);
}
public void delete3(Transaction t){
this.transactionRepository.delete(t);
}
public void updateDelete(Transaction t){
t.setBuyer(null);
this.transactionRepository.save(t);
}
private String tickerGenerator() {
String dateRes = "";
String numericRes = "";
final String alphanumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
dateRes = new SimpleDateFormat("yyMMdd").format(Calendar.getInstance().getTime());
for (int i = 0; i < 5; i++) {
final Random random = new Random();
numericRes = numericRes + alphanumeric.charAt(random.nextInt(alphanumeric.length() - 1));
}
return dateRes + "-" + numericRes;
}
public Collection<Transaction> getSalesByReader(){
Reader r = this.readerService.findOne(this.actorService.getActorLogged().getId());
Assert.notNull(r);
return this.transactionRepository.getSalesByReader(r);
}
public Collection<Transaction> getBuysByReader(){
Reader r = this.readerService.findOne(this.actorService.getActorLogged().getId());
Assert.notNull(r);
return this.transactionRepository.getBuysByReader(r);
}
public Collection<Transaction> getExchangesByReader(){
Reader r = this.readerService.findOne(this.actorService.getActorLogged().getId());
Assert.notNull(r);
return this.transactionRepository.getExchangesByReader(r);
}
public Collection<Transaction> getSalesWithoutBuyer(){
return this.transactionRepository.getSalesWithoutBuyer();
}
public Collection<Transaction> getExchanges(){
return this.transactionRepository.getExchanges();
}
public Collection<Transaction> findAllNotFinished() {return this.transactionRepository.findAllNotFinished();}
public Transaction getTransactionByComplaint(final int complaintId){
return this.transactionRepository.getTransactionByComplaint(complaintId);
}
}
<file_sep>package repositories;
import domain.Message;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Collection;
@Repository
public interface MessageRepository extends JpaRepository<Message, Integer> {
@Query("select mb.messages from MessageBox mb where mb.id = ?1")
Collection<Message> findByMessageBox(int messageBoxID);
@Query("select m from Message m where m.sender.id=?1")
Collection<Message> findAllSentByActor(int actorID);
@Query("select (count(s))/(select (count(t)*1.0) from Message t where t.sender.id=?1) from Message s where s.sender.id=?1 and s.isSpam=TRUE")
Double findSpamRatioByActor(int actorID);
@Query("select m from Message m join m.recipients r where r.id=?1")
Collection<Message> findAllReceivedByActor(int actorID);
}<file_sep>package converters;
import domain.Transaction;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import repositories.TransactionRepository;
import javax.transaction.Transactional;
@Component
@Transactional
public class StringToTransactionConverter implements Converter<String, Transaction> {
@Autowired
TransactionRepository transactionRepository;
@Override
public Transaction convert(final String text) {
Transaction result;
int id;
try {
if (StringUtils.isEmpty(text))
result = null;
else {
id = Integer.valueOf(text);
result = this.transactionRepository.findOne(id);
}
} catch (final Throwable oops) {
throw new IllegalArgumentException(oops);
}
return result;
}
}
<file_sep>package repositories;
import domain.Reader;
import domain.Transaction;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Collection;
@Repository
public interface TransactionRepository extends JpaRepository<Transaction, Integer> {
@Query("select t from Transaction t where t.isSale = true and t.seller = ?1")
Collection<Transaction> getSalesByReader(Reader r);
@Query("select t from Transaction t where t.isSale = true and t.buyer = ?1")
Collection<Transaction> getBuysByReader(Reader r);
@Query("select t from Transaction t where t.isSale = false and t.seller = ?1")
Collection<Transaction> getExchangesByReader(Reader r);
@Query("select t from Transaction t where t.isSale = true and t.buyer is null")
Collection<Transaction> getSalesWithoutBuyer();
@Query("select t from Transaction t where t.isSale = false and not exists(select o from Offer o where o.transaction = t and o.status like 'ACCEPTED')")
Collection<Transaction> getExchanges();
@Query("select t from Transaction t where t.isFinished=FALSE")
Collection<Transaction> findAllNotFinished();
@Query("select t from Transaction t join t.complaints c where c.id=?1")
Transaction getTransactionByComplaint(final int complaintId);
}
<file_sep>event.title = Title
event.description = Description
event.date = Date
event.maximumCapacity = Maximum capacity
event.status = Status
event.show = Show
event.edit = Edit
event.create = Create new event
event.draft = Draft
event.final = Final
event.address = Address
event.actualCapacity = Actual capacity
event.organizer = Organizer
event.registers = Registers
event.register.date = Date
event.register.reader = Reader
event.back = Back
event.saveDraft = Save Draft
event.saveFinal = Save Final
event.cancel = Cancel
event.delete = Delete
event.commit.error = Cannot commit this operation
event.checkIn = Check In<file_sep>report.moment = Moment
report.description = Description
report.attachments = Attachments
report.complaint = Complaint
report.comments = Comments
report.isFinal = Mode
report.final = Final mode
report.draft = Draft mode
report.edit = Edit
report.save = Save
report.cancel = Cancel
report.back = Back
report.commit.error = Can not commit this operation
comment.create = Create comment
<file_sep>package services;
import domain.Complaint;
import domain.Referee;
import domain.Report;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.ReportRepository;
import javax.transaction.Transactional;
import javax.validation.ValidationException;
import java.util.Collection;
import java.util.Date;
@Service
@Transactional
public class ReportService {
@Autowired
private ReportRepository reportRepository;
@Autowired
private ActorService actorService;
@Autowired
private RefereeService refereeService;
@Autowired
private ComplaintService complaintService;
@Autowired
private Validator validator;
public Report create(){
Assert.isTrue(actorService.getActorLogged() instanceof Referee);
Report result = new Report();
return result;
}
public Report findOne(int reportId){
return this.reportRepository.findOne(reportId);
}
public Collection<Report> findAll(){
return this.reportRepository.findAll();
}
public Report save(Report report, int complaintId){
Assert.isTrue(actorService.getActorLogged() instanceof Referee);
Referee referee = this.refereeService.findOne(actorService.getActorLogged().getId());
Complaint complaint = this.complaintService.findOne(complaintId);
Assert.isTrue(complaint.getReferee().equals(referee));
Assert.isTrue(report.getComplaint().equals(complaint));
Report result = this.reportRepository.save(report);
return result;
}
public Collection<Report> getReportsByReferee(int refereeId){
return this.reportRepository.getReportsByReferee(refereeId);
}
public Collection<Report> getReportsFinalByComplaint(int complaintId){
return this.reportRepository.getReportsFinalByComplaint(complaintId);
}
public Report reconstruct(final Report report, int complaintId, final BindingResult binding) {
Report result;
if(report.getId()==0) {
result = this.create();
result.setMoment(new Date());
result.setDescription(report.getDescription());
result.setIsFinal(report.getIsFinal());
result.setAttachments(report.getAttachments());
result.setComplaint(complaintService.findOne(complaintId));
result.setComments(report.getComments());
} else{
result = this.findOne(report.getId());
result.setDescription(report.getDescription());
result.setAttachments(report.getAttachments());
result.setIsFinal(report.getIsFinal());
}
this.validator.validate(result, binding);
if (binding.hasErrors())
throw new ValidationException();
return result;
}
public Collection<Report> getReportsByComplaint(final int complaintId){
Collection<Report> result = this.reportRepository.getReportsByComplaint(complaintId);
return result;
}
public void delete(final int reportId){
this.reportRepository.delete(reportId);
}
}
<file_sep>actor.name = Nombre
actor.surname = Apellidos
actor.email = Correo
actor.phoneNumber = Número de telefono
actor.address = Dirección
actor.vatNumber = IVA
edit.PD = Editar información personal
socialProfile = Redes sociales
actor.make = Marca
messageBox.goBack = Atrás
actor.deleteMSG = Este boton hara que toda la informacion almacenada sobre usted en nuestra base de datos y su cuenta\
sea eliminada. ¿Esta seguro de que desea continuar?
actor.deleteAccount = Borrar toda la informacion
messageBox.goBack = Atrás
profile.export = Exportar Datos Personales
<file_sep>start transaction;
drop database if exists `Acme-Library`;
create database `Acme-Library`;
use 'Acme-Library';
create user 'acme-user'@'%'
identified by password <PASSWORD>';
create user 'acme-manager'@'%'
identified by password <PASSWORD>';
grant select, insert, update, delete
on `Acme-Library`.* to 'acme-user'@'%';
grant select, insert, update, delete, create, drop, references, index, alter,
create temporary tables, lock tables, create view, create routine,
alter routine, execute, trigger, show view
on `Acme-Library`.* to 'acme-manager'@'%';
-- MySQL dump 10.13 Distrib 5.5.29, for Win64 (x86)
--
-- Host: localhost Database: Acme-Library
-- ------------------------------------------------------
-- Server version 5.5.29
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `actor_boxes`
--
DROP TABLE IF EXISTS `actor_boxes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `actor_boxes` (
`actor` int(11) NOT NULL,
`boxes` int(11) NOT NULL,
UNIQUE KEY `UK_6n6psqivvjho155qcf9kjvv1h` (`boxes`),
CONSTRAINT `FK_6n6psqivvjho155qcf9kjvv1h` FOREIGN KEY (`boxes`) REFERENCES `message_box` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `actor_boxes`
--
LOCK TABLES `actor_boxes` WRITE;
/*!40000 ALTER TABLE `actor_boxes` DISABLE KEYS */;
INSERT INTO `actor_boxes` VALUES (18,19),(18,20),(18,21),(18,22),(18,23);
/*!40000 ALTER TABLE `actor_boxes` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `actor_social_profiles`
--
DROP TABLE IF EXISTS `actor_social_profiles`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `actor_social_profiles` (
`actor` int(11) NOT NULL,
`social_profiles` int(11) NOT NULL,
UNIQUE KEY `UK_4suhrykpl9af1ubs85ycbyt6q` (`social_profiles`),
CONSTRAINT `FK_4suhrykpl9af1ubs85ycbyt6q` FOREIGN KEY (`social_profiles`) REFERENCES `social_profile` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `actor_social_profiles`
--
LOCK TABLES `actor_social_profiles` WRITE;
/*!40000 ALTER TABLE `actor_social_profiles` DISABLE KEYS */;
/*!40000 ALTER TABLE `actor_social_profiles` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `administrator`
--
DROP TABLE IF EXISTS `administrator`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `administrator` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`is_banned` bit(1) DEFAULT NULL,
`is_suspicious` bit(1) DEFAULT NULL,
`middle_name` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`phone_number` varchar(255) DEFAULT NULL,
`photo` varchar(255) DEFAULT NULL,
`score` double DEFAULT NULL,
`surname` varchar(255) DEFAULT NULL,
`user_account` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_7ohwsa2usmvu0yxb44je2lge` (`user_account`),
KEY `administratorUK_bu4olbe7htfrt00ughoyyrlor` (`is_suspicious`,`is_banned`),
CONSTRAINT `FK_7ohwsa2usmvu0yxb44je2lge` FOREIGN KEY (`user_account`) REFERENCES `user_account` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `administrator`
--
LOCK TABLES `administrator` WRITE;
/*!40000 ALTER TABLE `administrator` DISABLE KEYS */;
INSERT INTO `administrator` VALUES (18,0,'<NAME>','<EMAIL>','\0','\0',NULL,'admin1','+34 678123674','https://github.com/dp2-anacardo/DP2-D01',0,'admin1',17);
/*!40000 ALTER TABLE `administrator` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `book`
--
DROP TABLE IF EXISTS `book`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `book` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`author` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`isbn` varchar(255) DEFAULT NULL,
`language` varchar(255) DEFAULT NULL,
`moment` datetime DEFAULT NULL,
`page_number` int(11) NOT NULL,
`photo` varchar(255) DEFAULT NULL,
`publisher` varchar(255) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`title` varchar(255) DEFAULT NULL,
`reader` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_ebuux1jb5lk9lxjbsf692dyed` (`reader`),
CONSTRAINT `FK_ebuux1jb5lk9lxjbsf692dyed` FOREIGN KEY (`reader`) REFERENCES `reader` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `book`
--
LOCK TABLES `book` WRITE;
/*!40000 ALTER TABLE `book` DISABLE KEYS */;
/*!40000 ALTER TABLE `book` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `book_categories`
--
DROP TABLE IF EXISTS `book_categories`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `book_categories` (
`book` int(11) NOT NULL,
`categories` int(11) NOT NULL,
KEY `FK_3pm8trr8p0jcqoix788newbij` (`categories`),
KEY `FK_pd6fjxd601e42olxrm6f0v887` (`book`),
CONSTRAINT `FK_pd6fjxd601e42olxrm6f0v887` FOREIGN KEY (`book`) REFERENCES `book` (`id`),
CONSTRAINT `FK_3pm8trr8p0jcqoix788newbij` FOREIGN KEY (`categories`) REFERENCES `category` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `book_categories`
--
LOCK TABLES `book_categories` WRITE;
/*!40000 ALTER TABLE `book_categories` DISABLE KEYS */;
/*!40000 ALTER TABLE `book_categories` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `category`
--
DROP TABLE IF EXISTS `category`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `category` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`name_en` varchar(255) DEFAULT NULL,
`name_es` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `category`
--
LOCK TABLES `category` WRITE;
/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` VALUES (24,0,'Sci-fi','Ciencia ficción'),(25,0,'Scientific','Científico'),(26,0,'Biography','Biografía'),(27,0,'Song','Canción'),(28,0,'Romance','Romance'),(29,0,'Story','Cuento'),(30,0,'Drama','Dramático'),(31,0,'Default','Por defecto');
/*!40000 ALTER TABLE `category` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `comment`
--
DROP TABLE IF EXISTS `comment`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `comment` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`body` varchar(255) DEFAULT NULL,
`moment` datetime DEFAULT NULL,
`author` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_61mgdkv1yj5lo5vbvl8m3ddxr` (`author`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `comment`
--
LOCK TABLES `comment` WRITE;
/*!40000 ALTER TABLE `comment` DISABLE KEYS */;
/*!40000 ALTER TABLE `comment` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `complaint`
--
DROP TABLE IF EXISTS `complaint`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `complaint` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`body` varchar(255) DEFAULT NULL,
`moment` datetime DEFAULT NULL,
`ticker` varchar(255) DEFAULT NULL,
`reader` int(11) NOT NULL,
`referee` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_jlpo668tu0b8mmsjsg8g13inu` (`ticker`),
KEY `FK_olaghip74fn0u78ju8px659ur` (`reader`),
KEY `FK_n7kqs8a7c2q1jwjcc44oticll` (`referee`),
CONSTRAINT `FK_n7kqs8a7c2q1jwjcc44oticll` FOREIGN KEY (`referee`) REFERENCES `referee` (`id`),
CONSTRAINT `FK_olaghip74fn0u78ju8px659ur` FOREIGN KEY (`reader`) REFERENCES `reader` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `complaint`
--
LOCK TABLES `complaint` WRITE;
/*!40000 ALTER TABLE `complaint` DISABLE KEYS */;
/*!40000 ALTER TABLE `complaint` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `complaint_attachments`
--
DROP TABLE IF EXISTS `complaint_attachments`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `complaint_attachments` (
`complaint` int(11) NOT NULL,
`link` varchar(255) DEFAULT NULL,
KEY `FK_f4g1vv33vade4pm8t0qim14os` (`complaint`),
CONSTRAINT `FK_f4g1vv33vade4pm8t0qim14os` FOREIGN KEY (`complaint`) REFERENCES `complaint` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `complaint_attachments`
--
LOCK TABLES `complaint_attachments` WRITE;
/*!40000 ALTER TABLE `complaint_attachments` DISABLE KEYS */;
/*!40000 ALTER TABLE `complaint_attachments` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `configuration`
--
DROP TABLE IF EXISTS `configuration`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `configuration` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`banner` varchar(255) DEFAULT NULL,
`country_code` varchar(255) DEFAULT NULL,
`defaultvat` double DEFAULT NULL,
`flat_fee` double DEFAULT NULL,
`max_results` int(11) NOT NULL,
`max_time` int(11) NOT NULL,
`system_name` varchar(255) DEFAULT NULL,
`welcome_message_en` varchar(255) DEFAULT NULL,
`welcome_message_es` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `configuration`
--
LOCK TABLES `configuration` WRITE;
/*!40000 ALTER TABLE `configuration` DISABLE KEYS */;
INSERT INTO `configuration` VALUES (32,0,'https://tinyurl.com/acme-library','34',21,10,10,1,'Acme Library','Welcome to Acme Library, the site to sell your books.','¡Bienvenidos a Acme Biblioteca! Tu sitio para vender libros.');
/*!40000 ALTER TABLE `configuration` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `configuration_brand_name`
--
DROP TABLE IF EXISTS `configuration_brand_name`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `configuration_brand_name` (
`configuration` int(11) NOT NULL,
`brand_name` varchar(255) DEFAULT NULL,
KEY `FK_5d1b98sg2m4qxl288ir55wny7` (`configuration`),
CONSTRAINT `FK_5d1b98sg2m4qxl288ir55wny7` FOREIGN KEY (`configuration`) REFERENCES `configuration` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `configuration_brand_name`
--
LOCK TABLES `configuration_brand_name` WRITE;
/*!40000 ALTER TABLE `configuration_brand_name` DISABLE KEYS */;
INSERT INTO `configuration_brand_name` VALUES (32,'VISA'),(32,'MCARD'),(32,'DINNERS'),(32,'AMEX'),(32,'FLY');
/*!40000 ALTER TABLE `configuration_brand_name` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `configuration_neg_words`
--
DROP TABLE IF EXISTS `configuration_neg_words`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `configuration_neg_words` (
`configuration` int(11) NOT NULL,
`neg_words` varchar(255) DEFAULT NULL,
KEY `FK_5un6agbja8hccx37ns0mc0y1p` (`configuration`),
CONSTRAINT `FK_5un6agbja8hccx37ns0mc0y1p` FOREIGN KEY (`configuration`) REFERENCES `configuration` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `configuration_neg_words`
--
LOCK TABLES `configuration_neg_words` WRITE;
/*!40000 ALTER TABLE `configuration_neg_words` DISABLE KEYS */;
INSERT INTO `configuration_neg_words` VALUES (32,'not'),(32,'bad'),(32,'horrible'),(32,'average'),(32,'disaster'),(32,'no'),(32,'malo'),(32,'malos'),(32,'mala'),(32,'malas'),(32,'mediocre'),(32,'desastroso'),(32,'desastrosos'),(32,'desastrosa'),(32,'desastrosas');
/*!40000 ALTER TABLE `configuration_neg_words` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `configuration_pos_words`
--
DROP TABLE IF EXISTS `configuration_pos_words`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `configuration_pos_words` (
`configuration` int(11) NOT NULL,
`pos_words` varchar(255) DEFAULT NULL,
KEY `FK_ossba080fsry30u0wccnuv4yn` (`configuration`),
CONSTRAINT `FK_ossba080fsry30u0wccnuv4yn` FOREIGN KEY (`configuration`) REFERENCES `configuration` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `configuration_pos_words`
--
LOCK TABLES `configuration_pos_words` WRITE;
/*!40000 ALTER TABLE `configuration_pos_words` DISABLE KEYS */;
INSERT INTO `configuration_pos_words` VALUES (32,'good'),(32,'fantastic'),(32,'excellent'),(32,'great'),(32,'amazing'),(32,'terrific'),(32,'beautiful'),(32,'bueno'),(32,'buenos'),(32,'buena'),(32,'buenas'),(32,'fantastico'),(32,'fantasticos'),(32,'fantastica'),(32,'fantasticas'),(32,'excelente'),(32,'excelentes'),(32,'genial'),(32,'geniales'),(32,'increible'),(32,'increibles'),(32,'estupendo'),(32,'estupendos'),(32,'estupenda'),(32,'estupendas'),(32,'bonito'),(32,'bonitos'),(32,'bonita'),(32,'bonitas');
/*!40000 ALTER TABLE `configuration_pos_words` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `configuration_spam_words`
--
DROP TABLE IF EXISTS `configuration_spam_words`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `configuration_spam_words` (
`configuration` int(11) NOT NULL,
`spam_words` varchar(255) DEFAULT NULL,
KEY `FK_qk3m1jkx4rq87ofjee19f3b33` (`configuration`),
CONSTRAINT `FK_qk3m1jkx4rq87ofjee19f3b33` FOREIGN KEY (`configuration`) REFERENCES `configuration` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `configuration_spam_words`
--
LOCK TABLES `configuration_spam_words` WRITE;
/*!40000 ALTER TABLE `configuration_spam_words` DISABLE KEYS */;
INSERT INTO `configuration_spam_words` VALUES (32,'sex'),(32,'viagra'),(32,'cialis'),(32,'one million'),(32,'you\'ve been selected'),(32,'Nigeria'),(32,'sexo'),(32,'un millon'),(32,'has sido seleccionado'),(32,'has sido seleccionada');
/*!40000 ALTER TABLE `configuration_spam_words` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `event`
--
DROP TABLE IF EXISTS `event`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `event` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`is_final` bit(1) NOT NULL,
`maximum_capacity` int(11) NOT NULL,
`title` varchar(255) DEFAULT NULL,
`organizer` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_rujmgol7iwhb39gfrj7y4iwwd` (`organizer`),
CONSTRAINT `FK_rujmgol7iwhb39gfrj7y4iwwd` FOREIGN KEY (`organizer`) REFERENCES `organizer` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `event`
--
LOCK TABLES `event` WRITE;
/*!40000 ALTER TABLE `event` DISABLE KEYS */;
/*!40000 ALTER TABLE `event` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `event_registers`
--
DROP TABLE IF EXISTS `event_registers`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `event_registers` (
`event` int(11) NOT NULL,
`registers` int(11) NOT NULL,
UNIQUE KEY `UK_r593igus0vaava8bpvryvawgy` (`registers`),
KEY `FK_395ivyw44u06hbph9ijgm8s90` (`event`),
CONSTRAINT `FK_395ivyw44u06hbph9ijgm8s90` FOREIGN KEY (`event`) REFERENCES `event` (`id`),
CONSTRAINT `FK_r593igus0vaava8bpvryvawgy` FOREIGN KEY (`registers`) REFERENCES `register` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `event_registers`
--
LOCK TABLES `event_registers` WRITE;
/*!40000 ALTER TABLE `event_registers` DISABLE KEYS */;
/*!40000 ALTER TABLE `event_registers` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `finder`
--
DROP TABLE IF EXISTS `finder`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `finder` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`category_name` varchar(255) DEFAULT NULL,
`key_word` varchar(255) DEFAULT NULL,
`last_update` datetime DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `finder`
--
LOCK TABLES `finder` WRITE;
/*!40000 ALTER TABLE `finder` DISABLE KEYS */;
/*!40000 ALTER TABLE `finder` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `finder_transactions`
--
DROP TABLE IF EXISTS `finder_transactions`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `finder_transactions` (
`finder` int(11) NOT NULL,
`transactions` int(11) NOT NULL,
KEY `FK_lk453eye39wq0j2ckarym7byv` (`transactions`),
KEY `FK_dex0m9r64k8r6nr8ghwm51j98` (`finder`),
CONSTRAINT `FK_dex0m9r64k8r6nr8ghwm51j98` FOREIGN KEY (`finder`) REFERENCES `finder` (`id`),
CONSTRAINT `FK_lk453eye39wq0j2ckarym7byv` FOREIGN KEY (`transactions`) REFERENCES `transaction` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `finder_transactions`
--
LOCK TABLES `finder_transactions` WRITE;
/*!40000 ALTER TABLE `finder_transactions` DISABLE KEYS */;
/*!40000 ALTER TABLE `finder_transactions` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `hibernate_sequences`
--
DROP TABLE IF EXISTS `hibernate_sequences`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `hibernate_sequences` (
`sequence_name` varchar(255) DEFAULT NULL,
`sequence_next_hi_value` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `hibernate_sequences`
--
LOCK TABLES `hibernate_sequences` WRITE;
/*!40000 ALTER TABLE `hibernate_sequences` DISABLE KEYS */;
INSERT INTO `hibernate_sequences` VALUES ('domain_entity',1);
/*!40000 ALTER TABLE `hibernate_sequences` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `message`
--
DROP TABLE IF EXISTS `message`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`body` varchar(255) DEFAULT NULL,
`is_spam` bit(1) DEFAULT NULL,
`moment` datetime DEFAULT NULL,
`priority` varchar(255) DEFAULT NULL,
`subject` varchar(255) DEFAULT NULL,
`sender` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `message`
--
LOCK TABLES `message` WRITE;
/*!40000 ALTER TABLE `message` DISABLE KEYS */;
/*!40000 ALTER TABLE `message` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `message_box`
--
DROP TABLE IF EXISTS `message_box`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message_box` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`is_system` bit(1) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `message_box`
--
LOCK TABLES `message_box` WRITE;
/*!40000 ALTER TABLE `message_box` DISABLE KEYS */;
INSERT INTO `message_box` VALUES (19,0,'','INBOX'),(20,0,'','OUTBOX'),(21,0,'','SPAMBOX'),(22,0,'','TRASHBOX'),(23,0,'','NOTIFICATIONBOX');
/*!40000 ALTER TABLE `message_box` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `message_box_messages`
--
DROP TABLE IF EXISTS `message_box_messages`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message_box_messages` (
`message_box` int(11) NOT NULL,
`messages` int(11) NOT NULL,
KEY `FK_4ydibw5107qpqjwmw37t3cx5c` (`messages`),
KEY `FK_i9fsy1u5e0dyn977c4uhdupur` (`message_box`),
CONSTRAINT `FK_i9fsy1u5e0dyn977c4uhdupur` FOREIGN KEY (`message_box`) REFERENCES `message_box` (`id`),
CONSTRAINT `FK_4ydibw5107qpqjwmw37t3cx5c` FOREIGN KEY (`messages`) REFERENCES `message` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `message_box_messages`
--
LOCK TABLES `message_box_messages` WRITE;
/*!40000 ALTER TABLE `message_box_messages` DISABLE KEYS */;
/*!40000 ALTER TABLE `message_box_messages` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `message_message_boxes`
--
DROP TABLE IF EXISTS `message_message_boxes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message_message_boxes` (
`message` int(11) NOT NULL,
`message_boxes` int(11) NOT NULL,
KEY `FK_9e3s75h2409iiuiugj5h00enq` (`message_boxes`),
KEY `FK_pg69wrq7o02j8baa8d56f1x0q` (`message`),
CONSTRAINT `FK_pg69wrq7o02j8baa8d56f1x0q` FOREIGN KEY (`message`) REFERENCES `message` (`id`),
CONSTRAINT `FK_9e3s75h2409iiuiugj5h00enq` FOREIGN KEY (`message_boxes`) REFERENCES `message_box` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `message_message_boxes`
--
LOCK TABLES `message_message_boxes` WRITE;
/*!40000 ALTER TABLE `message_message_boxes` DISABLE KEYS */;
/*!40000 ALTER TABLE `message_message_boxes` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `message_recipients`
--
DROP TABLE IF EXISTS `message_recipients`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message_recipients` (
`message` int(11) NOT NULL,
`recipients` int(11) NOT NULL,
KEY `FK_1odmg2n3n487tvhuxx5oyyya2` (`message`),
CONSTRAINT `FK_1odmg2n3n487tvhuxx5oyyya2` FOREIGN KEY (`message`) REFERENCES `message` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `message_recipients`
--
LOCK TABLES `message_recipients` WRITE;
/*!40000 ALTER TABLE `message_recipients` DISABLE KEYS */;
/*!40000 ALTER TABLE `message_recipients` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `message_tags`
--
DROP TABLE IF EXISTS `message_tags`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message_tags` (
`message` int(11) NOT NULL,
`tags` varchar(255) DEFAULT NULL,
KEY `FK_suckduhsrrtot7go5ejeev57w` (`message`),
CONSTRAINT `FK_suckduhsrrtot7go5ejeev57w` FOREIGN KEY (`message`) REFERENCES `message` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `message_tags`
--
LOCK TABLES `message_tags` WRITE;
/*!40000 ALTER TABLE `message_tags` DISABLE KEYS */;
/*!40000 ALTER TABLE `message_tags` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `offer`
--
DROP TABLE IF EXISTS `offer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `offer` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`comment` varchar(255) DEFAULT NULL,
`moment` datetime DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`book` int(11) NOT NULL,
`reader` int(11) NOT NULL,
`transaction` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_q7ydmwhd7i0flsifa9psvhpa9` (`book`),
KEY `FK_mrkwq3d6bbb9i5m9bbabhkux` (`reader`),
KEY `FK_nxac2y59j75skt4j1gylv1ex9` (`transaction`),
CONSTRAINT `FK_nxac2y59j75skt4j1gylv1ex9` FOREIGN KEY (`transaction`) REFERENCES `transaction` (`id`),
CONSTRAINT `FK_mrkwq3d6bbb9i5m9bbabhkux` FOREIGN KEY (`reader`) REFERENCES `reader` (`id`),
CONSTRAINT `FK_q7ydmwhd7i0flsifa9psvhpa9` FOREIGN KEY (`book`) REFERENCES `book` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `offer`
--
LOCK TABLES `offer` WRITE;
/*!40000 ALTER TABLE `offer` DISABLE KEYS */;
/*!40000 ALTER TABLE `offer` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `organizer`
--
DROP TABLE IF EXISTS `organizer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `organizer` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`is_banned` bit(1) DEFAULT NULL,
`is_suspicious` bit(1) DEFAULT NULL,
`middle_name` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`phone_number` varchar(255) DEFAULT NULL,
`photo` varchar(255) DEFAULT NULL,
`score` double DEFAULT NULL,
`surname` varchar(255) DEFAULT NULL,
`user_account` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_ca1qcg8j5ftgyirqhyuc8hawb` (`user_account`),
KEY `organizerUK_bu4olbe7htfrt00ughoyyrlor` (`is_suspicious`,`is_banned`),
CONSTRAINT `FK_ca1qcg8j5ftgyirqhyuc8hawb` FOREIGN KEY (`user_account`) REFERENCES `user_account` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `organizer`
--
LOCK TABLES `organizer` WRITE;
/*!40000 ALTER TABLE `organizer` DISABLE KEYS */;
/*!40000 ALTER TABLE `organizer` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `reader`
--
DROP TABLE IF EXISTS `reader`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reader` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`is_banned` bit(1) DEFAULT NULL,
`is_suspicious` bit(1) DEFAULT NULL,
`middle_name` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`phone_number` varchar(255) DEFAULT NULL,
`photo` varchar(255) DEFAULT NULL,
`score` double DEFAULT NULL,
`surname` varchar(255) DEFAULT NULL,
`user_account` int(11) NOT NULL,
`finder` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_qlj7vanpxdlw0sr0ab58aciae` (`finder`),
UNIQUE KEY `UK_3xs5anj4cilhtancciqe3s8un` (`user_account`),
KEY `readerUK_bu4olbe7htfrt00ughoyyrlor` (`is_suspicious`,`is_banned`),
CONSTRAINT `FK_3xs5anj4cilhtancciqe3s8un` FOREIGN KEY (`user_account`) REFERENCES `user_account` (`id`),
CONSTRAINT `FK_qlj7vanpxdlw0sr0ab58aciae` FOREIGN KEY (`finder`) REFERENCES `finder` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `reader`
--
LOCK TABLES `reader` WRITE;
/*!40000 ALTER TABLE `reader` DISABLE KEYS */;
/*!40000 ALTER TABLE `reader` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `referee`
--
DROP TABLE IF EXISTS `referee`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `referee` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`is_banned` bit(1) DEFAULT NULL,
`is_suspicious` bit(1) DEFAULT NULL,
`middle_name` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`phone_number` varchar(255) DEFAULT NULL,
`photo` varchar(255) DEFAULT NULL,
`score` double DEFAULT NULL,
`surname` varchar(255) DEFAULT NULL,
`user_account` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_303c1oipw0t6mbnnpvtfv70w5` (`user_account`),
KEY `refereeUK_bu4olbe7htfrt00ughoyyrlor` (`is_suspicious`,`is_banned`),
CONSTRAINT `FK_303c1oipw0t6mbnnpvtfv70w5` FOREIGN KEY (`user_account`) REFERENCES `user_account` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `referee`
--
LOCK TABLES `referee` WRITE;
/*!40000 ALTER TABLE `referee` DISABLE KEYS */;
/*!40000 ALTER TABLE `referee` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `register`
--
DROP TABLE IF EXISTS `register`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `register` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`moment` datetime DEFAULT NULL,
`reader` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_icw6h5ekbybb6hdsemxeoaa4p` (`reader`),
CONSTRAINT `FK_icw6h5ekbybb6hdsemxeoaa4p` FOREIGN KEY (`reader`) REFERENCES `reader` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `register`
--
LOCK TABLES `register` WRITE;
/*!40000 ALTER TABLE `register` DISABLE KEYS */;
/*!40000 ALTER TABLE `register` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `report`
--
DROP TABLE IF EXISTS `report`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `report` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`description` varchar(255) DEFAULT NULL,
`is_final` bit(1) NOT NULL,
`moment` datetime DEFAULT NULL,
`complaint` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_48rqaecflpcs8unotw4drrtfw` (`complaint`),
CONSTRAINT `FK_48rqaecflpcs8unotw4drrtfw` FOREIGN KEY (`complaint`) REFERENCES `complaint` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `report`
--
LOCK TABLES `report` WRITE;
/*!40000 ALTER TABLE `report` DISABLE KEYS */;
/*!40000 ALTER TABLE `report` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `report_attachments`
--
DROP TABLE IF EXISTS `report_attachments`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `report_attachments` (
`report` int(11) NOT NULL,
`link` varchar(255) DEFAULT NULL,
KEY `FK_8pqwcub4o2xip8o8ohqk3bu05` (`report`),
CONSTRAINT `FK_8pqwcub4o2xip8o8ohqk3bu05` FOREIGN KEY (`report`) REFERENCES `report` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `report_attachments`
--
LOCK TABLES `report_attachments` WRITE;
/*!40000 ALTER TABLE `report_attachments` DISABLE KEYS */;
/*!40000 ALTER TABLE `report_attachments` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `report_comments`
--
DROP TABLE IF EXISTS `report_comments`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `report_comments` (
`report` int(11) NOT NULL,
`comments` int(11) NOT NULL,
UNIQUE KEY `UK_<KEY>` (`comments`),
KEY `FK_rv98td83ckn33xg2dtq0jq62u` (`report`),
CONSTRAINT `FK_rv98td83ckn33xg2dtq0jq62u` FOREIGN KEY (`report`) REFERENCES `report` (`id`),
CONSTRAINT `FK_d4y879fifriio51somrqna2ax` FOREIGN KEY (`comments`) REFERENCES `comment` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `report_comments`
--
LOCK TABLES `report_comments` WRITE;
/*!40000 ALTER TABLE `report_comments` DISABLE KEYS */;
/*!40000 ALTER TABLE `report_comments` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `social_profile`
--
DROP TABLE IF EXISTS `social_profile`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `social_profile` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`nick` varchar(255) DEFAULT NULL,
`profile_link` varchar(255) DEFAULT NULL,
`social_network_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `social_profile`
--
LOCK TABLES `social_profile` WRITE;
/*!40000 ALTER TABLE `social_profile` DISABLE KEYS */;
/*!40000 ALTER TABLE `social_profile` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `sponsor`
--
DROP TABLE IF EXISTS `sponsor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sponsor` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`is_banned` bit(1) DEFAULT NULL,
`is_suspicious` bit(1) DEFAULT NULL,
`middle_name` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`phone_number` varchar(255) DEFAULT NULL,
`photo` varchar(255) DEFAULT NULL,
`score` double DEFAULT NULL,
`surname` varchar(255) DEFAULT NULL,
`user_account` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_du2w5ldt8rvlvxvtr7vyxk7g3` (`user_account`),
KEY `sponsorUK_bu4olbe7htfrt00ughoyyrlor` (`is_suspicious`,`is_banned`),
CONSTRAINT `FK_du2w5ldt8rvlvxvtr7vyxk7g3` FOREIGN KEY (`user_account`) REFERENCES `user_account` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `sponsor`
--
LOCK TABLES `sponsor` WRITE;
/*!40000 ALTER TABLE `sponsor` DISABLE KEYS */;
/*!40000 ALTER TABLE `sponsor` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `sponsorship`
--
DROP TABLE IF EXISTS `sponsorship`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sponsorship` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`banner` varchar(255) DEFAULT NULL,
`brand_name` varchar(255) DEFAULT NULL,
`cvv` int(11) DEFAULT NULL,
`expiration_year` date DEFAULT NULL,
`holder` varchar(255) DEFAULT NULL,
`number` varchar(255) DEFAULT NULL,
`status` bit(1) DEFAULT NULL,
`event` int(11) NOT NULL,
`sponsor` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_kmuj14sjw9vdjuttjpamsh2fv` (`event`),
KEY `FK_huglhkud0ihqdljyou4eshra6` (`sponsor`),
CONSTRAINT `FK_huglhkud0ihqdljyou4eshra6` FOREIGN KEY (`sponsor`) REFERENCES `sponsor` (`id`),
CONSTRAINT `FK_kmuj14sjw9vdjuttjpamsh2fv` FOREIGN KEY (`event`) REFERENCES `event` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `sponsorship`
--
LOCK TABLES `sponsorship` WRITE;
/*!40000 ALTER TABLE `sponsorship` DISABLE KEYS */;
/*!40000 ALTER TABLE `sponsorship` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `transaction`
--
DROP TABLE IF EXISTS `transaction`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `transaction` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`brand_name` varchar(255) DEFAULT NULL,
`cvv` int(11) DEFAULT NULL,
`expiration_year` date DEFAULT NULL,
`holder` varchar(255) DEFAULT NULL,
`number` varchar(255) DEFAULT NULL,
`is_finished` bit(1) DEFAULT NULL,
`is_sale` bit(1) DEFAULT NULL,
`moment` datetime DEFAULT NULL,
`price` double DEFAULT NULL,
`ticker` varchar(255) DEFAULT NULL,
`book` int(11) NOT NULL,
`buyer` int(11) DEFAULT NULL,
`seller` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_ajpwq837sua56ombpkofw4sk0` (`book`),
UNIQUE KEY `UK_hvrhhjy3m6yvxdua0dikkrmqc` (`ticker`),
KEY `FK_6r68osugpcasab5ghde2w8hh5` (`buyer`),
KEY `FK_ql7nm7sapd66v55rkqkm9th5i` (`seller`),
CONSTRAINT `FK_ql7nm7sapd66v55rkqkm9th5i` FOREIGN KEY (`seller`) REFERENCES `reader` (`id`),
CONSTRAINT `FK_6r68osugpcasab5ghde2w8hh5` FOREIGN KEY (`buyer`) REFERENCES `reader` (`id`),
CONSTRAINT `FK_ajpwq837sua56ombpkofw4sk0` FOREIGN KEY (`book`) REFERENCES `book` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `transaction`
--
LOCK TABLES `transaction` WRITE;
/*!40000 ALTER TABLE `transaction` DISABLE KEYS */;
/*!40000 ALTER TABLE `transaction` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `transaction_complaints`
--
DROP TABLE IF EXISTS `transaction_complaints`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `transaction_complaints` (
`transaction` int(11) NOT NULL,
`complaints` int(11) NOT NULL,
UNIQUE KEY `UK_r711s1c4xovkx9lhw3vxk1nd0` (`complaints`),
KEY `FK_2hjjgs1m3exi1kprpdn4iqup1` (`transaction`),
CONSTRAINT `FK_2hjjgs1m3exi1kprpdn4iqup1` FOREIGN KEY (`transaction`) REFERENCES `transaction` (`id`),
CONSTRAINT `FK_r711s1c4xovkx9lhw3vxk1nd0` FOREIGN KEY (`complaints`) REFERENCES `complaint` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `transaction_complaints`
--
LOCK TABLES `transaction_complaints` WRITE;
/*!40000 ALTER TABLE `transaction_complaints` DISABLE KEYS */;
/*!40000 ALTER TABLE `transaction_complaints` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `user_account`
--
DROP TABLE IF EXISTS `user_account`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_account` (
`id` int(11) NOT NULL,
`version` int(11) NOT NULL,
`password` varchar(255) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_castjbvpeeus0r8lbpehiu0e4` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `user_account`
--
LOCK TABLES `user_account` WRITE;
/*!40000 ALTER TABLE `user_account` DISABLE KEYS */;
INSERT INTO `user_account` VALUES (17,0,'<KEY>','admin1');
/*!40000 ALTER TABLE `user_account` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `user_account_authorities`
--
DROP TABLE IF EXISTS `user_account_authorities`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_account_authorities` (
`user_account` int(11) NOT NULL,
`authority` varchar(255) DEFAULT NULL,
KEY `FK_pao8cwh93fpccb0bx6ilq6gsl` (`user_account`),
CONSTRAINT `FK_pao8cwh93fpccb0bx6ilq6gsl` FOREIGN KEY (`user_account`) REFERENCES `user_account` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `user_account_authorities`
--
LOCK TABLES `user_account_authorities` WRITE;
/*!40000 ALTER TABLE `user_account_authorities` DISABLE KEYS */;
INSERT INTO `user_account_authorities` VALUES (17,'ADMIN');
/*!40000 ALTER TABLE `user_account_authorities` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2019-06-06 3:11:24
commit;<file_sep>
package repositories;
import domain.Organizer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OrganizerRepository extends JpaRepository<Organizer, Integer> {
}
<file_sep>
package services;
import domain.Actor;
import domain.MessageBox;
import domain.Organizer;
import domain.SocialProfile;
import forms.OrganizerForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.OrganizerRepository;
import security.Authority;
import security.UserAccount;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Collection;
@Service
@Transactional
public class OrganizerService {
//Managed Repositories
@Autowired
private OrganizerRepository organizerRepository;
@Autowired
private MessageBoxService messageBoxService;
//Supporting services
@Autowired
private ActorService actorService;
@Autowired
private ConfigurationService configurationService;
@Autowired
private Validator validator;
public Organizer create() {
final Authority auth;
final UserAccount userAccount;
final Collection<Authority> authorities;
final Collection<SocialProfile> profiles;
final Collection<MessageBox> boxes;
final Organizer a = new Organizer();
userAccount = new UserAccount();
auth = new Authority();
authorities = new ArrayList<Authority>();
profiles = new ArrayList<SocialProfile>();
boxes = new ArrayList<MessageBox>();
auth.setAuthority(Authority.ORGANIZER);
authorities.add(auth);
userAccount.setAuthorities(authorities);
a.setUserAccount(userAccount);
a.setIsBanned(false);
a.setIsSuspicious(false);
a.setSocialProfiles(profiles);
a.setBoxes(boxes);
return a;
}
public Collection<Organizer> findAll() {
Collection<Organizer> result;
result = this.organizerRepository.findAll();
return result;
}
public Organizer findOne(final int organizerId) {
Assert.isTrue(organizerId != 0);
Organizer result;
result = this.organizerRepository.findOne(organizerId);
return result;
}
public Organizer save(final Organizer o) {
Assert.notNull(o);
Organizer result;
final char[] c = o.getPhoneNumber().toCharArray();
if ((!o.getPhoneNumber().equals(null) && !o.getPhoneNumber().equals("")))
if (c[0] != '+') {
final String i = this.configurationService.findAll().get(0).getCountryCode();
o.setPhoneNumber("+" + i + " " + o.getPhoneNumber());
}
if (o.getId() == 0) {
final Md5PasswordEncoder encoder = new Md5PasswordEncoder();
final String res = encoder.encodePassword(o.getUserAccount().getPassword(), null);
o.getUserAccount().setPassword(res);
o.setBoxes(this.messageBoxService.createSystemMessageBox());
}
result = this.organizerRepository.save(o);
return result;
}
public void updateAdmin(final Organizer r){
this.organizerRepository.save(r);
}
public void delete(final Organizer o) {
final Actor actor = this.actorService.getActorLogged();
Assert.isTrue(actor.getUserAccount().getAuthorities().iterator().next().getAuthority().equals("ORGANIZER"));
Assert.notNull(o);
Assert.isTrue(actor.getId() != 0);
this.organizerRepository.delete(o);
}
public Organizer reconstruct(final Organizer o, final BindingResult binding) {
Organizer result;
if (o.getId() == 0) {
this.validator.validate(o, binding);
result = o;
} else {
result = this.organizerRepository.findOne(o.getId());
result.setName(o.getName());
result.setPhoto(o.getPhoto());
result.setPhoneNumber(o.getPhoneNumber());
result.setEmail(o.getEmail());
result.setAddress(o.getAddress());
result.setSurname(o.getSurname());
this.validator.validate(o, binding);
}
return result;
}
//Objeto formulario
public Organizer reconstruct(final OrganizerForm o, final BindingResult binding) {
final Organizer result = this.create();
result.setAddress(o.getAddress());
result.setEmail(o.getEmail());
result.setId(o.getId());
result.setName(o.getName());
result.setPhoneNumber(o.getPhoneNumber());
result.setPhoto(o.getPhoto());
result.setSurname(o.getSurname());
result.getUserAccount().setPassword(<PASSWORD>());
result.getUserAccount().setUsername(o.getUsername());
result.setVersion(o.getVersion());
result.setMiddleName(o.getMiddleName());
this.validator.validate(result, binding);
return result;
}
public void flush(){
this.organizerRepository.flush();
}
}
<file_sep>complaint.moment = Moment
complaint.body = Body
complaint.attachments = Attachments
complaint.referee = Referee
complaint.reader = Reader
complaint.back = Back
complaint.commit.error = Can not commit this operation
complaint.save = Save
complaint.cancel = Cancel
complaint.autoAssign = Assign complaint
complaint.show = Show complaint
report.create = Create report
complaint.reports = Reports
<file_sep>
package services;
import domain.Actor;
import domain.Message;
import domain.Sponsor;
import domain.Sponsorship;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.SponsorshipRepository;
import javax.validation.ValidationException;
import java.util.*;
@Service
@Transactional
public class SponsorshipService {
// Manage Repository
@Autowired
private SponsorshipRepository sponsorshipRepository;
@Autowired
private ConfigurationService configurationService;
@Autowired
private MessageService messageService;
@Autowired
private ActorService actorService;
@Autowired
private Validator validator;
// CRUD methods
public Sponsorship create() {
final Sponsorship result = new Sponsorship();
final Sponsor principal = (Sponsor) this.actorService.getActorLogged();
result.setSponsor(principal);
return result;
}
public Sponsorship findOne(final int sponsorshipID) {
final Sponsorship result = this.sponsorshipRepository.findOne(sponsorshipID);
Assert.notNull(result);
return result;
}
public Collection<Sponsorship> findAll() {
final Collection<Sponsorship> result = this.sponsorshipRepository.findAll();
Assert.notNull(result);
return result;
}
public Sponsorship save(final Sponsorship sponsorship) {
Assert.notNull(sponsorship);
final Actor principal = this.actorService.getActorLogged();
Assert.isInstanceOf(Sponsor.class, principal);
final Sponsorship result = this.sponsorshipRepository.save(sponsorship);
return result;
}
public void delete(final Sponsorship sponsorship) {
Assert.notNull(sponsorship);
this.sponsorshipRepository.delete(sponsorship);
}
// Other business methods
public Collection<Sponsorship> findBySponsor(final int sponsorId) {
final Actor principal = this.actorService.getActorLogged();
Assert.isInstanceOf(Sponsor.class, principal);
return this.sponsorshipRepository.findBySponsor(sponsorId);
}
public void activate(final Sponsorship sponsorship) {
final Date date = new Date();
Assert.notNull(sponsorship);
Assert.isTrue(sponsorship.getStatus() == false);
Assert.isTrue(sponsorship.getCreditCard().getExpirationYear().after(date));
sponsorship.setStatus(true);
this.sponsorshipRepository.save(sponsorship);
}
public void desactivate(final Sponsorship sponsorship) {
Assert.notNull(sponsorship);
Assert.isTrue(sponsorship.getStatus() == true);
sponsorship.setStatus(false);
this.sponsorshipRepository.save(sponsorship);
}
public Sponsorship reconstruct(final Sponsorship sponsorship, final BindingResult binding) {
Sponsorship result;
if (sponsorship.getId() == 0) {
result = this.create();
result.setEvent(sponsorship.getEvent());
} else
result = this.sponsorshipRepository.findOne(sponsorship.getId());
result.setBanner(sponsorship.getBanner());
result.setCreditCard(sponsorship.getCreditCard());
result.setStatus(sponsorship.getStatus());
this.validator.validate(result, binding);
final Collection<String> brandNames = this.configurationService.getConfiguration().getBrandName();
if(!brandNames.contains(result.getCreditCard().getBrandName()))
binding.rejectValue("creditCard.brandName", "sponsorship.creditCard.brandName.error");
// (!result.getEvent().getIsFinal())
// binding.rejectValue("event", "sponsorship.event.error.notFinal");
final Date date = new Date();
if(result.getCreditCard().getExpirationYear() != null && result.getCreditCard().getExpirationYear().before(date))
binding.rejectValue("creditCard.expirationYear", "sponsorship.creditCard.expiration.future");
if (binding.hasErrors())
throw new ValidationException();
return result;
}
public List<Sponsorship> findAllByActiveEvent(final int eventID) {
Assert.notNull(eventID);
List<Sponsorship> sponsorships;
sponsorships = this.sponsorshipRepository.findAllByActiveEvent(eventID);
return sponsorships;
}
public Collection<Sponsorship> findAllExpiredCreditCard() {
final Collection<Sponsorship> sponsorships = this.sponsorshipRepository.findAllExpiredCreditCard();
return sponsorships;
}
public Sponsorship showSponsorship(final int eventID) {
Sponsorship result = null;
final List<Sponsorship> sponsorships = this.findAllByActiveEvent(eventID);
if (sponsorships.size() > 0) {
final Random rnd = new Random();
result = sponsorships.get(rnd.nextInt(sponsorships.size()));
final Double vat = this.configurationService.getConfiguration().getDefaultVAT();
final Double fee = this.configurationService.getConfiguration().getFlatFee();
final Double totalAmount = (vat / 100) * fee + fee;
final Message message = this.messageService.create();
final Collection<Actor> recipients = new ArrayList<Actor>();
recipients.add(result.getSponsor());
message.setRecipients(recipients);
message.setSubject("A sponsorship has been shown \n Se ha mostrado un anuncio");
message.setBody("Se le cargará un importe de: " + totalAmount + "\n Se le cargará un importe de:" + totalAmount);
this.messageService.notification(message);
}
return result;
}
public Collection<Sponsorship> findAllByEvent(final int eventId){
Collection<Sponsorship> result = this.sponsorshipRepository.findAllByEvent(eventId);
return result;
}
}
<file_sep>report.moment = Fecha de creación
report.description = Descripción
report.attachments = Adjuntos
report.complaint = Queja
report.comments = Comentarios
report.isFinal = Modo
report.final = Modo final
report.draft = Modo borrador
report.edit = Editar
report.save = Guardar
report.cancel = Cancelar
report.back = Volver
report.commit.error = No se pudo realizar esta operación
comment.create = Crear comentario<file_sep>complaint.moment = Fecha de creación
complaint.body = Cuerpo
complaint.attachments = Adjuntos
complaint.referee = Árbitro
complaint.reader = Lector
complaint.back = Volver
complaint.commit.error = No se puede realizar esta operación
complaint.save = Guardar
complaint.cancel = Cancel
complaint.autoAssign = Asignarse queja
complaint.show = Mostrar queja
report.create = Crear informe
complaint.reports = Informes
<file_sep>
package service;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.transaction.Transactional;
import javax.validation.ValidationException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.validation.DataBinder;
import datatype.CreditCard;
import domain.Book;
import domain.Offer;
import domain.Transaction;
import services.BookService;
import services.OfferService;
import services.TransactionService;
import utilities.AbstractTest;
@ContextConfiguration(locations = {
"classpath:spring/junit.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class TransactionTest extends AbstractTest {
@Autowired
private TransactionService transactionService;
@Autowired
private BookService bookService;
@Autowired
private OfferService offerService;
/*
* Testing functional requirement : 31.2 An actor that is authenticated as a reader must be able to Buy books and/or send offers for exchanges
* Positive: A reader tries to create a sale
* Negative: A reader tries to create a sale with invalid data
* Sentence coverage: 96%
* Data coverage: 66%
*/
@Test
public void createSaleDriver() {
final Object testingData[][] = {
{
20.99, "book3", "reader1", null
}, {
-1.0, "book3", "reader1", ValidationException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.createSaleTemplate((Double) testingData[i][0], super.getEntityId((String) testingData[i][1]), (String) testingData[i][2], (Class<?>) testingData[i][3]);
}
public void createSaleTemplate(final Double price, final int bookId, final String reader, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
final Book book = this.bookService.findOne(bookId);
super.authenticate(reader);
Transaction t = this.transactionService.create();
t.setPrice(price);
t.setBook(book);
final DataBinder binding = new DataBinder(new Transaction());
t = this.transactionService.reconstructSale(t, binding.getBindingResult());
this.transactionService.saveSale(t);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
/*
* Testing functional requirement : 31.2 An actor that is authenticated as a reader must be able to Buy books and/or send offers for exchanges
* Positive: A reader tries to create an exchange
* Negative: A sponsor tries to create an exchange
* Sentence coverage: 96%
* Data coverage: 50%
*/
@Test
public void createExchange() {
final Object testingData[][] = {
{
"book3", "reader1", null
}, {
"book3", "sponsor1", IllegalArgumentException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.createExchangeTemplate(super.getEntityId((String) testingData[i][0]), (String) testingData[i][1], (Class<?>) testingData[i][2]);
}
public void createExchangeTemplate(final int bookId, final String reader, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
final Book book = this.bookService.findOne(bookId);
super.authenticate(reader);
final Transaction t = this.transactionService.create();
t.setBook(book);
this.transactionService.saveExchange(t);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
/*
* Testing functional requirement : 31.2 An actor that is authenticated as a reader must be able to Buy books and/or send offers for exchanges
* Positive: A reader tries to buy a sale
* Negative: A sponsor tries to buy a sale with invalid data
* Sentence coverage: 96%
* Data coverage: 33%
*/
@Test
public void buySale() {
final Object testingData[][] = {
{
"transaction3", "reader1", ValidationException.class, "Sponsor 1", "asdadas", 856, "4934124580909324", "2026/10/20"
}, {
"transaction3", "reader1", null, "Sponsor 1", "VISA", 856, "4934124580909324", "2026/10/20"
}
};
for (int i = 0; i < testingData.length; i++)
this.buySaleTemplate(super.getEntityId((String) testingData[i][0]), (String) testingData[i][1], (Class<?>) testingData[i][2], (String) testingData[i][3], (String) testingData[i][4], (int) testingData[i][5], (String) testingData[i][6],
(String) testingData[i][7]);
}
private void buySaleTemplate(final int entityId, final String s, final Class<?> expected, final String holder, final String brand, final int cvv, final String number, final String expiration) {
Class<?> caught;
caught = null;
try {
super.authenticate(s);
Transaction transaction = this.transactionService.findOne(entityId);
final CreditCard c = new CreditCard();
c.setBrandName(brand);
c.setCvv(cvv);
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
final Date date = sdf.parse(expiration);
c.setExpirationYear(date);
c.setHolder(holder);
c.setNumber(number);
transaction.setCreditCard(c);
final DataBinder binding = new DataBinder(new Transaction());
transaction = this.transactionService.reconstructSale(transaction, binding.getBindingResult());
this.transactionService.saveSale(transaction);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
/*
* Testing functional requirement : 9.2 An actor that is authenticated as a reader must be able to Buy books and/or send offers for exchanges
* Positive: A reader tries to create an offer
* Negative: A sponsor tries to create an offer
* Sentence coverage: 77%
* Data coverage: 50%
*/
@Test
public void createOffer() {
final Object testingData[][] = {
{
"book3", "reader1", "transaction1", IllegalArgumentException.class
}, {
"book3", "reader1", "transaction4", null
}
};
for (int i = 0; i < testingData.length; i++)
this.createOfferTemplate(super.getEntityId((String) testingData[i][0]), (String) testingData[i][1], super.getEntityId((String) testingData[i][2]), (Class<?>) testingData[i][3]);
}
private void createOfferTemplate(final int bookId, final String reader, final int transactionId, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
final Book book = this.bookService.findOne(bookId);
final Transaction transaction = this.transactionService.findOne(transactionId);
super.authenticate(reader);
Offer o = this.offerService.create();
o.setBook(book);
o.setTransaction(transaction);
final DataBinder binding = new DataBinder(new Offer());
o = this.offerService.reconstruct(o, binding.getBindingResult());
this.offerService.save(o);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
}
<file_sep>event.title = Título
event.description = Descripción
event.date = Fecha
event.maximumCapacity = Capacidad máxima
event.status = Estado
event.show = Mostrar
event.edit = Editar
event.create = Crear nuevo evento
event.draft = Borrador
event.final = Final
event.address = Direcición
event.actualCapacity = Capacidad actual
event.organizer = Organizador
event.registers = Registros
event.register.date = Fecha
event.register.reader = Lector
event.back = Volver
event.saveDraft = Guardar en borrador
event.saveFinal = Guardar en final
event.cancel = Cancel
event.delete = Delete
event.commit.error = No se puede realizar la operación
event.checkIn = Registrarse<file_sep>book.title = Título
book.author = Autor
book.publisher = Editorial
book.numPag = Número de Páginas
book.photo = Foto
book.isbn = ISBN
book.show = Mostrar
book.edit = Editar
book.create = Crear nuevo libro
book.language = Idioma
book.description = Descripción
book.pageNumber = Número de páginas
book.status = Estado
book.moment = Momento de creación
book.categories = Categorias
book.back = Volver
book.save = Guardar
book.delete = Borrar
book.commit.error = No se puede realizar la operación
book.status.veryGood = MUY BUENO
book.status.good = BUENO
book.status.bad = MALO
book.status.veryBad = MUY MALO<file_sep>book.title = Title
book.author = Author
book.publisher = Publisher
book.numPag = Pages
book.photo = Photo
book.isbn = ISBN
book.show = Show
book.edit = Edit
book.create = Create new book
book.language = Language
book.description = Description
book.pageNumber = Number of pages
book.status = Status
book.moment = Moment of creation
book.categories = Categories
book.back = Back
book.save = Save
book.delete = Delete
book.commit.error = Cannot commit this operation
book.status.veryGood = VERY GOOD
book.status.good = GOOD
book.status.bad = BAD
book.status.veryBad = VERY BAD<file_sep>offer.bidder = Bidder
offer.exchange = Exchange
offer.comment = Comment
offer.accept = Accept
offer.reject = Reject<file_sep>package domain;
import datatype.Url;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.SafeHtml;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.Date;
@Entity
@Access(AccessType.PROPERTY)
public class Complaint extends DomainEntity{
private String ticker;
private Date moment;
private String body;
private Collection<Url> attachments;
private Reader reader;
private Referee referee;
@NotBlank
@Column(unique = true)
@SafeHtml(whitelistType = SafeHtml.WhiteListType.NONE)
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
public Date getMoment() {
return moment;
}
public void setMoment(Date moment) {
this.moment = moment;
}
@NotBlank
@SafeHtml(whitelistType = SafeHtml.WhiteListType.NONE)
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Valid
@ElementCollection(fetch = FetchType.EAGER)
public Collection<Url> getAttachments() {
return attachments;
}
public void setAttachments(Collection<Url> attachments) {
this.attachments = attachments;
}
@ManyToOne(optional = false)
public Reader getReader() {
return reader;
}
public void setReader(Reader reader) {
this.reader = reader;
}
@ManyToOne
public Referee getReferee() {
return referee;
}
public void setReferee(Referee referee) {
this.referee = referee;
}
}
<file_sep>
package service;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.transaction.Transactional;
import javax.validation.ValidationException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.validation.DataBinder;
import domain.Event;
import services.EventService;
import utilities.AbstractTest;
@ContextConfiguration(locations = {
"classpath:spring/junit.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class EventTest extends AbstractTest {
@Autowired
EventService eventService;
/*
* Testing functional requirement : 32.1 An actor who is authenticated as organizer must be able to manage their events
* Positive: An organizer create an event in draft mode
* Negative: A reader try create an event in draft mode
* Sentence coverage: 98%
* Data coverage: 20%
*/
@Test
public void createDraftEventDriver() {
final Object testingData[][] = {
{
"prueba", "prueba", "02/02/2025 19:00", "prueba", 5, "organizer1", null
}, {
"prueba", "prueba", "02/02/2025 19:00", "prueba", 5, "reader1", IllegalArgumentException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.createDraftEventTemplate((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (String) testingData[i][3], (int) testingData[i][4], (String) testingData[i][5], (Class<?>) testingData[i][6]);
}
private void createDraftEventTemplate(final String title, final String description, final String date, final String address, final int maximumCapacity, final String user, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(user);
Event event = this.eventService.create();
event.setTitle(title);
event.setDescription(description);
final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
final Date res = sdf.parse(date);
event.setDate(res);
event.setAddress(address);
event.setMaximumCapacity(maximumCapacity);
final DataBinder binding = new DataBinder(new Event());
event = this.eventService.reconstruct(event, binding.getBindingResult());
this.eventService.saveDraft(event);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
/*
* Testing functional requirement : 32.1 An actor who is authenticated as organizer must be able to manage their events
* Positive: An organizer create an event in final mode
* Negative: A reader try create an event in final mode
* Sentence coverage: 98%
* Data coverage: 20%
*/
@Test
public void createFinalEventDriver() {
final Object testingData[][] = {
{
"prueba", "prueba", "02/02/2025 19:00", "prueba", 5, "organizer1", null
}, {
"prueba", "prueba", "02/02/2025 19:00", "prueba", 5, "reader1", IllegalArgumentException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.createFinalEventTemplate((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (String) testingData[i][3], (int) testingData[i][4], (String) testingData[i][5], (Class<?>) testingData[i][6]);
}
private void createFinalEventTemplate(final String title, final String description, final String date, final String address, final int maximumCapacity, final String user, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(user);
Event event = this.eventService.create();
event.setTitle(title);
event.setDescription(description);
final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
final Date res = sdf.parse(date);
event.setDate(res);
event.setAddress(address);
event.setMaximumCapacity(maximumCapacity);
final DataBinder binding = new DataBinder(new Event());
event = this.eventService.reconstruct(event, binding.getBindingResult());
this.eventService.saveFinal(event);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
/*
* Testing functional requirement : 32.1 An actor who is authenticated as organizer must be able to manage their events
* Positive: An organizer edit an event
* Negative: A reader try edit an event. An organizer try edit an event with invalid data.
* Sentence coverage: 98%
* Data coverage: 66%
*/
@Test
public void editEventDriver() {
final Object testingData[][] = {
{
"event2", "pruebaEdit", "organizer1", null
}, {
"event2", "pruebaEdit", "reader1", IllegalArgumentException.class
}, {
"event2", "", "organizer1", ValidationException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.editEventTemplate(super.getEntityId((String) testingData[i][0]), (String) testingData[i][1], (String) testingData[i][2], (Class<?>) testingData[i][3]);
}
private void editEventTemplate(final int entityId, final String title, final String user, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(user);
Event event = this.eventService.findOne(entityId);
event.setTitle(title);
final DataBinder binding = new DataBinder(new Event());
event = this.eventService.reconstruct(event, binding.getBindingResult());
this.eventService.saveFinal(event);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
/*
* Testing functional requirement : 32.1 An actor who is authenticated as organizer must be able to manage their events
* Positive: An organizer delete an event
* Negative: A reader try delete an event
* Sentence coverage: 92%
* Data coverage: Not applicable
*/
@Test
public void deleteEventDriver() {
final Object testingData[][] = {
{
"event2", "organizer1", null
}, {
"event2", "reader1", IllegalArgumentException.class
}
};
for (int i = 0; i < testingData.length; i++)
this.deleteEventTemplate(super.getEntityId((String) testingData[i][0]), (String) testingData[i][1], (Class<?>) testingData[i][2]);
}
private void deleteEventTemplate(final int entityId, final String user, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
this.authenticate(user);
final Event event = this.eventService.findOne(entityId);
this.eventService.delete(event);
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
}
}
<file_sep>comment.moment = Fecha de creación
comment.body = Cuerpo
comment.author = Autor
comment.back = Volver
comment.save = Guardar
comment.cancel = Cancelar
comment.commit.error = No se pudo realizar esta operación<file_sep>actor.username = User name
actor.password = <PASSWORD>
actor.confirmPass = Confirm password
actor.photo = Photo
actor.show = Show
actor.middleName = Middle
actor.score = Score
actor.isBanned = Banned
credit.holderName = Holder name
credit.brandName =Brand name
credit.number =Credit card number
credit.expiration = Expiration
credit.cvvCode = Cvv code
actor.confirm = Confirm this phone number?
terms = Terms and conditions
actor.save = Save
error.username = User name exists!
error.password = The passwords do not match!
error.duplicated = Actor exists!
error.commit.error = Cannot commit this operation!
actor.firstMessage = You must fill fields with*
actor.isSpammer = Spammer
actor.ban = Ban/Unban
administrator.ban = Ban
administrator.unban = Unban
administrator.calculateSpam = Calculate spam
administrator.calculateScore = Calculate Score
administrator.deactivateCreditCards = Deactivate sponsorships with expired credit cards
administrator.deleteInactiveBooks = Delete inactive books
administrator.deletedBooks = Number of deleted books:
administrator.deactivateSponsorships = Number of deactivated sponsorships:
administrator.Top5OrganizersWithMoreEvents = Top 5 organizers with more events
administrator.AvgTransactionsPrice = Average of transactions's prices
administrator.MinTransactionsPrice = Minimum of transactions's prices
administrator.MaxTransactionsPrice = Maximum of transactions's prices
administrator.StddevTransactionsPrice = Standard desviation of transactions's prices
administrator.AvgBooksPerReader = Average of book's per reader
administrator.MinBooksPerReader = Minimum of book's per reader
administrator.MaxBooksPerReader = Maximum of book's per reader
administrator.StddevBooksPerReader = Standard desviation of book's per reader
administrator.AvgTransactionsComplaint = Average of number of transactions's complaints
administrator.MinTransactionsComplaint = Minimum of transactions's complaints
administrator.MaxTransactionsComplaint = Maximum of transactions's complaints
administrator.StddevTransactionsComplaint = Standard desviation of transactions's complaints
administrator.AvgSponsorPerEvent = Average sponsors per events
administrator.MinSponsorPerEvent = Minimum sponsors per events
administrator.MaxSponsorPerEvent = Maximum sponsors per events
administrator.StddevSponsorPerEvent = Stddev sponsors per events
administrator.RatioOfActiveVSInnactiveSpons = Ratio of active VS innactive Sponsors
administrator.RatioOfFullFinders = Ratio of full finders
administrator.RatioOfEmptyFinders = Ratio of empty finders
administrator.RatioOfEmptyVSFullFinders = Ratio of empty VS full finders
administrator.RatioOfEmptyVSFullTransactionsComplaints = Ratio of empty VS full transactions complaints
administrator.Top5ReadersWithMoreComplaints = Top 5 readers eith more complaints
administrator.RatioOfSalesVSExchanges = Ratio of sales VS exchanges
actor.PersonalData = Personal Data
actor.CreditCard = Credit card
administrator.numberOfSoldBooksByCategory = Number of sold books by category<file_sep>offer.bidder = Ofertante
offer.exchange = Intercambio
offer.comment = Comentarios
offer.accept = Accept
offer.reject = Reject<file_sep>actor.username = Nombre de usuario
actor.password = <PASSWORD>
actor.confirmPass =Confirmar contraseña
actor.photo = Foto
actor.show = Mostrar
actor.middleName = Segundo nombre
actor.score = Puntuación
actor.isBanned = Baneado
credit.holderName = Nombre del titular
credit.brandName = Marca
credit.number =Número de tarjeta
credit.expiration = Fecha de expiración
credit.cvvCode = Codigo cvv
actor.confirm = ¿Confirmar este número de telefono?
terms = Terminos y condiciones
actor.save = Guardar
error.username = ¡Nombre de usuario existente!
error.password = ¡<PASSWORD>ñas <PASSWORD>!
error.duplicated = ¡Actor existente!
error.commit.error = ¡No se pudo realizar la operación!
actor.firstMessage = Debes rellenar los campos que tengan *
actor.isSpammer = Spammer
actor.ban = Ban/Unban
administrator.ban = Ban
administrator.unban = Unban
administrator.calculateScore = Calcular puntuación
administrator.deactivateCreditCards = Desactivar patrocinios con tarjetas caducadas
administrator.deleteInactiveBooks = Eliminar libros inactivos
administrator.deletedBooks = Número de libros eliminados:
administrator.deactivateSponsorships = Número de patrocinios desactivados:
administrator.Top5OrganizersWithMoreEvents = Top 5 organizadores con mas eventos
administrator.AvgTransactionsPrice = Media de precios por transaccion
administrator.MinTransactionsPrice = Precio minimo de transaccion
administrator.MaxTransactionsPrice = Precio maximo de transaccion
administrator.StddevTransactionsPrice = Desviacion estandar de precios por transaccion
administrator.AvgBooksPerReader = Media de libros por lector
administrator.MinBooksPerReader = Minimo de libros de entre los lectores
administrator.MaxBooksPerReader = Maximo de libros de entre los lectores
administrator.StddevBooksPerReader = Desviacion estandar de libros por lector
administrator.AvgTransactionsComplaint = Media de numero de quejas por transaccion
administrator.MinTransactionsComplaint = Minimo de quejas por transaccion
administrator.MaxTransactionsComplaint = Maximo de quejas por transaccion
administrator.StddevTransactionsComplaint = Desviacion estandar de quejas por transaccion
administrator.AvgSponsorPerEvent = Media de patrocinadores por evento
administrator.MinSponsorPerEvent = Minimo de patrocinadores por evento
administrator.MaxSponsorPerEvent = Maximo de patrocinadores por evento
administrator.StddevSponsorPerEvent = Desviacion estandar de patrocinadores por evento
administrator.RatioOfActiveVSInnactiveSpons = Ratio de Patrocinadores activos VS inactivos
administrator.RatioOfFullFinders = Ratio de buscadores llenos
administrator.RatioOfEmptyFinders = Ratio de buscadores vacios
administrator.RatioOfEmptyVSFullFinders = Ratio de buscadores vacios VS llenos
administrator.RatioOfEmptyVSFullTransactionsComplaints = Ratio de numero de transaccion sin quejas VS con quejas
administrator.Top5ReadersWithMoreComplaints = Top 5 lectores con mas quejas
administrator.RatioOfSalesVSExchanges = Ratio de ventas VS intercambios
actor.PersonalData = Información personal
actor.CreditCard = Tarjeta de credito
administrator.numberOfSoldBooksByCategory = Libros vendidos por categoria<file_sep>package services;
import domain.Event;
import domain.Reader;
import domain.Register;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import repositories.RegisterRepository;
import security.UserAccount;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.Date;
@Service
@Transactional
public class RegisterService {
@Autowired
private RegisterRepository registerRepository;
@Autowired
private ActorService actorService;
@Autowired
private EventService eventService;
@Autowired
private ReaderService readerService;
public Collection<Register> findAll(){
Collection<Register> res;
res = this.registerRepository.findAll();
Assert.notNull(res);
return res;
}
public Register findOne(int registerId){
Register res;
res = this.registerRepository.findOne(registerId);
Assert.notNull(res);
return res;
}
public Register save(int eventId){
UserAccount userAccount;
userAccount = this.actorService.getActorLogged().getUserAccount();
Assert.isTrue(userAccount.getAuthorities().iterator().next().getAuthority().equals("READER"));
Event event = this.eventService.findOne(eventId);
Assert.notNull(event);
Assert.isTrue(event.getMaximumCapacity() > 0);
Assert.isTrue(event.getActualCapacity() < event.getMaximumCapacity());
Assert.isTrue(new Date().before(event.getDate()));
Register register = new Register();
register.setMoment(new Date());
Reader r = this.readerService.findOne(this.actorService.getActorLogged().getId());
register.setReader(r);
Register result = this.registerRepository.save(register);
Collection<Event> events = this.getEventsPerReader(r);
Assert.isTrue(events.contains(event) == false);
Collection<Register> registers = event.getRegisters();
registers.add(result);
event.setRegisters(registers);
return result;
}
public void cancel(int registerId, int eventId){
Event event = this.eventService.findOne(eventId);
Assert.notNull(event);
Register register = this.registerRepository.findOne(registerId);
Assert.notNull(register);
Assert.isTrue(register.getReader().equals(this.readerService.findOne(this.actorService.getActorLogged().getId())));
Reader r = this.readerService.findOne(this.actorService.getActorLogged().getId());
Collection<Event> events = this.getEventsPerReader(r);
Assert.isTrue(events.contains(event));
Date now = new Date();
Assert.isTrue(now.before(event.getDate()));
Collection<Register> registers = event.getRegisters();
registers.remove(register);
//event.setRegisters(registers);
this.delete(registerId);
}
public void delete(final int registerId){
this.registerRepository.delete(registerId);
}
public Collection<Event> getEventsPerReader(Reader reader){
Collection<Event> res;
res = this.registerRepository.getEventsPerReader(reader);
Assert.notNull(res);
return res;
}
public Collection<Register> getRegistersPerReader(final int readerId){
return this.registerRepository.getRegistersPerReader(readerId);
}
}
<file_sep>transaction.buyer = Buyer
transaction.seller = Seller
transaction.moment = Moment
transaction.book = Book
transaction.state = Status
transaction.price = Price
transaction.sold = Sold
transaction.onSale = On sale
transaction.delete = Delete
transaction.createSale = Create Sale
transaction.createExchange = Create Exchange
transaction.save = Save
transaction.cancel = Cancel
transaction.offers = Offers
transaction.show = Display
transaction.commit.error = Cannot commit this operation
transaction.price.error = Must be not null
transaction.buy = Buy
complaint.create = Create complaint
transaction.back = Back
transaction.Offer = Make an Offer<file_sep>package domain;
import com.google.gson.annotations.Expose;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.SafeHtml;
import org.hibernate.validator.constraints.SafeHtml.WhiteListType;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Collection;
@Entity
@Access(AccessType.PROPERTY)
@Table(indexes = {
@Index(columnList = "name")
})
public class MessageBox extends DomainEntity {
// Attributes -------------------------------------------------------------
@Expose
private String name;
@Expose
private Boolean isSystem;
@NotBlank
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
@NotNull
public Boolean getIsSystem() {
return this.isSystem;
}
public void setIsSystem(final Boolean isSystem) {
this.isSystem = isSystem;
}
// Relationships -------------------------------------------------------------
@Expose
private Collection<Message> messages;
@Valid
@ManyToMany
public Collection<Message> getMessages() {
return this.messages;
}
public void setMessages(final Collection<Message> messages) {
this.messages = messages;
}
//Methods
public void addMessage(final Message message) {
this.messages.add(message);
}
public void deleteMessage(final Message message) {
this.messages.remove(message);
}
public boolean equals(final MessageBox obj) {
boolean res = false;
if (this.getName().equals(obj.getName()))
res = true;
return res;
}
}
|
065584eff49d6397c64a9600ef0e531ed5a554d7
|
[
"Markdown",
"Java",
"SQL",
"INI"
] | 52
|
Java
|
dp2-anacardo/Acme-Library
|
6db09e3d0910a0069e78ed6324da2e3fb16cdd00
|
77229826e351e07b9bf71c2df386b5f40a3b22ec
|
refs/heads/master
|
<file_sep>//
// MovieGridCell.swift
// flixsterapp
//
// Created by <NAME> on 2/9/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class MovieGridCell: UICollectionViewCell {
@IBOutlet weak var posterView: UIImageView!
}
|
92bef3a46a1b42dec5edfb721f8518748905b1c0
|
[
"Swift"
] | 1
|
Swift
|
Mac561/flixsterapp
|
b0987e3f28457b837c9596858f1ef3934fa3a3e4
|
d68852cabc793bc34093cf829a0a4c445b3c6ea5
|
refs/heads/master
|
<file_sep>baosteeltech_android
====================
<file_sep>var $jqm = $.mobile;
var MobileApp = {
loginPath: "http://www.baosteeltech.com:8080/jw/web/mobile",
init: function() {
// fix for ios7 status bar
var updateStatusBar = navigator.userAgent.match(/iphone|ipad|ipod/i) && parseInt(navigator.appVersion.match(/OS (\d)/)[1], 10) >= 7;
if (updateStatusBar) {
document.body.style.webkitTransform = 'translate3d(0, 20px, 0)';
}
//load profiles
var list = MobileApp.getProfileList();
var profiles = list.split(";");
if (list !== "") {
$(".profile_container").append("<select id=\"profile\" name=\"profile\"></select>");
for (var i = 0; i < profiles.length; i++) {
if (profiles[i] !== "") {
$("#profile").append("<option>"+profiles[i]+"</option>");
}
}
$("#profile").selectmenu();
$("#profile").change(function(){
var p = $("#profile").val();
MobileApp.loadProfile(p);
});
$(".profile_container").append("<div data-role=\"controlgroup\" data-type=\"horizontal\"><a href=\"#\" data-role=\"button\" data-icon=\"plus\" data-iconpos=\"notext\">Add</a><a href=\"#\" data-role=\"button\" data-icon=\"minus\" data-iconpos=\"notext\">Delete</a></div>");
$(".profile_container [data-role='controlgroup']").controlgroup();
$(".profile_container [data-icon='plus']").click(function() {
MobileApp.newProfile();
});
$(".profile_container [data-icon='minus']").click(function() {
MobileApp.deleteProfile();
});
} else {
$(".profile_container").append("<input id=\"profile\" name=\"profile\" />");
$("#profile").textinput();
}
var profile = MobileApp.getLastLogin();
if (!profile || profile == '') {
if (list !== "") {
profile = profiles[0];
} else {
profile = "Default";
}
}
$("#profile").val(profile).selectmenu("refresh");
MobileApp.loadProfile(profile);
},
supportsHtml5Storage: function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
},
getData: function(name) {
var data;
if (MobileApp.supportsHtml5Storage()) {
data = localStorage.getItem(name);
} else {
data = $.cookie(name);
}
if (data == null) {
data = "";
}
return data;
},
getProfileList: function() {
return MobileApp.getData("profiles");
},
getLastLogin: function() {
return MobileApp.getData("lastLogin");
},
getHomeUrl: function(profile) {
return MobileApp.getData(profile + "_homeUrl");
},
getUsername: function(profile) {
return MobileApp.getData(profile + "_username");
},
getPassword: function(profile) {
return MobileApp.getData(profile + "_password");
},
getRememberPassword: function(profile) {
return MobileApp.getData(profile + "_rememberPassword");
},
setData: function(name, value) {
if (MobileApp.supportsHtml5Storage()) {
localStorage.setItem(name, value);
} else {
$.cookie(name, value);
}
},
setLastLogin: function(profile){
MobileApp.setData("lastLogin", profile);
},
setHomeUrl: function(profile, url) {
MobileApp.setData(profile + "_homeUrl", url);
},
setUsername: function(profile, username) {
MobileApp.setData(profile + "_username", username);
},
setPassword: function(profile, password) {
MobileApp.setData(profile + "_password", password);
},
setRememberPassword: function(profile, rememberPassword) {
MobileApp.setData(profile + "_rememberPassword", rememberPassword);
},
getFullUrl: function(url) {
if (!url || url === "") {
return "";
}
//remove extra "/" at the end of the url
if (url.match(/\/$/)) {
url = url.substring(0, url.length - 1);
}
//if no http/https, add http
if (!url.match(/(http|https):\/\/.*$/)) {
url = "http://" + url;
}
var fullUrl;
//if url is userview or mobile direct link
if (url.indexOf("/web/userview/") > 0 || url.indexOf("/web/mobile/") > 0) {
fullUrl = url;
} else {
fullUrl = url
// if without context path, add /jw
if (!url.match(/(http|https):\/\/.*\/.*$/)) {
fullUrl = fullUrl + "/jw";
}
fullUrl = fullUrl + MobileApp.loginPath;
}
return fullUrl;
},
/**
addProfile: function(profile) {
var profileList = MobileApp.getProfileList();
MobileApp.setData("profiles", profileList + profile + ";");
},
deleteProfile: function() {
var profile = $("#profile").val();
var profileList = MobileApp.getProfileList();
profileList = profileList.replace(profile+";", "");
MobileApp.setData("profiles", profileList);
$(".profile_container").html("");
MobileApp.init();
},
newProfile: function() {
$(".profile_container").html("");
$(".profile_container").append("<input id=\"profile\" name=\"profile\" />");
$("#profile").textinput();
$(".profile_container").append("<div data-role=\"controlgroup\" data-type=\"horizontal\"><a href=\"#\" data-role=\"button\" data-icon=\"back\" data-iconpos=\"notext\">Back</a></div>");
$(".profile_container [data-role='controlgroup']").controlgroup();
$(".profile_container [data-icon='back']").click(function() {
$(".profile_container").html("");
MobileApp.init();
});
MobileApp.loadProfile("");
$("#profile").focus();
},
*/
loadProfile: function(profile) {
var homeUrl = (profile === "") ? "" : MobileApp.getHomeUrl(profile);
var username = (profile === "") ? "" : MobileApp.getUsername(profile);
var password = (profile === "") ? "" : MobileApp.getPassword(profile);
var rememberPassword = (profile === "") ? "" : MobileApp.getRememberPassword(profile);
$("#url").val(homeUrl).textinput("refresh");
$("#username").val(username).textinput("refresh");
$("#password").val(password).textinput("refresh");
if (rememberPassword == "true") {
$("#rememberPassword").prop('checked', true).checkboxradio('refresh');
}
if (!homeUrl || homeUrl == '') {
$("#url").val("http://").textinput("refresh");
$("#url").focus();
} else if (!username || username == '') {
$("#username").focus();
} else if (!password || password == '') {
$("#password").focus();
} else {
$("#login").focus();
}
},
login: function() {
var profile = $("#profile").val();
var url = $("#url").attr("value");
var username = $("#username").attr("value");
var password = $("#password").attr("value");
var registerID = $("#registerID").attr("value");
var rememberPassword = $("#rememberPassword:checked").attr("value");
$(".required").remove();
if (profile === "") {
$("#profile").parent().after("<span class=\"required\">This field is required</span>");
}
if (url === "") {
$("#url").parent().after("<span class=\"required\">This field is required</span>");
}
if (username === "") {
$("#username").parent().after("<span class=\"required\">This field is required</span>");
}
if (password === "") {
$("#password").parent().after("<span class=\"required\">This field is required</span>");
}
//if (profile && profile != "" && url && url != "" && username && username != "" && password && password != "") {
if (username && username != "" && password && password != "") {
$.mobile.loading('show');
var fullUrl = MobileApp.loginPath;
try {
var urlParser = document.createElement("a");
urlParser.href = fullUrl;
var pathName = urlParser.pathname;
var idx = pathName.substring(1, pathName.length).indexOf("/");
if (idx > 0) {
var contextPath = pathName.substring(1, idx+1);
var apiUrl = urlParser.protocol + "//" + urlParser.host + "/" + contextPath + "/web/json/plugin/org.joget.apps.ext.ConsoleWebPlugin/service?spot=mobile";
$.support.cors = true;
var success = false;
$.ajax({
type: 'GET',
url: apiUrl,
dataType : "jsonp",
success: function(data) {
if (data.support) {
success = true;
if ($(".ui-input-text #profile").length > 0) {
MobileApp.addProfile(profile);
}
MobileApp.setLastLogin(profile);
MobileApp.setHomeUrl(profile, url);
MobileApp.setUsername(profile, username);
if (rememberPassword == "true") {
MobileApp.setPassword(profile, password);
} else {
MobileApp.setPassword(profile, "");
}
MobileApp.setRememberPassword(profile, rememberPassword);
$("#loginForm").attr("action", fullUrl);
$("#loginForm").submit();
//调用JPush api 设置别名
var deviceApiUrl = urlParser.protocol + "//" + urlParser.host + "/" + contextPath + "/web/json/plugin/org.joget.valuprosys.mobile.MobileDeviceApi/service?deviceType=Android&callback=json&userId="+username+"&deviceNo="+registerID+"&password="+<PASSWORD>;
$.ajax({
type: 'GET',
url: deviceApiUrl,
dataType : "json",
success: function(data) {
//alert(data);
}
});
} else {
$.mobile.loading('hide');
alert("Unsupported Version");
}
},
error: function(data) {
$.mobile.loading('hide');
alert("Unsupported Version");
}
});
setTimeout(function() {
if (!success) {
alert("Invalid URL " + fullUrl);
$.mobile.loading('hide');
}
}, 5000);
} else {
$.mobile.loading('hide');
alert("Invalid URL " + fullUrl);
}
} catch (e) {
$.mobile.loading('hide');
alert("Invalid URL: " + fullUrl);
}
return false;
} else {
return false;
}
}
}
$(function() {
MobileApp.init();
});
<file_sep>package com.joget.baosteeltech;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import android.util.Log;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.android.tpush.common.Constants;
import com.tencent.android.tpush.service.cache.CacheManager;
public class MainActivity extends DroidGap {
public void mySuperloadUrl(String registerID){
super.loadUrl("file:///android_asset/www/index.html?registerID="
+ registerID);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// JPushInterface.setDebugMode(false);
// JPushInterface.init(this);
// String registerID = JPushInterface.getRegistrationID(this);
// System.out.println("本机注册码是:"+registerID);
// 注册接口
XGOperateCallback callback = new XGOperateCallback();
callback.setMainActivity(this);
XGPushManager.registerPush(getApplicationContext(),
callback);
//mySuperloadUrl("");
}
@Override
protected void onResume() {
// JPushInterface.onResume(this);
super.onResume();
}
@Override
protected void onPause() {
// JPushInterface.onPause(this);
super.onPause();
}
class XGOperateCallback implements XGIOperateCallback{
private MainActivity activiy;
private String token;
public void setMainActivity(MainActivity activiy){
this.activiy = activiy;
}
@Override
public void onSuccess(Object data, int flag) {
Log.w(Constants.LogTag,
"+++ register push sucess. token:" + data);
token= (String)data;
CacheManager.getRegisterInfo(getApplicationContext());
MainActivity.this.runOnUiThread(new Runnable()
{
public void run()
{
activiy.mySuperloadUrl(token);
}
});
//activiy.mySuperloadUrl((String)data);
}
@Override
public void onFail(Object data, int errCode, String msg) {
Log.w(Constants.LogTag,
"+++ register push fail. token:" + data
+ ", errCode:" + errCode + ",msg:"
+ msg);
//activiy.mySuperloadUrl((String)data);
}
}
}
|
27f5bbc89330dd8586788076833559a1a0c57c62
|
[
"Markdown",
"Java",
"JavaScript"
] | 3
|
Markdown
|
yjbyf/baosteeltech_android
|
e3b36895f89a90aa2fd274e6939fbaecec9273c3
|
70aecf1b317cf2626da4a1508b62c0296b0d24c3
|
refs/heads/master
|
<file_sep>import React from 'react';
import Loading from '../../assets/images/loading.gif';
export const LoadingScreen = () => {
return (
<div className="loading__main animate__animated animate__fadeIn">
<h3 className="loading__title">Please wait...</h3>
<img src={Loading} className="loading__img" alt="Loading" />
</div>
);
};
<file_sep>import Swal from 'sweetalert2';
export const toast = Swal.mixin({
toast: true,
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
});
export const toastError = Swal.mixin({
toast: true,
showConfirmButton: false,
icon: 'error',
timer: 5000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer);
toast.addEventListener('mouseleave', Swal.resumeTimer);
},
});
export const message = Swal.mixin({
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
});
export const messageButton = Swal.mixin({
showConfirmButton: true,
});
export const closeUploaderImg = Swal.mixin({
showConfirmButton: false,
willOpen: () => {
Swal.close();
},
});
export const uploaderImg = Swal.mixin({
position: 'center',
title: 'Uploading...',
text: 'Please wait',
showConfirmButton: false,
allowOutsideClick: false,
willOpen: () => {
Swal.showLoading();
},
});
<file_sep>import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
const firebaseConfig = {
apiKey: '<KEY>',
authDomain: 'journal-react-app-a0f14.firebaseapp.com',
projectId: 'journal-react-app-a0f14',
storageBucket: 'journal-react-app-a0f14.appspot.com',
messagingSenderId: '306062118893',
appId: '1:306062118893:web:49deb6ec1f833e2cfe61e4',
measurementId: 'G-WKXH9B5DFE',
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//Provider
const db = firebase.firestore();
const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
export { db, googleAuthProvider, firebase };
<file_sep>import React, { useEffect, useRef } from 'react';
import Swal from 'sweetalert2';
import { useDispatch, useSelector } from 'react-redux';
import { activeNote, startDeleteNote } from '../../actions/notes';
import { useForm } from '../../hooks/useForm';
import { NotesAppBar } from './NotesAppBar';
export const NoteScreen = () => {
const dispatch = useDispatch();
const { active: note } = useSelector((state) => state.notes);
const [formValues, handleInputChange, reset] = useForm({ ...note });
const {
id,
body,
title,
} = formValues; /* 👈 acá creo que está mi problema,
pero no sé como tomar esa url del storage de redux y establezerlo en el useForm, para
que, cuando al ingresar valores en el form no me borre la imagen en el useEffect*/
const activeId = useRef(note.id);
useEffect(() => {
if (note.id !== activeId.current) {
reset(note);
activeId.current = note.id;
}
}, [note, reset]);
useEffect(() => {
dispatch(activeNote(formValues.id, { ...formValues }));
}, [formValues, dispatch]);
const handleDelete = () => {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
}).then((result) => {
if (result.isConfirmed) {
dispatch(startDeleteNote(id));
}
});
};
return (
<div className="notes__main-content">
<NotesAppBar />
<div className="notes__content">
<input
type="text"
placeholder="Write here your title"
className="notes__title-input"
autoComplete="off"
name="title"
value={title}
onChange={handleInputChange}
/>
<textarea
placeholder="Write here your event 📝"
className="notes__textarea"
name="body"
value={body}
onChange={handleInputChange}
></textarea>
{note.url && (
<div className="notes__image animate__animated animate__fadeIn">
<img
src={note.url}
alt="note-img"
name="url"
value={note.url}
onChange={handleInputChange}
/>
</div>
)}
</div>
<button className="btn btn-danger" onClick={handleDelete}>
DELETE
</button>
</div>
);
};
|
b83b16940fa91f6af10293f09947f40a94113f93
|
[
"JavaScript"
] | 4
|
JavaScript
|
BernhardSilva/journal-app
|
35982ea2d35ea0b7e0b3df3f8bde341de6d2773f
|
b57e0960eb3c6ef2df1cf137bb72934d8c489096
|
refs/heads/master
|
<repo_name>BrotooLu/android-demo<file_sep>/buildSrc/build.gradle
apply plugin: 'groovy'
Properties properties = new Properties()
properties.load(new FileInputStream(project.getRootDir().getPath() + "/../gradle.properties"))
def androidPlugin = properties.get('android.plugin')
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
maven { url 'https://dl.google.com/dl/android/maven2' }
}
dependencies {
compile gradleApi()
compile localGroovy()
compile androidPlugin
compile 'org.javassist:javassist:3.24.0-GA'
compile "commons-io:commons-io:2.6"
}<file_sep>/b2lib/src/main/java/com/bro2/util/SynchronizeInvoker.java
package com.bro2.util;
import android.os.Handler;
/**
* Created by Bro2 on 2017/4/17
* 工作流程:
* invokeThread workThread
* | ...
* | invoke/invokeWithLock
* |-------------------------------->|doWork
* |
* workDone/timeout |
* |<--------------------------------|
* | checkException
* | ...
*/
public final class SynchronizeInvoker {
private static class LockableRunnable implements Runnable {
final Runnable mRunnable;
final Object mLock;
final long mWaitMax;
Exception exception;
LockableRunnable(Runnable runnable, Object lock, long waitMax) {
mRunnable = runnable;
mLock = lock == null ? new Object() : lock;
mWaitMax = waitMax < 0 ? 0 : waitMax;
}
Object getLock() {
return mLock;
}
void waitLock() {
try {
mLock.wait(mWaitMax);
} catch (InterruptedException e) {
// do nothing
}
}
@Override
public void run() {
try {
mRunnable.run();
} catch (Exception e) {
exception = e;
} finally {
synchronized (mLock) {
mLock.notify();
}
}
}
}
/**
* 直接新启动一个线程作为工作线程
* @param runnable 工作线程work的Runnable
* @param threadName 启动新线程的线程名字
* @param waitMax 调用线程等待的最长时间,(-,0]代表一直等待
* @param lock 自定义的锁,不提供则直接创建一把新锁
* @return 工作线程调用产生的exception
*/
public static Exception invokeWithLock(Runnable runnable, String threadName,
long waitMax, final Object lock) {
if (runnable == null) {
throw new IllegalArgumentException("no runnable specify");
}
final LockableRunnable lockableRunnable = new LockableRunnable(runnable, lock, waitMax);
synchronized (lockableRunnable.getLock()) {
new Thread(lockableRunnable, threadName).start();
lockableRunnable.waitLock();
}
return lockableRunnable.exception;
}
/**
* 直接新启动一个线程作为工作线程
* @param runnable 工作线程work的Runnable
* @param threadName 启动新线程的线程名字
* @param waitMax 调用线程等待的最长时间,(-,0]代表一直等待
* @return 工作线程调用产生的exception
*/
public static Exception invoke(Runnable runnable, String threadName, long waitMax) {
return invokeWithLock(runnable, threadName, waitMax, null);
}
/**
* 使用handler绑定的线程作为工作线程,当工作线程和调用线程是同一个线程时会抛异常
* @param runnable 工作线程work的Runnable
* @param waitMax 调用线程等待的最长时间,(-,0]代表一直等待
* @param lock 自定义的锁,不提供则直接创建一把新锁
* @return 工作线程调用产生的exception
*/
public static Exception invokeWithLock(Runnable runnable, Handler handler,
long waitMax, Object lock) {
if (runnable == null || handler == null) {
throw new IllegalArgumentException("no runnable specify");
}
if (Thread.currentThread() == handler.getLooper().getThread()) {
throw new IllegalArgumentException("can't wait on worker thread");
}
final LockableRunnable lockableRunnable = new LockableRunnable(runnable, lock, waitMax);
synchronized (lockableRunnable.getLock()) {
handler.postAtFrontOfQueue(lockableRunnable);
lockableRunnable.waitLock();
}
return lockableRunnable.exception;
}
/**
* 使用handler绑定的线程作为工作线程,当工作线程和调用线程是同一个线程时会抛异常
* @param runnable 工作线程work的Runnable
* @param waitMax 调用线程等待的最长时间,(-,0]代表一直等待
* @return 工作线程调用产生的exception
*/
public static Exception invoke(Runnable runnable, Handler handler, long waitMax) {
return invokeWithLock(runnable, handler, waitMax, null);
}
}
<file_sep>/b2lib/src/main/java/com/bro2/tljpref/TileJMap.java
package com.bro2.tljpref;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by Brotoo on 15/01/2018.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TileJMap {
boolean isLeaf() default true;
String tileName() default "";
}
<file_sep>/buildSrc/src/main/resources/META-INF/gradle-plugins/resource-remove.properties
implementation-class=com.bro2.gradle.ResourceRemovePlugin<file_sep>/b2jni/src/main/cpp/bsdiff/Android.mk
LOCAL_PATH := $(call my-dir)
####################################################
# bsdiff
####################################################
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(LOCAL_PATH)/../bzip2
LOCAL_LDFLAGS += -pie
LOCAL_CFLAGS += -Werror
LOCAL_MODULE := bsdiff
LOCAL_SRC_FILES := bsdiff.c
LOCAL_STATIC_LIBRARIES := bzip
include $(BUILD_EXECUTABLE)
####################################################
# bspatch
####################################################
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(LOCAL_PATH)/../bzip2
LOCAL_LDFLAGS += -pie
LOCAL_CFLAGS += -Werror
LOCAL_MODULE := bspatch
LOCAL_SRC_FILES := bspatch.c
LOCAL_STATIC_LIBRARIES := bzip
include $(BUILD_EXECUTABLE)
<file_sep>/demo/src/main/java/com/bro2/demo/localsocket/ClientService.java
package com.bro2.demo.localsocket;
import android.app.Service;
import android.content.Intent;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static com.bro2.demo.DemoEnv.DEBUG;
import static com.bro2.demo.DemoEnv.TAG_PREFIX;
public class ClientService extends Service {
public static final String KEY_SERVER_NAME = "server-name";
public static final String KEY_COMMAND = "cmd";
public static final int CMD_SEND_MSG = 1;
public static final int CMD_STOP = 2;
private static final String TAG = TAG_PREFIX + "socket_client";
LocalSocket mSocket;
OutputStream mOs;
InputStream mIn;
public ClientService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
return super.onStartCommand(null, flags, startId);
}
int cmd = intent.getIntExtra(KEY_COMMAND, CMD_SEND_MSG);
try {
if (cmd == CMD_SEND_MSG) {
if (mSocket == null || !mSocket.isConnected()) {
if (DEBUG) {
Log.d(TAG, "[ClientService.onStartCommand] start connect");
}
String server = intent.getStringExtra(KEY_SERVER_NAME);
mSocket = new LocalSocket();
LocalSocketAddress address = new LocalSocketAddress(server);
try {
mSocket.connect(address);
if (DEBUG) {
Log.d(TAG, "[ClientService.onStartCommand] connected");
}
mOs = mSocket.getOutputStream();
mIn = mSocket.getInputStream();
} catch (Exception e) {
if (DEBUG) {
Log.e(TAG, "[ClientService.onStartCommand] ", e);
}
}
}
byte[] buffer = new byte[1024];
int read = mIn.available();
if (read > 0) {
read = mIn.read(buffer, 0, read);
if (DEBUG) {
if (read > 0) {
Log.d(TAG, "server: " + new String(buffer, 0, read));
} else {
Log.d(TAG, "no msg from server");
}
}
}
mOs.write("hello, server".getBytes());
} else if (cmd == CMD_STOP) {
if (DEBUG) {
Log.d(TAG, "[ClientService.onStartCommand] close");
}
mOs.close();
mSocket.close();
stopSelf();
}
} catch (Exception e) {
if (DEBUG) {
Log.e(TAG, "[ClientService.onStartCommand] ", e);
}
}
return super.onStartCommand(intent, flags, startId);
}
}
<file_sep>/b2lib/src/main/java/com/bro2/tljpref/TileJPref.java
package com.bro2.tljpref;
/**
* Created by Brotoo on 15/01/2018.
*/
public final class TileJPref {
}
<file_sep>/b2lib/src/main/java/com/bro2/util/RWLock.java
package com.bro2.util;
import android.util.Log;
import java.util.HashMap;
import static com.bro2.b2lib.B2LibEnv.DEBUG;
import static com.bro2.b2lib.B2LibEnv.TAG_PREFIX;
/**
* Created by Bro2 on 2017/7/24
*/
public class RWLock<T> {
private final Object sRWCheckLock = new Object();
private final HashMap<T, Integer> sReadFlag = new HashMap<>();
private final HashMap<T, Boolean> sWriteFlag = new HashMap<>();
public boolean checkAndSetRead(T key, boolean read) {
synchronized (sRWCheckLock) {
if (sWriteFlag.containsKey(key)) {
return false;
}
Integer count = sReadFlag.get(key);
if (count == null) {
count = 0;
}
if (read) {
sReadFlag.put(key, count + 1);
} else {
int c = count - 1;
if (c < 0) {
if (DEBUG) {
Log.e(TAG_PREFIX, "[RWLock.checkAndSetRead] invoke incorrectly");
}
c = 0;
}
if (c == 0) {
sReadFlag.remove(key);
} else {
sReadFlag.put(key, count - 1);
}
}
return true;
}
}
public boolean checkAndSetWrite(T key, boolean expected, boolean val) {
synchronized (sRWCheckLock) {
Integer read = sReadFlag.get(key);
if (read != null && read > 0) {
return false;
}
boolean old = sWriteFlag.containsKey(key);
if (old != expected) {
return false;
}
if (val) {
sWriteFlag.put(key, null);
} else {
sWriteFlag.remove(key);
}
return true;
}
}
public void dump() {
if (DEBUG) {
Log.d(TAG_PREFIX, "[RWLock.dump] read flags: ");
}
for (T k : sReadFlag.keySet()) {
if (DEBUG) {
Log.d(TAG_PREFIX, "key: " + k + " count: " + sReadFlag.get(k));
}
}
if (DEBUG) {
Log.d(TAG_PREFIX, "[RWLock.dump] write flags: ");
}
for (T k : sWriteFlag.keySet()) {
if (DEBUG) {
Log.d(TAG_PREFIX, "key: " + k + " val: " + sWriteFlag.get(k));
}
}
}
}
<file_sep>/b2lib/src/main/java/com/bro2/ui/MultipleIndexLayout.java
package com.bro2.ui;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;
import com.bro2.b2lib.R;
import com.bro2.exception.B2Exception;
/**
* Created by Brotoo on 2018/7/23
*/
public class MultipleIndexLayout extends ViewGroup {
private final SparseIntArray indexHeightMap = new SparseIntArray();
public MultipleIndexLayout(Context context) {
this(context, null);
}
public MultipleIndexLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MultipleIndexLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MultipleIndexLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
indexHeightMap.clear();
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int height = heightSize;
int maxWidth = 0;
int maxHeight = 0;
boolean matchWidth = false;
int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
LayoutParams params = (LayoutParams) child.getLayoutParams();
if (!matchWidth && params.width == ViewGroup.LayoutParams.MATCH_PARENT) {
matchWidth = true;
}
int index = params.zIndex;
int old = indexHeightMap.get(index);
if (old == 0) {
height = heightSize;
} else {
height -= old;
}
measureChild(child, widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, heightMode));
int indexTotalHeight = old + child.getMeasuredHeight();
indexHeightMap.put(index, indexTotalHeight);
maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
maxHeight = Math.max(maxHeight, indexTotalHeight);
}
setMeasuredDimension(maxWidth, maxHeight);
if (matchWidth) {
for (int i = 0; i < childCount; ++i) {
View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
LayoutParams params = (LayoutParams) child.getLayoutParams();
if (params.width == ViewGroup.LayoutParams.MATCH_PARENT) {
measureChild(child, MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), heightMeasureSpec);
}
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int nowIndex = Integer.MAX_VALUE;
int top = 0;
for (int i = 0, n = getChildCount(); i < n; ++i) {
View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
int index = ((LayoutParams) child.getLayoutParams()).zIndex;
if (nowIndex != index) {
nowIndex = index;
top = 0;
}
int height = child.getMeasuredHeight();
child.layout(l, top, l + child.getMeasuredWidth(), top + height);
top += height;
}
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (!checkLayoutParams(params)) {
params = generateLayoutParams(params);
} else if (!(params instanceof LayoutParams)) {
throw new B2Exception("ill params");
}
int newIndex = -1;
int zIndex = ((LayoutParams) params).zIndex;
for (int i = 0, n = getChildCount(); i < n; ++i) {
LayoutParams childParams = (LayoutParams) getChildAt(i).getLayoutParams();
if (childParams.zIndex > zIndex) {
newIndex = i;
break;
}
}
super.addView(child, newIndex, params);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
public static class LayoutParams extends ViewGroup.LayoutParams {
public int zIndex;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.MultipleIndexLayout_Layout);
if (a != null) {
try {
zIndex = a.getInt(R.styleable.MultipleIndexLayout_Layout_zIndex, 0);
} finally {
a.recycle();
}
}
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
if (source instanceof LayoutParams) {
LayoutParams params = (LayoutParams) source;
zIndex = params.zIndex;
}
}
}
}
<file_sep>/buildSrc/src/main/resources/META-INF/gradle-plugins/com.bro2.gradle.transform-demo.properties
implementation-class=com.bro2.gradle.transform.DemoPlugin<file_sep>/b2lib/src/main/java/com/bro2/util/EncryptUtil.java
package com.bro2.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by Brotoo on 2017/12/11
*/
public final class EncryptUtil {
private EncryptUtil() {
}
private static final char[] sHexChar = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String md5(String content) throws NoSuchAlgorithmException, IOException {
ByteArrayInputStream stream = new ByteArrayInputStream(content.getBytes());
return md5(stream);
}
public static String md5(InputStream stream) throws NoSuchAlgorithmException, IOException {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024 * 4];
int read;
while ((read = stream.read(buffer)) != -1) {
digest.update(buffer, 0, read);
}
return toHexString(digest.digest());
}
public static String toHexString(byte bytes[]) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(sHexChar[(b & 0xf0) >>> 4]);
sb.append(sHexChar[b & 0xf]);
}
return sb.toString();
}
}
<file_sep>/b2lib/src/main/java/com/bro2/util/BitOperator.java
package com.bro2.util;
/**
* Created by Brotoo on 2018/6/23.
*/
public final class BitOperator {
public static boolean getBit(int value, int mask) {
return (value & mask) != 0;
}
public static int setBit(int value, int mask, boolean bit) {
if (bit) {
return value | mask;
} else {
return value & ~mask;
}
}
}
<file_sep>/demo/src/main/java/com/bro2/demo/MainActivity.java
package com.bro2.demo;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Bro2 on 2017/6/4
*/
public class MainActivity extends ListActivity {
private static final String TAG = DemoEnv.TAG_PREFIX + "main";
private abstract static class TestCase implements Comparable<TestCase> {
int priority = Integer.MIN_VALUE;
String title;
TestCase(String title) {
this.title = title;
}
@Override
public int compareTo(@NonNull TestCase o) {
return priority - o.priority;
}
abstract void onClick();
}
private final ArrayList<TestCase> mCases = new ArrayList<>();
{
Context ctx = DemoApp.getApplication();
PackageManager pm = ctx.getPackageManager();
try {
PackageInfo packageInfo = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
ActivityInfo[] activities = packageInfo == null ? null : packageInfo.activities;
for (int i = 0, l = activities == null ? 0 : activities.length; i < l; ++i) {
ActivityInfo activity = activities[i];
String name = activity.name;
if (name.startsWith("com.bro2.demo.entry")) {
String tag = name.substring(name.lastIndexOf('.') + 1);
final Class target = Class.forName(name);
addCase(new TestCase(tag) {
@Override
void onClick() {
startActivity(new Intent(MainActivity.this, target));
}
});
}
}
} catch (Throwable e) {
Log.e(TAG, null, e);
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new BaseAdapter() {
@Override
public int getCount() {
return mCases.size();
}
@Override
public Object getItem(int i) {
return mCases.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
TextView textView;
if (view == null) {
view = textView = new TextView(viewGroup.getContext());
textView.setPadding(60, 20, 60, 20);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
} else {
textView = (TextView) view;
}
TestCase testCase = (TestCase) getItem(i);
textView.setText(testCase.title);
return view;
}
});
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
TestCase testCase = (TestCase) getListAdapter().getItem(position);
testCase.onClick();
}
private void addCase(TestCase testCase) {
if (testCase.priority == Integer.MIN_VALUE) {
testCase.priority = mCases.size();
}
mCases.add(testCase);
}
}
<file_sep>/build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
ext {
COMPILE_SDK_VERSION = 28
BUILD_TOOLS_VERSION = "28.0.3"
MIN_SDK_VERSION = 19
TARGET_SDK_VERSION = 28
APPLICATION_ID = "com.bro2.demo"
VERSION_CODE = 1
VERSION_NAME = "1.0"
TEST_INSTRUMENTATION_RUNNER = "android.support.test.runner.AndroidJUnitRunner"
ANDROID_TEST = "com.android.support.test.espresso:espresso-core:2.2.2"
JUNIT = "junit:junit:4.12"
SUPPORT_V7 = "com.android.support:appcompat-v7:28.0.0"
CONSTRAINT_LAYOUT = "com.android.support.constraint:constraint-layout:1.0.2"
}
buildscript {
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
maven { url 'https://dl.google.com/dl/android/maven2' }
}
dependencies {
classpath property('android.plugin')
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
maven { url 'https://dl.google.com/dl/android/maven2' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
<file_sep>/b2lib/src/test/java/com/bro2/b2lib/TimingTest.java
package com.bro2.b2lib;
import com.bro2.timing.AverageClerk;
import com.bro2.timing.Marker;
import com.bro2.timing.Timing;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
/**
* Created by Bro2 on 2017/9/8
*/
public class TimingTest {
@Before
public void setUp() {
Timing.prepareClerk(new AverageClerk());
}
@Test
public void test() {
ArrayList<Marker> markers = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
markers.add(new Marker("step" + i, i));
}
for (int i = 0; i < 50; ++i) {
for (Marker marker : markers) {
Timing.enter(marker);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Timing.leave(marker);
}
}
}
System.out.println(Timing.dump());
}
}
<file_sep>/settings.gradle
include ':b2lib', ':demo', ':b2jni'
<file_sep>/b2lib/src/main/java/com/bro2/io/ProcUtil.java
package com.bro2.io;
import android.text.TextUtils;
import android.util.Pair;
import android.util.SparseArray;
import com.bro2.b2lib.B2LibEnv;
import java.io.FileInputStream;
/**
* Created by Brotoo on 2017/12/6
*/
public final class ProcUtil {
private ProcUtil() {
}
private static final int CAPACITY_PROCESS = 10;
private static final int CAPACITY_THREAD = 30;
private static final SparseArray<String> sProcessName = new SparseArray<>(CAPACITY_PROCESS);
private static final SparseArray<String> sThreadName = new SparseArray<>(CAPACITY_THREAD);
public static Pair<String, String> getProcessName(int pid, int tid) {
FileInputStream fis = null;
String pName = null;
String tName = null;
try {
pName = sProcessName.get(pid);
if (TextUtils.isEmpty(pName)) {
String cmdLine = String.format("/proc/%d/cmdline", pid);
fis = new FileInputStream(cmdLine);
byte[] buffer = new byte[1024];
int read = fis.read(buffer);
for (int i = 0; i < read; i++) {
if (buffer[i] == 0) {
pName = new String(buffer, 0, i);
if (sProcessName.size() > CAPACITY_PROCESS) {
sProcessName.clear();
}
sProcessName.append(pid, pName);
break;
}
}
}
} catch (Throwable e) {
if (B2LibEnv.DEBUG) {
throw new RuntimeException(e);
}
} finally {
IOUtil.closeSilently(fis);
}
try {
tName = sThreadName.get(tid);
if (TextUtils.isEmpty(tName)) {
String statPath = String.format("/proc/%d/task/%d/stat", pid, tid);
fis = new FileInputStream(statPath);
byte[] buffer = new byte[1024];
int read = fis.read(buffer);
int start = -1;
for (int i = 0; i < read; i++) {
if (buffer[i] == ' ') {
if (start == -1) {
start = i;
} else {
tName = new String(buffer, start + 2, i - start - 3);
if (sThreadName.size() > CAPACITY_THREAD) {
sThreadName.clear();
}
sThreadName.append(tid, tName);
break;
}
}
}
}
} catch (Throwable e) {
if (B2LibEnv.DEBUG) {
throw new RuntimeException(e);
}
} finally {
IOUtil.closeSilently(fis);
}
return new Pair<>(pName, tName);
}
}
<file_sep>/b2jni/src/main/cpp/bzip2/Android.mk
LOCAL_PATH := $(call my-dir)
####################################################
# bzip
####################################################
include $(CLEAR_VARS)
LOCAL_CFLAGS += -Werror
LOCAL_MODULE := bzip
LOCAL_SRC_FILES := blocksort.c \
huffman.c \
crctable.c \
randtable.c \
compress.c \
decompress.c \
bzlib.c
include $(BUILD_STATIC_LIBRARY)<file_sep>/b2lib/src/main/java/com/bro2/io/IOUtil.java
package com.bro2.io;
import android.util.Log;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static com.bro2.b2lib.B2LibEnv.DEBUG;
import static com.bro2.b2lib.B2LibEnv.TAG_PREFIX;
/**
* Created by Brotoo on 2017/11/29
*/
public final class IOUtil {
public static final int DEFAULT_STREAM_BUFFER_SIZE = 10 * 1024;
private static final String TAG = TAG_PREFIX + "io";
private IOUtil() {
}
public static void closeSilently(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
if (DEBUG) {
Log.e(TAG, "closeCloseable", e);
}
}
}
}
public static void copyStreamWithClose(InputStream src, OutputStream dest) throws IOException {
try {
int read;
byte[] buffer = new byte[1024 * 4];
while ((read = src.read(buffer, 0, buffer.length)) != -1) {
dest.write(buffer, 0, read);
}
} finally {
closeSilently(dest);
closeSilently(src);
}
}
public static void copy(InputStream src, OutputStream dest) throws IOException {
int read;
byte[] buffer = new byte[1024 * 4];
while ((read = src.read(buffer, 0, buffer.length)) != -1) {
dest.write(buffer, 0, read);
}
}
public static int readStreamAtMost(InputStream inputStream, byte[] buffer) throws IOException {
int remain = buffer.length;
int start = 0;
while (remain > 0) {
int read = inputStream.read(buffer, start, remain);
if (read == -1) {
break;
}
start += read;
remain -= read;
}
return start;
}
}
<file_sep>/b2jni/src/main/cpp/emudetector/emulator_detect.cpp
//
// Created by Brotoo on 2017/9/16.
//
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/errno.h>
#include <string.h>
extern "C" int detect_arm();
static void *g_shared_mem = MAP_FAILED;
static volatile bool g_has_invoked = false;
static volatile bool g_is_emulator = false;
void dump() {
unsigned char *p = (unsigned char *) g_shared_mem;
for (int i = 0; i < 50; ++i) {
char buf[80] = {0};
for (int j = 0; j < 16; ++j) {
sprintf(buf, "%s %02x", buf, p[i * 16 + j]);
}
printf("%s\n", buf);
}
}
bool is_emulator() {
if (g_has_invoked || g_shared_mem == MAP_FAILED) {
return g_is_emulator;
}
printf("start execute\n");
g_has_invoked = true;
int res = ((int (*)()) g_shared_mem)();
printf("execute result: %d\n", res);
dump();
if (res == 1) {
g_is_emulator = true;
} else if (res == 2) {
g_is_emulator = false;
} else {
printf("impossible things happen: %d\n", res);
}
return g_is_emulator;
}
int main() {
size_t page_size = (size_t) getpagesize();
do {
g_shared_mem = mmap(NULL, page_size, PROT_EXEC | PROT_WRITE | PROT_READ,
MAP_ANONYMOUS | MAP_PRIVATE, -1, (off_t) 0);
} while (errno == EINTR);
if (g_shared_mem == MAP_FAILED) {
int err = errno;
printf("mmap err: %s\n", strerror(err));
return 0;
}
printf("JNI_OnLoad mmap result: %p\n", g_shared_mem);
#ifdef __LP64__
memcpy(g_shared_mem, (void **) detect_arm, 21 * 4);
#else
memcpy(g_shared_mem, (void **) detect_arm, 17 * 4);
#endif
dump();
if (is_emulator()) {
printf("detect result: emulator\n");
} else {
printf("detect result: real machine\n");
}
return 0;
}
<file_sep>/b2jni/src/main/cpp/emudetector/Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := emulator-detect
LOCAL_SRC_FILES := emulator_detect.cpp
ifeq ($(TARGET_ARCH_ABI), armeabi-v7a)
LOCAL_SRC_FILES += detect_arm.S
else
ifeq ($(TARGET_ARCH_ABI), arm64-v8a)
LOCAL_SRC_FILES += detect_arm64.S
endif
endif
LOCAL_LDFLAGS += -pie
LOCAL_CFLAGS += -Werror
include $(BUILD_EXECUTABLE)
<file_sep>/demo/src/main/java/com/bro2/demo/entry/LocalSocketActivity.java
package com.bro2.demo.entry;
import android.app.Activity;
import android.content.Intent;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.bro2.demo.R;
import com.bro2.demo.localsocket.ClientService;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.bro2.demo.DemoEnv.DEBUG;
import static com.bro2.demo.DemoEnv.TAG_PREFIX;
public class LocalSocketActivity extends Activity implements View.OnClickListener {
public static final String SERVER_NAME = "sock_server";
private static final String TAG = TAG_PREFIX + "socket_server";
private static final String WHO_SERVER = "server";
private static final String WHO_CLIENT = "client";
private TextView mStatusTv;
private ExecutorService mExecutor = Executors.newSingleThreadExecutor();
LocalServerSocket mSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_local_socket);
mStatusTv = (TextView) findViewById(R.id.tv_status);
findViewById(R.id.bt_start_server).setOnClickListener(this);
findViewById(R.id.bt_stop_server).setOnClickListener(this);
findViewById(R.id.bt_start_client).setOnClickListener(this);
findViewById(R.id.bt_stop_client).setOnClickListener(this);
findViewById(R.id.bt_clear_status).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_start_server:
startServer();
break;
case R.id.bt_stop_server:
stopServer();
break;
case R.id.bt_start_client:
startClient();
break;
case R.id.bt_stop_client:
stopClient();
break;
case R.id.bt_clear_status:
mStatusTv.setText("");
break;
}
}
private void appendStatus(final String who, final String status) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mStatusTv.append("\n" + who + ": " + status);
}
});
}
private void startServer() {
try {
mSocket = new LocalServerSocket(SERVER_NAME);
} catch (Exception e) {
appendStatus(WHO_SERVER, e.toString());
return;
}
mExecutor.execute(new Runnable() {
@Override
public void run() {
boolean flag = Thread.currentThread().isInterrupted();
while (!flag) {
LocalSocket client = null;
InputStream mIn = null;
try {
appendStatus(WHO_SERVER, "start accept");
client = mSocket.accept();
mIn = client.getInputStream();
byte[] buffer = new byte[1024];
int read;
while ((read = mIn.read(buffer, 0, buffer.length)) != -1) {
appendStatus(WHO_CLIENT, new String(buffer, 0, read));
}
flag = Thread.currentThread().isInterrupted();
appendStatus(WHO_SERVER, "closed client");
} catch (Exception e) {
appendStatus(WHO_SERVER, e.toString());
} finally {
close(mIn);
close(client);
}
}
appendStatus(WHO_SERVER, "start close server");
try {
mSocket.close();
} catch (Exception e) {
appendStatus(WHO_SERVER, e.toString());
}
}
});
}
private void stopServer() {
System.exit(0);
}
private void startClient() {
Intent service = new Intent(this, ClientService.class);
service.putExtra(ClientService.KEY_SERVER_NAME, SERVER_NAME);
startService(service);
}
private void stopClient() {
Intent service = new Intent(this, ClientService.class);
service.putExtra(ClientService.KEY_COMMAND, ClientService.CMD_STOP);
startService(service);
}
private void close(Closeable close) {
if (close != null) {
try {
close.close();
} catch (IOException e) {
if (DEBUG) {
Log.e(TAG, "[LocalSocketActivity.close] ", e);
}
}
}
}
}
<file_sep>/b2jni/CMakeLists.txt
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.6.0)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
enable_language(ASM)
SET(CMAKE_ASM_FLAGS "${CFLAGS} -x assembler-with-cpp")
if(${ANDROID_ABI} STREQUAL "armeabi")
set(asm_SRCS src/main/cpp/emudetector/detect_arm.S)
else()
set(asm_SRCS src/main/cpp/emudetector/detect_arm64.S)
endif()
add_executable( # Sets the name of the library.
emulator-detect
# Provides a relative path to your source file(s).
src/main/cpp/emudetector/emulator_detect.cpp
#src/main/cpp/emudetector/detect.S
${asm_SRCS}
)
target_compile_options(
emulator-detect
PRIVATE
-Werror
)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
emulator-detect
# Links the target library to the log library
# included in the NDK.
${log-lib}
z )<file_sep>/demo/src/main/java/com/bro2/demo/entry/LineTitleActivity.java
package com.bro2.demo.entry;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import com.bro2.demo.R;
import com.bro2.ui.LineTitleLayout;
/**
* Created by Brotoo on 2018/6/21
*/
public class LineTitleActivity extends Activity {
private LineTitleLayout titleLayout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_line_title);
titleLayout = findViewById(R.id.ltl_title);
titleLayout.setOnElementClickListener("back", new LineTitleLayout.OnElementClickListener() {
@Override
public void onClick(View view, String action) {
finish();
}
});
}
private boolean progressStyle;
private boolean borderStyle;
public void debug(View view) {
switch (view.getId()) {
case R.id.bt_progress_visible:
titleLayout.setProgressVisible(!titleLayout.getProgressVisible());
break;
case R.id.bt_inc_progress:
titleLayout.setProgress(titleLayout.getProgress() + 10);
break;
case R.id.bt_dec_progress:
titleLayout.setProgress(titleLayout.getProgress() - 10);
break;
case R.id.bt_progress_style:
Drawable progressDrawable;
if (!progressStyle) {
progressStyle = true;
progressDrawable = new ClipDrawable(new ColorDrawable(Color.BLUE), Gravity.START, ClipDrawable.HORIZONTAL);
} else {
progressStyle = false;
progressDrawable = getResources().getDrawable(R.drawable.horizontal_progress);
}
titleLayout.setProgressDrawable(progressDrawable);
break;
case R.id.bt_border_visible:
titleLayout.setBorderVisible(!titleLayout.getBorderVisible());
break;
case R.id.bt_border_style:
Drawable borderDrawable;
if (!borderStyle) {
borderStyle = true;
borderDrawable = new ColorDrawable(getResources().getColor(R.color.colorPrimary));
} else {
borderStyle = false;
borderDrawable = getResources().getDrawable(R.drawable.border_shadow);
}
titleLayout.setBorderDrawable(borderDrawable);
break;
case R.id.bt_title_layout_visible:
titleLayout.setLayoutVisible(!titleLayout.getLayoutVisible());
break;
case R.id.bt_primary_start:
titleLayout.setPrimaryGravity(LineTitleLayout.PRIMARY_GRAVITY_START);
break;
case R.id.bt_primary_center:
titleLayout.setPrimaryGravity(LineTitleLayout.PRIMARY_GRAVITY_CENTER);
break;
case R.id.bt_primary_end:
titleLayout.setPrimaryGravity(LineTitleLayout.PRIMARY_GRAVITY_END);
break;
}
}
}
<file_sep>/b2lib/src/main/java/com/bro2/crm/Column.java
package com.bro2.crm;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by Bro2 on 2017/6/10
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
String name();
boolean key() default false;
}
|
ff79ca9e0ad76de1d6658a009d53802445081a83
|
[
"CMake",
"Makefile",
"INI",
"Gradle",
"Java",
"C++"
] | 25
|
Gradle
|
BrotooLu/android-demo
|
bd3c4b26719da262b0a353cba9f8ed649cf8476d
|
1627a8cbe516996dd1f4ad300e76069ce4ff7832
|
refs/heads/master
|
<file_sep>//EXERCICE 1
// $( "button" ).last().click(function() {
// $( "#clicker" ).last().fadeToggle( "fast", function() {
// $( "#secret" ).append( "Click me to toggle a hidden secret!" );
// });
// });
// $(document).ready(function(){
// $("button").click(function(){
// $("#clicker").fadeIn();
// $("#secret").fadeIn("slow");
// $("div").fadeIn(1000);
// });
// });
// $( document.body ).click(function () {
// $( "button" ).last().click(function() {
// if ( $( "div" ).first().is( ":hidden" ) ) {
// $( "#clicker" ).last().fadeToggle( "fast", function() {
// $( "div" ).slideDown( "slow" );
// $( "#secret" ).append( "Click me to toggle a hidden secret!" );
// }else{
// });
// $( "div" ).hide();
// });
//---------------------------------------------------------
//EXERCICE 2
// $( document.body ).click(function() {
// if ( $( "#clicker" ).first().is( ":hidden" ) ) {
// $( "#secret" ).show( "slow" );
// } else {
// $( "p.secret" ).slideUp();
// }
// });
//--------------------------------------------------------------
//EXERCICE 3
$(document).ready(function()
{
$("#clicker").click(function(){
$("img").attr('src', 'img1.gif');
$("#clicker").hide();
});
});
|
a3f7870f086d1c5fa43c758fa67f53b803578389
|
[
"JavaScript"
] | 1
|
JavaScript
|
Afnan26/hw-week-06-jquery-2
|
8b7e2bd899de6cc33f49114d3d96c69ccb4b8ae5
|
c1cc11674741f27826b0f7b3ddc8bdf073c30f8c
|
refs/heads/main
|
<file_sep>package school;
public class ctv extends giangvien{
void DayHocNuaBuoi(){
System.out.println("Cộng tác viên chỉ dạy nửa buổi");
}
}
<file_sep>package school;
public class nvbaove extends nhanvien {
void BaoVe(){
System.out.println("Nhân viên bảo vệ thực hiển bảo đảm an ninh");
}
void LamCa(){
System.out.println("Nhân viên bảo vệ phải làm theo ca");
}
}
<file_sep>package school;
public class thinhgiang extends giangvien {
void DayHocThinhThoang(){
System.out.println("Giáo viên thỉnh giảng dạy một vài lần");
}
}
<file_sep>package school;
import java.util.Date;
public class nhanvien {
String manv;
String ten;
Date NgaySinh;
String PhongBan;
}
<file_sep>package school;
public class svdanghoc {
void DiHoc(){
System.out.println("Sinh viên đi học");
}
void DiThi(){
System.out.println("Sinh viên đi thi");
}
}
<file_sep>package school;
import java.util.Date;
public class sinhvien {
String masv;
String lop;
String khoa;
String ten;
Date NgaySinh;
Date NgayNhapHoc;
}
<file_sep>package school;
import java.util.Date;
public class svdaratruong extends sinhvien{
Date NamTotNghiep;
String LoaiTotNghiep;
String CongTy;
void DiLam(){
System.out.println("Sinh viên đã ra trường đi làm");
}
}
|
c93d4d140d833d25f0a900002313ea99657e1600
|
[
"Java"
] | 7
|
Java
|
thaodp0312/BTVN_buoi17
|
34ff661b37e329be2b499d9038c1e3a3ab75dd8a
|
13b680866c9383da69182861c1032e08dc813d9c
|
refs/heads/master
|
<file_sep>import RPi.GPIO as GPIO
from time import sleep, time, strftime, localtime
from datetime import *
async def GrowLight(StartTime, StopTime):
hour = int(strftime("%H", localtime()))
GPIO.setmode(GPIO.BCM)
light_relay = 23
GPIO.setwarnings(False)
GPIO.setup(light_relay, GPIO.OUT)
if hour in range(StartTime, StopTime+1):
# print("LED ON!!!")
GPIO.output(light_relay, 0)
else:
# print("LED OFF!!!")
GPIO.output(light_relay, 1)
return True<file_sep>import time
import signal
import Adafruit_DHT
from multiprocessing import Process
import asyncio
class BlntReadError(Exception):
pass
def timeout(signum, frame):
raise BlntReadError('took too long')
signal.signal(signal.SIGALRM, timeout)
def getSen(pin_x):
temperature = -274
start = time.time()
signal.alarm(1)
try:
humid,temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22,pin_x)
except BlntReadError:
print('action timed out!')
signal.alarm(0)
if temperature is None or temperature == -274:
return None
if temperature is not None:
temperature = round(temperature, 3)
print(temperature,"before end_val","pin",pin_x)
# print("\n")
return temperature
# def getCon(pin):
#
# pc = Process(target=getSen,args =(pin,))
# pc.start()
# pc.join()
def getTemp():
p1 = Process(target=getSen, args=(4,))
p2 = Process(target=getSen, args=(20,))
p3 = Process(target=getSen, args=(21,))
p1.start() # spawn process
p2.start()
p3.start()
#
p1.join() # blocks until done
p2.join()
p3.join()
result = []
end_result = list(filter(None,result))
#
if len(end_result) == 0:
return False
#
end_val = round(sum(filter(None,result)) / len(end_result),3)
print("-------")
print(end_val)
return end_val
# getTemp()
<file_sep>from base64 import b64encode, decodestring, decodebytes
import asyncio
def decodePicture(name):
file = '/home/pi/Desktop/smartGarden/SmartGarden/Pictures/' + str(name)+".jpg"
with open(file, "rb") as imageFile:
encoded = b64encode(imageFile.read())
return encoded.decode('utf-8')
async def encodePicture(encoded):
fh = open("imageToSave.jpeg", "wb")
fh.write(decodebytes(encoded))
fh.close()
<file_sep>import csv
import asyncio
async def writeFile(name, data):
with open(name, mode='a') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow(data)
async def readFile(name):
with open(name) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
return list(csv_reader)
async def deleteFile(name):
f = open(name, 'w+')
f.close()
return True
async def find_data(data, file):
fileData = await readFile(file)
for row in fileData:
if data == row[0]:
return row
return False
def getTime(time):
with open('executeTime.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(str(time))
csvFile.close()
<file_sep>#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries
# Author: <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import Adafruit_DHT
# sensor = Adafruit_DHT.DHT22
# pin = 4
#humidity,temperature = Adafruit_DHT.read_retry(sensor,pin)
import time
import signal
import asyncio
# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
class BlntReadError(Exception):
pass
def timeout(signum, frame):
raise BlntReadError('took too long')
signal.signal(signal.SIGALRM, timeout)
async def Temperature(pin=20):
start = time.time()
temperature = -274
signal.alarm(1)
try:
humid,temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22,pin)
except BlntReadError:
# print('action timed out!')
pass
signal.alarm(0)
temperature = round(temperature, 3)
return temperature
async def Temp(prevTemp):
t = await Temperature()
if t == -274:
t = prevTemp
return t
# out = -274
# errorcount = 0
# totalcount = 0
# while True:
# try:
# t = Temperature()
# if t != -274:
# out = t
# print("CHANGE")
# if t == -274:
# errorcount += 1
# time.sleep(1)
# print(out)
# totalcount += 1
# print("TOTAL = " + str(totalcount) + "\nERROR = " + str(errorcount))
# print("Error percentage", (errorcount/totalcount * 100))
<file_sep>import RPi.GPIO as GPIO
from time import sleep
import asyncio
async def HeatControl(command, fan_relay, heat_relay, tempVal=0, maxTemp=0, minTemp=0):
if command:
if tempVal > maxTemp:
await FanBlow(True, fan_relay)
await HeatPad(False, heat_relay)
return True
elif tempVal < minTemp:
await FanBlow(False, fan_relay)
await HeatPad(True, heat_relay)
return True
else:
await FanBlow(False, fan_relay)
await HeatPad(False, heat_relay)
return True
else:
await FanBlow(False, fan_relay)
await HeatPad(False, heat_relay)
return False
async def FanBlow(command, fan_relay):
if command:
GPIO.output(fan_relay, 0)
return True
else:
GPIO.output(fan_relay, 1)
return False
async def HeatPad(command, heat_relay):
if command:
GPIO.output(heat_relay, 0)
return True
else:
GPIO.output(heat_relay, 1)
return False
<file_sep>import RPi.GPIO as GPIO
from time import sleep
import asyncio
plantDict = { "water spinach": {"tempType" : 'tropical', "waterType" : 'hydric'},
"plantA": {"tempType" : 'temperate', "waterType": 'mesic'}
}
waterTypes = { "xeric" : [20,29] ,
"mesic" : [30,49] ,
"hydric" : [50,60]
}
async def WaterControl(humVal, minHum):
# print('Value:', min(waterTypes[plantDict["plantA"]["waterType"]]))
if humVal < minHum:
# print("humidity ==> ",humVal)
return await WaterPump(2) # 5 sec is time for openning valve
async def WaterPump(seconds):
GPIO.setmode(GPIO.BCM)
pump_relay = 26
GPIO.setwarnings(False)
GPIO.setup(pump_relay, GPIO.OUT)
# GPIO.output(pump_relay, 1)
# sleep(1)
# try:
GPIO.output(pump_relay, 0)
await asyncio.sleep(seconds)
GPIO.output(pump_relay, 1)
return True
# print("I pump for", seconds , "secs!")
# except KeyboardInterrupt:
# print("I except na")
<file_sep>import RPi.GPIO as GPIO
import threading
import asyncio
async def WaterControl(command, pump_relay, humVal=0, minHum=0, seconds=2): # open valve for 2 sec
if command:
if humVal < minHum:
return await WaterPump(seconds, pump_relay)
else:
GPIO.output(pump_relay, 1)
await asyncio.sleep(seconds)
return True
else:
GPIO.output(pump_relay, 1)
return False
async def WaterPump(seconds, pump_relay):
GPIO.output(pump_relay, 0)
await asyncio.sleep(seconds)
GPIO.output(pump_relay, 1)
return True
<file_sep>'''
import serial
import struct
import asyncio
data = serial.Serial('/dev/ttyACM0', 115200)
async def checkHumidity():
i = "h".encode() #Arduino is ascii, python is unicode
data.write(i)
while True:
if (data.in_waiting > 0):
result = data.readline()
humiVal = float(result.strip().decode("utf-8"))
return humiVal
await asyncio.sleep(0.01)
async def checkTemperature():
i = "t".encode() #Arduino is ascii, python is unicode
data.write(i)
while True:
if (data.in_waiting > 0):
result = data.readline()
tempVal = float(result.strip().decode("utf-8"))
return tempVal
await asyncio.sleep(0.01)
'''
import sys
import Adafruit_DHT
import asyncio
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import time
import asyncio
async def checkTemperature(sensor=Adafruit_DHT.DHT22, pin=4):# Parse command line parameters.
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if temperature is not None:
return temperature
else:
print('Failed to Read Temperature')
return ''
async def mapping(val, maxval):
return 100 - (val/maxval)*100
async def checkHumidity(mcp, pin=6):
values = mcp.read_adc(pin)
result = round(await mapping(values, 1023), 2)
return result
async def weight(hx):
val = hx.get_weight(5)
hx.power_down()
hx.power_up()
return float(val)
async def checkWaterLevel(hx):
return round(await weight(hx), 2)
<file_sep>from editfiles import readFile, writeFile, deleteFile, find_data
from base64 import b64encode, decodestring, decodebytes
from datetime import *
from Controller.Camera import camera
from encoding import decodePicture
import time
import ast
import asyncio
import threading
import websockets
import RPi.GPIO as GPIO
async def response(websocket, path):
while True:
start = False
while start != True:
pin = await websocket.recv()
if pin == 'camera':
name = await camera()
code = decodePicture(name)
await websocket.send(str(code))
else:
start = await find_data(pin, 'controllerPin.csv')
if not start:
await websocket.send('Invalid pin, Please try again.')
else:
start = True
await websocket.send('Access!')
checkFile = 'check['+ str(pin) + '].csv'
dataFile = 'data['+ str(pin) + '].csv'
settingFile = 'ifconfig['+ str(pin) + '].csv'
message = await websocket.recv()
if await readFile(checkFile) != []:
if len(message) > 1 and message[0] == '[' and message[-1] == ']':
data = ast.literal_eval(message)
await writeFile(dataFile, data)
# print("hum",data[0])
# print("tem",data[1])
await websocket.send("Done")
else:
print("We got message from client:", message)
if message == 'status':
await websocket.send("Status: On")
elif message == 'data':
dataCollection = await readFile(dataFile)
if len(dataCollection) == 0:
await websocket.send("no data")
else:
await websocket.send(str(dataCollection))
elif message == 'water level':
waterLevel = await readFile(dataFile)
waterPercent = float(waterLevel[-1][-1])/10
waterPercent = round(waterPercent, 3)
if waterPercent < 30:
msg = "The water tank is now at critical level [water level: "+ str(waterPercent) +"%]"
else:
msg = "The water tank is now "+ str(waterPercent)+ "%"
await websocket.send(msg)
elif message == 'stop':
await deleteFile(checkFile)
await deleteFile(dataFile)
await websocket.send('Stop!')
elif message == 'setting':
await websocket.send('What do you want to do?')
setting = await websocket.recv()
if setting == 'frequent checking':
frequency = await websocket.recv()
if int(frequency) < 5:
await websocket.send('Please give more than or equal to 5 sec')
await writeFile(settingFile, [frequency])
await websocket.send('Please restart your device')
elif setting == 'reset':
await deleteFile(settingFile)
await websocket.send('Please restart your device')
else:
await websocket.send('Please try again')
else:
await websocket.send("Please try again")
else:
print("We got message from client:", message)
if message == 'status':
await websocket.send("Status: Off")
elif message == 'start':
PlantList = [i[0] for i in await readFile('database.csv')]
del PlantList[0]
await websocket.send(str(PlantList))
plant_name = await websocket.recv()
print("client's plant:", plant_name)
plantData = await find_data(plant_name, 'database.csv')
if plantData == False:
await websocket.send('Sorry, that plant\'s name is not included')
else:
await deleteFile(dataFile)
await writeFile(checkFile, plantData)
await websocket.send('Start!')
elif message == 'setting':
await websocket.send('What do you want to do?')
setting = await websocket.recv()
if setting == 'frequent checking':
frequency = await websocket.recv()
print('frequecy:', frequency)
if int(frequency) < 5:
await websocket.send('Please give more than or equal to 5 sec')
return
await writeFile(settingFile, [frequency])
await websocket.send('Done')
elif setting == 'reset':
await deleteFile(settingFile)
await websocket.send('Done')
else:
await websocket.send('Please try again')
elif message == 'water level' or message == 'camera':
await websocket.send("Please start the machine")
elif message == 'data':
await websocket.send("no data")
elif message == 'stop':
await websocket.send("the machine already stop")
else:
await websocket.send("Please try again")
start_server = websockets.serve(response, '0.0.0.0', 5679)
loop = asyncio.get_event_loop()
loop.run_until_complete(start_server)
loop.run_forever()<file_sep>import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import time
import asyncio
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
def mapping(val, maxval):
return 100 - (val/maxval)*100
async def moisture():
values = mcp.read_adc(0)
return (round(mapping(values, 1023), 2))
asyncio.get_event_loop().run_until_complete(moisture())
<file_sep>#! /usr/bin/python2
import time
import sys
import threading
import asyncio
# EMULATE_HX711=False
#
# referenceUnit = -423.3
#
# if not EMULATE_HX711:
# import RPi.GPIO as GPIO
# from hx711 import HX711
# else:
# from emulated_hx711 import HX711
# hx = HX711(5,6)
#
# hx.set_reading_format("MSB", "MSB")
#
# hx.set_reference_unit(-423.3)
#
# hx.reset()
#
# hx.tare()
# while True:
# try:
# #max = 1200ml
# val = round((hx.get_weight(5) - 145)/1200 * 100, 3)
# print(float(val))
#
# hx.power_down()
# hx.power_up()
# time.sleep(1)
#
# except (KeyboardInterrupt, SystemExit):
# cleanAndExit()
def cleanAndExit():
print("Cleaning...")
if not EMULATE_HX711:
GPIO.cleanup()
print("Bye!")
sys.exit()
async def get_weight(hx):
val = round((hx.get_weight(5) - 145)/1200 * 100, 3)
hx.power_down()
hx.power_up()
return float(val)
<file_sep>from Controller.HumidControl import WaterPump, WaterControl
from Controller.GrowlightControl import GrowLight
from Controller.TempControl import HeatControl, FanBlow, HeatPad
from editfiles import readFile
from datetime import *
from RequestData.hx711py.weight import get_weight
from RequestData.RequestData import checkTemperature, checkHumidity, checkWaterLevel
from RequestData.MoistureSensor import moisture
from RequestData.TemperatureSensor import Temp, Temperature
import websockets
import time
import threading
import asyncio
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import RPi.GPIO as GPIO
async def setupController():
""" Setup GPIO """
GPIO.setmode(GPIO.BCM)
light_relay = 23
fan_relay = 25
pump_relay = 26
heat_relay = 24
GPIO.setwarnings(False)
GPIO.setup(light_relay, GPIO.OUT)
GPIO.setup(fan_relay, GPIO.OUT)
GPIO.setup(pump_relay, GPIO.OUT)
GPIO.setup(heat_relay, GPIO.OUT)
'''Setup weight sensor'''
EMULATE_HX711=False
if not EMULATE_HX711:
from RequestData.hx711py.hx711 import HX711
else:
from RequestData.hx711py.emulated_hx711 import HX711
hx = HX711(5,6)
hx.set_reading_format("MSB", "MSB")
hx.set_reference_unit(-423.3)
hx.reset()
hx.tare()
'''Setup temperature sensor'''
# prevTemp = -274
# while prevTemp == -274:
# prevTemp = await Temp(prevTemp)
# print("Done setup temp sensor")
'''Setup moisture sensor'''
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
return int(light_relay), int(fan_relay), int(pump_relay), int(heat_relay), hx, mcp
async def controller(pin=1234):
light_relay, fan_relay, pump_relay, heat_relay, hx, mcp = await setupController()
command = False
frequencyChecking=5
checkFile = 'check['+ str(pin) + '].csv'
settingFile = 'ifconfig['+ str(pin) + '].csv'
while True:
if await readFile(checkFile) != []:
prevTemp = -274
while prevTemp == -274:
prevTemp = await Temp(prevTemp)
# frequencyChecking=5
# fre = await readFile(settingFile)
# if fre != []: frequencyChecking = int(fre[0][0])
# print('freCheck:', frequencyChecking)
data = await readFile(checkFile)
command = True
maxTemp, minTemp, maxHum, minHum, timeStart, timeStop = int(data[0][1]),int(data[0][2]),int(data[0][3]),int(data[0][4]),int(data[0][5]),int(data[0][6])
while command:
if await readFile(checkFile) == []: break
print('running')
# threading.Timer(frequencyChecking, main).start() # run every 5 secs
""" Water Control System"""
waterVal = await get_weight(hx)
humVal = await checkHumidity(mcp)
await WaterControl(command, pump_relay, humVal, minHum)
""" Temperature Control System """
# tempVal = await checkTemperature()
tempVal = await Temp(prevTemp)
await HeatControl(command, fan_relay, heat_relay, tempVal, maxTemp, minTemp)
""" Growlight Control System """
await GrowLight(command, light_relay, timeStart, timeStop)
""" Storing Data """
await sentData(str([humVal, tempVal, waterVal]), str(pin))
# await writeData([humVal, tempVal, waterVal])
# print("hum",humVal)
# print("tem",tempVal)
prevTemp = tempVal
await asyncio.sleep(frequencyChecking-2)
print('stop')
if command:
command = False
# waterVal = await checkWaterLevel(hx)
await WaterControl(command, pump_relay)
await GrowLight(command, light_relay)
await HeatControl(command, fan_relay, heat_relay)
await asyncio.sleep(1)
async def sentData(data, pin):
async with websockets.connect('ws://0.0.0.0:5679') as websocket:
await websocket.send(pin)
await websocket.recv()
await websocket.send(data)
await websocket.recv()
asyncio.get_event_loop().run_until_complete(controller())
<file_sep>import RPi.GPIO as GPIO
from time import sleep
async def HeatControl(tempVal, maxTemp, minTemp):
plantDict = { "water spinach": {"tempType" : 'tropical', "waterType" : 'hydric'},
"plantA": {"tempType" : 'temperate', "waterType": 'mesic'}
}
tempTypes = { "tropical" : [25,40] ,
"temperate": [15,24]
} # temperate = 15-25 ==> mean 20 , tropical = 25-40 ==> mean 32.5
if tempVal > maxTemp: # too hot # 15 min 25 max
# print("Fan OPEN!!!")
return await FanBlow(True)
elif tempVal < minTemp:
# print("Fan CLOSE!!!")
await FanBlow(False)
pass # Heat up # Fan Close
return
else:
# Temp OK!!! ==> stop heating , fan close
# print("Fan CLOSE!!!")
return await FanBlow(False)
async def FanBlow(command):
GPIO.setmode(GPIO.BCM)
fan_relay = 25
GPIO.setwarnings(False)
GPIO.setup(fan_relay, GPIO.OUT)
if command:
GPIO.output(fan_relay, 0)
else:
GPIO.output(fan_relay, 1)
return True
<file_sep>from picamera import PiCamera
from time import sleep
from datetime import *
import asyncio
async def camera():
today = datetime.now()
camera = PiCamera()
camera.resolution = (320,240)
camera.start_preview()
camera.capture('/home/pi/Desktop/smartGarden/SmartGarden/Pictures/'+str(today)+'.jpg')
camera.stop_preview()
camera.close()
return today
<file_sep>import RPi.GPIO as GPIO
from time import sleep, time, strftime, localtime
from datetime import *
import asyncio
async def GrowLight(command, light_relay ,StartTime=0, StopTime=0):
if command:
hour = int(strftime("%H", localtime()))
if hour in range(StartTime, StopTime+1):
GPIO.output(light_relay, 0)
else:
GPIO.output(light_relay, 1)
return True
else:
GPIO.output(light_relay, 1)
return False
|
299ad607a9905aae00516cf3518753d485a36d99
|
[
"Python"
] | 16
|
Python
|
Project-CIE/smartGarden
|
253785860f5660267e7053fad7c1a81eb893d057
|
b0f9e55c5803bfd17e68f66b5013b6fb895f26fb
|
refs/heads/master
|
<file_sep>var toMidi = require('./to-midi.js')
/**
* does this pitch sound higher than that pitch?
*
* @param {PitchString} sciPitch1 - a pitch in scientific pitch notation.
* @param {PitchString} sciPitch2 - a pitch in scientific pitch notation.
* @returns {boolean} is sciPitch1 higher than sciPitch2?
*
* @throws Will throw an error if string is not a valid pitch
*
* @example
* isHigher('D4', 'C4') => true
* isHigher('C4', 'D4') => false
* isHigher('C4', 'B#3') => false // enharmonic, so they actually sound equal
* isHigher('B##3', 'C4') => true // B##3 sounds higher than C4
*/
var isHigher = function (sciPitch1, sciPitch2) {
return toMidi(sciPitch1) > toMidi(sciPitch2)
}
module.exports = isHigher
<file_sep>var test = require('tape')
var semitonesBetween = require('../../lib/pitch/semitones-between.js')
test('toMidi returns the correct number', function (t) {
t.equal(semitonesBetween('C4', 'C4'), 0)
t.equal(semitonesBetween('C4', 'B#3'), 0)
t.equal(semitonesBetween('Cb4', 'B3'), 0)
t.equal(semitonesBetween('C4', 'E4'), 4)
t.equal(semitonesBetween('C4', 'C5'), 12)
t.equal(semitonesBetween('C4', 'C#5'), 13)
t.equal(semitonesBetween('C4', 'Cb5'), 11)
t.equal(semitonesBetween('B#3', 'C5'), 12)
t.equal(semitonesBetween('C4', 'Eb5'), 15)
t.end()
})
<file_sep>var test = require('tape')
var parseInterval = require('../../lib/pitch/parse-interval.js')
test('interval parsing works for notes without accidentals', function (t) {
t.deepEqual(parseInterval('M6'),
{
interval : 'M6',
direction : 1,
quality : 'M',
size : 6,
perfectable : false,
simpleSize : 6,
octaves : 0,
halfsteps : 9
})
t.deepEqual(parseInterval('-P5'),
{
interval : '-P5',
direction : -1,
quality : 'P',
size : 5,
perfectable : true,
simpleSize : 5,
octaves : 0,
halfsteps : 7
})
t.deepEqual(parseInterval(10),
{
interval : '10',
direction : 1,
quality : null,
size : 10,
perfectable : false,
simpleSize : 3,
octaves : 1
})
t.deepEqual(parseInterval(-18),
{
interval : '-18',
direction : -1,
quality : null,
size : 18,
perfectable : true,
simpleSize : 4,
octaves : 2
})
t.deepEqual(parseInterval('A1'),
{
interval : 'A1',
direction : 1,
quality : 'A',
size : 1,
perfectable : true,
simpleSize : 1,
octaves : 0,
halfsteps : 1
})
t.deepEqual(parseInterval('-d9'),
{
interval : '-d9',
direction : -1,
quality : 'd',
size : 9,
perfectable : false,
simpleSize : 2,
octaves : 1,
halfsteps : 12
})
t.deepEqual(parseInterval('d15'),
{
interval : 'd15',
direction : 1,
quality : 'd',
size : 15,
simpleSize : 1,
perfectable : true,
octaves : 2,
halfsteps : 23
})
t.deepEqual(parseInterval('AA1'),
{
interval : 'AA1',
direction : 1,
quality : 'AA',
size : 1,
simpleSize : 1,
perfectable : true,
octaves : 0,
halfsteps : 2
})
t.deepEqual(parseInterval('dd5'),
{
interval : 'dd5',
direction : 1,
quality : 'dd',
size : 5,
simpleSize : 5,
perfectable : true,
octaves : 0,
halfsteps : 5
})
t.end()
})
test('interval parsing returns false for non-interval strings', function (t) {
[0, '', 'M0', '-P0', 'g5', 'M5', '-P10', 'test', 53535, 'm12', 'bA4'].forEach(function (nonPitch) {
t.equal(parseInterval(nonPitch) , false , 'returns false')
})
t.end()
})
test('throws an error when given non-string arguments', function (t) {
t.throws(parseInterval({}))
t.throws(parseInterval(5))
t.throws(parseInterval(['Db4']))
t.throws(parseInterval(undefined))
t.end()
})
<file_sep>var LETTERS_PER_OCTAVE = 7
/**
* simplify compound intervals to within the range of 1-7. Works for
* negative intervals as well.
*
* @param {Number} intervalSize - any valid interval number
* @returns {Number} the simplified interval
*
* @throws Will throw an error if intervalSize is 0
*
* @example
* simplifyIntervalSize(10) => 3
* simplifyIntervalSize(-12) => -5
* simplifyIntervalSize(-4) => -4
* simplifyIntervalSize(8) => 1
*/
var simplifyIntervalSize = function (intervalSize) {
if (intervalSize === 0) {
throw new Error('0 is not a valid interval size')
}
var base1adjust = 1
if (intervalSize < 0) {
base1adjust *= -1
}
return (intervalSize - base1adjust) % LETTERS_PER_OCTAVE + base1adjust
}
module.exports = simplifyIntervalSize
<file_sep>var simplifyIntervalSize = require('./simplify-interval-size.js')
var PERFECTABLE_INTERVALS = [1, 4, 5]
var PERFECT_QUALITIES = 'dAP'
var IMPERFECT_QUALITIES = 'MmAd'
var LETTERS_PER_OCTAVE = 7
var NOTES_PER_OCTAVE = 12
// Map of half steps in interval, given first size, then interval quality
// HALFSTEPS_FROM_INTERVAL_QUALITY[simpleIntervalSize][intervalQuality] = number of halfsteps
var HALFSTEPS_FROM_INTERVAL_QUALITY = {
'1' : {P: 0, A: 1, d: -1}, // d1 does not exist conceptually, but d8 will simplify to it for this
'2' : {d: 0, m: 1, M: 2, A: 3},
'3' : {d: 2, m: 3, M: 4, A: 5},
'4' : {d: 4, P: 5, A: 6},
'5' : {d: 6, P: 7, A: 8},
'6' : {d: 7, m: 8, M: 9, A: 10},
'7' : {d: 9, m: 10, M: 11, A: 12}
}
/**
* parses an interval string or number and return its properties in an object or
* return false if the string or number is not valid
*
* @param {String|Number} interval - an interval string with interval quality or a number
* representing only interval size. Both types of input may be signed ('-P5' or -5)
* to indicate a descending interval.
*
* @returns {Object|false} False if invalid interval else an object
* with the following properties:
* - interval: string
* - direction: number -1 or 1
* - quality: string of 'm', 'M', 'P', 'd', or 'A' OR null if not given
* - size: number, size of the interval, never negative
* - simpleSize: number in range [1,7]
* - perfectable: boolean (if false, this is an imperfect interval)
* - octaves: number of octave changes. Will be >= 0.
* - halfsteps: number|undefined if given quality, number of halfsteps this interval translates to
*
* @example
* parseInterval('-M6') => {interval: '-M6', direction: -1, quality: 'M', size: 6, simpleSize: 6,
* perfectable: false, octaves: 0, halfsteps: 9}
* parseInterval(12) => {interval: '12', direction: 1, quality: null, size: 12, simpleSize: 5,
* perfectable: true, octaves 1}
* parseInterval('M5') => false
*/
var parseInterval = function (interval) {
var els = /^(-)?([mMP]|A+|d+)?(\d{1,2})$/.exec(String(interval))
// els[0]= interval, els[1]= sign, els[2]= quality, els[3]= size
if (!els || els[3] === '0') return false
var i = {}
i.interval = els[0]
i.direction = (els[1] === undefined) ? 1 : -1
i.quality = (els[2] === undefined) ? null : els[2]
i.size = Number(els[3])
i.simpleSize = simplifyIntervalSize(i.size)
i.perfectable = PERFECTABLE_INTERVALS.indexOf(i.simpleSize) > -1
i.simpleSize = simplifyIntervalSize(i.size)
i.octaves = Math.floor((i.size - 1) / LETTERS_PER_OCTAVE)
if (i.quality !== null) {
if ((i.perfectable && PERFECT_QUALITIES.indexOf(i.quality[0]) === -1) ||
(!i.perfectable && IMPERFECT_QUALITIES.indexOf(i.quality[0]) === -1)) {
return false
}
i.halfsteps = HALFSTEPS_FROM_INTERVAL_QUALITY[i.simpleSize][i.quality[0]] +
i.octaves * NOTES_PER_OCTAVE
if (i.quality.length > 1) {
i.halfsteps += (i.quality[0] === 'A') ? i.quality.length - 1 : -(i.quality.length - 1)
}
}
return i
}
module.exports = parseInterval
<file_sep>var test = require('tape')
var Key = require('../../lib/key/key.js')
var Pitch = require('../../lib/pitch/pitch.js')
test('Key constructor', function (t) {
var pitch_Bb4 = new Pitch('Bb4')
t.true(Key('Bb', 'major') instanceof Key)
t.true(Key(pitch_Bb4, 'minor') instanceof Key)
t.equal(Key('Bb4', 'Major').toString(), 'Bb major')
t.equal(String(new Key('Bb4', 'DORIAN')), 'Bb dorian')
t.equal(String(Key('a', ['P1', 'M2', 'M3', 'A4', 'A5', 'A6'])), 'A custom-scale')
var a_major = new Key('A3', 'major')
t.equal(a_major.tonic.pitchClass(), 'A')
t.equal(a_major.modeName, 'major')
t.deepEqual(a_major.mode, ['P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'M7'])
t.deepEqual(a_major.scale, ['A', 'B', 'C#', 'D', 'E', 'F#', 'G#'])
a_major.mode = 'test'
t.equal(a_major.modeName, 'major')
t.throws(function () {
a_major.mode.push('A8')
}, Error)
a_major.scale[0] = 'Eb'
t.deepEqual(a_major.scale, ['A', 'B', 'C#', 'D', 'E', 'F#', 'G#'])
t.end()
})
test('Key.pitchAtDegree()', function (t) {
var a_major = new Key('A3', 'major')
t.deepEqual(a_major.pitchAtDegree(1), Pitch('A'))
t.deepEqual(a_major.pitchAtDegree(3), Pitch('C#'))
t.deepEqual(a_major.pitchAtDegree(9), Pitch('B'))
t.deepEqual(a_major.pitchAtDegree(10), Pitch('C#'))
var eb_dorian = new Key('Eb5', 'dorian')
t.deepEqual(eb_dorian.pitchAtDegree(1), Pitch('Eb'))
t.deepEqual(eb_dorian.pitchAtDegree(3), Pitch('Gb'))
t.deepEqual(eb_dorian.pitchAtDegree(6), Pitch('C'))
t.deepEqual(eb_dorian.pitchAtDegree(9), Pitch('F'))
t.end()
})
test('Key.inKey()', function (t) {
var f_sharp_minor = new Key('F#2', 'minor')
t.true(f_sharp_minor.inKey('F#1'))
t.true(f_sharp_minor.inKey('F#10'))
t.true(f_sharp_minor.inKey(Pitch('G#3')))
t.true(f_sharp_minor.inKey('C#5'))
t.true(f_sharp_minor.inKey('D'))
t.true(f_sharp_minor.inKey('E'))
t.false(f_sharp_minor.inKey('Eb4'))
t.false(f_sharp_minor.inKey('C2'))
t.false(f_sharp_minor.inKey('F'))
t.false(f_sharp_minor.inKey(Pitch('G')))
t.end()
})
test('Key.scaleDegree()', function (t) {
var eb_major = new Key('Eb', 'major')
t.equal(eb_major.scaleDegree('B'), -1)
t.equal(eb_major.scaleDegree('Eb2'), 1)
t.equal(eb_major.scaleDegree('Eb9'), 1)
t.equal(eb_major.scaleDegree('F3'), 2)
t.equal(eb_major.scaleDegree('Ab'), 4)
t.equal(eb_major.scaleDegree('B#3'), -1)
t.equal(eb_major.scaleDegree('C5'), 6)
t.end()
})
test('Key.accidentalOn()', function (t) {
var eb_major = new Key('Eb', 'major')
t.equal(eb_major.accidentalOn('B'), 'b')
t.equal(eb_major.accidentalOn('E#2'), 'b')
t.equal(eb_major.accidentalOn('F3'), '')
t.equal(eb_major.accidentalOn('A'), 'b')
var c_sharp_major = new Key('C#', 'major')
t.equal(c_sharp_major.accidentalOn('C'), '#')
t.equal(c_sharp_major.accidentalOn('B'), '#')
t.equal(c_sharp_major.accidentalOn('Db2'), '#')
var f_dorian = new Key('F6', 'dorian')
t.equal(f_dorian.accidentalOn(Pitch('F2')), '')
t.equal(f_dorian.accidentalOn(Pitch('F8')), '')
t.equal(f_dorian.accidentalOn(Pitch('A1')), 'b')
t.equal(f_dorian.accidentalOn(Pitch('B9')), 'b')
t.equal(f_dorian.accidentalOn(Pitch('D')), '')
t.equal(f_dorian.accidentalOn(Pitch('E')), 'b')
t.end()
})
test('Key.plusInterval()', function (t) {
var a_flat_major = new Key('Ab', 'major')
t.deepEqual(a_flat_major.plusInterval('C4', 2), Pitch('Db4'))
t.deepEqual(a_flat_major.plusInterval('C4', -2), Pitch('Bb3'))
t.deepEqual(a_flat_major.plusInterval('Eb2', 4), Pitch('Ab2'))
t.deepEqual(a_flat_major.plusInterval('Eb2', -4), Pitch('Bb1'))
t.deepEqual(a_flat_major.plusInterval('Ab4', 6), Pitch('F5'))
t.deepEqual(a_flat_major.plusInterval('F##2', 1), Pitch('F2'))
t.deepEqual(a_flat_major.plusInterval('Fbb2', 2), Pitch('G2'))
t.end()
})
test('Key.range()', function (t) {
var d_minor = new Key('D', 'minor')
var Db_major = new Key('Db', 'major')
t.deepEqual(d_minor.range('A3', 'E4'),
'A3 Bb3 C4 D4 E4'.split(' ').map(Pitch))
t.deepEqual(Db_major.range('Eb3', 'F5'),
'Eb3 F3 Gb3 Ab3 Bb3 C4 Db4 Eb4 F4 Gb4 Ab4 Bb4 C5 Db5 Eb5 F5'.split(' ').map(Pitch))
t.end()
})
<file_sep>var Pitch = require('./pitch/pitch.js')
var parsePitch = require('./pitch/parse-pitch.js')
var nmusic = function (input) {
if (input instanceof Pitch) return input
if (parsePitch(input)) return new Pitch(input)
return null
}
nmusic.Pitch = Pitch
nmusic.intervalQuality = require('./pitch/interval-quality.js')
nmusic.intervalSize = require('./pitch/interval-size.js')
nmusic.interval = require('./pitch/interval.js')
nmusic.parseInterval = require('./pitch/parse-interval.js')
nmusic.parsePitch = require('./pitch/parse-pitch.js')
nmusic.plusInterval = require('./pitch/plus-interval.js')
nmusic.semitonesBetween = require('./pitch/semitones-between.js')
nmusic.simplifyIntervalSize = require('./pitch/simplify-interval-size.js')
nmusic.toMidi = require('./pitch/to-midi.js')
nmusic.isHigher = require('./pitch/is-higher.js')
nmusic.sortPitches = require('./pitch/sort-pitches.js')
nmusic.Key = require('./key/key.js')
nmusic.modeIntervals = require('./key/mode-intervals.js')
nmusic.scaleSet = require('./key/scale-set.js')
nmusic.scale = require('./key/scale.js')
exports = module.exports = nmusic
<file_sep>var intervalSize = require('./interval-size.js')
var semitonesBetween = require('./semitones-between.js')
// Map of interval quality, given first size, then number of half steps
// INTERVAL_QUALITY[intervalSize][semitonesTo] = quality
// P = perfect, m = minor, M = major, d = diminished, A = augmented
var INTERVAL_QUALITY = {
'1' : {'0': 'P', '1': 'A', '2': 'AA', '11': 'd'}, // 11 is for diminished octaves b/c interval uses mod 12
'2' : {'11': 'dd', '0': 'd', '1': 'm', '2': 'M', '3': 'A', '4': 'AA'},
'3' : {'2': 'd', '3': 'm', '4': 'M', '5': 'A', '6': 'AA'},
'4' : {'4': 'd', '5': 'P', '6': 'A', 7: 'AA'},
'5' : {'6': 'd', '7': 'P', '8': 'A', '9': 'AA'},
'6' : {'7': 'd', '8': 'm', '9': 'M', '10': 'A', '11': 'AA'},
'7' : {'9': 'd', '10': 'm', '11': 'M', '0': 'A', '1': 'AA'}, // A7 is 0 instead of 12 b/c interval uses mod 12
'8' : {'11': 'd', '12': 'P', '13': 'A'}
}
/**
* the interval quality between two pitch strings
*
* @param {PitchString} sciPitch1 - a pitch in scientific pitch notation.
* @param {PitchString} sciPitch2 - a pitch in scientific pitch notation.
* @returns {String} a character representing the interval between the two pitches:
* - 'P' = perfect
* - 'm' = minor
* - 'M' = major
* - 'd' = diminished
* - 'A' = augmented
*
* @throws an error if either string is not a valid pitch
*
* @example
* intervalQuality('C4', 'E4') => 'M'
* intervalQuality('E4', 'Eb4') => 'm'
* intervalQuality('C4', 'F4') => 'P'
* intervalQuality('C4', 'F#4') => 'A'
* intervalQuality('B3', 'Ab4') => 'd'
*/
var intervalQuality = function (sciPitch1, sciPitch2) {
var sizeBetween = intervalSize.simple(sciPitch1, sciPitch2)
var halfSteps = semitonesBetween(sciPitch1, sciPitch2) % 12
return INTERVAL_QUALITY[sizeBetween][halfSteps]
}
module.exports = intervalQuality
<file_sep>var test = require('tape')
var scale = require('../../lib/key/scale.js')
test('scale()', function (t) {
t.deepEqual(scale('Eb4', 'major'),
['Eb4', 'F4', 'G4', 'Ab4', 'Bb4', 'C5', 'D5'])
t.deepEqual(scale('Eb', 'major'),
['Eb4', 'F4', 'G4', 'Ab4', 'Bb4', 'C5', 'D5'])
t.deepEqual(scale('Eb4', 'minor'),
['Eb4', 'F4', 'Gb4', 'Ab4', 'Bb4', 'Cb5', 'Db5'])
t.deepEqual(scale('Eb4', 'lydian'),
['Eb4', 'F4', 'G4', 'A4', 'Bb4', 'C5', 'D5'])
t.deepEqual(scale('B2', 'minor'),
['B2', 'C#3', 'D3', 'E3', 'F#3', 'G3', 'A3'])
t.deepEqual(scale('C4', ['P1', 'M2', 'M3', 'A4', 'A5', 'A6']),
['C4', 'D4', 'E4', 'F#4', 'G#4', 'A#4'])
t.end()
})
<file_sep>var test = require('tape')
var intervalQuality = require('../../lib/pitch/interval-quality.js')
test('intervalQuality()', function (t) {
t.equal(intervalQuality('C4', 'C4'), 'P')
t.equal(intervalQuality('C4', 'Db4'), 'm')
t.equal(intervalQuality('C4', 'D4'), 'M')
t.equal(intervalQuality('C4', 'Eb4'), 'm')
t.equal(intervalQuality('C4', 'E4'), 'M')
t.equal(intervalQuality('C4', 'F4'), 'P')
t.equal(intervalQuality('C4', 'F#4'), 'A')
t.equal(intervalQuality('C4', 'Gb4'), 'd')
t.equal(intervalQuality('C4', 'G4'), 'P')
t.equal(intervalQuality('C4', 'G#4'), 'A')
t.equal(intervalQuality('C4', 'Ab4'), 'm')
t.equal(intervalQuality('C4', 'A4'), 'M')
t.equal(intervalQuality('C4', 'A#4'), 'A')
t.equal(intervalQuality('C4', 'Bb4'), 'm')
t.equal(intervalQuality('C4', 'B4'), 'M')
t.equal(intervalQuality('C4', 'B#4'), 'A')
t.equal(intervalQuality('C4', 'C5'), 'P')
t.equal(intervalQuality('C4', 'Cb5'), 'd')
t.equal(intervalQuality('C4', 'C#5'), 'A')
t.equal(intervalQuality('B#3', 'C4'), 'd')
t.equal(intervalQuality('Bb3', 'Bbb3'), 'A')
t.equal(intervalQuality('B3', 'Ab4'), 'd')
t.end()
})
<file_sep>var parsePitch = require('./parse-pitch.js')
var simplifyIntervalSize = require('./simplify-interval-size.js')
// order of note letter names in an octave cycle
var LETTERS = 'CDEFGAB'
/**
* the generic interval size between two pitch strings, disregarding accidentals
*
* @param {PitchString} sciPitch1 - a pitch in scientific pitch notation.
* @param {PitchString} sciPitch2 - a pitch in scientific pitch notation.
* @returns {Number} the absolute interval size between the two pitches. Always positive, even if
* the first argument is higher than the second.
*
* @throws an error if string is not a valid pitch
*
* @see [intervalSize.simple]{@link intervalSize.simple} for returning the simple interval size
*
* @example
* intervalSize('C4', 'E4') => 3
* intervalSize('E4', 'C4') => 3
* intervalSize('C4', 'E5') => 10
* intervalSize('C4', 'Eb5') => 10
* intervalSize('C5', 'C5') => 1
*/
var intervalSize = function (sciPitch1, sciPitch2) {
var p = parsePitch(sciPitch1)
var q = parsePitch(sciPitch2)
if (!p || !q) throw Error('At least one invalid pitch name:', sciPitch1, sciPitch2)
return Math.abs(LETTERS.indexOf(p.letter) - LETTERS.indexOf(q.letter) +
LETTERS.length * (p.octave - q.octave)) + 1 // add 1 for music's 1-based numbering
}
/**
* the generic simple interval size (1-7) between two pitch strings, disregarding accidentals
*
* @param {PitchString} sciPitch1 - a pitch in scientific pitch notation.
* @param {PitchString} sciPitch2 - a pitch in scientific pitch notation.
* @returns {Number} the simple interval size between the two pitches in range [1, 7].
* Contrary to standard practice, an octave is considered compound and reduces to 1.
*
* @throws an error if string is not a valid pitch
*
* @example
* intervalSize.simple('C4', 'E4') => 3
* intervalSize.simple('C4', 'E5') => 3
* intervalSize.simple('C1', 'E9') => 3
*/
intervalSize.simple = function (sciPitch1, sciPitch2) {
return simplifyIntervalSize(intervalSize(sciPitch1, sciPitch2))
}
module.exports = intervalSize
<file_sep>var MODES = {
major : ['P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'M7'],
minor : ['P1', 'M2', 'm3', 'P4', 'P5', 'm6', 'm7'],
ionian : ['P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'M7'],
dorian : ['P1', 'M2', 'm3', 'P4', 'P5', 'M6', 'm7'],
phrygian : ['P1', 'm2', 'm3', 'P4', 'P5', 'm6', 'm7'],
lydian : ['P1', 'M2', 'M3', 'A4', 'P5', 'M6', 'M7'],
mixolydian : ['P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'm7'],
aeolian : ['P1', 'M2', 'm3', 'P4', 'P5', 'm6', 'm7'],
locrian : ['P1', 'm2', 'm3', 'P4', 'd5', 'm6', 'm7']
}
// these will be passed around, make them immutable
for (var mode in MODES) {
Object.freeze(MODES[mode])
}
/**
* returns the intervals that define the scale degrees of a given mode
*
* @param {'major'|'minor'|'ionian'|'dorian'|'phrygian'|
'lydian'|'mixolydian'|'aeolian'|'locrian'} modeName - a mode name
* @returns {string[]} an array of interval strings representing the
* interval each scale degree is from tonic, always starting with 'P1' for tonic
*
* @example
* modeIntervals('major') => ['P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'M7']
* modeIntervals('dorian') => ['P1', 'M2', 'm3', 'P4', 'P5', 'M6', 'm7']
*/
var modeIntervals = function (modeName) {
modeName = modeName.toLowerCase()
if (!(modeName in MODES)) throw new Error('Unrecognized mode name:', modeName)
return MODES[modeName]
}
module.exports = modeIntervals
<file_sep>var parsePitch = require('./parse-pitch.js')
// number of halfsteps each letter is from C
var HALFSTEPS_FROM_C = {C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11}
// number of notes per octave cycle
var MUSIC_RADIX = 12
/**
* the [midi number]{@link http://newt.phys.unsw.edu.au/jw/notes.html} of this pitch string
*
* @param {PitchString} sciPitch - a pitch in scientific pitch notation.
* @returns {Number} the midi number for this pitch. C4 is 60.
* [Enharmonic]{@link https://en.wikipedia.org/wiki/Enharmonic} notes will return the same
* midi number.
*
* @throws Will throw an error if string is not a valid pitch
*
* @example
* toMidi('C4') => 60
* toMidi('B#3') => 60
* toMidi('Bb3') => 58
* toMidi('A#3') => 58
*/
var toMidi = function (sciPitch) {
var p = parsePitch(sciPitch)
if (!p) throw Error('Invalid pitch name: ' + sciPitch)
return HALFSTEPS_FROM_C[p.letter] + // start with number of half steps from C
(MUSIC_RADIX * (p.octave + 1)) + // add one to octave num so C4 = 60
p.numAccidental // add or subtract accidental
}
module.exports = toMidi
<file_sep>var test = require('tape')
var isHigher = require('../../lib/pitch/is-higher.js')
test('isHigher()', function (t) {
t.equal(isHigher('C4', 'C4'), false)
t.equal(isHigher('C4', 'D4'), false)
t.equal(isHigher('D4', 'C4'), true)
t.equal(isHigher('C4', 'B#3'), false)
t.equal(isHigher('B#3', 'C4'), false)
t.equal(isHigher('B##3', 'C4'), true)
t.equal(isHigher('Cb4', 'B3'), false)
t.equal(isHigher('Cb4', 'B#3'), false)
t.equal(isHigher('C4', 'C5'), false)
t.equal(isHigher('C5', 'C4'), true)
t.equal(isHigher('C4', 'C#5'), false)
t.equal(isHigher('C4', 'Cb4'), true)
t.equal(isHigher('C4', 'Eb5'), false)
t.end()
})
<file_sep>var scale = require('./scale.js')
var parsePitch = require('../pitch/parse-pitch.js')
/**
* given a pitch string and scale mode, build a pitch class scale from that pitch
*
* @param {PitchString} tonic - the [tonic](@link https://en.wikipedia.org/wiki/Tonic_(music))
* of this scale. If octave number is provided, it will be ignored.
* @param {string|string[]} mode - a string representing a mode name (minor, major, dorian) or
* an array of interval strings representing the interval each scale degree is from tonic
*
* @returns {PitchString[]} an array of pitch class strings (without octave number)
* @see for a similar function which uses octave numbers, see {@link scale}
* @example
* scale('Eb4', 'major')
* => ['Eb', 'F', 'G', 'Ab', 'Bb', 'C', 'D']
*/
var scaleSet = function (tonic, mode) {
return scale(tonic, mode).map(function (pitch) {
var parsed = parsePitch(pitch)
return parsed.letter + parsed.accidental
})
}
module.exports = scaleSet
<file_sep>nmusic is a JavaScript music library for programmatic music composition which offers an intuitive mix of functional and object-oriented programming styles. It is thoroughly tested and well [documented](api.md) but **currently in development**.
## Usage
Navigate to your project directory and install nmusic:
```
npm install nmusic
```
In your project file, import nmusic.
```js
var nmusic = require('nmusic')
// if you'd like, create global variables for the functions you will be using
var plusInterval = nmusic.plusInterval
plusInterval('G3', 'P5') => 'D4'
// or, call all functions directly from nmusic
nmusic.interval('Bb3', 'Ab4') => 'm7'
```
To work in a functional style, use the many functional methods. These methods all return strings and numbers which represent pitches and intervals. (The example assumes you have assigned all methods to global variables).
```js
interval('B3', 'F#5') => 'P12'
interval.simple('B3', 'F#5') => 'P5'
semitonesBetween('B3', 'D#4') => 4
plusInterval('B3', -6) => 'D3'
plusInterval('B3', '-m6') => 'D#3'
```
To work in an object-oriented style, create Pitch objects. The Pitch methods will return other Pitch objects, but behind the scenes they are just using the same functional methods introduced above.
```js
var p1 = new Pitch('Bb3')
var p2 = p1.plusInterval('P5')
p2.toString() => 'F4'
p2 instanceof Pitch => true
p1.interval(p2) => 'P5'
```
## Goals
nmusic is made of a set of sensical music classes like Note, Pitch, Duration, Measure. Most of the functionality of the library will be loaded into the factory method `nmusic` which will parse a variety of arguments and return objects of the appropriate class.
```js
nmusic('Bb3') => Bb3
nmusic('Bb3') instanceof Note => true
nmusic('Bb3').plus('P4') => Eb4
nmusic('Bb3').interval('Eb4') => P4
nmusic('Bb3').scale('major') => [Bb3, C4, D4, Eb4, F4, G4, A4]
```
## Docs
[View the api documentation here.](api.md)
## Development
To run eslint and tape tests:
```
npm test
```
To generate api documentation:
```
npm run docs
```
## Background & Credits
My first programming project was a simple object oriented music library which I made from scratch to solve [counterpoint problems](https://github.com/jrleszcz/Computational-Counterpoint). As I've learned more, I've come back to that library and refactored it several times, and now I aim to completely rebuild it.
There are already some very good JavaScript music libraries out there which have influenced this project:
[tonal](https://github.com/danigb/tonal) is an elegant library written in a functional style.
[teoria](https://github.com/saebekassebil/teoria) is an object oriented library.
This library aims to be an intuitive mix between a functional and object-oriented style.<file_sep>var plusInterval = require('../pitch/plus-interval.js')
var modeIntervals = require('./mode-intervals.js')
/**
* given a pitch string and scale mode, build a scale from that pitch
*
* @param {PitchString} tonic - the [tonic](@link https://en.wikipedia.org/wiki/Tonic_(music))
* of this scale
* @param {string|string[]} mode - a string representing a mode name (minor, major, dorian) or
* an array of interval strings representing the interval each scale degree is from tonic
*
* @returns {PitchString[]} an array of pitch strings
*
* @example
* scale('Eb4', 'major')
* => ['Eb4', 'F4', 'G4', 'Ab4', 'Bb4', 'C5', 'D5']
*/
var scale = function (tonic, mode) {
mode = (typeof mode === 'string') ? modeIntervals(mode)
: mode
return mode.map(plusInterval(tonic))
}
module.exports = scale
<file_sep>var Pitch = require('../pitch/pitch.js')
var modeIntervals = require('./mode-intervals.js')
var scaleSet = require('./scale-set.js')
var parsePitch = require('../pitch/parse-pitch.js')
var intervalSize = require('../pitch/interval-size.js')
/**
* Creates a new key. Note that most Key methods use pitch classes without reguards
* to octave number.
* @constructor
*
* @param {Pitch|PitchString} tonic - the [tonic](@link https://en.wikipedia.org/wiki/Tonic_(music))
* of this scale. Octave number may be provided, but do not affect the Key methods.
* @param {string|string[]} mode - a string representing a mode name (minor, major, dorian) or
* an array of interval strings representing the interval each scale degree is from tonic
*
* @prop {Pitch} tonic - the tonic of this scale. Although all Pitch instances have an
* octave number, it is not used in the Key methods.
* @prop {string} modeName - a string representing the mode name. If custom mode is provided,
* defaults to 'custom-scale'
* @prop {string[]} mode - an array of interval strings representing the interval each
* scale degree is from tonic
* @prop {PitchString[]} scale - an array of pitch class strings
*/
var Key = function (tonic, mode) {
if (!(this instanceof Key)) return new Key(tonic, mode)
this.tonic = Pitch(tonic)
this.modeName = (typeof mode === 'string') ? mode.toLowerCase()
: 'custom-scale'
this.mode = (typeof mode === 'string') ? modeIntervals(mode)
: mode
this.scale = scaleSet(this.tonic.pitchClass(), this.mode)
Object.freeze(this.scale)
Object.freeze(this)
}
Key.prototype = {
constructor: Key,
/**
* @returns {String} the tonic + the modeName ('Bb major')
*/
toString: function () {
return this.tonic.pitchClass() + ' ' + this.modeName
},
/**
* is this pitch a member of this key?
* @param {Pitch|PitchString} pitch - a pitch string or Pitch
* @returns {boolean} is this pitch in the key?
* @example
* var a_major = new Key('A3', 'major')
* a_major.inKey('C3') => false
* a_major.inKey('C#3') => true
*/
inKey: function (pitch) {
return this.scale.indexOf(Pitch(pitch).pitchClass()) > -1
},
/**
* given a letter and key, returns the accidental that should be on this letter
* in this key. This method only works for standard keys like major or dorian which map evenly
* to the seven music letters.
* @param {Pitch|PitchString} pitch - a pitch string or Pitch
* @returns {string} the accidental that needs to be added to this letter for it
* to be in the key
*/
accidentalOn: function (pitch) {
// make sure target pitch is higher than tonic; get simple interval size for index
var interval = intervalSize.simple(this.tonic.name,
Pitch(pitch).letter() + (this.tonic.octave() + 1))
return parsePitch(this.scale[interval - 1]).accidental
},
/**
* returns the Pitch at the requested scale degree. Although Pitches default to octave
* number 4, this should be thought of as a pitch class
* @param {number} degree - the desired scale degree of this scale (an integer > 0)
* @returns {Pitch} a pitch class string
* @example
* var a_major = new Key('A3', 'major')
* a_major.scaleDegree(3) => 'C#4'<Pitch>
* a_major.scaleDegree(10) => 'C#4'<Pitch>
*/
pitchAtDegree: function (degree) {
// get the note within an octave of the tonic
return Pitch(this.scale[(degree - 1) % this.scale.length])
},
/**
* returns the scale degree of this pitch or -1 if it is not in the key
* @param {Pitch|PitchString} pitch - a pitch string or Pitch
* @returns {number} the scale degree of this pitch or -1 if not in key
* @example
* var a_major = new Key('A3', 'major')
* a_major.scaleDegree('C3') => -1
* a_major.scaleDegree('C#3') => 3
*/
scaleDegree: function (pitch) {
if (!this.inKey(pitch)) {
return -1
} else {
return this.scale.indexOf(Pitch(pitch).pitchClass()) + 1
}
},
/**
* gets the correct pitch in the key which is the given interval size away
* @param {Pitch|PitchString} pitch - the starting Pitch or pitch string
* @param {number} intervalSize - an interval as a positive or negative number.
* @returns {Pitch} the resulting Pitch
* @example
* var a_flat_major = new Key('Ab', 'major')
* a_flat_major.plusInterval('C4', 2) => Pitch: Db4
* a_flat_major.plusInterval('C4', -2) => Pitch: Bb3
* a_flat_major.plusInterval('Eb2', 4) => Pitch: Ab2
* a_flat_major.plusInterval('G5', -10) => Pitch: Eb4
*/
plusInterval: function (pitch, intervalSize) {
var result = Pitch(pitch).plusInterval(intervalSize)
return new Pitch(result.letter() +
this.accidentalOn(result) +
result.octave())
},
/**
* Get all the notes in this key between lo and hi (both inclusive)
*
* @param {Pitch|PitchString} lo - the starting Pitch or pitch string
* @param {Pitch|PitchString} hi - the ending Pitch or pitch string
*
* @returns {Pitch[]} an array of Pitches with all the notes of this key
* between lo and hi (both inclusive)
*
* @throws an Error if lo and hi are not both {@link Key#inKey}
*/
range: function (lo, hi) {
if (!this.inKey(lo) || !this.inKey(hi)) {
throw new Error('One or both of lo and hi are not in key:', lo, hi)
}
// check if hi is actually higher than lo
var r = [Pitch(lo)]
while (!r[r.length - 1].equals(hi)) { // while we haven't reached the hi note
r.push(this.plusInterval(r[r.length - 1], 2))
}
return r
}
}
module.exports = Key
<file_sep>/**
* parses a pitch string and return its components in an object or
* false if the string is not valid
*
* @param {PitchString} sciPitch - a pitch in scientific pitch notation
* @returns {object|false} False if invalid pitch string or an object
* with the following properties:
* - letter: string
* - accidental: {@link AccidentalString}
* - numAccidental: number of accidentals [-2, 2], positive for sharps, negative for flats
* - octave: integer (if not provided, defaults to 4)
* - sciPitch: {@link PitchString}
*
* @example
* parsePitch('Bb3') => {letter: 'B', accidental: 'b', numAccidental: -1, octave: 3, sciPitch:'Bb3'}
* parsePitch('Xb4') => false
*/
var parsePitch = function (sciPitch) {
var els = /^([a-gA-G])(b{1,2}|#{1,2})?(\d{1,2})?$/.exec(sciPitch)
// els[0]= scientific pitch, els[1]= letter, els[2]= accidentals, els[3]= octaveNumber
if (!els) return false
var p = {}
p.letter = els[1].toUpperCase()
p.accidental = (els[2] === undefined) ? '' : els[2]
p.numAccidental = (p.accidental.length > 0 && p.accidental[0] === 'b') ? -1 * p.accidental.length
: p.accidental.length
p.octave = (els[3] === undefined) ? 4 : Number(els[3])
p.sciPitch = p.letter + p.accidental + p.octave
return p
}
module.exports = parsePitch
<file_sep>/**
* helper function to clone a simple object/array made up of primitives.
* Will not work if the object or array contains non-primitives.
* @param {object|array} obj - an object array made up only of primitives
* @returns {object|array} a new clone of the provided object or array
*/
function clone (obj) {
return JSON.parse(JSON.stringify(obj))
}
module.exports = clone
<file_sep>var parsePitch = require('./parse-pitch.js')
var toMidi = require('./to-midi.js')
var semitonesBetween = require('./semitones-between.js')
var intervalSize = require('./interval-size.js')
var interval = require('./interval.js')
var plusInterval = require('./plus-interval.js')
var isHigher = require('./is-higher.js')
/**
* @typedef {'A'|'B'|'C'|'D'|'E'|'F'|'G'} MusicLetter - [A-G] representing a musical lettername
*/
/**
* @typedef {'#'|'b'|'##'|'bb'} AccidentalString - '#' for sharp, 'b' for flat.
* '##'' for double sharp, 'bb' for double flat.
*/
/**
* @typedef {string} PitchString - {@link MusicLetter} + [{@link AccidentalString}] +
* [octave number]. Must match the regular expression:
* /(A-G)(b{1,2}|#{1,2})?(\d{1,2})?/. Accidental and octave number are optional,
* but if octave number is not provided, it will default to octave 4.
* @example
* 'C4' // middle C on a piano, the fourth octave
* 'B3' // the B one note below C4 on the piano (octave numbers change on C)
* 'Eb3' // Eb in octave 3
* 'F#2' // F# in octave 2
* 'F##7' // F double sharp in octave 7
* 'Dbb5' // D double flat in octave 5
*/
/**
* @typedef {string} PitchClassString - {@link MusicLetter} + [{@link AccidentalString}].
* @link same as {@link PitchString} but without octave number.
* @example
* 'C'
* 'Eb'
* 'F#'
* 'F##'
* 'Dbb'
*/
/**
* Creates a new immutable Pitch or if given an existing Pitch, returns it.
* @constructor
* @prop {PitchString} Pitch.name - this pitch in scientific pitch notation
*
* @param {PitchString|Pitch} sciPitch - a pitch string in scientific pitch notation
* or a Pitch.
* @throws Will throw an error if string is not a valid pitch
*
* @example
* var p = new Pitch('Bb3')
* p.name => 'Bb3'
* // if you forget the 'new' keyword, the constructor will call it for you
* var p2 = Pitch('C4')
* p2 instanceof Pitch => true
* // if given a Pitch as its argument, the same Pitch will be returned
* var p3 = Pitch(p2)
* p2 === p3 => true
* // this can be used to write functions which accept pitch strings or Pitches as a parameter
*/
function Pitch (sciPitch) {
if (sciPitch instanceof Pitch) return sciPitch
if (!(this instanceof Pitch)) return new Pitch(sciPitch)
var p = parsePitch(sciPitch)
if (!p) throw Error('Invalid pitch name: ' + sciPitch)
this.name = p.sciPitch
Object.freeze(this)
}
Pitch.prototype = {
constructor: Pitch,
/**
* @returns {PitchString} string in scientfic pitch notation
*/
toString: function () {
return this.name
},
/**
* @returns {Number} the midi number of this pitch, so enharmonic notes will be equal
* @see [pitch.midi()]{@link Pitch#midi}
*/
valueOf: function () {
return this.midi()
},
/**
* @param {Pitch|PitchString} that - a Pitch or a pitch string
* @returns {Boolean} is this pitch spelled the same as that pitch?
*/
equals: function (that) {
return this.name === Pitch(that).name
},
/**
* @param {Pitch|PitchString} that - a Pitch or a pitch string
* @returns {Boolean} does this pitch sound identical to that pitch?
*/
isEnharmonic: function (that) {
return this.midi() === Pitch(that).midi()
},
/**
* @param {Pitch|PitchString} that - a Pitch or a pitch string
* @returns {Boolean} does this pitch sound higher than that pitch?
* @see {@link isHigher}
*/
isHigher: function (that) {
return isHigher(this.name, Pitch(that).name)
},
/**
* @returns {PitchString}
* in [scientfic pitch notation]{@link https://en.wikipedia.org/wiki/Scientific_pitch_notation}
* (same as pitch.name)
*/
sciPitch: function () {
return this.name
},
/**
* @returns {MusicLetter} will return 'A', 'B', 'C', 'D', 'E', 'F', or 'G'
*/
letter: function () {
return parsePitch(this.name).letter
},
/**
* @returns {AccidentalString} 'b', 'bb', '#', '##' (double sharp is not 'x'),
* or '', the empty string if there is no accidental.
*/
accidental: function () {
return parsePitch(this.name).accidental
},
/**
* @returns {Number} the octave number (C4 is
* [middle C]{@link https://en.wikipedia.org/wiki/C_(musical_note)#Middle_C})
*/
octave: function () {
return parsePitch(this.name).octave
},
/**
* @returns {PitchClassString} the [pitch class]{@link https://en.wikipedia.org/wiki/Pitch_class},
* same as [pitch.sciPitch()]{@link Pitch#sciPitch} but without octave number.
*/
pitchClass: function () {
var parsed = parsePitch(this.name)
return parsed.letter + parsed.accidental
},
/**
* returns the number of accidentals on this letter:
* positive for sharps, negative for flats.
* @returns {Number} how many half steps from its letter, will be in the range [-2, 2]
* @example
* var p = new Pitch('Abb3')
* p.halfSteps() => -2
*/
numAccidental: function () {
return parsePitch(this.name).numAccidental
},
/**
* What is the [midi number]{@link http://newt.phys.unsw.edu.au/jw/notes.html} of this pitch?
*
* @returns {Number} the midi number for this pitch. C4 is 60.
*
* @example
* toMidi('C4') => 60
* toMidi('B#3') => 60
* toMidi('Bb3') => 58
* toMidi('A#3') => 58
*/
midi: function () {
return toMidi(this.name)
},
/**
* @param {Pitch|PitchString} that - a Pitch or a pitch string
* @returns {Number} how many half steps are there between these pitches?
*/
semitonesTo: function (that) {
return semitonesBetween(this.name, Pitch(that).name)
},
/**
* @param {Pitch|PitchString} that - a Pitch or a pitch string
* @returns {Number} the interval size between these pitches
* @see {@link intervalSize}
*/
intervalSize: function (that) {
return intervalSize(this.name, Pitch(that).name)
},
/**
* @param {Pitch|PitchString} that - a Pitch or a pitch string
* @returns {Number} the simple interval size between these pitches in range [1,7]
* @see {@link intervalSize.simple}
*/
simpleIntervalSize: function (that) {
return intervalSize.simple(this.name, Pitch(that).name)
},
/**
* @param {Pitch|PitchString} that - a Pitch or a pitch string
* @returns {String} the interval between these pitches
* @see {@link interval}
*/
interval: function (that) {
return interval(this.name, Pitch(that).name)
},
/**
* @param {Pitch|PitchString} that - a Pitch or a pitch string
* @returns {String} the simple interval between these pitches
* @see {@link interval.simple}
*/
simpleInterval: function (that) {
return interval.simple(this.name, Pitch(that).name)
},
/**
* @param {String|Number} interval - an interval string or number with or without quality. If
* interval quality is not provided, accidentals on this Pitch will be ignored.
* @returns {Pitch} the resulting Pitch
* @see {@link plusInterval}
* @example
* var pitch_C4 = new Pitch('C4')
* plusInterval(pitch_C4, 10) => Pitch: E5
* plusInterval(pitch_C4, -10) => Pitch: A2
* plusInterval(pitch_C4, 'm10') => Pitch: Eb5
* plusInterval(pitch_C4, '-d7') => Pitch: D#3
*/
plusInterval: function (interval) {
return new Pitch(plusInterval(this.name, interval))
}
}
module.exports = Pitch
<file_sep>## Classes
<dl>
<dt><a href="#Key">Key</a></dt>
<dd></dd>
<dt><a href="#Pitch">Pitch</a></dt>
<dd></dd>
</dl>
## Functions
<dl>
<dt><a href="#modeIntervals">modeIntervals(modeName)</a> ⇒ <code>Array.<string></code></dt>
<dd><p>returns the intervals that define the scale degrees of a given mode</p>
</dd>
<dt><a href="#scaleSet">scaleSet(tonic, mode)</a> ⇒ <code><a href="#PitchString">Array.<PitchString></a></code></dt>
<dd><p>given a pitch string and scale mode, build a pitch class scale from that pitch</p>
</dd>
<dt><a href="#scale">scale(tonic, mode)</a> ⇒ <code><a href="#PitchString">Array.<PitchString></a></code></dt>
<dd><p>given a pitch string and scale mode, build a scale from that pitch</p>
</dd>
<dt><a href="#intervalQuality">intervalQuality(sciPitch1, sciPitch2)</a> ⇒ <code>String</code></dt>
<dd><p>the interval quality between two pitch strings</p>
</dd>
<dt><a href="#intervalSize">intervalSize(sciPitch1, sciPitch2)</a> ⇒ <code>Number</code></dt>
<dd><p>the generic interval size between two pitch strings, disregarding accidentals</p>
</dd>
<dt><a href="#interval">interval(sciPitch1, sciPitch2)</a> ⇒ <code>String</code></dt>
<dd><p>the interval between two pitch strings</p>
</dd>
<dt><a href="#isHigher">isHigher(sciPitch1, sciPitch2)</a> ⇒ <code>boolean</code></dt>
<dd><p>does this pitch sound higher than that pitch?</p>
</dd>
<dt><a href="#parseInterval">parseInterval(interval)</a> ⇒ <code>Object</code> | <code>false</code></dt>
<dd><p>parses an interval string or number and return its properties in an object or
return false if the string or number is not valid</p>
</dd>
<dt><a href="#parsePitch">parsePitch(sciPitch)</a> ⇒ <code>object</code> | <code>false</code></dt>
<dd><p>parses a pitch string and return its components in an object or
false if the string is not valid</p>
</dd>
<dt><a href="#plusInterval">plusInterval(sciPitch, interval)</a> ⇒ <code><a href="#PitchString">PitchString</a></code> | <code>function</code></dt>
<dd><p>given pitch string plus given interval string equals new pitch string</p>
<p>Optionally, give only one parameter and get back a function with that parameter
set as the default.</p>
</dd>
<dt><a href="#semitonesBetween">semitonesBetween(sciPitch1, sciPitch2)</a> ⇒ <code>Number</code></dt>
<dd><p>the number of semitones between these two pitch strings</p>
</dd>
<dt><a href="#simplifyIntervalSize">simplifyIntervalSize(intervalSize)</a> ⇒ <code>Number</code></dt>
<dd><p>simplify compound intervals to within the range of 1-7. Works for
negative intervals as well.</p>
</dd>
<dt><a href="#sortPitches">sortPitches(pitches)</a> ⇒ <code><a href="#PitchString">Array.<PitchString></a></code></dt>
<dd><p>helper function to sort an array of PitchStrings from lowest to highest</p>
</dd>
<dt><a href="#toMidi">toMidi(sciPitch)</a> ⇒ <code>Number</code></dt>
<dd><p>the <a href="http://newt.phys.unsw.edu.au/jw/notes.html">midi number</a> of this pitch string</p>
</dd>
<dt><a href="#clone">clone(obj)</a> ⇒ <code>object</code> | <code>array</code></dt>
<dd><p>helper function to clone a simple object/array made up of primitives.
Will not work if the object or array contains non-primitives.</p>
</dd>
</dl>
## Typedefs
<dl>
<dt><a href="#MusicLetter">MusicLetter</a> : <code>'A'</code> | <code>'B'</code> | <code>'C'</code> | <code>'D'</code> | <code>'E'</code> | <code>'F'</code> | <code>'G'</code></dt>
<dd><p>[A-G] representing a musical lettername</p>
</dd>
<dt><a href="#AccidentalString">AccidentalString</a> : <code>'#'</code> | <code>'b'</code> | <code>'##'</code> | <code>'bb'</code></dt>
<dd><p>'#' for sharp, 'b' for flat.
'##'' for double sharp, 'bb' for double flat.</p>
</dd>
<dt><a href="#PitchString">PitchString</a> : <code>string</code></dt>
<dd><p><a href="#MusicLetter">MusicLetter</a> + [<a href="#AccidentalString">AccidentalString</a>] +
[octave number]. Must match the regular expression:
/(A-G)(b{1,2}|#{1,2})?(\d{1,2})?/. Accidental and octave number are optional,
but if octave number is not provided, it will default to octave 4.</p>
</dd>
<dt><a href="#PitchClassString">PitchClassString</a> : <code>string</code></dt>
<dd><p><a href="#MusicLetter">MusicLetter</a> + [<a href="#AccidentalString">AccidentalString</a>].</p>
</dd>
</dl>
<a name="Key"></a>
## Key
**Kind**: global class
**Properties**
| Name | Type | Description |
| --- | --- | --- |
| tonic | <code>[Pitch](#Pitch)</code> | the tonic of this scale. Although all Pitch instances have an octave number, it is not used in the Key methods. |
| modeName | <code>string</code> | a string representing the mode name. If custom mode is provided, defaults to 'custom-scale' |
| mode | <code>Array.<string></code> | an array of interval strings representing the interval each scale degree is from tonic |
| scale | <code>[Array.<PitchString>](#PitchString)</code> | an array of pitch class strings |
* [Key](#Key)
* [new Key(tonic, mode)](#new_Key_new)
* [.toString()](#Key+toString) ⇒ <code>String</code>
* [.inKey(pitch)](#Key+inKey) ⇒ <code>boolean</code>
* [.accidentalOn(pitch)](#Key+accidentalOn) ⇒ <code>string</code>
* [.pitchAtDegree(degree)](#Key+pitchAtDegree) ⇒ <code>[Pitch](#Pitch)</code>
* [.scaleDegree(pitch)](#Key+scaleDegree) ⇒ <code>number</code>
* [.plusInterval(pitch, intervalSize)](#Key+plusInterval) ⇒ <code>[Pitch](#Pitch)</code>
* [.range(lo, hi)](#Key+range) ⇒ <code>[Array.<Pitch>](#Pitch)</code>
<a name="new_Key_new"></a>
### new Key(tonic, mode)
Creates a new key. Note that most Key methods use pitch classes without reguards
to octave number.
| Param | Type | Description |
| --- | --- | --- |
| tonic | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | the [tonic](@link https://en.wikipedia.org/wiki/Tonic_(music)) of this scale. Octave number may be provided, but do not affect the Key methods. |
| mode | <code>string</code> | <code>Array.<string></code> | a string representing a mode name (minor, major, dorian) or an array of interval strings representing the interval each scale degree is from tonic |
<a name="Key+toString"></a>
### key.toString() ⇒ <code>String</code>
**Kind**: instance method of <code>[Key](#Key)</code>
**Returns**: <code>String</code> - the tonic + the modeName ('Bb major')
<a name="Key+inKey"></a>
### key.inKey(pitch) ⇒ <code>boolean</code>
is this pitch a member of this key?
**Kind**: instance method of <code>[Key](#Key)</code>
**Returns**: <code>boolean</code> - is this pitch in the key?
| Param | Type | Description |
| --- | --- | --- |
| pitch | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a pitch string or Pitch |
**Example**
```js
var a_major = new Key('A3', 'major')
a_major.inKey('C3') => false
a_major.inKey('C#3') => true
```
<a name="Key+accidentalOn"></a>
### key.accidentalOn(pitch) ⇒ <code>string</code>
given a letter and key, returns the accidental that should be on this letter
in this key. This method only works for standard keys like major or dorian which map evenly
to the seven music letters.
**Kind**: instance method of <code>[Key](#Key)</code>
**Returns**: <code>string</code> - the accidental that needs to be added to this letter for it
to be in the key
| Param | Type | Description |
| --- | --- | --- |
| pitch | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a pitch string or Pitch |
<a name="Key+pitchAtDegree"></a>
### key.pitchAtDegree(degree) ⇒ <code>[Pitch](#Pitch)</code>
returns the Pitch at the requested scale degree. Although Pitches default to octave
number 4, this should be thought of as a pitch class
**Kind**: instance method of <code>[Key](#Key)</code>
**Returns**: <code>[Pitch](#Pitch)</code> - a pitch class string
| Param | Type | Description |
| --- | --- | --- |
| degree | <code>number</code> | the desired scale degree of this scale (an integer > 0) |
**Example**
```js
var a_major = new Key('A3', 'major')
a_major.scaleDegree(3) => 'C#4'<Pitch>
a_major.scaleDegree(10) => 'C#4'<Pitch>
```
<a name="Key+scaleDegree"></a>
### key.scaleDegree(pitch) ⇒ <code>number</code>
returns the scale degree of this pitch or -1 if it is not in the key
**Kind**: instance method of <code>[Key](#Key)</code>
**Returns**: <code>number</code> - the scale degree of this pitch or -1 if not in key
| Param | Type | Description |
| --- | --- | --- |
| pitch | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a pitch string or Pitch |
**Example**
```js
var a_major = new Key('A3', 'major')
a_major.scaleDegree('C3') => -1
a_major.scaleDegree('C#3') => 3
```
<a name="Key+plusInterval"></a>
### key.plusInterval(pitch, intervalSize) ⇒ <code>[Pitch](#Pitch)</code>
gets the correct pitch in the key which is the given interval size away
**Kind**: instance method of <code>[Key](#Key)</code>
**Returns**: <code>[Pitch](#Pitch)</code> - the resulting Pitch
| Param | Type | Description |
| --- | --- | --- |
| pitch | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | the starting Pitch or pitch string |
| intervalSize | <code>number</code> | an interval as a positive or negative number. |
**Example**
```js
var a_flat_major = new Key('Ab', 'major')
a_flat_major.plusInterval('C4', 2) => Pitch: Db4
a_flat_major.plusInterval('C4', -2) => Pitch: Bb3
a_flat_major.plusInterval('Eb2', 4) => Pitch: Ab2
a_flat_major.plusInterval('G5', -10) => Pitch: Eb4
```
<a name="Key+range"></a>
### key.range(lo, hi) ⇒ <code>[Array.<Pitch>](#Pitch)</code>
Get all the notes in this key between lo and hi (both inclusive)
**Kind**: instance method of <code>[Key](#Key)</code>
**Returns**: <code>[Array.<Pitch>](#Pitch)</code> - an array of Pitches with all the notes of this key
between lo and hi (both inclusive)
**Throws**:
- an Error if lo and hi are not both [inKey](#Key+inKey)
| Param | Type | Description |
| --- | --- | --- |
| lo | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | the starting Pitch or pitch string |
| hi | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | the ending Pitch or pitch string |
<a name="Pitch"></a>
## Pitch
**Kind**: global class
**Properties**
| Name | Type | Description |
| --- | --- | --- |
| Pitch.name | <code>[PitchString](#PitchString)</code> | this pitch in scientific pitch notation |
* [Pitch](#Pitch)
* [new Pitch(sciPitch)](#new_Pitch_new)
* [.toString()](#Pitch+toString) ⇒ <code>[PitchString](#PitchString)</code>
* [.valueOf()](#Pitch+valueOf) ⇒ <code>Number</code>
* [.equals(that)](#Pitch+equals) ⇒ <code>Boolean</code>
* [.isEnharmonic(that)](#Pitch+isEnharmonic) ⇒ <code>Boolean</code>
* [.isHigher(that)](#Pitch+isHigher) ⇒ <code>Boolean</code>
* [.sciPitch()](#Pitch+sciPitch) ⇒ <code>[PitchString](#PitchString)</code>
* [.letter()](#Pitch+letter) ⇒ <code>[MusicLetter](#MusicLetter)</code>
* [.accidental()](#Pitch+accidental) ⇒ <code>[AccidentalString](#AccidentalString)</code>
* [.octave()](#Pitch+octave) ⇒ <code>Number</code>
* [.pitchClass()](#Pitch+pitchClass) ⇒ <code>[PitchClassString](#PitchClassString)</code>
* [.numAccidental()](#Pitch+numAccidental) ⇒ <code>Number</code>
* [.midi()](#Pitch+midi) ⇒ <code>Number</code>
* [.semitonesTo(that)](#Pitch+semitonesTo) ⇒ <code>Number</code>
* [.intervalSize(that)](#Pitch+intervalSize) ⇒ <code>Number</code>
* [.simpleIntervalSize(that)](#Pitch+simpleIntervalSize) ⇒ <code>Number</code>
* [.interval(that)](#Pitch+interval) ⇒ <code>String</code>
* [.simpleInterval(that)](#Pitch+simpleInterval) ⇒ <code>String</code>
* [.plusInterval(interval)](#Pitch+plusInterval) ⇒ <code>[Pitch](#Pitch)</code>
<a name="new_Pitch_new"></a>
### new Pitch(sciPitch)
Creates a new immutable Pitch or if given an existing Pitch, returns it.
**Throws**:
- Will throw an error if string is not a valid pitch
| Param | Type | Description |
| --- | --- | --- |
| sciPitch | <code>[PitchString](#PitchString)</code> | <code>[Pitch](#Pitch)</code> | a pitch string in scientific pitch notation or a Pitch. |
**Example**
```js
var p = new Pitch('Bb3')
p.name => 'Bb3'
// if you forget the 'new' keyword, the constructor will call it for you
var p2 = Pitch('C4')
p2 instanceof Pitch => true
// if given a Pitch as its argument, the same Pitch will be returned
var p3 = Pitch(p2)
p2 === p3 => true
// this can be used to write functions which accept pitch strings or Pitches as a parameter
```
<a name="Pitch+toString"></a>
### pitch.toString() ⇒ <code>[PitchString](#PitchString)</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>[PitchString](#PitchString)</code> - string in scientfic pitch notation
<a name="Pitch+valueOf"></a>
### pitch.valueOf() ⇒ <code>Number</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Number</code> - the midi number of this pitch, so enharmonic notes will be equal
**See**: [pitch.midi()](#Pitch+midi)
<a name="Pitch+equals"></a>
### pitch.equals(that) ⇒ <code>Boolean</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Boolean</code> - is this pitch spelled the same as that pitch?
| Param | Type | Description |
| --- | --- | --- |
| that | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a Pitch or a pitch string |
<a name="Pitch+isEnharmonic"></a>
### pitch.isEnharmonic(that) ⇒ <code>Boolean</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Boolean</code> - does this pitch sound identical to that pitch?
| Param | Type | Description |
| --- | --- | --- |
| that | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a Pitch or a pitch string |
<a name="Pitch+isHigher"></a>
### pitch.isHigher(that) ⇒ <code>Boolean</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Boolean</code> - does this pitch sound higher than that pitch?
**See**: [isHigher](#isHigher)
| Param | Type | Description |
| --- | --- | --- |
| that | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a Pitch or a pitch string |
<a name="Pitch+sciPitch"></a>
### pitch.sciPitch() ⇒ <code>[PitchString](#PitchString)</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>[PitchString](#PitchString)</code> - in [scientfic pitch notation](https://en.wikipedia.org/wiki/Scientific_pitch_notation)
(same as pitch.name)
<a name="Pitch+letter"></a>
### pitch.letter() ⇒ <code>[MusicLetter](#MusicLetter)</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>[MusicLetter](#MusicLetter)</code> - will return 'A', 'B', 'C', 'D', 'E', 'F', or 'G'
<a name="Pitch+accidental"></a>
### pitch.accidental() ⇒ <code>[AccidentalString](#AccidentalString)</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>[AccidentalString](#AccidentalString)</code> - 'b', 'bb', '#', '##' (double sharp is not 'x'),
or '', the empty string if there is no accidental.
<a name="Pitch+octave"></a>
### pitch.octave() ⇒ <code>Number</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Number</code> - the octave number (C4 is
[middle C](https://en.wikipedia.org/wiki/C_(musical_note)#Middle_C))
<a name="Pitch+pitchClass"></a>
### pitch.pitchClass() ⇒ <code>[PitchClassString](#PitchClassString)</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>[PitchClassString](#PitchClassString)</code> - the [pitch class](https://en.wikipedia.org/wiki/Pitch_class),
same as [pitch.sciPitch()](#Pitch+sciPitch) but without octave number.
<a name="Pitch+numAccidental"></a>
### pitch.numAccidental() ⇒ <code>Number</code>
returns the number of accidentals on this letter:
positive for sharps, negative for flats.
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Number</code> - how many half steps from its letter, will be in the range [-2, 2]
**Example**
```js
var p = new Pitch('Abb3')
p.halfSteps() => -2
```
<a name="Pitch+midi"></a>
### pitch.midi() ⇒ <code>Number</code>
What is the [midi number](http://newt.phys.unsw.edu.au/jw/notes.html) of this pitch?
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Number</code> - the midi number for this pitch. C4 is 60.
**Example**
```js
toMidi('C4') => 60
toMidi('B#3') => 60
toMidi('Bb3') => 58
toMidi('A#3') => 58
```
<a name="Pitch+semitonesTo"></a>
### pitch.semitonesTo(that) ⇒ <code>Number</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Number</code> - how many half steps are there between these pitches?
| Param | Type | Description |
| --- | --- | --- |
| that | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a Pitch or a pitch string |
<a name="Pitch+intervalSize"></a>
### pitch.intervalSize(that) ⇒ <code>Number</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Number</code> - the interval size between these pitches
**See**: [intervalSize](#intervalSize)
| Param | Type | Description |
| --- | --- | --- |
| that | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a Pitch or a pitch string |
<a name="Pitch+simpleIntervalSize"></a>
### pitch.simpleIntervalSize(that) ⇒ <code>Number</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>Number</code> - the simple interval size between these pitches in range [1,7]
**See**: [simple](#intervalSize.simple)
| Param | Type | Description |
| --- | --- | --- |
| that | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a Pitch or a pitch string |
<a name="Pitch+interval"></a>
### pitch.interval(that) ⇒ <code>String</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>String</code> - the interval between these pitches
**See**: [interval](#interval)
| Param | Type | Description |
| --- | --- | --- |
| that | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a Pitch or a pitch string |
<a name="Pitch+simpleInterval"></a>
### pitch.simpleInterval(that) ⇒ <code>String</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>String</code> - the simple interval between these pitches
**See**: [simple](#interval.simple)
| Param | Type | Description |
| --- | --- | --- |
| that | <code>[Pitch](#Pitch)</code> | <code>[PitchString](#PitchString)</code> | a Pitch or a pitch string |
<a name="Pitch+plusInterval"></a>
### pitch.plusInterval(interval) ⇒ <code>[Pitch](#Pitch)</code>
**Kind**: instance method of <code>[Pitch](#Pitch)</code>
**Returns**: <code>[Pitch](#Pitch)</code> - the resulting Pitch
**See**: [plusInterval](#plusInterval)
| Param | Type | Description |
| --- | --- | --- |
| interval | <code>String</code> | <code>Number</code> | an interval string or number with or without quality. If interval quality is not provided, accidentals on this Pitch will be ignored. |
**Example**
```js
var pitch_C4 = new Pitch('C4')
plusInterval(pitch_C4, 10) => Pitch: E5
plusInterval(pitch_C4, -10) => Pitch: A2
plusInterval(pitch_C4, 'm10') => Pitch: Eb5
plusInterval(pitch_C4, '-d7') => Pitch: D#3
```
<a name="modeIntervals"></a>
## modeIntervals(modeName) ⇒ <code>Array.<string></code>
returns the intervals that define the scale degrees of a given mode
**Kind**: global function
**Returns**: <code>Array.<string></code> - an array of interval strings representing the
interval each scale degree is from tonic, always starting with 'P1' for tonic
| Param | Type | Description |
| --- | --- | --- |
| modeName | <code>'major'</code> | <code>'minor'</code> | <code>'ionian'</code> | <code>'dorian'</code> | <code>'phrygian'</code> | <code>'lydian'</code> | <code>'mixolydian'</code> | <code>'aeolian'</code> | <code>'locrian'</code> | a mode name |
**Example**
```js
modeIntervals('major') => ['P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'M7']
modeIntervals('dorian') => ['P1', 'M2', 'm3', 'P4', 'P5', 'M6', 'm7']
```
<a name="scaleSet"></a>
## scaleSet(tonic, mode) ⇒ <code>[Array.<PitchString>](#PitchString)</code>
given a pitch string and scale mode, build a pitch class scale from that pitch
**Kind**: global function
**Returns**: <code>[Array.<PitchString>](#PitchString)</code> - an array of pitch class strings (without octave number)
**See**: for a similar function which uses octave numbers, see [scale](#scale)
| Param | Type | Description |
| --- | --- | --- |
| tonic | <code>[PitchString](#PitchString)</code> | the [tonic](@link https://en.wikipedia.org/wiki/Tonic_(music)) of this scale. If octave number is provided, it will be ignored. |
| mode | <code>string</code> | <code>Array.<string></code> | a string representing a mode name (minor, major, dorian) or an array of interval strings representing the interval each scale degree is from tonic |
**Example**
```js
scale('Eb4', 'major')
=> ['Eb', 'F', 'G', 'Ab', 'Bb', 'C', 'D']
```
<a name="scale"></a>
## scale(tonic, mode) ⇒ <code>[Array.<PitchString>](#PitchString)</code>
given a pitch string and scale mode, build a scale from that pitch
**Kind**: global function
**Returns**: <code>[Array.<PitchString>](#PitchString)</code> - an array of pitch strings
| Param | Type | Description |
| --- | --- | --- |
| tonic | <code>[PitchString](#PitchString)</code> | the [tonic](@link https://en.wikipedia.org/wiki/Tonic_(music)) of this scale |
| mode | <code>string</code> | <code>Array.<string></code> | a string representing a mode name (minor, major, dorian) or an array of interval strings representing the interval each scale degree is from tonic |
**Example**
```js
scale('Eb4', 'major')
=> ['Eb4', 'F4', 'G4', 'Ab4', 'Bb4', 'C5', 'D5']
```
<a name="intervalQuality"></a>
## intervalQuality(sciPitch1, sciPitch2) ⇒ <code>String</code>
the interval quality between two pitch strings
**Kind**: global function
**Returns**: <code>String</code> - a character representing the interval between the two pitches:
- 'P' = perfect
- 'm' = minor
- 'M' = major
- 'd' = diminished
- 'A' = augmented
**Throws**:
- an error if either string is not a valid pitch
| Param | Type | Description |
| --- | --- | --- |
| sciPitch1 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
| sciPitch2 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
**Example**
```js
intervalQuality('C4', 'E4') => 'M'
intervalQuality('E4', 'Eb4') => 'm'
intervalQuality('C4', 'F4') => 'P'
intervalQuality('C4', 'F#4') => 'A'
intervalQuality('B3', 'Ab4') => 'd'
```
<a name="intervalSize"></a>
## intervalSize(sciPitch1, sciPitch2) ⇒ <code>Number</code>
the generic interval size between two pitch strings, disregarding accidentals
**Kind**: global function
**Returns**: <code>Number</code> - the absolute interval size between the two pitches. Always positive, even if
the first argument is higher than the second.
**Throws**:
- an error if string is not a valid pitch
**See**: [simple](#intervalSize.simple) for returning the simple interval size
| Param | Type | Description |
| --- | --- | --- |
| sciPitch1 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
| sciPitch2 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
**Example**
```js
intervalSize('C4', 'E4') => 3
intervalSize('E4', 'C4') => 3
intervalSize('C4', 'E5') => 10
intervalSize('C4', 'Eb5') => 10
intervalSize('C5', 'C5') => 1
```
<a name="intervalSize.simple"></a>
### intervalSize.simple(sciPitch1, sciPitch2) ⇒ <code>Number</code>
the generic simple interval size (1-7) between two pitch strings, disregarding accidentals
**Kind**: static method of <code>[intervalSize](#intervalSize)</code>
**Returns**: <code>Number</code> - the simple interval size between the two pitches in range [1, 7].
Contrary to standard practice, an octave is considered compound and reduces to 1.
**Throws**:
- an error if string is not a valid pitch
| Param | Type | Description |
| --- | --- | --- |
| sciPitch1 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
| sciPitch2 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
**Example**
```js
intervalSize.simple('C4', 'E4') => 3
intervalSize.simple('C4', 'E5') => 3
intervalSize.simple('C1', 'E9') => 3
```
<a name="interval"></a>
## interval(sciPitch1, sciPitch2) ⇒ <code>String</code>
the interval between two pitch strings
**Kind**: global function
**Returns**: <code>String</code> - the interval between the two pitches
**Throws**:
- an error if either string is not a valid pitch
**See**: [simple](#interval.simple) for returning the simple interval
| Param | Type | Description |
| --- | --- | --- |
| sciPitch1 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
| sciPitch2 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
**Example**
```js
interval('C4', 'E4') => 'M3'
interval('E4', 'Eb4') => 'm3'
interval('C4', 'F4') => 'P4'
interval('C4', 'F#4') => 'A4'
interval('B3', 'Ab4') => 'd7'
```
<a name="interval.simple"></a>
### interval.simple(sciPitch1, sciPitch2) ⇒ <code>Number</code>
the simple interval between two pitch strings
**Kind**: static method of <code>[interval](#interval)</code>
**Returns**: <code>Number</code> - the simple interval between the two pitches.
Contrary to standard practice, an octave is considered compound and reduces to 1 as in [simple](#intervalSize.simple)
**Throws**:
- an error if string is not a valid pitch
| Param | Type | Description |
| --- | --- | --- |
| sciPitch1 | <code>String</code> | a pitch in scientific pitch notation. |
| sciPitch2 | <code>String</code> | a pitch in scientific pitch notation. |
**Example**
```js
interval.simple('C4', 'E4') => 'M3'
interval.simple('C4', 'E5') => 'M3'
interval.simple('C1', 'E9') => 'M3'
```
<a name="isHigher"></a>
## isHigher(sciPitch1, sciPitch2) ⇒ <code>boolean</code>
does this pitch sound higher than that pitch?
**Kind**: global function
**Returns**: <code>boolean</code> - is sciPitch1 higher than sciPitch2?
**Throws**:
- Will throw an error if string is not a valid pitch
| Param | Type | Description |
| --- | --- | --- |
| sciPitch1 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
| sciPitch2 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
**Example**
```js
isHigher('D4', 'C4') => true
isHigher('C4', 'D4') => false
isHigher('C4', 'B#3') => false // enharmonic, so they actually sound equal
isHigher('B##3', 'C4') => true // B##3 sounds higher than C4
```
<a name="parseInterval"></a>
## parseInterval(interval) ⇒ <code>Object</code> | <code>false</code>
parses an interval string or number and return its properties in an object or
return false if the string or number is not valid
**Kind**: global function
**Returns**: <code>Object</code> | <code>false</code> - False if invalid interval else an object
with the following properties:
- interval: string
- direction: number -1 or 1
- quality: string of 'm', 'M', 'P', 'd', or 'A' OR null if not given
- size: number, size of the interval, never negative
- simpleSize: number in range [1,7]
- perfectable: boolean (if false, this is an imperfect interval)
- octaves: number of octave changes. Will be >= 0.
- halfsteps: number|undefined if given quality, number of halfsteps this interval translates to
| Param | Type | Description |
| --- | --- | --- |
| interval | <code>String</code> | <code>Number</code> | an interval string with interval quality or a number representing only interval size. Both types of input may be signed ('-P5' or -5) to indicate a descending interval. |
**Example**
```js
parseInterval('-M6') => {interval: '-M6', direction: -1, quality: 'M', size: 6, simpleSize: 6,
perfectable: false, octaves: 0, halfsteps: 9}
parseInterval(12) => {interval: '12', direction: 1, quality: null, size: 12, simpleSize: 5,
perfectable: true, octaves 1}
parseInterval('M5') => false
```
<a name="parsePitch"></a>
## parsePitch(sciPitch) ⇒ <code>object</code> | <code>false</code>
parses a pitch string and return its components in an object or
false if the string is not valid
**Kind**: global function
**Returns**: <code>object</code> | <code>false</code> - False if invalid pitch string or an object
with the following properties:
- letter: string
- accidental: [AccidentalString](#AccidentalString)
- numAccidental: number of accidentals [-2, 2], positive for sharps, negative for flats
- octave: integer (if not provided, defaults to 4)
- sciPitch: [PitchString](#PitchString)
| Param | Type | Description |
| --- | --- | --- |
| sciPitch | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation |
**Example**
```js
parsePitch('Bb3') => {letter: 'B', accidental: 'b', numAccidental: -1, octave: 3, sciPitch:'Bb3'}
parsePitch('Xb4') => false
```
<a name="plusInterval"></a>
## plusInterval(sciPitch, interval) ⇒ <code>[PitchString](#PitchString)</code> | <code>function</code>
given pitch string plus given interval string equals new pitch string
Optionally, give only one parameter and get back a function with that parameter
set as the default.
**Kind**: global function
**Returns**: <code>[PitchString](#PitchString)</code> | <code>function</code> - the resulting pitch string, or if one argument is null, returns
a function with the provided argument set as a default.
**Throws**:
- an error if pitch string or interval string is not valid
| Param | Type | Description |
| --- | --- | --- |
| sciPitch | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
| interval | <code>String</code> | <code>Number</code> | an interval string or number with or without quality. If quality is not provided, accidentals on given pitch will be ignored. |
**Example**
```js
plusInterval('C4', 10) => 'E5'
plusInterval('C4', -10) => 'A2'
plusInterval('C4', 'm10') => 'Eb5'
plusInterval('C4', '-d7') => 'D#3'
var majorscale = ['P1', 'M2', 'M3', 'P4', 'P5', 'M6', 'M7', 'P8']
majorscale.map(plusInterval('Eb4', null))
=> ['Eb4', 'F4', 'G4', 'Ab4', 'Bb4', 'C5', 'D5', 'Eb5']
majorscale.map(plusInterval('Eb4', null)).map(plusInterval(null, '-m9'))
=> ['D3', 'E3', 'F#3', 'G3', 'A3', 'B3', 'C#4', 'D4']
```
<a name="semitonesBetween"></a>
## semitonesBetween(sciPitch1, sciPitch2) ⇒ <code>Number</code>
the number of semitones between these two pitch strings
**Kind**: global function
**Returns**: <code>Number</code> - the semitones between these two pitch strings.
**Throws**:
- Will throw an error if string is not a valid pitch
| Param | Type | Description |
| --- | --- | --- |
| sciPitch1 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
| sciPitch2 | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
**Example**
```js
semitonesBetween('C4', 'Db4') => 1
semitonesBetween('C4', 'B#3') => 0
semitonesBetween('C4', 'C5') => 12
```
<a name="simplifyIntervalSize"></a>
## simplifyIntervalSize(intervalSize) ⇒ <code>Number</code>
simplify compound intervals to within the range of 1-7. Works for
negative intervals as well.
**Kind**: global function
**Returns**: <code>Number</code> - the simplified interval
**Throws**:
- Will throw an error if intervalSize is 0
| Param | Type | Description |
| --- | --- | --- |
| intervalSize | <code>Number</code> | any valid interval number |
**Example**
```js
simplifyIntervalSize(10) => 3
simplifyIntervalSize(-12) => -5
simplifyIntervalSize(-4) => -4
simplifyIntervalSize(8) => 1
```
<a name="sortPitches"></a>
## sortPitches(pitches) ⇒ <code>[Array.<PitchString>](#PitchString)</code>
helper function to sort an array of PitchStrings from lowest to highest
**Kind**: global function
**Returns**: <code>[Array.<PitchString>](#PitchString)</code> - a new clone of the provided pitch string
array sorted from low pitch to high pitch
| Param | Type | Description |
| --- | --- | --- |
| pitches | <code>[Array.<PitchString>](#PitchString)</code> | an array of pitch strings |
<a name="toMidi"></a>
## toMidi(sciPitch) ⇒ <code>Number</code>
the [midi number](http://newt.phys.unsw.edu.au/jw/notes.html) of this pitch string
**Kind**: global function
**Returns**: <code>Number</code> - the midi number for this pitch. C4 is 60.
[Enharmonic](https://en.wikipedia.org/wiki/Enharmonic) notes will return the same
midi number.
**Throws**:
- Will throw an error if string is not a valid pitch
| Param | Type | Description |
| --- | --- | --- |
| sciPitch | <code>[PitchString](#PitchString)</code> | a pitch in scientific pitch notation. |
**Example**
```js
toMidi('C4') => 60
toMidi('B#3') => 60
toMidi('Bb3') => 58
toMidi('A#3') => 58
```
<a name="clone"></a>
## clone(obj) ⇒ <code>object</code> | <code>array</code>
helper function to clone a simple object/array made up of primitives.
Will not work if the object or array contains non-primitives.
**Kind**: global function
**Returns**: <code>object</code> | <code>array</code> - a new clone of the provided object or array
| Param | Type | Description |
| --- | --- | --- |
| obj | <code>object</code> | <code>array</code> | an object array made up only of primitives |
<a name="MusicLetter"></a>
## MusicLetter : <code>'A'</code> | <code>'B'</code> | <code>'C'</code> | <code>'D'</code> | <code>'E'</code> | <code>'F'</code> | <code>'G'</code>
[A-G] representing a musical lettername
**Kind**: global typedef
<a name="AccidentalString"></a>
## AccidentalString : <code>'#'</code> | <code>'b'</code> | <code>'##'</code> | <code>'bb'</code>
'#' for sharp, 'b' for flat.
'##'' for double sharp, 'bb' for double flat.
**Kind**: global typedef
<a name="PitchString"></a>
## PitchString : <code>string</code>
[MusicLetter](#MusicLetter) + [[AccidentalString](#AccidentalString)] +
[octave number]. Must match the regular expression:
/(A-G)(b{1,2}|#{1,2})?(\d{1,2})?/. Accidental and octave number are optional,
but if octave number is not provided, it will default to octave 4.
**Kind**: global typedef
**Example**
```js
'C4' // middle C on a piano, the fourth octave
'B3' // the B one note below C4 on the piano (octave numbers change on C)
'Eb3' // Eb in octave 3
'F#2' // F# in octave 2
'F##7' // F double sharp in octave 7
'Dbb5' // D double flat in octave 5
```
<a name="PitchClassString"></a>
## PitchClassString : <code>string</code>
[MusicLetter](#MusicLetter) + [[AccidentalString](#AccidentalString)].
**Kind**: global typedef
**Link**: same as [PitchString](#PitchString) but without octave number.
**Example**
```js
'C'
'Eb'
'F#'
'F##'
'Dbb'
```
<file_sep>var nmusic = require('nmusic')
// major 6th below G5 -> Bb4
nmusic.plusInterval('G5', '-M6')
|
a4baaffa877a4b965888a25dbf80184e9711957b
|
[
"JavaScript",
"Markdown"
] | 23
|
JavaScript
|
jrleszcz/nmusic
|
57978b51f327ace84310e8fae6dfb335a6fe9def
|
1a6b98ec8e74eead770f0df8dc8a992abd54068d
|
refs/heads/master
|
<repo_name>Keshabpal9933/foody_learning_project<file_sep>/FoodFun/user_save.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$uname= $password = "";
include 'db.php';
// Escape user inputs for security
$uname = mysqli_real_escape_string($conn, $_REQUEST['uname']);
$password = mysqli_real_escape_string($conn, $_REQUEST['password']);
$sql = "INSERT INTO user (uname, password)
VALUES ('$uname', '$password')";
if ($conn->query($sql) === TRUE) {
header("location:index.php");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
</html><file_sep>/FoodFun/mexican_order_check.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include 'session.php';
$uname= $name =$phone= $email = $address= $date = $time= $suggestions = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$address = test_input($_POST["address"]);
$suggestions = test_input($_POST["suggestions"]);
$phone = test_input($_POST["phone"]);
$date = test_input($_POST["date"]);
$time = test_input($_POST["time"]);
$uname = test_input($_SESSION['uname']);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
include 'db.php';
$sql = "INSERT INTO customer_order (uname,item, price, name, phone, address, date, time, email, suggestions)
VALUES ('$uname', 'Mexican Eggrolls', '$14.50', '$name', '$phone', '$address', '$date', '$time', '$email','$suggestions')";
if ($conn->query($sql) === TRUE) {
header("location: view_mexican_order.php");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<!-- <a href="view_mexican_order.php">Your Order</a> -->
</body>
</html>
<file_sep>/FoodFun/delete.php
<?php
include 'db.php';
$id=$_GET['id'];
$sql = "DELETE FROM customer_order WHERE id=$id";
$result = mysqli_query($conn, $sql);
if($result){
header("location: view_mexican_order.php");
}
else
{
echo "There is some problem while deleting item";
}
mysqli_close($conn);
?><file_sep>/FoodFun/edit.php
<?php
$conn =new PDO("mysql:host=localhost;dbname=foodfun;","root","");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['submit'])){
$id = $_POST['id'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$date = $_POST['date'];
$time = $_POST['time'];
$email = $_POST['email'];
$suggection = $_POST['suggestions'];
$sql = "UPDATE customer_order SET name = '$name', phone='$phone', address='$address', email='$email',
date='$date', time='$time', suggestions='$suggection' WHERE id=$id";
$stmt = $conn->prepare($sql);
$stmt->execute();
if($stmt){
header("location:view_mexican_order.php");
}
}
?>
<!DOCTYPE HTML>
<html>
<head><title>Order</title>
<link rel="stylesheet" href="design/css/bootstrap.min.css">
</head>
<body class="background: bg-info" style="height: auto;">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<h2 style="text-align: center">Fill the Detail</h2>
<hr>
<?php
$conn =new PDO("mysql:host=localhost;dbname=foodfun;","root","");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = $_GET['id'];
$sql = "SELECT *FROM customer_order WHERE id=$id";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($data as $key => $value){
$name = $value->name;
$phone = $value->phone;
$address = $value->address;
$date = $value->date;
$time = $value->time;
$email = $value->email;
$suggestions = $value->suggestions;
}
?>
<form method="post" action="" class="form">
<div class="form-group">
<label for="name" class="col-4"><strong> Name</strong></label>
<div class="col-8">
<input type="text" name="name" class="form-control" value="<?php global $name; echo $name;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Phone</strong></label>
<div class="col-8">
<input type="number" name="phone" class="form-control" value="<?php global $phone; echo $phone;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Address</strong></label>
<div class="col-8">
<input type="text" name="address" class="form-control" value="<?php global $address; echo $address; ?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Date to Deliver</strong></label>
<div class="col-8">
<input type="date" name="date" class="form-control" value="<?php global $date; echo $date; ?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Time</strong></label>
<div class="col-8">
<input type="time" name="time" class="form-control" value="<?php global $time; echo $time;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Email</strong></label>
<div class="col-8">
<input type="email" name="email" class="form-control" value="<?php global $email; echo $email;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Any Suggestion</strong></label>
<div class="col-8">
<textarea name="suggestions" class="form-control" cols="5" rows="5" value="<?php global $suggestions; echo $suggestions;?>" required> </textarea>
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
</div>
</div>
<div class="form-group">
<label for="" class="col-4"></label>
<input type="submit" name="submit" class="btn btn-success" value="Order">
</div>
</div>
</div>
</div>
</form>
</body>
</html><file_sep>/FoodFun/mexican_receipt.php
<!DOCTYPE HTML>
<html>
<head><title>Order</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2 style="text-align: center">Fill the detail</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="#" class="form">
<label for="name" class="col-4"></label>
<input type="text" name="name" value="<?php echo $name;?>" required>
<br><br>
Phone no: <input type="number" name="phone" value="<?php echo $phone;?>" required>
<br><br>
Address: <input type="text" name="address" value="<?php echo $address;?>" required>
<br><br>
Date to deliver:<input type="Date" name="date" value="<?php echo $date?>" required>
<br><br>
Time : <input type="Time" name="time" value="<?php echo $time?>" required>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>" required>
<br><br>
Any Suggestions??:<input type="text" name="suggestions" value="<?php echo $suggestions;?>" required>
<br><br>
<input type="submit" name="submit" value="Order">
</form>
</body>
</html>
</body>
</html><file_sep>/FoodFun/view_mexican_order.php
<!DOCTYPE html>
<html>
<head>
<title>Your Order</title>
<link rel="stylesheet" href="design/css/all.min.css">
<link rel="stylesheet" href="design/css/bootstrap.min.css">
</head>
<body style="background: #a3b6bf;">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<a href="main.php"><button class="btn btn-primary" style="margin-top: 10px">Go to Home</button></a>
<h2 class="text-center">Your Order Is Given Below</h2>
<table class="table" border="1px" >
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Address</th>
<th>Date to deliver</th>
<th>Time</th>
<th>Email</th>
<th>Any suggestions!!</th>
<th>Action</th>
</tr>
</thead>
<?php
include 'session.php';
$uname = $_SESSION['uname'];
include 'db.php';
$sql = "SELECT * FROM customer_order where uname = '$uname'";
$result = $conn->query($sql);
if (@$result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<!-- echo "<tr><td>".$row["name"]."</td><td>".$row["phone"]."</td><td>".$row["address"]."</td><td>".$row["date"]."</td><td>".$row["time"]."</td><td>".$row["email"]."</td><td>".$row["suggestions"]."</td></tr>"; -->
<tbody>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['phone'] ?></td>
<td><?php echo $row['address'] ?></td>
<td><?php echo $row['date'] ?></td>
<td><?php echo $row['time'] ?></td>
<td><?php echo $row['email'] ?></td>
<td><?php echo $row['suggestions'] ?></td>
<td>
<a href="delete.php?id=<?php echo $row['id'];?>" class="btn btn-danger" style="border-radius: 10%">Del</a>
<a href="edit.php?id=<?php echo $row['id'];?>" class="btn btn-success" style="border-radius: 10%">Edit</a>
</td>
</tr>
</tbody>
<?php
}
}
$conn->close();
?>
</table>
</div>
</div>
</div>
</body>
</html><file_sep>/FoodFun/login_check.php
<?php
include 'db.php';// Inialize session
session_start();
if(!empty($_POST['submit']))
{
$uname = $_POST['uname'];
$password = $_POST['password'];
$qz = "SELECT * FROM user where uname='$uname' and password='$password'" ;
$result = mysqli_query($conn,$qz);
$row = mysqli_num_rows($result);
if($row>0)
{// Set username session variable
$_SESSION['uname'] = $_POST['uname'];
$_SESSION['id']=$_POST['id'];
header("location:main.php");
}
else
{
echo "username and password didn't match!";
header("location:index.php");
}
mysqli_close($conn);
}
?><file_sep>/FoodFun/main.php
<?php
include 'session.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required Meta Tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Page Title -->
<title>Foodfun</title>
<!-- Favicon -->
<link rel="shortcut icon" href="assets/images/logo/favicon.png" type="image/x-icon">
<!-- CSS Files -->
<link rel="stylesheet" href="assets/css/animate-3.7.0.css">
<link rel="stylesheet" href="assets/css/font-awesome-4.7.0.min.css">
<link rel="stylesheet" href="assets/css/bootstrap-4.1.3.min.css">
<link rel="stylesheet" href="assets/css/owl-carousel.min.css">
<link rel="stylesheet" href="assets/css/jquery.datetimepicker.min.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<!-- Preloader Starts -->
<div class="preloader">
<div class="spinner"></div>
</div>
<!-- Preloader End -->
<!-- Header Area Starts -->
<header class="header-area">
<div class="container">
<div class="row">
<a href="main.php">
<div class="col-lg-2">
<div class="logo-area">
<img src="assets/images/logo/logo.png" alt="logo">
</div>
</div></a>
<div class="col-lg-10">
<div class="custom-navbar">
<span></span>
<span></span>
<span></span>
</div>
<div class="main-menu">
<ul>
<li><a href="main.php">menu</a></li>
<li><a href="view_mexican_order.php">My order</a></li>
<li><a href="logout.php">Log out</a></li>
</ul>
</div>
</div>
</div>
</div>
</header>
<!-- Header Area End -->
<!-- Banner Area Starts -->
<section class="banner-area text-center">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h6>the best food ordering site</h6>
<h1>Discover the <span class="prime-color">flavors</span><br>
<span class="style-change">of <span class="prime-color">food</span>fun</span></h1>
</div>
</div>
</div>
</section>
<!-- Banner Area End -->
<!-- Food Area starts -->
<section class="food-area section-padding">
<div class="container">
<div class="row">
<div class="col-md-5">
<div class="section-top">
<h3><span class="style-change">we serve</span> <br>delicious food</h3>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-6">
<div class="single-food">
<div class="food-img">
<a href="order.php"> <img src="assets/images/food1.jpg" class="img-fluid" alt=""></a>
</div>
<div class="food-content">
<div class="d-flex justify-content-between">
<h5 class="ord">Mexican Eggrolls</h5>
<span class="style-change">$14.50</span>
</div>
<p class="pt-3">Face together given moveth divided form Of Seasons that fruitful.</p>
</div>
</div>
</div>
<div class="col-md-4 col-sm-6">
<div class="single-food mt-5 mt-sm-0">
<div class="food-img">
<img src="assets/images/food2.jpg" class="img-fluid" alt="">
</div>
<div class="food-content">
<div class="d-flex justify-content-between">
<h5 class="ord">chicken burger</h5>
<span class="style-change">$9.50</span>
</div>
<p class="pt-3">Face together given moveth divided form Of Seasons that fruitful.</p>
</div>
</div>
</div>
<div class="col-md-4 col-sm-6">
<div class="single-food mt-5 mt-md-0">
<div class="food-img">
<img src="assets/images/food3.jpg" class="img-fluid" alt="">
</div>
<div class="food-content">
<div class="d-flex justify-content-between">
<h5 class="ord">topu lasange</h5>
<span class="style-change">$12.50</span>
</div>
<p class="pt-3">Face together given moveth divided form Of Seasons that fruitful.</p>
</div>
</div>
</div>
<div class="col-md-4 col-sm-6">
<div class="single-food mt-5">
<div class="food-img">
<img src="assets/images/food4.jpg" class="img-fluid" alt="">
</div>
<div class="food-content">
<div class="d-flex justify-content-between">
<h5 class="ord">pepper potatoas</h5>
<span class="style-change">$14.50</span>
</div>
<p class="pt-3">Face together given moveth divided form Of Seasons that fruitful.</p>
</div>
</div>
</div>
<div class="col-md-4 col-sm-6">
<div class="single-food mt-5">
<div class="food-img">
<img src="assets/images/food5.jpg" class="img-fluid" alt="">
</div>
<div class="food-content">
<div class="d-flex justify-content-between">
<h5 class="ord">bean salad</h5>
<span class="style-change">$8.50</span>
</div>
<p class="pt-3">Face together given moveth divided form Of Seasons that fruitful.</p>
</div>
</div>
</div>
<div class="col-md-4 col-sm-6">
<div class="single-food mt-5">
<div class="food-img">
<img src="assets/images/food6.jpg" class="img-fluid" alt="">
</div>
<div class="food-content">
<div class="d-flex justify-content-between">
<h5 class="ord">beatball hoagie</h5>
<span class="style-change">$11.50</span>
</div>
<p class="pt-3">Face together given moveth divided form Of Seasons that fruitful.</p>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Food Area End -->
<!-- Footer Area Starts -->
<footer class="footer-area">
<div class="footer-widget section-padding">
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="single-widget single-widget1">
<a href="index.html"><img src="assets/images/logo/logo2.png" alt=""></a>
<p class="mt-3">the best food ordering site</p>
</div>
</div>
<div class="col-md-4">
<div class="single-widget single-widget2 my-5 my-md-0">
<h5 class="mb-4">contact us</h5>
<div class="d-flex">
<div class="into-icon">
<i class="fa fa-map-marker"></i>
</div>
<div class="info-text">
<p>New Baneswor, Kathmandu </p>
</div>
</div>
<div class="d-flex">
<div class="into-icon">
<i class="fa fa-phone"></i>
</div>
<div class="info-text">
<p>(+977) 014 789 90</p>
</div>
</div>
<div class="d-flex">
<div class="into-icon">
<i class="fa fa-envelope-o"></i>
</div>
<div class="info-text">
<p><EMAIL></p>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="single-widget single-widget3">
<h5 class="mb-4">ordering hours</h5>
<p>Monday ...................... Closed</p>
<p>Tue-Fri .............. 10 am - 12 pm</p>
<p>Sat-Sun ............... 8 am - 11 pm</p>
<p>Holidays ............. 10 am - 12 pm</p>
</div>
</div>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
<div class="row">
<div class="col-lg-7 col-md-6">
<span><!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. -->
Copyright ©<script>document.write(new Date().getFullYear());</script> All rights reserved |by <a href="https://w3schools.com" target="_blank">PK</a>
<!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --></span>
</div>
<div class="col-lg-5 col-md-6">
<div class="social-icons">
<ul>
<li class="no-margin">Follow Us</li>
<li><a href="#"><i class="fa fa-facebook"></i></a></li>
<li><a href="#"><i class="fa fa-twitter"></i></a></li>
<li><a href="#"><i class="fa fa-google-plus"></i></a></li>
<li><a href="#"><i class="fa fa-pinterest"></i></a></li>
<li><a href="#"><i class="fa fa-instagram"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</footer>
<!-- Footer Area End -->
<!-- Javascript -->
<script src="assets/js/vendor/jquery-2.2.4.min.js"></script>
<script src="assets/js/vendor/bootstrap-4.1.3.min.js"></script>
<script src="assets/js/vendor/wow.min.js"></script>
<script src="assets/js/vendor/owl-carousel.min.js"></script>
<script src="assets/js/vendor/jquery.datetimepicker.full.min.js"></script>
<script src="assets/js/vendor/jquery.nice-select.min.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<file_sep>/FoodFun/order.php
<!DOCTYPE HTML>
<html>
<head><title>Order</title>
<link rel="stylesheet" href="design/css/bootstrap.min.css">
<style>
.error {color: #FF0000;}
</style>
</head>
<body class="background: bg-info" style="height: auto;">
<?php
include 'session.php';
$name =$phone= $email = $address= $date = $time= $suggestions = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$address = test_input($_POST["address"]);
$suggestions = test_input($_POST["suggestions"]);
$phone = test_input($_POST["phone"]);
$date = test_input($_POST["date"]);
$time = test_input($_POST["time"]);
$uname = test_input($_SESSION['uname']);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<h2 style="text-align: center">Fill the Detail</h2>
<hr>
<p><span class="error">* required field</span></p>
<form method="post" action="mexican_order_check.php" class="form">
<div class="form-group">
<label for="name" class="col-4"><strong> Name</strong></label>
<div class="col-8">
<input type="text" name="name" class="form-control" value="<?php echo $name;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Phone</strong></label>
<div class="col-8">
<input type="number" name="phone" class="form-control" value="<?php echo $phone;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Address</strong></label>
<div class="col-8">
<input type="text" name="address" class="form-control" value="<?php echo $address;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Date to Deliver</strong></label>
<div class="col-8">
<input type="date" name="date" class="form-control" value="<?php echo $date;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Time</strong></label>
<div class="col-8">
<input type="time" name="time" class="form-control" value="<?php echo $time;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Email</strong></label>
<div class="col-8">
<input type="email" name="email" class="form-control" value="<?php echo $email;?>" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-4"><strong>Any Suggestion</strong></label>
<div class="col-8">
<textarea name="suggestions" class="form-control" cols="5" rows="5" value="<?php echo $suggestions;?>" required> </textarea>
</div>
</div>
<div class="form-group">
<label for="" class="col-4"></label>
<input type="submit" name="submit" class="btn btn-success" value="Order">
</div>
</div>
</div>
</div>
</form>
</body>
</html>
|
63006f37e7289e83c0439a6a5b8a8f808d1dbe78
|
[
"PHP"
] | 9
|
PHP
|
Keshabpal9933/foody_learning_project
|
0bd5b7c6693c89070773fce375ce68f8f6c48990
|
b259601f336b2c8002e33e9c0cd07de84091f5b7
|
refs/heads/master
|
<repo_name>adityakaushikNITW/Examples<file_sep>/executor/src/main/java/com/training/two/model/Task1.java
package com.training.two.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.concurrent.Callable;
@AllArgsConstructor
public class Task1 implements Callable<Integer> {
private Integer a;
private Integer b;
@Override
public Integer call() throws Exception {
return a+b;
}
}
<file_sep>/executor/src/main/java/com/training/two/init/InitProcess.java
package com.training.two.init;
import com.training.two.App2;
import com.training.two.config.ThreadPoolConfig;
import com.training.two.model.Task1;
import io.dropwizard.lifecycle.Managed;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
//@AllArgsConstructor(onConstructor = @__({@javax.inject.Inject}))
@Slf4j
public class InitProcess implements Managed {
private Logger logger = LoggerFactory.getLogger(InitProcess.class);
private ThreadPoolConfig threadPoolConfig;
@Inject
public InitProcess(ThreadPoolConfig threadPoolConfig) {
this.threadPoolConfig = threadPoolConfig;
App2.executorService = Executors.newFixedThreadPool(threadPoolConfig.getJob1());
}
@Override
public void start() throws Exception {
Future<Integer> result = App2.executorService.submit(new Task1(2,5));
logger.info(result.get()+" <<<<$$$");
}
@Override
public void stop() throws Exception {
}
}
<file_sep>/api/src/main/java/com/training/ApiApp.java
package com.training;
import com.google.inject.Stage;
import com.hubspot.dropwizard.guice.GuiceBundle;
import com.training.config.ApiConfiguration;
import com.training.module.MyModule;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
public class ApiApp extends Application<ApiConfiguration> {
public static void main(String[] args) throws Exception {
new ApiApp().run(args);
}
@Override
public void initialize(Bootstrap<ApiConfiguration> bootstrap){
GuiceBundle<ApiConfiguration> myGuiceBundle = new GuiceBundle.Builder<ApiConfiguration>().
addModule(new MyModule()).
setConfigClass(ApiConfiguration.class).
enableAutoConfig("com.training").
build(Stage.DEVELOPMENT);
bootstrap.addBundle(myGuiceBundle);
}
@Override
public void run(ApiConfiguration apiConfiguration, Environment environment) throws Exception {
environment.lifecycle().addServerLifecycleListener(server -> {});
}
}
<file_sep>/executor/src/main/java/com/training/two/config/ThreadPoolConfig.java
package com.training.two.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class ThreadPoolConfig {
@JsonProperty("job1")
private int job1;
@JsonProperty("job2")
private int job2;
}
<file_sep>/executor/src/main/java/com/training/two/module/MyModule.java
package com.training.two.module;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.training.two.config.ExecutorConfiguration;
import com.training.two.config.ThreadPoolConfig;
public class MyModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton
ThreadPoolConfig getthreadPoolConfig(ExecutorConfiguration executorConfiguration){
return executorConfiguration.getThreadPoolConfig();
}
}
|
a5076a88e3672cadc555747c810aae5861ec01f2
|
[
"Java"
] | 5
|
Java
|
adityakaushikNITW/Examples
|
d2a39f0a9df1416a8a6def68f5c83bf6633d34a1
|
9af84522a83439a35d47e3b8a5ec39d722169554
|
refs/heads/master
|
<repo_name>sksubhani/ordermgmt<file_sep>/src/main/java/org/subhani/ordermgmt/service/impl/CustomerServiceImpl.java
package org.subhani.ordermgmt.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.subhani.ordermgmt.dao.CustomerDao;
import org.subhani.ordermgmt.domain.data.Customer;
import org.subhani.ordermgmt.service.CustomerService;
/**
*
* @author Subhani
*
*/
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
CustomerDao customerDao;
public List<Customer> getCustomers() {
List<Customer> customers = customerDao.getCustomers();
return customers;
}
public List<Customer> getCustomersByCustomerNumber(Integer customerNumber) {
List<Customer> customers = customerDao.getCustomersByCustomerNumber(customerNumber);
return customers;
}
public List<Customer> getCustomersByCity(String cityName) {
List<Customer> customers = customerDao.getCustomersByCity(cityName);
return customers;
}
}
<file_sep>/src/main/java/org/subhani/ordermgmt/dao/OrderDao.java
package org.subhani.ordermgmt.dao;
import java.util.List;
import org.subhani.ordermgmt.domain.data.Order;
public interface OrderDao {
public List<Order> getOrders();
}
<file_sep>/src/main/java/org/subhani/ordermgmt/dao/impl/OrderDaoImpl.java
package org.subhani.ordermgmt.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.subhani.ordermgmt.dao.OrderDao;
import org.subhani.ordermgmt.domain.data.Order;
@Repository
public class OrderDaoImpl implements OrderDao {
@PersistenceContext
private EntityManager entityManager;
public List<Order> getOrders() {
Query query = entityManager.createQuery("SELECT a FROM Order a");
return query.getResultList();
}
}
<file_sep>/src/main/java/org/subhani/ordermgmt/dao/CustomerDao.java
package org.subhani.ordermgmt.dao;
import java.util.List;
import org.subhani.ordermgmt.domain.data.Customer;
/**
*
* @author Subhani
*
*/
public interface CustomerDao {
/**
* Retrieve all customers from the database.
* @return list customer list
*/
public List<Customer> getCustomers();
/**
* Retrieve customer details by customer number
* @param Integer customer number
* @return list customer details
*/
public List<Customer> getCustomersByCustomerNumber(Integer customerNumber);
/**
* Retrieve all customers by city name
* @param String cityName
* @return list customer list
*/
public List<Customer> getCustomersByCity(String cityName);
}
<file_sep>/src/main/java/org/subhani/ordermgmt/dao/impl/CustomerDaoImpl.java
/**
*
*/
package org.subhani.ordermgmt.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.subhani.ordermgmt.dao.CustomerDao;
import org.subhani.ordermgmt.domain.data.Customer;
/**
* @author Subhani
*
*/
@Repository
public class CustomerDaoImpl implements CustomerDao {
@PersistenceContext
EntityManager entityManager;
public List<Customer> getCustomers() {
Query query = entityManager.createNamedQuery( "getAllCustomers" );
List<Customer> customers = (List<Customer>) query.getResultList();
return customers;
}
// We are returning the result list instead of single result of Customer object as we can reuse the same JSP for all scenarios.
public List<Customer> getCustomersByCustomerNumber(Integer customerNumber) {
Query query = entityManager.createNamedQuery( "getCustomerByCustomerNumber" );
query.setParameter("customerNumber", customerNumber.intValue());
// Ideal : Customer customer = (Customer) query.getSingleResult();
List<Customer> customers = (List<Customer>) query.getResultList();
if(customers == null) {
System.out.println("No customer found.");
}
return customers;
}
public List<Customer> getCustomersByCity(String cityName) {
Query query = entityManager.createNamedQuery( "getAllCustomersByCity" );
query.setParameter("city", cityName);
List<Customer> customers = (List<Customer>) query.getResultList();
return customers;
}
}
<file_sep>/src/test/java/org/subhani/ordermgmt/controller/CustomerControllerTest.java
/**
*
*/
package org.subhani.ordermgmt.controller;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.easymock.EasyMock;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.servlet.ModelAndView;
import org.subhani.ordermgmt.domain.data.Customer;
import org.subhani.ordermgmt.service.CustomerService;
/**
* @author Subhani
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "**/applicationContext.xml" })
public class CustomerControllerTest {
private static int SIZE_ONE = 1;
private static int SIZE_ZERO = 0;
private CustomerController customerController;
private CustomerService customerService;
ModelAndView modelAndView;
@Before
public void setUp() {
customerService = EasyMock.createMock(CustomerService.class);
customerController = EasyMock.createMock(CustomerController.class);
customerController.setCustomerService(customerService);
modelAndView = new ModelAndView();
}
/**
* Test method to retrieve all customers.
* {@link org.subhani.ordermgmt.controller.CustomerController#getCustomers()}.
*/
@Test
public void testGetCustomers() {
prepareCustomerListForAll(modelAndView);
expect(customerController.getCustomers()).andReturn(modelAndView);
replay(customerController);
modelAndView = customerController.getCustomers();
assertTrue("View received", modelAndView.getViewName().equals("customers"));
assertTrue("Customer list received.",
((List) (modelAndView.getModelMap().get("customers"))) != null);
}
/**
* Test method to retrieve customer by customer number.
* {@link org.subhani.ordermgmt.controller.CustomerController#getCustomersByCustomerNumber(java.lang.Integer)}.
*/
@Test
public void testGetCustomersByCustomerNumber() {
Integer customerNumber = new Integer(103);
prepareCustomerByCustomerNumber(modelAndView, customerNumber);
expect(customerController.getCustomersByCustomerNumber(customerNumber)).andReturn(modelAndView);
replay(customerController);
modelAndView = customerController.getCustomersByCustomerNumber(customerNumber);
assertTrue("One customer found with Customer Number " + customerNumber,
((List) (modelAndView.getModelMap().get("customers"))).size() == SIZE_ONE);
}
/**
* Test method to retrieve customer by customer number where no customer
* exists for given customer number.
* {@link org.subhani.ordermgmt.controller.CustomerController#getCustomersByCustomerNumber(java.lang.Integer)}.
*/
@Test
public void testGetCustomersByCustomerNumberWhenNoRecordsFound() {
Integer customerNumber = new Integer(104);
prepareCustomerByCustomerNumber(modelAndView, customerNumber);
expect(customerController.getCustomersByCustomerNumber(customerNumber)).andReturn(modelAndView);
replay(customerController);
modelAndView = customerController.getCustomersByCustomerNumber(customerNumber);
assertTrue("Customer not found for customer number " + customerNumber,
((List) (modelAndView.getModelMap().get("customers"))) == Collections.emptyList());
}
/**
* Test method to retrieve customers by city name.
* {@link org.subhani.ordermgmt.controller.CustomerController#getCustomersByCity(java.lang.String)}.
*/
@Test
public void testGetCustomersByCity() {
String cityName = "Nantes";
prepareCustomerByCity(modelAndView, cityName);
expect(customerController.getCustomersByCity(cityName)).andReturn(modelAndView);
replay(customerController);
modelAndView = customerController.getCustomersByCity(cityName);
assertTrue("Customer list received. ",
((List) (modelAndView.getModelMap().get("customers"))) != null);
}
/**
* Class level life cycle method to shut down all the used resources.
*/
@AfterClass
public static void teardown() {
}
private void prepareCustomerListForAll(ModelAndView modelAndView) {
modelAndView.addObject("pageTitle", "All Customers");
List<Customer> customers = new ArrayList<Customer>();
modelAndView.addObject("customers", customers);
modelAndView.setViewName("customers");
}
private void prepareCustomerByCustomerNumber(ModelAndView modelAndView, Integer customerNumber) {
List<Customer> customers = new ArrayList<Customer>();
if (customerNumber == 103) {
customers.add(new Customer());
} else {
customers = Collections.emptyList();
}
modelAndView.addObject("pageTitle", "Customers Details of Customer Number " + customerNumber);
modelAndView.addObject("customers", customers);
modelAndView.setViewName("customers");
}
private void prepareCustomerByCity(ModelAndView modelAndView, String cityName) {
List<Customer> customers = new ArrayList<Customer>();
modelAndView.addObject("pageTitle", "Customers in " + cityName);
modelAndView.addObject("customers", customers);
modelAndView.setViewName("customers");
}
}
<file_sep>/src/main/java/org/subhani/ordermgmt/service/impl/OrderServiceImpl.java
package org.subhani.ordermgmt.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.subhani.ordermgmt.dao.OrderDao;
import org.subhani.ordermgmt.domain.data.Order;
import org.subhani.ordermgmt.service.OrderService;
import java.util.List;
/**
*
* @author Subhani
*
*/
@Service(value = "orderService")
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderDao orderDao;
public List<Order> getOrders() {
return orderDao.getOrders();
}
}
<file_sep>/README.md
# ordermgmt (Order Management)
A Spring MVC, JPA, Hibernate and MySQL Example <br> <br>
This is a sample Order Management application showcasing the use of below mentioned technologies. <br>
<b> Project Description </b> <br>
We have Customers who places the Orders. An Order an be placed by a Customer. Customer can place multiple orders.
There are more tables in the database which we can use for our demo in later part.
Additional configuration info:
The database with tables and data can be simply downloaded from http://www.mysqltutorial.org/mysql-sample-database.aspx and configure and keep it ready to use.
<table>
<tr>
<td> <b> User Interface </b>: </td>
<td> HTML, Bootstrap, CSS, JQuery, JQuery Plugins - Data Tables, Java Script, JSP (Java Server Pages) </td>
</tr>
<tr>
<td> <b> Middle Tier (Java / J2EE): </b> </td>
<td> Java, J2EE, JPA (Java Persistence API), Spring (Core, Context, MVC, REST), Hibernate </td>
</tr>
<tr>
<td> <b> Backend (Database) </b>: </td>
<td> HQL / SQL, MySQL </td>
</tr>
<tr>
<td> <b> Logging </b>: </td>
<td> SLF4J over Log4J </td>
</tr>
<tr>
<td> <b> Testing </b>: </td>
<td> JUnit, EasyMock </td>
</tr>
<tr>
<td> <b> Application / Web Server: </b> </td>
<td> Tomcat8 </td>
</tr>
<tr>
<td> <b> Source code repository: </b> </td>
<td> Github </td>
</tr>
</table>
<br>
<b> Sample REST URIs: </b> <br>
Retrieve all Customers: <br>
http://localhost:8080/ordermgmt/customers
Retrieve Customer by Customer Number: <br>
http://localhost:8080/ordermgmt/customers/119
Retrieve all customers within a City: <br>
http://localhost:8080/ordermgmt/customers/cities/Nantes
Retrieve all avaialble Orders: <br>
http://localhost:8080/ordermgmt/orders/all
Retrieve all Orders: <br>
http://localhost:8080/ordermgmt/orders
<file_sep>/src/main/java/org/subhani/ordermgmt/controller/CustomerController.java
package org.subhani.ordermgmt.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.subhani.ordermgmt.domain.data.Customer;
import org.subhani.ordermgmt.service.CustomerService;
/**
*
* @author Subhani
*
*/
@Controller
@RequestMapping( "/customers" )
public class CustomerController {
private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);
@Autowired
CustomerService customerService;
/**
* Get all customers from the database.
* @return ModelAndView
*/
@RequestMapping(method = RequestMethod.GET)
public ModelAndView getCustomers() {
logger.debug("Request received for to get all customers." );
ModelAndView modelAndView = new ModelAndView();
List<Customer> customers = customerService.getCustomers();
modelAndView.addObject("pageTitle", "All Customers");
modelAndView.addObject("customers", customers);
modelAndView.setViewName("customers");
return modelAndView;
}
/**
* Get customer details by customer number.
* @param customerNumber
* @return ModelAndView
*/
@RequestMapping( value = "/{customerNumber}", method = RequestMethod.GET)
public ModelAndView getCustomersByCustomerNumber(@PathVariable Integer customerNumber) {
logger.debug("Request received for to get a customer details for customer: " + customerNumber);
ModelAndView modelAndView = new ModelAndView();
List<Customer> customers = customerService.getCustomersByCustomerNumber(customerNumber);
modelAndView.addObject("pageTitle", "Customers Details of Customer Number " + customerNumber);
modelAndView.addObject("customers", customers);
modelAndView.setViewName("customers");
return modelAndView;
}
/**
* Get all customers by city name.
* @param cityName
* @return ModelAndView
*/
@RequestMapping( value = "/cities/{cityName}", method = RequestMethod.GET)
public ModelAndView getCustomersByCity(@PathVariable String cityName) {
logger.debug("Request received for to get all customers in the city: " + cityName);
ModelAndView modelAndView = new ModelAndView();
List<Customer> customers = customerService.getCustomersByCity(cityName);
modelAndView.addObject("pageTitle", "Customers in " + cityName);
modelAndView.addObject("customers", customers);
modelAndView.setViewName("customers");
return modelAndView;
}
public CustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
}
|
f29620d7ace969f38eb9a258bea71ec58dcb6963
|
[
"Markdown",
"Java"
] | 9
|
Java
|
sksubhani/ordermgmt
|
30794a5166424f886b3da7e3707fe156381e0d78
|
91165c3c77ab708b489f1e679fc815d16f7684e7
|
refs/heads/main
|
<file_sep># Virtual-Dressing-Room
Built by -
<NAME>, <NAME>, <NAME> and <NAME>
<file_sep>
# Project Automated Wardrobe main.py file
from tkinter import *
from PIL import Image, ImageTk
import cv2
import requests
import os
import json
#***********************************************************************
#SpeechRegonition imported modules
import os
import time
import playsound
import speech_recognition as sr
from gtts import gTTS
#*** All Modules imported till here **************************************
checker = True
avoid_repetions_of_cloth = 0
#******************************************** Speech_recog functions Code Here **************************************************
def speak(text , mp3_file_number):
tts = gTTS(text=text , lang="en")
filename = "voice" + mp3_file_number + ".mp3"
tts.save(filename)
playsound.playsound(filename)
speak("Hey! How are you doing? I am bot and i will be guiding you througout the application",str(0))
speak("Let me brief you about the project idea, We will take your cloths input from your wardrobe and help you to figure out which one to wear today",str(1))
#speak("good",str(1))
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception : " + str(e))
return said
#get_audio()
#************************* SpeechRecog_ functions ends here *******************************************************************
#****SpeechRecog_ Interaction with the user***************************************************************************************
output = []
speak("Are you an existing user?",str(2))
user_answer1 = get_audio()
speak("Can you please enter your name in the terminal",str(3))
user_name_temp = input("Enter Your name here : ")
user_name = "/" + user_name_temp
prompt_to_user = "Hi " + user_name + "! I am assigned to help you, Do you need my help?"
#THIS IF CONTAINS CODE TO HANDLE THE EXISTING USER
if "yes" in user_answer1:
speak("hi"+ user_name +"how are you?,I hope you are doing good",str(4))
speak("I am looking for your digital wardrobe till then please wait!", str(5))
speak("Thank you for waiting,I found your wardrobe i am good to go",str(6))
speak("Can you please tell your city name?",str(7))
user_city = get_audio();
# API call for the temperature
# *************************************************************************************
# Enter your API key here
temperature_integral_value = -1
api_key = "e376bdd305b3501ab3ed789f7a1a2787"
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"
# Give city name
city_name = user_city
# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
# get method of requests module
# return response object
response = requests.get(complete_url)
# json method of response object
# convert json format data into
# python format data
x = response.json()
# Now x contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if x["cod"] != "404":
# store the value of "main"
# key in variable y
y = x["main"]
# store the value corresponding
# to the "temp" key of y
current_temperature = y["temp"]
temperature_in_cel = int(current_temperature) - 273
# store the value corresponding
# to the "humidity" key of y
current_humidiy = y["humidity"]
# print following values
print("Temperature (Celcius) = " + str(temperature_in_cel))
print("Humidity = " + str(current_humidiy))
else:
print("City Not Found ")
# ***************************************************************************************************
# APi call ends Here
temperature_integral_value = temperature_in_cel
prompt_to_user2 = "oh" + user_city + "is a beautiful city, I have few friends there"
speak(prompt_to_user2, str(8))
speak("Please wait, I am searching your wardrobe",str(9))
# Deciding the season based on the temperature
season = "none"
if 0 <= temperature_integral_value <= 18:
season = "Exterme Winter"
elif 19 <= temperature_integral_value <= 24:
season = "Winter"
elif 25 <= temperature_integral_value <= 34:
season = "summer"
elif 35 <= temperature_integral_value <= 39:
season = "Extreme Summer"
else:
season = "none"
# season decided
speak("Oh i got one match for today,It will pop up in new window", str(10))
speak("Thank you for using my service I hope you have great day ahead",str(11))
# creating address manually and poping up wear
if season == "Exterme Winter":
if (avoid_repetions_of_cloth > 5):
avoid_repetions_of_cloth = 0
pic_address = r"C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images" + user_name + "\sw" + str(0) + ".jpg"
avoid_repetions_of_cloth += 1
img = cv2.imread(pic_address, -1)
cv2.imshow('Your_Wear_For_Today', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(pic_address)
elif season == "Winter":
if (avoid_repetions_of_cloth > 5):
avoid_repetions_of_cloth = 0
pic_address = r"C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images" + user_name + "\swt" + str(0) + ".jpg"
avoid_repetions_of_cloth += 1
img = cv2.imread(pic_address, -1)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(pic_address)
elif season == "summer":
if (avoid_repetions_of_cloth > 5):
avoid_repetions_of_cloth = 0
pic_address = r"C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images" + user_name + r"\fullsv" + str(0) + ".jpg"
avoid_repetions_of_cloth += 1
img = cv2.imread(pic_address, -1)
cv2.imshow('Your_Wear_For_Today', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(pic_address)
elif season == "Extreme Summer":
if (avoid_repetions_of_cloth > 5):
avoid_repetions_of_cloth = 0
pic_address = r"C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images" + user_name + "\halfsv" + str(0) + ".jpg"
avoid_repetions_of_cloth += 1
img = cv2.imread(pic_address, -1)
cv2.imshow('Your_Wear_For_Today', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(pic_address)
else:
print("Sorry, even I am confused now ")
print("\nThank You !")
# address creation done and new window opens with todays wear pic
# THIS WILL ELSE WILL HANDEL NEW USERS
else:
speak("Ok,i will help you to setup your digital wardrobe", str(4))
speak("Please create a new folder with your name at the provided location, the location is displayed at the terminal",str(5))
print(r"Location --> C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images")
input("Please press enter once you created folder : ")
speak("Once your folder is created you can proceed further in one of the ways, either I will guide you or you can use our graphical user interface service",str(6))
speak(prompt_to_user, str(12))
user_choice_to_use = get_audio()
if "yes" in user_choice_to_use :
output.append("Y")
speak("Ohh you need my help, Ok i will guide you",str(13))
speak("welcome to the automated wardobe",str(14))
speak("How would you like to give your cloth input option one manually option two by image capturing", str(15))
user_answer3 = get_audio()
if "manually" in user_answer3:
speak("Ok, please save your cloths photos in your folder", str(16))
output.append(1)
else:
output.append(2)
speak("Alright webcam will open later and it will click photos one by one",str(17))
speak("Can you please provide me with following data which is displayed at the terminal", str(18))
output.append(input("Enter number of sweaters you have"))
output.append(input("Enter number of sweatshirts you have"))
output.append(input("Enter number of full sleeve t-shirt/shirts you have"))
output.append(input("Enter number of half sleeve t-shirt/shirts you have"))
speak("Oh same pinch even i have " + output[2] + "sweaters",str(19))
speak("thank you for providing your data, I am allotting space for your digital wardrobe",str(20))
output.append(2)
speak("Can you tell me in which city you are in?",str(21))
user_city = (get_audio())
output.append(user_city)
prompt_to_user3 = "oh" + user_city + "is a beautiful city, I have few friends there"
speak(prompt_to_user3,str(22))
speak("Please wait i am reading wheather forecast of " + user_city , str(23))
else :
speak("Ohh you don't need my help, Ok new window will pop up and that will guide you,Thanks for listening me ,i am signing off",str(13))
# **************************************************************************************************************************************
# GUI CODE HERE
def save():
text = e1.get() + "\n" + e2.get() + "\n" + e3.get() + "\n" + e4.get() + "\n" + e5.get() + "\n" + e6.get() + "\n" + e7.get() + "\n" + e8.get()
with open("test.txt", "w") as f:
f.writelines(text)
def show():
with open("test.txt", "r") as f:
f.readlines()
e1.get(f.seek(0))
e2.get(f.seek(1))
e3.get(f.seek(2))
e4.get(f.seek(3))
e5.get(f.seek(4))
e6.get(f.seek(5))
e7.get(f.seek(6))
e8.get(f.seek(7))
master = Tk(className="Automated wardrobe")
master.geometry("600x600")
# master.config(bg='black')
load = Image.open(r'C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images\shivaay1.jpeg')
render = ImageTk.PhotoImage(load)
img = Label(master, image=render)
img.place(x=0, y=0)
Label(master, text="i.Would you like to give your clothes collection?\n(Y/N)", padx=10, pady=10).grid(row=3,
column=0)
Label(master, text="ii.Would you like to give your cloyhes collection?\nManually(1)\nImage processing(2)", padx=10,
pady=10).grid(row=4)
Label(master, text="iii.Enter the number of sweater you have.", padx=10, pady=10).grid(row=5)
Label(master, text="iv.Enter the number of sweatshirt you have.", padx=10, pady=10).grid(row=6)
Label(master, text="v.Enter the number of full sleev shirt/t-shirt you have.", padx=10, pady=10).grid(row=7)
Label(master, text="vi.Enter the number of half sleev shirt/t-shirt you have.", padx=10, pady=10).grid(row=8)
Label(master, text="vii.Which way you want to take temperature of city.\nManually(1)\nAutomatically(2)", padx=10,
pady=10).grid(row=9)
Label(master,
text="If you chose manually please enter temperature of your city \nOR\n If you chose Automatically please enter city name",
padx=10, pady=10).grid(row=10)
e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master)
e4 = Entry(master)
e5 = Entry(master)
e6 = Entry(master)
e7 = Entry(master)
e8 = Entry(master)
e1.grid(row=3, column=1)
e2.grid(row=4, column=1)
e3.grid(row=5, column=1)
e4.grid(row=6, column=1)
e5.grid(row=7, column=1)
e6.grid(row=8, column=1)
e7.grid(row=9, column=1)
e8.grid(row=10, column=1)
Button(master, text='Save', command=save, bg="red", font="comicsansms 20 bold").grid(row=12, column=1, sticky=W,
pady=6)
Button(master, text='Exit', command=master.destroy, bg="gray", font="comicsansms 20 bold").grid(row=12, column=2,
sticky=W, pady=6)
mainloop()
file = open("test.txt", "r")
# output=[]
for line in file:
output.append(line.strip())
print(output)
file.close()
# *******************************************************************************************************************************************
# GUI CODE ENDS HERE
print(" WELCOME TO AUTOMATED WARDROBE")
yes_or_no = output[0]
if yes_or_no == "Y":
opt_selection = int(output[1])
# list for variety of cloths user has
varierty_of_cloth = ["Sweaters", "Sweatshirts", "Full_Sleeve_T-Shirts/Shirts", "Half_Sleeve_T-Shirts/Shirts"]
varities = len(varierty_of_cloth)
# abb for the cloths to save name for addressing
abb_for_cloth = ["sw" , "swt" , "fullsv" , "halfsv"]
number_of_sweaters = int (output[2])
number_of_sweatshirts = int (output[3])
number_of_fullsleeve_shirts_tshirts = int (output[4])
number_of_halfsleeve_shirts_tshirts = int (output[5])
#quantity of each variety clothes
quantity_of_cloth = [number_of_sweaters, number_of_sweatshirts, number_of_halfsleeve_shirts_tshirts , number_of_fullsleeve_shirts_tshirts]
if opt_selection == 1:
# taking cloth input
print("Please copy and paste the collected pics in the project folder, manually")
print("Thank You for Your Input \n")
# cloth input taken
elif opt_selection == 2:
print("We will be using your webcam for this process , Thank You !\n")
#Taking pics from webcam and saving in folder
# **********************************************************************************************
for k in range(varities):
print("Please click all "+ varierty_of_cloth[k] + " one by one : ")
i = quantity_of_cloth[k]
j = -1
current_running = True
while current_running:
j += 1
videoCaptureObject = cv2.VideoCapture(0)
result = True
while (result):
ret, frame = videoCaptureObject.read()
cv2.imwrite("NewPicture.jpg", frame)
result = False
videoCaptureObject.release()
cv2.destroyAllWindows()
img = cv2.imread("NewPicture.jpg", -1)
cv2.imshow('Just_clicked', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = cv2.imread('NewPicture.jpg', 1)
path = r'C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images' + user_name
cv2.imwrite(os.path.join(path, abb_for_cloth[k] + str(j) + '.jpg'), img)
cv2.waitKey(0)
if j >= i-1:
current_running = False
#*************************************************************************************************************************
# image clicked till here
# creating address for cloths
address_to_sweaters = []
address_to_sweatshits = []
address_to_full_sleeve = []
address_to_half_sleeve = []
for i in range(number_of_sweaters):
address_to_sweaters.append(i)
for i in range(number_of_sweatshirts):
address_to_sweatshits.append(i)
for i in range(number_of_fullsleeve_shirts_tshirts):
address_to_full_sleeve.append(i)
for i in range(number_of_halfsleeve_shirts_tshirts):
address_to_half_sleeve.append(i)
# addressing done
# asking for temperature
choice = int(output[6])
temperature_integral_value = -1
while(True):
if choice == 1:
temp = output[7]
temperature_integral_value = int(temp)
break
elif choice == 2:
print("Dont worry we will read wheather report for you")
#API call for the temperature
#*************************************************************************************
# Enter your API key here
api_key = "e376bdd305b3501ab3ed789f7a1a2787"
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"
# Give city name
city_name = output[7]
# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
# get method of requests module
# return response object
response = requests.get(complete_url)
# json method of response object
# convert json format data into
# python format data
x = response.json()
# Now x contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if x["cod"] != "404":
# store the value of "main"
# key in variable y
y = x["main"]
# store the value corresponding
# to the "temp" key of y
current_temperature = y["temp"]
temperature_in_cel = int(current_temperature) - 273
# store the value corresponding
# to the "humidity" key of y
current_humidiy = y["humidity"]
# print following values
print("Temperature (Celcius) = " + str(temperature_in_cel))
print("Humidity = " + str(current_humidiy))
else:
print("City Not Found ")
#***************************************************************************************************
#APi call ends Here
temperature_integral_value = temperature_in_cel
break
else:
choice = int(input("Invalid Input , Please provide input again : "))
# temperature taken
# temp_speak_to_user = "Oh, It is " + str(temperature_in_cel) + "Celcius temperature at" + user_city
# speak(temp_speak_to_user,str(24))
# Deciding the season based on the temperature
season = "none"
if 0 <= temperature_integral_value <=18:
season = "Exterme Winter"
elif 19 <= temperature_integral_value <= 24:
season = "Winter"
elif 25<= temperature_integral_value <= 34:
season = "summer"
elif 35<= temperature_integral_value <= 39:
season = "Extreme Summer"
else:
season = "none"
# season decided
season_speak_to_user = "Oh its " + season + " according to me,I am looking for something good in your digital wardrobtill then please wait"
# speak(season_speak_to_user,str(25))
#speak("Oh,I found one match it will pop up in new window,Please have a look",str(26))
print("Check Your Wear for Today in new window :--")
#temp_speak_to_user = "Oh, It is " + str(temperature_in_cel) + "Celcius temperature at" + user_city
#speak(temp_speak_to_user, str(24))
season_speak_to_user = "Oh its " + season + " according to me,I am looking for something good in your digital wardrobtill then please wait"
speak(season_speak_to_user, str(25))
speak("Oh,I found one match it will pop up in new window,Please have a look", str(26))
# creating address manually and poping up wear
if season == "Exterme Winter":
if(avoid_repetions_of_cloth>number_of_sweaters):
avoid_repetions_of_cloth = 0
pic_address = r"C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images"+ user_name +"\sw" + str(address_to_sweaters[avoid_repetions_of_cloth]) + ".jpg"
avoid_repetions_of_cloth+= 1
img = cv2.imread(pic_address, -1)
cv2.imshow('Your_Wear_For_Today', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(pic_address)
elif season == "Winter":
if(avoid_repetions_of_cloth>number_of_sweatshirts):
avoid_repetions_of_cloth = 0
pic_address = r"C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images" + user_name + "\swt" + str(address_to_sweatshits[avoid_repetions_of_cloth]) + ".jpg"
avoid_repetions_of_cloth+= 1
img = cv2.imread(pic_address,-1)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(pic_address)
elif season == "summer":
if(avoid_repetions_of_cloth>number_of_fullsleeve_shirts_tshirts):
avoid_repetions_of_cloth = 0
pic_address = r"C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images" + user_name +r"\fullsv" + str(address_to_full_sleeve[avoid_repetions_of_cloth]) + ".jpg"
avoid_repetions_of_cloth+= 1
img = cv2.imread(pic_address, -1)
cv2.imshow('Your_Wear_For_Today', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(pic_address)
elif season == "Extreme Summer":
if(avoid_repetions_of_cloth>number_of_halfsleeve_shirts_tshirts):
avoid_repetions_of_cloth = 0
pic_address = r"C:\Users\saura\PycharmProjects\pythonProjectAutoMated\Images" + user_name + "\halfsv" + str(address_to_half_sleeve[avoid_repetions_of_cloth])+".jpg"
avoid_repetions_of_cloth+= 1
img = cv2.imread(pic_address, -1)
cv2.imshow('Your_Wear_For_Today', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(pic_address)
else:
print("Sorry , even I am confused now ")
print("\nThank You !")
# address creation done and new window opens with todays wear pi
speak("thank You for using our service",str(27))
|
bac633ed670a51b829535c714912d61e5a85c6e8
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
shivanisorte/Virtual-Dressing-Room
|
a85fb503eb86601570d9f23fdf0d14aa9ab7097d
|
7df80f08d55257713e8988183222ac759f1e8352
|
refs/heads/master
|
<repo_name>EccRiley/CommPsy-SysLitRvw<file_sep>/cluster-populations.R
#' ---
#' title: "Cluster Analysis - Focal Populations \\& Sampling Frames"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#' \Frule
#'
#+ echo=FALSE
knitr::opts_template$set(invisible = list(echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE, fig.keep='none', fig.show='none'))
knitr::opts_chunk$set(fig.path="graphics/cluster/rplot-")
#'
#+ srcbibs, opts.label='invisible'
source("QCA.R")
#'
#' \newpage
#'
#' # Cluster - Populations
#'
#+ hclust_pops
pop <- cb[cb$cat == "POPULATION", ] %>% droplevels()
pop$bibkey <- paste0("@", pop$bibkey)
Rtdf(pop$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(align = c("l", "r"))
popmat <- ftable(pop$bibkey, pop$cid) %>% as.matrix
popmatpr <- ftable(pop$bibkey, pop$clab) %>% as.matrix()
popmatt <- t(popmat)
kable(Rmsmm(as.data.frame(popmatpr)))
kable(Rmsmm(as.data.frame(popmatt)))
popdist <- dist(popmat)
Rmsmm(popdist)
popclust <- hclust(popdist, method = "ward.D2")
# names(popclust)
# popclust$merge
# popclust$height
# popclust$order
# popclust$labels
palette(pal_my)
par(mar = c(0,2,2,1))
plot(popclust, sub = ' ', xlab = ' ', main = "Populations Clusters",
frame.plot = F, col = 19, cex = .75, cex.main = 0.75,
cex.lab = 0.75, cex.axis = 0.65)
abline(a = 3, b = 0, lty = 3, lwd = 1.5,
col = adjustcolor(pal_my[19], alpha.f = 0.75))
rect.hclust(popclust, h = 3, border = "#3B0C67") -> rhcl
popGrps <- cutree(popclust, 3)
barplot(table(popGrps), col = pal_sci[1], border = pal_sci[1], main = "Cluster Member Counts - Populations", xlab = ' ', cex = 1.25, cex.main = 1.15, cex.lab = 1, cex.axis = 0.85)
as.data.frame(table(popGrps)) %>%
dplyr::rename(Group = popGrps, Nmembers = Freq) %>% ## 'rename()' {dplyr} args: [output]=[input]
kable(caption = "3-Group Solution Membership Counts (Populations)")
popmembers <- sapply(unique(popGrps),function(g) paste(rownames(popmat)[popGrps == g]))
names(popmembers) <- paste0("Group.", seq_along(popmembers))
popmembers <- t(t(popmembers))
names(popmembers) <- "Group Members"
pander(popmembers, caption = "Group Memberships Resulting from 4-Group Hierarchical Cluster Solution (Populations)")
#'
#+ kclust_pops
library(cluster)
popkfit <- kmeans(popmat, 3)
palette(pal_sci)
clusplot(popmat, popkfit$cluster, main = '3-Cluster K-Means Solution (Populations)',
color = T, shade = T,
labels = 0, lines = 1, col.p = pal_my[19], font.main = 3, verbose = T, span = T)
pander(t(popkfit$centers), caption = "Per Variable Cluster Means ('centers') for 3-Cluster K-Means Solution (Populations)")
popkpam <- pam(popmat, 3) ## k = n-groups ##
popsil <- silhouette(popkpam)
plot(popsil, main = "Silhouette Plot of 3-Cluster Solution\n(Populations)", font.main = 3, do.n.k = T, col = mpal(1:4, p = grays), cex = 0.5)
popCluster <- c(seq(1:3))
popkpam.clus <- round(popkpam$clusinfo, 2)
popkpam.clus <- cbind(popCluster, popkpam.clus)
popkpam.cwidth <- popkpam$silinfo[2]
popkpam.cwidth <- cbind(popCluster, round(popkpam.cwidth[[1]], 2))
popkpam.sil <- round(popkpam$silinfo[[1]], 5)
popCase <- rownames(popkpam.sil)
popkpam.sil <- cbind(popCase, popkpam.sil)
kable(popkpam.clus, col.names = c("Cluster", "Size", "$Max_{Dissimilarity}$", "$\\mu_{Dissimilarity}$", "Diameter", "Separation"), align = c("c", rep("r", ncol(popkpam.clus) - 1)), caption = "K-pam Cluster Descriptives (Populations)")
names(popkpam$silinfo) <- c("Cluster Width", "$\\mu_{Cluster Width}", "\\mu_{Width_{Overall}}")
kable(popkpam.cwidth, caption = "Cluster Widths for 3-Cluster PAM Solution (Populations)", col.names = c("Cluster", "Width"), align = c("c", "r"))
kable(popkpam.sil, col.names = c("Case", "Cluster", "Neighbor", "Silhouette Width"), caption = "Silouette Information Per Case (Populations)", row.names = FALSE)
#'
#' \newpage
#'
#' # References
#'
#' \refs
#'
<file_sep>/data/incl.R
csid.all <- csid$caseid
incl <- MAP$caseid
csid.excl <- as.numeric(!csid.all %in% incl)
csid.incl <- as.numeric(csid.all %in% MAP$caseid)
csattr.INCL <- data.frame(id = csid.all, name = csid$case, INCL = csid.incl, EXCL = csid.excl)
csattr.INCL$x <- ifelse(csattr.INCL$INCL == 1, "INCLUDE", "X")
# write.csv(csattr.INCL, "data/SQL/RQDA-MAP-SQL/MAP-caseAttr-INCL.csv", row.names = FALSE)
dat <- read.csv("data/SQL/RQDA-MAP-SQL/MAP-caseAttr-INCL.csv")
dat <- dat[, c("SQL.prepend", "INCL", "id", "SQL.append")]
write.csv(dat, "data/SQL/RQDA-MAP-SQL/MAP-caseAttr-INCL-2.csv", row.names = FALSE)
<file_sep>/_comps_docs/_zmisc/MAP-AppB-TEMPLATE-LitDesc.Rmd
---
title: Appendix B. Literature Description & Data Extraction Form
author: <NAME>
date: NULL
---
```{r setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE}
# source("../SETUP.R")
knitr::opts_chunk$set(
tidy = FALSE,
echo = FALSE,
fig.keep = 'high',
fig.show = 'hold',
results = 'asis'
)
sm <- function(x) {
if (knitr:::is_latex_output()) {
sprintf("\\small{%s}", x)
} else {
sprintf("<span style=\"font-size:75\%;\">%s</span>", x)
}
}
```
\newpage
# Citation
# Substantive Research Topic(s)
\Frule
`r tufte::newthought("Study Purpose(s)")`
`r tufte::newthought("Research Question(s) (RQs)")`
\vspace*{-0.25em}
\hspace*{1em} _`r sm("Including theoretical model(s) (if applicable)")`_
`r tufte::newthought("Hypotheses")`
\vspace*{-0.25em}
\hspace*{1em} _`r sm("Including hypothesized/statistical model(s) (if applicable)")`_
\tufteskip
# Target Population(s) & Sampling Frame(s)
\Frule
## Target Population(s)
\vspace*{-0.5em}
\hspace*{1em} _`r sm("By Level of Specificity")`_
`r tufte::newthought("Includes")`
`r tufte::newthought("Excludes")`
## Sampling Frame Setting(s)
\tufteskip
## Sampling Frame (By Level of Specificity)
`r tufte::newthought("Includes")`
`r tufte::newthought("Excludes")`
\tufteskip
# Sampling Method(s) (By Sampling Frame Level)
\Frule
\parindent=1em\ $\square$ Probability/Random
\parindent=1em\ $\square$ Purposive
\parindent=1em\ $\square$ Convenience
\tufteskip
# Study Design(s)
\Frule
## Qua**L**itative Research Designs
\vspace*{-0.5em}
\hspace*{1em} _`r sm("(if applicable)")`_
<!-- \hspace*{1em} $\square$ Multi-method design -->
\parindent=1em\ $\square$ \textsc{Grounded Theory}
\parindent=1em\ $\square$ \textsc{Phenomenology}
\parindent=1em\ $\square$ \textsc{Ethnography}
\parindent=1em\ $\square$ \textsc{Case-Study}
\parindent=1em\ $\square$ \textsc{Narrative/Descriptive}
\parindent=2.25em\ $\square$ Biographical
\parindent=2.25em\ $\square$ Historical
## Qua**NT**itative Research Designs
\vspace*{-0.5em}
\hspace*{1em} _`r sm("(if applicable)")`_
\parindent=1em\ $\square$ \textsc{Experimental}
\parindent=2.5em\ $\square$ Longitudinal
\parindent=2.5em\ $\square$ Pre-Post
\parindent=2.5em\ $\square$ \textsc{Randomized Control Trial (RCT)}
\parindent=3.25em\ $\square$ RCT - Longitudinal
\parindent=3.25em\ $\square$ RCT - Pre-Post
\parindent=1em\ $\square$ \textsc{Quasi-Experimental}
\parindent=1em\ $\square$ \textsc{Cross-Sectional}
# Methodology
\Frule
\parindent=1em\ $\square$ \textsc{Qualitative}
\parindent=1em\ $\square$ \textsc{Quantitative}
\parindent=1em\ $\square$ \textsc{Mixed-Methods}
\tufteskip
# Data Collection Method(s) / Data Source(s)
\vspace*{-0.5em}
\hspace*{1em} _`r sm("By Sampling Frame Level \\& Methodology")`_
\Frule
`r tufte::newthought("Measure(s)")`
`r tufte::newthought("Archival / Secondary Data Source(s)")`
\tufteskip
# Data Analytic Approach(es)
\Frule
\tufteskip
\newpage
# Key Findings
\Frule
`r tufte::newthought("Sample Characteristics")`
\vspace*{-0.25em}
\hspace*{1em} _`r sm("By sampling frame level \\& methodology")`_
`r tufte::newthought("Findings")`
\vspace*{-0.25em}
\hspace*{1em} _`r sm("by methodology \\& hypothesis/RQ")`_
\tufteskip
# Social Ecological Levels of Analysis
\Frule
\parindent=1em\ $\square$ \textsc{Individual}
\parindent=1em\ $\square$ \textsc{Relationship}
\parindent=1em\ $\square$ \textsc{Community}
\parindent=1em\ $\square$ \textsc{Societal}
\SFrule
{#fig:sem}
`r tufte::quote_footer("--- @centers2015social; @dahlberg2002violence")`
\newpage
\refs
<file_sep>/auxDocs/tft_postprocessor.R
tft <- function(..., knitr, opts_hooks, opts_knit, i, hook_plot_md, knit_engines) {
format = html_document(theme = NULL, ...)
# when fig.margin = TRUE, set fig.beforecode = TRUE so plots are moved before
# code blocks, and they can be top-aligned
ohooks = knitr::opts_hooks$set(fig.margin = function(options) {
if (isTRUE(options$fig.margin)) options$fig.beforecode = TRUE
options
})
post_processor = format$post_processor
format$post_processor = function(metadata, input, output, clean, verbose) {
if (is.function(post_processor))
output = post_processor(metadata, input, output, clean, verbose)
knitr::opts_hooks$restore(ohooks)
x = readUTF8(output)
fn_label = paste0(knitr::opts_knit$get('rmarkdown.pandoc.id_prefix'), 'fn')
footnotes = tufte:::parse_footnotes(x)#, fn_label)
notes = footnotes$items
# replace footnotes with sidenotes
for (i in seq_along(notes)) {
num = sprintf(
'<a href="#%s%d" class="footnoteRef" id="%sref%d"><sup>%d</sup></a>',
fn_label, i, fn_label, i, i
)
con = sprintf(paste0(
'<label for="tufte-sn-%d" class="margin-toggle sidenote-number"></label>',
# '<label for="tufte-sn-%d" class="margin-toggle sidenote-number">%d</label>',
'<input type="checkbox" id="tufte-sn-%d" class="margin-toggle">',
'<span class="sidenote">%s</span>'
# '<span class="sidenote"><span class="sidenote-number">%d</span> %s</span>'
), i, i, notes[i])
x = gsub_fixed(num, con, x)
}
# remove footnotes at the bottom
if (length(footnotes$range)) x = x[-footnotes$range]
# replace citations with margin notes
x = margin_references(x)
# place figure captions in margin notes
x[x == '<p class="caption">'] = '<p class="caption marginnote shownote">'
# move </caption> to the same line as <caption>; the previous line should
# start with <table
for (i in intersect(grep('^<caption>', x), grep('^<table', x) + 1)) {
j = 0
while (!grepl('</caption>$', x[i])) {
j = j + 1
x[i] = paste0(x[i], x[i + j])
x[i + j] = ''
}
}
# place table captions in the margin
r = '^<caption>(.+)</caption>$'
for (i in grep(r, x)) {
# the previous line should be <table> or <table class=...>
if (!grepl('^<table( class=.+)?>$', x[i - 1])) next
cap = gsub(r, '\\1', x[i])
x[i] = x[i - 1]
x[i - 1] = paste0(
'<p><!--\n<caption>-->', '<span class="marginnote shownote">',
cap, '</span><!--</caption>--></p>'
)
}
# add an incremental number to the id of <label> and <input> for margin notes
r = '(<label|<input type="checkbox") (id|for)(="tufte-mn)-(" )'
m = gregexpr(r, x)
j = 1
regmatches(x, m) = lapply(regmatches(x, m), function(z) {
n = length(z)
if (n == 0) return(z)
if (n %% 2 != 0) warning('The number of labels is different with checkboxes')
for (i in seq(1, n, 2)) {
if (i + 1 > n) break
z[i + (0:1)] = gsub(r, paste0('\\1 \\2\\3-', j, '\\4'), z[i + (0:1)])
j <<- j + 1
}
z
})
# restore blockquote footer from <span class="blockquote footer">
r = '^<p><span class="blockquote footer">(.+)</span></p>$'
i = grep(r, x)
x[i] = gsub(r, '<footer>\\1</footer>', x[i])
writeUTF8(x, output)
output
}
if (is.null(format$knitr$knit_hooks)) format$knitr$knit_hooks = list()
format$knitr$knit_hooks$plot = function(x, options) {
# make sure the plot hook always generates HTML code instead of ![]()
if (is.null(options$out.extra)) options$out.extra = ''
fig_margin = isTRUE(options$fig.margin)
fig_fullwd = isTRUE(options$fig.fullwidth)
if (fig_margin || fig_fullwd) {
if (is.null(options$fig.cap)) options$fig.cap = ' ' # empty caption
} else if (is.null(options$fig.topcaption)) {
# for normal figures, place captions at the top of images
options$fig.topcaption = TRUE
}
res = knitr::hook_plot_md(x, options)
if (fig_margin) {
res = gsub_fixed('<p class="caption">', '<!--\n<p class="caption marginnote">-->', res)
res = gsub_fixed('</p>', '<!--</p>-->', res)
res = gsub_fixed('</div>', '<!--</div>--></span></p>', res)
res = gsub_fixed(
'<div class="figure">', paste0(
'<p>', '<span class="marginnote shownote">', '<!--\n<div class="figure">-->'
), res
)
} else if (fig_fullwd) {
res = gsub_fixed('<div class="figure">', '<div class="figure fullwidth">', res)
res = gsub_fixed(
'<p class="caption">', '<p class="caption marginnote shownote">', res
)
}
res
}
knitr::knit_engines$set(marginfigure = function(options) {
options$type = 'marginnote'
if (is.null(options$html.tag)) options$html.tag = 'span'
options$html.before = marginnote_html()
eng_block = knitr::knit_engines$get('block')
eng_block(options)
})
format$inherits = 'html_document'
format
}
Rhtout <- function() {
htouts <- list.files(pattern = "\\.html")
htouts_in <- sapply(htouts, readLines, encoding = "UTF-8")
for (i in 1:length(htouts_in)){
htouts_in[[i]] <- gsub("about_files/tufte\\-css\\-2015\\.12\\.29/tufte\\.css",
"auxDocs/riley.css", htouts_in[[i]],
fixed = FALSE, perl = TRUE, useBytes = TRUE)
htouts_in[[i]] <- gsub("about_files",
"auxDocs", htouts_in[[i]],
fixed = FALSE, perl = TRUE, useBytes = TRUE)
writeLines(htouts_in[[i]], htouts[i], useBytes = TRUE)
}
}
Rsite <- function(...) {
rmarkdown::render_site(output_format = tufte::tufte_html(self_contained = FALSE), encoding = 'UTF-8', ...)
tft()
Rhtout()
}
# gsub("(.*?)\\.html", "\\1_2.html", htouts_in[1]
<file_sep>/_comps_docs/_zmisc/MAPqca.R
#' ---
#' title: "MAP - Qualitative Comparative Analyses"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', fig.keep='none', fig.show='none', message=FALSE, warning=FALSE, cache=FALSE
# SETUP --------------------------------------------------------------
source("bibs_cp.R", echo = FALSE, print.eval = FALSE, verbose = FALSE)
knitr::opts_chunk$set(fig.path = "graphics/bibkeys_cp/rplot-")
# options(warn = -1)
#'
#' \Frule
#'
#' \newpage
#'
<file_sep>/_comps_docs/_bibkeys_new.R
#'
#' # Case-by-Case Timeline of Included Literature
#'
#+ echo=FALSE
par(mpar)
knitr::opts_chunk$set(fig.path = "graphics/bibkeys/rplot-",
fig.show = 'asis')#, echo = TRUE)
# options(warn = -1)
#'
#' \Frule
#'
#' \newpage
#'
#'
#+ tl_map, fig.fullwidth=TRUE, fig.width=7, out.width='\\linewidth', fig.align='center', figPath=TRUE
# PLOT - MAPtl ----------------
MAP <- MAP[, c("bibkey", "year", "journal", "caseid", "scat", "jrnl", "cpv", "j.loc", "j.year", "SJR", "Hindex", "title")]
MAPtl <- within(MAP, {
## - making a copy so i don't mess up anything already
## written below that may depend on the original
## version of "MAP" ##
# bibkey2 <- as.integer(factor(bibkey))
bibkey2 <- ifelse(bibkey == "boal2014barriers", "boala2014barriers", bibkey)
bibkey2 <- ifelse(bibkey2 == "boal2014impact", "boalb2014impact", bibkey2)
bibkey2 <- gsub("(\\w+)(\\d{4})\\w+", "\\1 (\\2)", bibkey2)
bibkey2 <- ifelse(bibkey == "boala (2014)", "boal (2014a)", bibkey2)
bibkey2 <- ifelse(bibkey == "boalb (2014)", "boal (2014b)", bibkey2)
bibkey2 <- sapply(bibkey2, RtCap, USE.NAMES = FALSE)
yrv <- ifelse(cpv == "V", year, 0)
yrcp <- ifelse(cpv == "CP", year, 0)
cpv <- factor(cpv, labels = c("Community-Psychology", "Violence"))
})
MAPtl <- MAPtl[order(MAPtl$yrv), , drop = FALSE] %>% within({
posv <- sequence(rle(sort(yrv))$lengths)
posv <- ifelse(yrv == 0, 0, posv)
posv <- log(posv + 0.5) * -0.5
})
MAPtl <- MAPtl[order(MAPtl$yrcp), , drop = FALSE] %>% within({
poscp <- sequence(rle(sort(yrcp))$lengths)
pos <- ifelse(yrcp == 0, posv, log(poscp - 0.5) * -0.5)
# pos <- jitter(pos, amount = 0)
## could've achieved the same in the previous line,
## but wanted to preserve the separate pos* columns just in case ##
})
## !!!! THANKS TO THIS SO ANSWER FOR THE "sequence(rle())" solution:
## http://stackoverflow.com/a/19998876/5944560
## (i spent HOURS trying to figure out how to do this,
## only to find that the geniuses behind R
## [specifically the {utils} pkg] had already developed
## an effecient, vectorized, solution) ##
# grays_nord <- colorRampPalette(pal_nord$polar[c(8, 1)]) ## add to pkg::Riley (in "Rpals.R")##
vawa <- 1994 ## year original VAWA was passed ##
vawaclr <- grays_nord(12)[7]
# yrcnt <- Rtdf(MAPtl$year, names = c("year", "yrcnt"))#[, 1, drop == FALSE]
# as.integer(MAPtl$year) %>% min() -> yrmin
# as.integer(MAPtl$year) %>% max()+1 -> yrmax
# GGPLOT - tl ----------------
gg.tl <- ggplot(MAPtl, aes(x = year, y = 0, colour = cpv)) +
thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE,
ptitle = TRUE, xtext = FALSE, xticks = FALSE) +
theme(legend.text = element_text(size = rel(0.75), face = "italic"),
legend.title = element_text(size = rel(0.95), face = "bold.italic"),
legend.background = element_rect(fill = "transparent", size = 0.1, colour = pal_my[19]),
legend.key.height = unit(0.5, "cm"),
# legend.key = element_rect(size = 1),
legend.justification = c(1, 0.67),
legend.box.spacing = unit(0.1, "cm")) +
labs(colour = "Journal Category", title = "Timeline of Reviewed Research\n") +
scale_colour_manual(values = pcpv) + #, guide = FALSE) +
geom_hline(yintercept = 0, size = 0.25, color = pal_nord$polar[7], alpha = 0.5) +
geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
colour = pal_my[19], alpha = 0.55,
na.rm = TRUE, size = 0.2, linetype = 3) +
geom_text(aes(y = pos, x = year, label = bibkey2), hjust = 0.5, vjust = 0,
angle = 25, size = 1.9, fontface = "bold", check_overlap = FALSE) +
# geom_vline(xintercept = vawa, size = 0.45, color = pal_nord$polar[1], linetype = 3) +
geom_text(aes(y = 0, x = vawa, label = "1994 Violence Against Women Act"),
alpha = 0.5, angle = 90, colour = adjustcolor(pal_my[19], alpha.f = 0.5), size = 2.75,
nudge_x = -0.25,
family = "serif", fontface = "italic") +
geom_text(aes(y = 0, x = year, label = year), check_overlap = TRUE,
vjust = 0.5, hjust = 0.5, angle = 0, colour = pal_my[20],
size = 2, fontface = "bold") +
xlim(min(MAPtl$year) - 0.25, max(MAPtl$year)) +
ylim(min(MAPtl$pos) - 0.15, max(MAPtl$pos) + 0.15)
gg.tl
#'
#' \newpage
#'
#' # \textsc{IPV Intervention \& Prevention Research}
#'
#' \Frule
#'
# reclab(cb$scat) ----------------
cb$scat2 <- factor(cb$scat, labels = c(1, 2))
cb$clab <- factor(cb$clab)
#'
# s3cb ----------------
s3cb <- cb[cb$scat2 == 1, ] %>% droplevels
# s3cb <- s3cb[!duplicated(s3cb), ]
s3cb.keys <- paste0("@", levels(factor(s3cb$bibkey)))
#'
#'
#+ tl_inv, fig.fullwidth=TRUE, fig.height=2.75, out.width='\\linewidth', figPath=TRUE
inv <- MAPtl[MAPtl$scat == "S3", ]
tl.inv <- inv[order(inv$year), c("bibkey", "year", "cpv", "journal", "title"), drop = FALSE] %>% droplevels()
tl.inv$bibkey <- paste0("@", tl.inv$bibkey)
tl.inv$journal <- paste0("_", tl.inv$journal, "_")
tl.inv <- dplyr::rename(tl.inv, "Study" = bibkey, "Journal" = journal, "Year Published" = year)
rownames(tl.inv) <- NULL
inv <- inv[order(inv$yrv), , drop = FALSE] %>% within({
posv <- sequence(rle(sort(yrv))$lengths)
posv <- ifelse(yrv == 0, 0, posv)
posv <- log(posv + 0.75) * -1
})
inv <- inv[order(inv$yrcp), , drop = FALSE] %>% within({
poscp <- sequence(rle(sort(yrcp))$lengths)
pos <- ifelse(yrcp == 0, posv, log(poscp - 0.5) * -1)
})
# GGPLOT - invtl ----------------
gg.invtl <- ggplot(inv, aes(x = year, y = 0, colour = cpv)) +
thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE,
ptitle = TRUE, xtext = FALSE, xticks = FALSE) +
theme(legend.text = element_text(size = rel(0.55)),
legend.title = element_text(size = rel(0.65), face = "bold"),
legend.justification = c(1, 0.8),
legend.box.spacing = unit(0, "cm")) +
# plot.margin = unit(c(1, rep(0.15, 3)), "cm")) +
ylim(min(inv$pos) - 0.5, max(inv$pos) + 0.5) +
labs(colour = "Journal Category", title = "IPV-Interventions Research Timeline") +
scale_colour_manual(values = pcpv) + #, guide = FALSE) +
geom_hline(yintercept = 0, size = 0.25, color = pal_nord$polar[7], alpha = 0.5) +
geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
colour = pal_my[19], alpha = 0.55,
na.rm = TRUE, size = 0.2, linetype = 3) +
geom_text(aes(y = pos, x = year, label = bibkey2), hjust = 0.5, vjust = 1,
angle = 25, size = 2.5, fontface = "bold") + #, nudge_y = -0.05) +
# geom_vline(xintercept = vawa, size = 0.45, color = pal_nord$polar[1], linetype = 3) +
geom_text(aes(y = 0, x = vawa, label = "1994 Violence Against Women Act"),
alpha = 0.5, angle = 90, colour = vawaclr, size = 2.5,
nudge_x = -0.25, family = "serif", fontface = "italic") +
geom_text(aes(y = 0, x = year, label = year), check_overlap = TRUE,
vjust = 0.5, hjust = 0.5, angle = 0, colour = pal_my[20],
size = 2.5, family = "serif", fontface = "bold") +
xlim(min(inv$year) - 0.25, max(inv$year)) +
ylim(min(inv$pos) - 0.15, max(inv$pos) + 0.15)
gg.invtl
tl.inv[, c(1, 4, 2)] %>% kable(caption = "IPV Interventions Research Timeline")
#'
#' \newpage
#'
#' ## Research Topics
#'
#+ topics_s3
## s3cb - TOPICS ================
# levels(droplevels(cb[cb$cat == "TOPIC", "clab"])) %>% as.list() %>% pander()
# l1tops <-levels(droplevels(cb[cb$cat == "TOPIC", "clab"]))[c(12, 16, )]
s3top <- s3cb[s3cb$cat == "TOPIC", ] %>% droplevels()
s3top <- s3top[!duplicated(s3top), ]
# x <- s4qt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
Rtdf(s3top$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Primary Topics Distribution (IPV Interventions Research)", align = c("l", "r"))
s3top.tly <- tally(group_by(s3top, clab))
lvls3.tp <- paste0(seq(1:nrow(s3top.tly)), " = ", levels(s3top$clab))
s3top$clab2 <- factor(s3top$clab, labels = seq(1:nrow(s3top.tly)))
# levels(s3top$clab) <- seq(1:length(unique(s3top$clab)))
ks3tp <- ftable(s3top$bibkey, s3top$clab2) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3tp <- ifelse(ks3tp >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3tp) <- paste0("@", rownames(ks3tp))
#'
#' \newpage
#'
#+ echo=FALSE
# panderOptions("table.split.table", 120)
kable(ks3tp[, 1:9], caption = "Primary Topics by Study (IPV Interventions Research [1/2])")
pander(lvls3.tp[1:9])
#'
#' \newpage
#'
#+ echo=FALSE
kable(ks3tp[, 10:ncol(ks3tp)], caption = "Primary Topics by Study (IPV Interventions Research [2/2])")
pander(lvls3.tp[10:length(lvls3.tp)])
#'
#' \newpage
#' ## Target Populations/Sampling Frames
#'
#+ pop_s3
## s3cb - POPULATIONS ================
s3pop <- s3cb[s3cb$cat == "POPULATION", ] %>% droplevels()
s3pop <- s3pop[!duplicated(s3pop), ]
# x <- s3pop[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3pop$clab, s3pop$jrnl)
Rtdf(s3pop$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Populations Included (IPV Interventions Research)", align = c("l", "r"))
s3pop.tly <- tally(group_by(s3pop, clab))
lvls3.pop <- paste0(seq(1:nrow(s3pop.tly)), " = ", levels(s3pop$clab))
s3pop$clab2 <- factor(s3pop$clab, labels = seq(1:nrow(s3pop.tly)))
# lvla3.pop <- paste0(seq(1:length(unique(s3pop$clab))), " = ", levels(s3pop$clab))
# levels(s3pop$clab) <- seq(1:length(unique(s3pop$clab)))
ks3pop <- ftable(s3pop$bibkey, s3pop$clab2) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3pop <- ifelse(ks3pop >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3pop) <- paste0("@", rownames(ks3pop))
kable(ks3pop, caption = "Populations Included by Study (IPV Interventions Research)")
pander(lvls3.pop)
#'
#'
#' \newpage
#'
#' ## Sampling Settings
#'
#'
#+ setLvls_s3
s3set <- s3cb[s3cb$cat == "M-SETTINGS", ] %>% droplevels()
s3set <- s3set[!duplicated(s3set), ]
Rtdf(s3set$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Sampling Settings (IPV Interventions Research)", align = c("l", "r"))
s3set.tly <- tally(group_by(s3set, clab))
lvls3.set <- paste0(seq(1:nrow(s3set.tly)), " = ", levels(s3set$clab))
s3set$clab2 <- factor(s3set$clab, labels = seq(1:nrow(s3set.tly)))
# lvla3.set <- paste0(seq(1:length(unique(s3set$clab))), " = ", levels(s3set$clab))
# levels(s3set$clab) <- seq(1:length(unique(s3set$clab)))
ks3set <- ftable(s3set$bibkey, s3set$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks3set <- ifelse(ks3set >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3set) <- paste0("@", rownames(ks3set))
kable(ks3set[, 1:10], caption = "Sampling Settings by Study (IPV Interventions Research [1/2])")
pander(lvls3.set[1:9])
#'
#' \newpage
#'
#+ echo=FALSE
kable(ks3set[, 11:ncol(ks3set)], caption = "Sampling Settings by Study (IPV Interventions Research [2/2])")
pander(lvls3.set[10:length(lvls3.set)])
#'
#'
#' \newpage
#'
#' ## Sampling Methods
#'
#'
#+ smthds_s3
s3smthds <- s3cb[s3cb$cat == "M-SAMPLING", ] %>% droplevels()
s3smthds <- s3smthds[!duplicated(s3smthds), ]
# x <- s3smthds[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s3smthds$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Ecological Levels of Analysis (IPV Interventions Research)", align = c("l", "r"))
s3smthds.tly <- tally(group_by(s3smthds, clab))
lvls3.smthds <- paste0(seq(1:nrow(s3smthds.tly)), " = ", levels(s3smthds$clab))
s3smthds$clab2 <- factor(s3smthds$clab, labels = seq(1:nrow(s3smthds.tly)))
# lvla3.smthds <- paste0(seq(1:length(unique(s3smthds$clab))), " = ", levels(s3smthds$clab))
# levels(s3smthds$clab) <- seq(1:length(unique(s3smthds$clab)))
ks3smthds <- ftable(s3smthds$bibkey, s3smthds$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks3smthds <- ifelse(ks3smthds >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3smthds) <- paste0("@", rownames(ks3smthds))
kable(ks3smthds, caption = "Sampling Methods by Study (IPV Interventions Research)")
pander(lvls3.smthds)
#'
#'
#' \newpage
#'
#' # Research Designs by Study
#'
#+ designs_s3
## s3cb - DESIGNS ================
s3d <- s3cb[s3cb$cat == "DESIGN", ] %>% droplevels()
s3d <- s3d[!duplicated(s3d), ]
# x <- s3d[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3d$clab, s3d$jrnl)
Rtdf(s3d$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Research Design (IPV Interventions Research)", align = c("l", "r"))
s3d.tly <- tally(group_by(s3d, clab))
lvls3.d <- paste0(seq(1:nrow(s3d.tly)), " = ", levels(s3d$clab))
s3d$clab2 <- factor(s3d$clab, labels = seq(1:nrow(s3d.tly)))
ks3d <- ftable(s3d$bibkey, s3d$clab2) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3d <- ifelse(ks3d >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3d) <- paste0("@", rownames(ks3d))
kable(ks3d, caption = "Research Design by Study (IPV Interventions Research)")
pander(lvls3.d)
#'
#' \newpage
#'
#' ## Overarching Methodology
#'
#+ mthds_s3
## s3cb - METHODS ================
s3mo <- s3cb[s3cb$cat == "METHODS", ] %>% droplevels()
s3mo <- s3mo[!duplicated(s3mo), ]
# x <- s3mo[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3mo$clab, s3mo$jrnl)
Rtdf(s3mo$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Overarching Methodology (IPV Interventions Research)", align = c("l", "r"))
s3mo.tly <- tally(group_by(s3mo, clab))
lvls3.mo <- paste0(seq(1:nrow(s3mo.tly)), " = ", levels(s3mo$clab))
s3mo$clab2 <- factor(s3mo$clab, labels = seq(1:nrow(s3mo.tly)))
lvla3.mo <- paste0(seq(1:length(unique(s3mo$clab2))), " = ", levels(s3mo$clab))
levels(s3mo$clab) <- seq(1:length(unique(s3mo$clab)))
ks3mo <- ftable(s3mo$bibkey, s3mo$clab) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3mo <- ifelse(ks3mo >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3mo) <- paste0("@", rownames(ks3mo))
kable(ks3mo, caption = "Methodology by Study (IPV Interventions Research)")
pander(lvls3.mo)
#'
#' \newpage
#'
#' ## Qua**L**itative Methods
#'
#+ QL_s3
## s3cb - QUAL ================
s3ql <- s3cb[s3cb$cat == "M-QL", ] %>% droplevels()
s3ql <- s3ql[!duplicated(s3ql), ]
# x <- s3ql[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3ql$clab, s3ql$jrnl)
Rtdf(s3ql$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**L**itative Methods (IPV Interventions Research)", align = c("l", "r"))
s3ql.tly <- tally(group_by(s3ql, clab))
lvls3.ql <- paste0(seq(1:nrow(s3ql.tly)), " = ", levels(s3ql$clab))
s3ql$clab2 <- factor(s3ql$clab, labels = seq(1:nrow(s3ql.tly)))
# lvla3.ql <- paste0(seq(1:length(unique(s3ql$clab))), " = ", levels(s3ql$clab))
# levels(s3ql$clab) <- seq(1:length(unique(s3ql$clab)))
ks3ql <- ftable(s3ql$bibkey, s3ql$clab2) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3ql <- ifelse(ks3ql >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3ql) <- paste0("@", rownames(ks3ql))
kable(ks3ql, caption = "Qua**L**itative Methods by Study (IPV Interventions Research)")
pander(lvls3.ql)
#'
#' ## Qua**L**itative Analytic Appraoches (IPV Interventions)
#'
#+ qlAnalytics_s3
## s3cb - QUAL ================
s3aql <- s3cb[s3cb$cat == "A-QL", ] %>% droplevels()
# s3aql <- s3ql[!duplicated(s3aql), ]
# x <- s3aql[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3aql$clab, s3aql$jrnl)
Rtdf(s3aql$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**L**itative Methods (IPV Interventions Research)", align = c("l", "r"))
s3aql.tly <- tally(group_by(s3aql, clab))
lvls3.aql <- paste0(seq(1:nrow(s3aql.tly)), " = ", levels(s3aql$clab))
s3aql$clab2 <- factor(s3aql$clab, labels = seq(1:nrow(s3aql.tly)))
# lvls3.ql <- paste0(seq(1:length(unique(s3aql$clab))), " = ", levels(s3aql$clab))
# levels(s3aql$clab) <- seq(1:length(unique(s3aql$clab)))
ks3aql <- ftable(s3aql$bibkey, s3aql$clab2) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3aql <- ifelse(ks3aql >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3aql) <- paste0("@", rownames(ks3aql))
kable(ks3aql, caption = "Qua**L**itative Analytic Approaches by Study (IPV Interventions Research)")
pander(lvls3.ql)
#'
#' \newpage
#'
#' ## Qua**NT**itative Methods
#'
#+ qtMethods_s3
## s3cb - QUANT ================
s3qt <- s3cb[s3cb$cat == "M-QT", ] %>% droplevels()
s3qt <- s3qt[!duplicated(s3qt), ]
# x <- s3qt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3qt$clab, s3qt$jrnl)
Rtdf(s3qt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**NT**itative Methods (IPV Interventions Research)", align = c("l", "r"))
s3qt.tly <- tally(group_by(s3qt, clab))
lvls3.qt <- paste0(seq(1:nrow(s3qt.tly)), " = ", levels(s3qt$clab))
s3qt$clab2 <- factor(s3qt$clab, labels = seq(1:nrow(s3qt.tly)))
# lvla3.qt <- paste0(seq(1:length(unique(s3qt$clab))), " = ", levels(s3qt$clab))
# levels(s3qt$clab) <- seq(1:length(unique(s3qt$clab)))
ks3qt <- ftable(s3qt$bibkey, s3qt$clab2) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3qt <- ifelse(ks3qt >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3qt) <- paste0("@", rownames(ks3qt))
kable(ks3qt, caption = "Qua**NT**itative Methods by Study (IPV Interventions Research)")
pander(lvls3.qt)
#'
#' ## QuaNTtitative Analytic Approaches
#'
#+ AQT_s3
## s3cb - QUANT - ANALYSIS ================
s3aqt <- s3cb[s3cb$cat == "A-QT", ] %>% droplevels()
s3aqt <- s3aqt[!duplicated(s3aqt), ]
# x <- s3aqt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3aqt$clab, s3aqt$jrnl)
Rtdf(s3aqt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**NT**itative Methods (IPV Interventions Research)", align = c("l", "r"))
s3aqt.tly <- tally(group_by(s3aqt, clab))
lvls3.aqt <- paste0(seq(1:nrow(s3aqt.tly)), " = ", levels(s3aqt$clab))
s3aqt$clab2 <- factor(s3aqt$clab, labels = seq(1:nrow(s3aqt.tly)))
# lvls3.aqt <- paste0(seq(1:length(unique(s3aqt$clab))), " = ", as.character(levels(s3aqt$clab)))
# levels(s3aqt$clab) <- seq(1:length(unique(s3aqt$clab)))
ks3aqt <- ftable(s3aqt$bibkey, s3aqt$clab2) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3aqt <- ifelse(ks3aqt >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3aqt) <- paste0("@", rownames(ks3aqt))
kable(ks3aqt, caption = "Qua**NT**itative Methods by Study (IPV Interventions Research)")
pander(lvls3.aqt)
#'
#' \newpage
#' ## Mixed-Methods
#'
#+ mmr_s3
## s3cb - MIXED-MTHDS ================
s3mm <- s3cb[s3cb$cat == "M-MM", ] %>% droplevels()
s3mm <- s3mm[!duplicated(s3mm), ]
# x <- s3mm[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3mm$clab, s3mm$jrnl)
Rtdf(s3mm$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Mixed-Methods (IPV Interventions Research)", align = c("l", "r"))
s3mm.tly <- tally(group_by(s3mm, clab))
lvls3.mm <- paste0(seq(1:nrow(s3mm.tly)), " = ", levels(s3mm$clab))
s3mm$clab2 <- factor(s3mm$clab, labels = seq(1:nrow(s3mm.tly)))
# lvls3.mm <- paste0(seq(1:length(unique(s3mm$clab))), " = ", levels(s3mm$clab))
# levels(s3mm$clab) <- seq(1:length(unique(s3mm$clab)))
ks3mm <- ftable(s3mm$bibkey, s3mm$clab2) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3mm <- ifelse(ks3mm >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3mm) <- paste0("@", rownames(ks3mm))
kable(ks3mm, caption = "Mixed-Methods by Study (IPV Interventions Research)")
pander(lvls3.mm)
#'
#'
#' \newpage
#'
#' ## Ecological Levels of Analysis
#'
#'
#+ ecoLvls_s3
s3eco <- s3cb[s3cb$cat == "ECO", ] %>% droplevels()
s3eco <- s3eco[!duplicated(s3eco), ]
# x <- s3eco[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s3eco$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Ecological Levels of Analysis (IPV Interventions Research)", align = c("l", "r"))
s3eco.tly <- tally(group_by(s3eco, clab))
lvls3.eco <- paste0(seq(1:nrow(s3eco.tly)), " = ", levels(s3eco$clab))
s3eco$clab2 <- factor(s3eco$clab, labels = seq(1:nrow(s3eco.tly)))
# lvls3.eco <- paste0(seq(1:length(unique(s3eco$clab))), " = ", levels(s3eco$clab))
# levels(s3eco$clab) <- seq(1:length(unique(s3eco$clab)))
ks3eco <- ftable(s3eco$bibkey, s3eco$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks3eco <- ifelse(ks3eco >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks3eco) <- paste0("@", rownames(ks3eco))
kable(ks3eco, caption = "Levels of Analysis by Study (IPV Interventions Research)")
pander(lvls3.eco)
#'
#' \newpage
#'
#' # \textsc{SMW-Inclusive IPV Research}
#'
#' \Frule
#'
#+ s4cb
# s4cb ----------------
s4cb <- cb[cb$scat2 == 2, ] %>% droplevels
s4cb.keys <- paste0("@", levels(s4cb$bibkey))
# s4cb.keys %>% as.list() %>% pander
#'
#+ tl_smw, fig.fullwidth=TRUE, fig.height=2, out.width='\\linewidth', fig.show='asis', figPath=TRUE
smw <- MAPtl[MAPtl$scat == "S4", ]
tl.smw <- smw[order(smw$year), c("bibkey", "year", "cpv", "journal", "title")] %>% droplevels()
tl.smw$bibkey <- paste0("@", tl.smw$bibkey)
tl.smw$journal <- paste0("_", tl.smw$journal, "_")
tl.smw <- dplyr::rename(tl.smw, "Study" = bibkey, "Journal" = journal, "Year Published" = year)
rownames(tl.smw) <- NULL
# psmw <- pal_sci[1:length(unique(smw$journal))]
# smw$pos <- rep_len(c(1, -1), length(smw$pos))
smw <- smw[order(smw$yrv), , drop = FALSE] %>% within({
posv <- sequence(rle(sort(yrv))$lengths)
posv <- ifelse(yrv == 0, 0, posv)
posv <- log(posv + 0.5) * -1
})
smw <- smw[order(smw$yrcp), , drop = FALSE] %>% within({
poscp <- sequence(rle(sort(yrcp))$lengths)
pos <- ifelse(yrcp == 0, posv, log(poscp - 0.5) * -0.5)
})
# GGPLOT - smwtl ----------------
gg.smwtl <- ggplot(smw, aes(x = year, y = 0, colour = cpv)) +
thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE,
ptitle = TRUE, xtext = FALSE, xticks = FALSE) +
theme(legend.text = element_text(size = rel(0.55)),
legend.title = element_text(size = rel(0.65), face = "bold"),
legend.justification = c(1, 0.635),
legend.box.spacing = unit(0, "cm")) +
# plot.margin = unit(c(1, rep(0.15, 3)), "cm")) +
ylim(min(smw$pos) - 0.5, max(smw$pos) + 0.5) +
labs(colour = "Journal Category", title = "SMW-Inclusive IPV Research Timeline\n") +
scale_colour_manual(values = pcpv) + #, guide = FALSE) +
geom_hline(yintercept = 0, size = 0.25, color = pal_nord$polar[7], alpha = 0.5) +
geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
colour = pal_my[19], alpha = 0.55,
na.rm = TRUE, size = 0.2, linetype = 3) +
geom_text(aes(y = pos, x = year, label = bibkey2), hjust = 0.5, vjust = 0,
angle = 45, size = 2.5, fontface = "bold") + #, nudge_y = -0.05) +
geom_text(aes(y = 0, x = year, label = year), check_overlap = TRUE,
vjust = 0.5, hjust = 0.5, angle = 0, colour = pal_my[20],
size = 2.5, family = "serif", fontface = "bold") +
xlim(min(smw$year) - 0.25, max(smw$year))
gg.smwtl
tl.smw[, c(1, 4)] %>% kable(caption = "SMW-Inclusive Research Timeline")
#'
#' \newpage
#'
#' ## Research Topics
#'
#+ topics_s4
## s4cb - TOPICS ================
s4top <- s4cb[s4cb$cat == "TOPIC", ] %>% droplevels()
s4top <- s4top[!duplicated(s4top), ]
# x <- s4top[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4top$clab, s4top$jrnl)
Rtdf(s4top$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Primary Topics (SMW-Inclusive Research)",
align = c("l", "r"))
s4top.tly <- tally(group_by(s4top, clab))
lvls4.tp <- paste0(seq(1:nrow(s4top.tly)), " = ", levels(s4top$clab))
s4top$clab2 <- factor(s4top$clab, labels = seq(1:nrow(s4top.tly)))
# lvls4.tp <- paste0(seq(1:length(unique(s4top$clab))), " = ", levels(s4top$clab))
# levels(s4top$clab) <- seq(1:length(unique(s4top$clab)))
ks4tp <- ftable(s4top$bibkey, s4top$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4tp <- ifelse(ks4tp >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4tp) <- paste0("@", rownames(ks4tp))
#'
#+ echo=FALSE
kable(ks4tp, caption = "Primary Topics by Study (SMW-Inclusive Research)")
pander(lvls4.tp)
#'
#' \newpage
#' ## Target Populations/Sampling Frames
#'
#+ pop_s4
## s4cb - POPULATIONS ================
s4pop <- s4cb[s4cb$cat == "POPULATION", ] %>% droplevels()
s4pop <- s4pop[!duplicated(s4pop), ]
# x <- s4pop[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4pop$clab, s4pop$jrnl)
Rtdf(s4pop$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Populations Included (SMW-Inclusive Research)",
align = c("l", "r"))
s4pop.tly <- tally(group_by(s4pop, clab))
lvls4.pop <- paste0(seq(1:nrow(s4pop.tly)), " = ", levels(s4pop$clab))
s4pop$clab2 <- factor(s4pop$clab, labels = seq(1:nrow(s4pop.tly)))
# lvla4.pop <- paste0(seq(1:length(unique(s4pop$clab))), " = ", levels(s4pop$clab))
# levels(s4pop$clab) <- seq(1:length(unique(s4pop$clab)))
ks4pop <- ftable(s4pop$bibkey, s4pop$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4pop <- ifelse(ks4pop >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4pop) <- paste0("@", rownames(ks4pop))
#'
#+ echo=FALSE
kable(ks4pop, caption = "Populations Included by Study (SMW-Inclusive Research)")
pander(lvls4.pop)
#'
#'
#' \newpage
#'
#' ## Sampling Settings
#'
#'
#+ setLvls_s4
s4set <- s4cb[s4cb$cat == "M-SETTINGS", ] %>% droplevels()
s4set <- s4set[!duplicated(s4set), ]
# x <- s4set[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s4set$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Sampling Settings (SMW-Inclusive Research)",
align = c("l", "r"))
s4set.tly <- tally(group_by(s4set, clab))
lvls4.set <- paste0(seq(1:nrow(s4set.tly)), " = ", levels(s4set$clab))
s4set$clab2 <- factor(s4set$clab, labels = seq(1:nrow(s4set.tly)))
# lvla4.set <- paste0(seq(1:length(unique(s4set$clab))), " = ", levels(s4set$clab))
# levels(s4set$clab) <- seq(1:length(unique(s4set$clab)))
ks4set <- ftable(s4set$bibkey, s4set$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4set <- ifelse(ks4set >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4set) <- paste0("@", rownames(ks4set))
#'
#+ echo=FALSE
kable(ks4set, caption = "Sampling Settings by Study (SMW-Inclusive IPV Research)")
pander(lvls4.set)
#'
#'
#' \newpage
#'
#' ## Sampling Methods
#'
#'
#+ smthdsLvls_s4
s4smthds <- s4cb[s4cb$cat == "M-SAMPLING", ] %>% droplevels()
s4smthds <- s4smthds[!duplicated(s4smthds), ]
# x <- s4smthds[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s4smthds$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Sampling Methods (SMW-Inclusive Research)",
align = c("l", "r"))
s4smthds.tly <- tally(group_by(s4smthds, clab))
lvls4.smthds <- paste0(seq(1:nrow(s4smthds.tly)), " = ", levels(s4smthds$clab))
s4smthds$clab2 <- factor(s4smthds$clab, labels = seq(1:nrow(s4smthds.tly)))
# lvla4.smthds <- paste0(seq(1:length(unique(s4smthds$clab))), " = ", levels(s4smthds$clab))
# levels(s4smthds$clab) <- seq(1:length(unique(s4smthds$clab)))
ks4smthds <- ftable(s4smthds$bibkey, s4smthds$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4smthds <- ifelse(ks4smthds >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4smthds) <- paste0("@", rownames(ks4smthds))
#'
#+ echo=FALSE
kable(ks4smthds, caption = "Sampling Methods by Study (SMW-Inclusve Research)")
pander(lvls4.smthds)
#'
#' \newpage
#'
#' # Research Designs by Study (SMW-Inclusvive Research)
#'
#+ designs_s4
## s4cb - DESIGNS ================
s4d <- s4cb[s4cb$cat == "DESIGN", ] %>% droplevels()
s4d <- s4d[!duplicated(s4d), ]
# x <- s4d[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4d$clab, s4d$jrnl)
Rtdf(s4d$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Research Design (SMW-Inclusive Research)", align = c("l", "r"))
s4d.tly <- tally(group_by(s4d, clab))
lvls4.d <- paste0(seq(1:nrow(s4d.tly)), " = ", levels(s4d$clab))
s4d$clab2 <- factor(s4d$clab, labels = seq(1:nrow(s4d.tly)))
# lvla3.mo <- paste0(seq(1:length(unique(s4d$clab))), " = ", levels(s4d$clab))
# levels(s4d$clab) <- seq(1:length(unique(s4d$clab)))
ks4d <- ftable(s4d$bibkey, s4d$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4d <- ifelse(ks4d >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4d) <- paste0("@", rownames(ks4d))
kable(ks4d, caption = "Research Design by Study (SMW-Inclusive Research)")
pander(lvla3.mo)
#'
#' \newpage
#'
#' ## Overarching Methodology
#'
#+ mthds_s4
## s4cb - METHODS ================
s4mo <- s4cb[s4cb$cat == "METHODS", ] %>% droplevels()
s4mo <- s4mo[!duplicated(s4mo), ]
# x <- s4mo[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4mo$clab, s4mo$jrnl)
Rtdf(s4mo$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Overarching Methodology (SMW-Inclusive Research)",
align = c("l", "r"))
s4mo.tly <- tally(group_by(s4mo, clab))
lvls4.mo <- paste0(seq(1:nrow(s4mo.tly)), " = ", levels(s4mo$clab))
s4mo$clab2 <- factor(s4mo$clab, labels = seq(1:nrow(s4mo.tly)))
# lvla4.mo <- paste0(seq(1:length(unique(s4mo$clab))), " = ", levels(s4mo$clab))
# levels(s4mo$clab) <- seq(1:length(unique(s4mo$clab)))
ks4mo <- ftable(s4mo$bibkey, s4mo$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4mo <- ifelse(ks4mo >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4mo) <- paste0("@", rownames(ks4mo))
#'
#+ echo=FALSE
kable(ks4mo, caption = "Methodology by Study (SMW-Inclusive Research)")
pander(lvls4.mo)
#'
#' \newpage
#'
#' ## QuaLitative Methods
#'
#+ QL_s4
## s4cb - QUAL ================
s4ql <- s4cb[s4cb$cat == "M-QL", ] %>% droplevels()
s4ql <- s4ql[!duplicated(s4ql), ]
# x <- s4ql[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s4ql$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**L**itative Methods (SMW-Inclusive Research)", align = c("l", "r"))
s4ql.tly <- tally(group_by(s4ql, clab))
lvls4.ql <- paste0(seq(1:nrow(s4ql.tly)), " = ", levels(s4ql$clab))
s4ql$clab2 <- factor(s4ql$clab, labels = seq(1:nrow(s4ql.tly)))
# lvla4.ql <- paste0(seq(1:length(unique(s4ql$clab))), " = ", levels(s4ql$clab))
# levels(s4ql$clab) <- seq(1:length(unique(s4ql$clab)))
ks4ql <- ftable(s4ql$bibkey, s4ql$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4ql <- ifelse(ks4ql >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4ql) <- paste0("@", rownames(ks4ql))
#'
#+ echo=FALSE
kable(ks4ql, caption = "Qua**L**itative Methods by Study (SMW-Inclusive Research)")
pander(lvls4.ql)
#'
#' ## Qua**L**itative Analytic Appraoches
#'
#+ AQL_s4
## s4cb - QUAL-ANALYTICS ================
s4aql <- s4cb[s4cb$cat == "A-QL", ] %>% droplevels()
# s4aql <- s4ql[!duplicated(s4aql), ]
# x <- s4aql[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4aql$clab, s4aql$jrnl)
Rtdf(s4aql$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**NT**itative Methods (SMW-Inclusive IPV Research)", align = c("l", "r"))
s4aql.tly <- tally(group_by(s4aql, clab))
lvls4.aql <- paste0(seq(1:nrow(s4aql.tly)), " = ", levels(s4aql$clab))
s4aql$clab2 <- factor(s4aql$clab, labels = seq(1:nrow(s4aql.tly)))
# lvla4.qt <- paste0(seq(1:length(unique(s4aql$clab))), " = ", levels(s4aql$code))
# levels(s4aql$clab) <- seq(1:length(unique(s4aql$clab)))
ks4aql <- ftable(s4aql$bibkey, s4aql$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4aql <- ifelse(ks4aql >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4aql) <- paste0("@", rownames(ks4aql))
kable(ks4aql, caption = "Qua**L**itative Analytic Approaches by Study (SMW-Inclusive IPV Research)")
pander(lvls4.aql)
#'
#' \newpage
#' ## QuaNTitative Methods
#'
#+ QT_s4
## s4cb - QUANT ================
s4qt <- s4cb[s4cb$cat == "M-QT", ] %>% droplevels()
s4qt <- s4qt[!duplicated(s4qt), ]
# x <- s4qt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4qt$clab, s4qt$jrnl)
Rtdf(s4qt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**NT**itative Methods (SMW-Inclusive Research)", align = c("l", "r"))
s4qt.tly <- tally(group_by(s4qt, clab))
lvls4.qt <- paste0(seq(1:nrow(s4qt.tly)), " = ", levels(s4qt$clab))
s4qt$clab2 <- factor(s4qt$clab, labels = seq(1:nrow(s4qt.tly)))
# lvla4.qt <- paste0(seq(1:length(unique(s4qt$clab))), " = ", levels(s4qt$clab))
# levels(s4qt$clab) <- seq(1:length(unique(s4qt$clab)))
ks4qt <- ftable(s4qt$bibkey, s4qt$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4qt <- ifelse(ks4qt >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4qt) <- paste0("@", rownames(ks4qt))
kable(ks4qt, caption = "Qua**NT**itative Methods by Study (SMW-Inclusive Research)")
pander(lvls4.qt)
#'
#' ## Quantitative Analytic Appraoches
#'
#+ AQT_s4
## s4cb - QUANT-ANALYTICS ================
s4aqt <- s4cb[s4cb$cat == "A-QT", ] %>% droplevels()
# s4aqt <- s4ql[!duplicated(s4aqt), ]
# x <- s4aqt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4aqt$clab, s4aqt$jrnl)
Rtdf(s4aqt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**NT**itative Methods (IPV Interventions Research)", align = c("l", "r"))
s4aqt.tly <- tally(group_by(s4aqt, clab))
lvls4.aqt <- paste0(seq(1:nrow(s4aqt.tly)), " = ", levels(s4aqt$clab))
s4aqt$clab2 <- factor(s4aqt$clab, labels = seq(1:nrow(s4aqt.tly)))
# lvla4.qt <- paste0(seq(1:length(unique(s4aqt$clab))), " = ", levels(s4aqt$code))
# levels(s4aqt$clab) <- seq(1:length(unique(s4aqt$clab)))
ks4aqt <- ftable(s4aqt$bibkey, s4aqt$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4aqt <- ifelse(ks4aqt >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4aqt) <- paste0("@", rownames(ks4aqt))
kable(ks4aqt, caption = "Qua**NT**itative Analytic Approaches by Study (IPV Interventions Research)")
pander(lvls4.qt)
#'
#' \newpage
#' ## Mixed-Methods
#'
#+ mmr_s4
## s4cb - MIXED-MTHDS ================
s4mm <- s4cb[s4cb$cat == "M-MM", ] %>% droplevels()
s4mm <- s4mm[!duplicated(s4mm), ]
# s4ql <- s4ql[!duplicated(s4ql), ]
# x <- s4ql[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4mm$clab, s4mm$jrnl)
Rtdf(s4mm$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Mixed-Methods (SMW-Inclusive Research)", align = c("l", "r"))
s4mm.tly <- tally(group_by(s4mm, clab))
lvls4.mm <- paste0(seq(1:nrow(s4mm.tly)), " = ", levels(s4mm$clab))
s4mm$clab2 <- factor(s4mm$clab, labels = seq(1:nrow(s4mm.tly)))
# lvla4.mm <- paste0(seq(1:length(unique(s4mm$clab))), " = ", levels(s4mm$clab))
# levels(s4mm$clab) <- seq(1:length(unique(s4mm$clab)))
ks4mm <- ftable(s4mm$bibkey, s4mm$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4mm <- ifelse(ks4mm >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4mm) <- paste0("@", rownames(ks4mm))
kable(ks4mm, caption = "Mixed-Methods by Study (SMW-Inclusive Research)")
pander(lvls4.mm)
#'
#'
#' \newpage
#'
#' ## Ecological Levels of Analysis
#'
#'
#+ ecoLvls_s4
s4eco <- s4cb[s4cb$cat == "ECO", ] %>% droplevels()
s4eco <- s4eco[!duplicated(s4eco), ]
# x <- s4eco[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s4eco$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Ecological Levels of Analysis (SMW-Inclusive Research)", align = c("l", "r"))
s4eco.tly <- tally(group_by(s4eco, clab))
lvls4.eco <- paste0(seq(1:nrow(s4eco.tly)), " = ", levels(s4eco$clab))
s4eco$clab2 <- factor(s4eco$clab, labels = seq(1:nrow(s4eco.tly)))
# lvla4.eco <- paste0(seq(1:length(unique(s4eco$clab))), " = ", levels(s4eco$clab))
# levels(s4eco$clab) <- seq(1:length(unique(s4eco$clab)))
ks4eco <- ftable(s4eco$bibkey, s4eco$clab2) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4eco <- ifelse(ks4eco >= 1, "$\\checkmark$", "$\\cdot$")
rownames(ks4eco) <- paste0("@", rownames(ks4eco))
kable(ks4eco, caption = "Levels of Analysis by Study (SMW-Inclusive Research)")
pander(lvls4.eco)
par(pmar)
#'
#' \newpage\onehalfspacing
#'
#' # References`r Rcite_r(file = "../auxREFs.bib", footnote = TRUE)`
#'
#' \refs
#'
<file_sep>/_comps_docs/_zmisc/MAP-models.R
library(dplyr); library(Riley); library(lavaan); library(semPlot)
# Variable Descriptions For Reference
v1 <- "Pre-Trial Referral"
v2 <- "Post-Conviction Referral & Added Sanctions"
v3 <- "Program Duration"
v4 <- "Additional Alcohol and Substance Abuse Services"
v5 <- "Victim Services"
v6 <- "CTS-2"
v7 <- "Inventories of Non-Physical Abuse"
m.gondolf99 <- 'Intensity =~ v1 + v2 + v3
Services =~ v4 + v5
Comprehensiveness =~ Intensity + Services
Recidivism =~ v6 + v7
Recidivism ~ b*Intervention +
a*(Intervention)(Comprehensiveness)
ab := a*b
total := ab + c' %>% lavaanify()
semPaths(m.gondolf99)
<file_sep>/_comps_docs/_zmisc/journals.R
#' ---
#' title: "Journals Included in Literature Search"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE
source("../SETUP.R")
# knitr::opts_chunk$set(
# tidy = TRUE,
# echo = TRUE,
# fig.keep = 'high',
# fig.show = 'hold',
# results = 'asis'
# )
rpm()
#'
#' \Frule
#'
#' # Community Psychology Journals^[http://www.scra27.org/publications/other-journals-relevant-community-psychology/]
#'
#+ tidy=FALSE, echoRule=NULL, Rrule=TRUE, Rerule=NULL
JOURNAL <- c("Action Research",
"American Journal of Community Psychology",
"American Journal of Health Promotion",
"American Journal of Orthopsychiatry",
"American Journal of Preventive Medicine",
"American Journal of Public Health",
"Australian Community Psychologist",
"Community Development",
"Community Development Journal",
"Community Mental Health Journal",
"Community Psychology in Global Perspective",
"Cultural Diversity and Ethnic Minority Psychology",
"Global Journal of Community Psychology Practice",
"Health Education and Behavior",
"Health Promotion Practice",
"Journal of Applied Social Psychology",
"Journal of Community and Applied Social Psychology",
"Journal of Community Practice",
"Journal of Health and Social Behavior",
"Journal of Prevention and Intervention",
"Journal of Primary Prevention",
"Journal of Rural Community Psychology",
"Journal of Social Issues",
"Journal of Community Psychology",
"Psychiatric Rehabilitation Journal",
"Psychology of Women Quarterly",
"Psychosocial Intervention",
"Social Science and Medicine",
"The Community Psychologist",
"Transcultural Psychiatry",
"Progress in Community Health Partnerships: Research, Education, and Action",
"Journal of Interpersonal Violence",
"Violence Against Women",
"Violence and Victims",
"Journal of Family Violence")
#'
#+ tidy=TRUE, echoRule=NULL, Rrule=NULL, Rerule=TRUE
Year <- c(2003, 1973, 1986, 1930, 1985, 1971, 2006, 2005, 1966, 1965, 2015, 1995, 2010, 1997, 2000, 1971, 1991, 1994, 1967, 1996, 1981, 1980, 1997, 1973, 1996, 1976, 2011, 1967, 1975, 1997, 2007, 1986, 1995, 1986, 1986)
SJR <- c(0.33, 1.237, 0.821, 0.756, 2.764, 2.52, NA, NA, 0.47, 0.467, NA, NA, NA, 1.177, 0.769, 0.639, 0.855, 0.278, 1.727, 0.231, 0.64, NA, 1.467, 0.425, 0.692, 1.216, 0.331, 1.894, NA, 1.141, 0.427, 1.064, 0.851, 0.449, 0.639) ## SJR is for 2015 (most recent available on http://www.scimagojr.com) ##
H <- c(15, 83, 72, 69, 154, 196, NA, NA, 28, 51, NA, NA, NA, 72, 32, 78, 44, 15, 93, 21, 36, NA, 89, 65, 48, 66, 8, 177, NA, 35, 15, 78, 66, 64, 56) ## also retrieved from http://www.scimagojr.com ##
Med <- c(0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0)
Psych <- c(0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1)
SocSci <- c(1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1)
Biz <- c(1, rep(0, length(JOURNAL)-1))
AH <- c(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0)
Nurs <- c(rep(0, 14), 1, rep(0, length(JOURNAL)-15))
HlthPrf <- c(rep(0, 21), 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0)
Location <- c("UK", "US", "US", "US", "US", "US", "AU", "UK", "UK", "NL", "IT", "US", "US", "US", "US", "UK", "UK", "US", "US", "US", "US", "US", "UK", "US", "US", "UK", "ES", "UK", "US", "UK", "US", "US", "US", "US", "US")
dat <- data.frame(JOURNAL, Location, Year, SJR, H)
dat$jrnl <- sapply(as.character(dat$JOURNAL), Rabbr)
dat.subj <- data.frame(Med, Psych, SocSci, Biz, AH, Nurs, HlthPrf)
dat.subj$Nsubj <- apply(dat.subj, 1, sum)
dat <- cbind(dat, dat.subj) %>% as.data.frame()
dat.narm <- na.omit(dat) %>% as.data.frame()
names(dat.narm) <- c("Journal", "Location", "Year", "ScimagoJourn.Rating", "H-Index", "Medical", "Psychology", "SocialSciences", "Business", "Arts&Humanities", "Nursing", "HealthProfessions", "N_CoveredTopics")
# cor(dat.narm[, -1:-2]) %>% corrplot::corrplot.mixed(lower = "number", upper = "shade", tl.pos = "lt", diag = "u", bg = NA, col = blgrmg(length(cor(dat.narm[, -1:-2]))), tl.col = pal_my[19])
cl <- mpal(H, p = cols3); bg <- adjustcolor(cl, alpha.f = 0.6)
with(dat, {lm1 <- lm(H ~ SJR); plot(SJR, H, col = cl, bg = bg, pch = 21, xlab = "Scimago Journal Rating", ylab = "H Index"); abline(lm1, lwd = 2.5, col = pal_my[18])})
cor.test(dat$H, dat$SJR)
#'
#'
#' # IPV-Related Journals
#'
#' The following is for determining which IPV-related journals to include in the formal literature searches conducted for this review.
#'
#' The data below contain the publication names and corresponding count of articles from each publication resulting from the inital broad-strokes database search^[The initial broad-strokes IPV-related literature search was conducted using the following command-line search: "`SU('intimate partner violence' OR 'domestic violence' OR 'partner abuse') AND YR($>1965$)`"]
#'
dat2 <- read.csv("data/ipvJournalsSearch.csv")[c(-1, -6, -7), ]
## Exclude Theses and Dissertations ##
m.cnt <- mean(dat2[, 2])
s.cnt <- sd(dat2[, 2])
dat2.m <- dat2[dat2[,2] >= m.cnt, ]
dat2.s <- dat2[dat2[,2] >= s.cnt, ]
#+ echo=FALSE
pander(dat2.m, justify = c("right", "left", "right"), caption = "Journals with article counts greater than or equal to the mean of all journal article counts in the 'broad-strokes' database search results set")
pander(dat2.s, justify = c("right", "left", "right"), caption = "Journals with article counts greater than or equal one standard deviation of the distribution for all journal article counts in the 'broad-strokes' database search results set")
<file_sep>/_comps_docs/_zmisc/MAP-MyReadingListSrchs.md
---
title: "Reading List Search Results"
---
# \Large{Search Files Using \texttt{"grep"}}
-----
```{bash }
cd Dropbox/ReadingList
ls *.pdf
```
```{bash }
cat > searchResults.md
'
---
title: "Reading List Search Results"
---
-----
# Community Psychology
## Search = "`grep -ic 'community psychology' *.pdf`"
```
'
## [CTRL-D] ##
```
```{bash }
grep -ic 'community psychology' *.pdf >> searchResults.md
cat >> searchResults.md
'
```
-----
'
## [CTRL-D] ##
```
```{bash }
cat >> searchResults.md
'
## Search = "`grep -ic 'action research' *.pdf`"
```
'
## [CTRL-D] ##
```
```{bash }
grep -ic 'action research' *.pdf >> searchResults.md
cat >> searchResults.md
'
```
-----
'
## [CTRL-D] ##
```
```{bash }
cat >> searchResults.md
'
## Search = "`grep -ic 'participatory' *.pdf`"
```
'
## [CTRL-D] ##
```
```{bash }
grep -ic 'participatory' *.pdf >> searchResults.md
cat >> searchResults.md
'
```
-----
'
## [CTRL-D] ##
```
```{bash }
cat >> searchResults.md
'
## Search = "`grep -ic 'quantitative' *.pdf`"
```
'
## [CTRL-D] ##
```
```{bash }
grep -ic 'quantitative' *.pdf >> searchResults.md
cat >> searchResults.md
'
```
-----
'
## [CTRL-D] ##
```
```{bash }
cat >> searchResults.md
'
## Search = "`grep -ic 'qualitative' *.pdf`"
```
'
## [CTRL-D] ##
```
```{bash }
grep -ic 'qualitative' *.pdf >> searchResults.md
cat >> searchResults.md
'
```
-----
'
## [CTRL-D] ##
```
```{bash }
cat >> searchResults.md
'
## Search = "`grep -ic 'mixed methods' *.pdf`"
```
'
## [CTRL-D] ##
```
```{bash }
grep -ic 'mixed methods' *.pdf >> searchResults.md
cat >> searchResults.md
'
```
-----
'
## [CTRL-D] ##
```
<file_sep>/data/summary-thompson2000.md
A randomized control trial
<file_sep>/_comps_docs/_MAP-Tables-untex.Rmd
---
title: |
| Major Area Paper
| (v13.1)
author: "<NAME>"
date: "`r format(Sys.Date(), '%d %B %Y')`"
fignos-plus-name: "Figure "
tablenos-plus-name: "Table "
---
```{r setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE, fig.show='none', fig.keep='none'}
source("z.R")
knitr::opts_chunk$set(echo = FALSE)
panderOptions("p.copula", ", and ")
```
# Tables
```{r dbsrchkable2}
##BELOW IS FOR .DOCX OUTPUT##
dbsrch[, 2] <- sapply(dbsrch[, 2], Rretex, op = 2, USE.NAMES = F)
dbsrch[, 2] <- gsub("\\\\textsc\\{(.*?)}", "**\\1**", dbsrch[, 2])
dbsrch[, 3] <- sapply(dbsrch[, 3], Rretex, op = 2, USE.NAMES = F)
dbsrch[, 3] <- gsub("\\\\footnotesize\\{(.*?)\\}", "\\1", dbsrch[, 3])
names(dbsrch) <- c("", "Database Search[note]", "$Range_{N_{Results}}$")
library(kableExtra)
kable(dbsrch, caption = "Descriptions of database searches conducted with corresponding ranges of the number of results returned {#tbl:dbsrch}", align = c("r", "l", "l")) %>%
add_footnote("For each database search, multiple search terms were included for the subject/keywords parameters to represent intimate partner violence<br /><br />", threeparttable = TRUE)
```
```{r jcpkable2}
jlvls <- levels(MAP$journal)
jncp <- j.cppr[!levels(factor(j.cppr)) %in% jlvls]
levels(MAP$journal) <- c(jlvls, jncp)
jcpv <- Rtdf(MAP$journal, names = c("j", "frq"))
jcpv$cpv <- ifelse(jcpv$j %in% j.cppr, "Community Psychology", "Violence")
jv <- jcpv[jcpv$cpv == "Violence", c("j", "frq")]
jcp <- jcpv[jcpv$cpv != "Violence", c("j", "frq")]
kable(jcp, col.names = c("Publication Title", "$N_{articles}$"), caption = "_Community-Psychology_-Specific Journal Titles Included in Literature Database Searches with the Corresponding Number of Formally Reviewed Articles per Journal {#tbl:jcp}")
```
```{r jvkable2}
kable(jv, col.names = c("Publication Title", "$N_{articles}$"), caption = "_Violence_-Specific Journal Titles Included in Literature Database Searches with the Corresponding Number of Formally Reviewed Articles per Journal Included {#tbl:jv}")
```
```{r jsftkable}
MAP$journal <- droplevels(MAP$journal)
MAPp <- MAP[, c("journal", "scat")] %>% dplyr::rename("Publication Title" = journal, "Research Category" = scat)
MAPp[, 2] <- factor(MAPp[, 2],
labels = c("IPV Interventions Research",
"SMW-Specific IPV Research"))
jsft1 <- ftable(MAPp) %>% as.matrix()
jsft2 <- ifelse(jsft1 == 0, NA, jsft1)
jsftt <- apply(jsft2, 1, sum, na.rm = TRUE)
jsftt <- paste0("**", jsftt, "**")
jsft <- cbind(jsft2, jsftt)
kable(jsft, col.names = c(colnames(jsft)[1:2], "$N_{Articles_{Total}}$"), caption = "Number of Formally Reviewed Articles per Journal in Each Research Domain Covered in this Review {#tbl:jsft}", align = c("c", "c", "c"))
```
```{r cdbk, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE, fig.show='none', fig.keep='none'}
source("cdbk.R")
```
```{r tblcdbk2}
# cdbk.ft$clab <- gsub("\n", "", cdbk.ft$clab)
kable(cdbk.ft, col.names = c("**Information Category**", "Codes"), caption = "Codebook Constructed from the Discrete Summative Data Compiled Across the Formally Reviewed Literature {#tbl:cdbk}", align = c("r", "l"))
```
```{r ftmtpp}
ftm.tpp %>% kable(align = rep("r", 3),
caption = "Substantive Research Topics Covered {#tbl:ftmtpp}")
```
```{r ktop}
kable(ktop[, 1:11], caption = "Substantive Research Topics by Study (1/2) {#tbl:ktop}")
pander(lvl.top[1:11])
kable(ktop[, 12:length(lvl.top)], caption = "Substantive Research Topics by Study (2/2)")
pander(lvl.top[12:length(lvl.top)])
```
```{r ftmpopp}
ftm.popp %>% kable(align = rep("r", ncol(ftm.popp)), caption = "Populations _Included_ in Sampling Frames among the Reviewed Literature {#tbl:ftmpopp}")
```
```{r kpop}
kable(kpop[, 1:9], caption = "Sampling Frames by Study (1/2) {#tbl:kpop}") %>%
add_footnote("SMW-Inclusive", notation = "symbol")
pander(lvl.pop[1:9])
kable(kpop[, 10:length(lvl.pop)], caption = "Sampling Frames by Study (2/2)") %>%
add_footnote("SMW-Inclusive", notation = "symbol")
pander(lvl.pop[10:length(lvl.pop)])
```
```{r ftmsetp}
ftm.setp %>% kable(align = rep("r", ncol(ftm.setp)), caption = "Sampling Settings among the Reviewed Literature {#tbl:ftmsetp}")
```
```{r ksset}
kable(ksset[, 1:12], caption = "Sampling Settings by Study (1/2) {#tbl:ksset}") %>%
add_footnote("SMW-Inclusive", notation = "symbol")
pander(lvl.sset[1:12])
kable(ksset[, 13:length(lvl.sset)], caption = "Sampling Settings by Study (2/2) ") %>%
add_footnote("SMW-Inclusive", notation = "symbol")
pander(lvl.sset[13:length(lvl.sset)])
```
```{r ftmaql}
rownames(ftm.aqlp) <- gsub("\n", "", rownames(ftm.aqlp))
ftm.aqlp %>% kable(align = rep("r", 3),
caption = "QuaLitative Analytic Approaches Employed across the Reviewed Literature {#tbl:aql}")
```
```{r kaql}
kable(kaql, caption = "Qua**L**itative Analytic Approaches by Study {#tbl:kaql}") %>%
add_footnote("SMW-Specific", notation = "symbol")
pander(lvl.aql)
```
```{r ftmaqt}
ftm.aqtp %>% kable(align = rep("r", 3),
caption = "QuaNTitative Analytic Approaches Employed across the Reviewed Literature {#tbl:aqt}")
```
```{r kaqt}
kable(kaqt, caption = "Qua**NT**itative Analytic Approaches by Study {#tbl:kaqt}") %>%
add_footnote("SMW-Specific", notation = "symbol")
pander(lvl.aqt)
```
```{r ftmexpp}
rownames(ftm.expp) <- gsub("\n", "", rownames(ftm.expp))
ftm.expp %>% kable(align = rep("r", 3),
caption = "Experimental Research Designs {#tbl:expp}")
```
```{r kexp}
kable(kexp, caption = "Experimental Designs by Study {#tbl:kexp}") %>%
add_footnote("SMW-Specific", notation = "symbol")
pander(lvl.exp)
```
# Figures
{#fig:sem}
{#fig:yrhist}
{#fig:tl_map}
{#fig:flowchart}
{#fig:topics}
{#fig:populations}
{#fig:sampling}
{#fig:aql}
{#fig:aqt}
![Ecological Network: Levels of Analysis. Group memberships derived from clustering algorithm which maximizes modularity across all possible partitions of the graph data in order to calculate the optimal cluster structure for the data [@brandes2008on]](graphics/inputs/net_lvls_keys_bibkeys_mat-1.png){#fig:llgmat}
{#fig:kclust_top}
{#fig:keysnet}
{#fig:arc_analyses}
{#fig:sysnet}
# References
<file_sep>/_comps_docs/_zmisc/MAP-slides-v1.Rmd
# Part I. Background & Significance
## Rationale for the Present Review
> "... despite our awareness of context for those we study, we do not always apply that understanding to ourselves".
>
> `r tufte::quote_footer("--- [@riger1993what, p. 279]")`
\hrulefill
`r tufte::newthought("Community psychological values, theories, and methods favor...")`
- inclusion over exclusion
- participant voices considered equally with researchers' voices
- participatory or purposive sampling methods
> `r tufte::quote_footer("[@balcazar2004participatory; @senn2005you; @maguire1987doing]")`
- resistance to research methodologies, social policies, and implementation practices that ultimately served to reinforce and/or strengthen social and economic inequalities
> `r tufte::quote_footer("[@fine2003participatory; @senn2005you; @balcazar2004participatory]")`
## Theoretical Grounding
> "... community scientists study domestic violence using methods and theories that are consistent with the view that domestic violence is not just an individual behavior, but a complex process shaped by historical, social, financial, and legal contexts".
>
> `r tufte::quote_footer("--- @luke2005getting, p. 185")`
- Social **Ecological** framework [@espino2008spirit; @kelly1977social; @dahlberg2002violence]
- **Action**-oriented theory and methodology [@kelly2004community; @seidman2012emerging]
- Social scientific theory related to **IPV** and **sexual minority women** [@meyer1995minority; @meyer2015resilience]
## Theoretical Grounding: Ecological systems theory and the Social Ecological Model
```{r fig.cap="Social-Ecological Model"}
knitr::include_graphics("graphics/inputs/sem.png")
```
# Part II. Systematic Literature Review
## Systematic Literature Search Methods (1/2) {.shrink}
```{r fig.cap="Systematic Literature Search and Inclusion Flow-Chart"}
knitr::include_graphics("graphics/inputs/flowchart.png")
```
## Systematic Literature Search Methods (2/2) {.shrink}
```{r dbsrchkable}
pander(dbsrch, caption = "Descriptions of database searches conducted with corresponding ranges of the number of results returned^a^ {#tbl:dbsrch}", justify = c("right", "left", "left"))
```
\smallskip
\footnotesize{$^a$ For each database search, multiple search terms were included for the subject/keywords parameters to represent intimate partner violence}
## Initial Literature Assessment \& Screening Procedures {.shrink}
```{r jsftkable}
MAP$journal <- droplevels(MAP$journal)
MAPp <- MAP[, c("journal", "scat")] %>% dplyr::rename("Publication Title" = journal, "Research Category" = scat)
MAPp[, 2] <- factor(MAPp[, 2],
labels = c("IPV Interventions Research",
"SMW-Inclusive IPV Research"))
jsft1 <- ftable(MAPp) %>% as.matrix()
jsft2 <- ifelse(jsft1 == 0, NA, jsft1)
jsftt <- apply(jsft2, 1, sum, na.rm = TRUE)
jsftt <- paste0("**", jsftt, "**")
jsft <- cbind(jsft2, jsftt)
kable(jsft, col.names = c(colnames(jsft)[1:2], "$N_{Articles_{Total}}$"), caption = "Number of Formally Reviewed Articles per Journal in Each Research Domain Covered in this Review {#tbl:jsft}", align = c("c", "c", "c"))
```
## Systematic Review \& Evaluation Analytic Approach {.shrink}
```{r cdbk, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE, fig.show='none', fig.keep='none'}
source("cdbk.R")
```
```{r tblcdbk}
cdbk.ft$clab <- gsub("\\n", "", cdbk.ft$clab)
kable(cdbk.ft, col.names = c("\\textbf{Information Category}", "Codes"), caption = "Codebook Constructed from the Discrete Summative Data Compiled Across the Formally Reviewed Literature {#tbl:cdbk}", align = c("r", "l"))
```
## Methodological Rigor
# Part III. Literature Review \& Methodological Critique
## IPV Perpetrator Interventions Efficacy
## Overview of IPV-Related Community-Based and Action-Oriented IPV Research {.shrink}
```{r fig.cap="Timeline of publication years of the reviewed literature"}
knitr::include_graphics("graphics/inputs/yrhist.png")
```
## Substantive Research Topics
```{r fig.cap="Substantive Research Topics Covered across the Reviewed Empirical Research"}
knitr::include_graphics("graphics/inputs/topics.png")
```
## Target Populations
```{r fig.cap="Target Populations Included in the Sampling Frames among the Review Literature in Each Substantive Research Category"}
knitr::include_graphics("graphics/inputs/populations.png")
```
## Sampling Frame Definitions \& Sampling Methods
```{r fig.cap="Sampling Methods Employed among the Review Literature in Each Substantive Research Category"}
knitr::include_graphics("graphics/inputs/sampling.png")
```
## Sampling \& Data Collection Settings
```{r}
knitr::include_graphics("graphics/inputs/settings.png")
```
## Methodologies \& Methods Utilized {.shrink}
\begin{columns}[c]
\begin{column}[0.48\linewidth]
`r tufte::newthought("Research Designs")`
```{r}
knitr::include_graphics("graphics/inputs/designs.png")
```
\end{column}
\begin{column}[0.48\linewidth]
`r tufte::newthought("Research Methodologies")`
```{r}
knitr::include_graphics("graphics/inputs/methodologies.png")
```
## Methodological Strengths and Weaknesses of the Reviewed Literature
## Ecological Levels of Analysis
## Epilogue: Reflections on the Unique Challenges of Conducting a Community-Psychology-Focused Systematic Literature Reviews
<file_sep>/_comps_docs/_zmisc/MAPtimeline.R
journals <- data.frame(
j = c("Action Research",
"American Journal of Community Psychology",
"American Journal of Health Promotion",
"American Journal of Orthopsychiatry",
"American Journal of Preventive Medicine",
"American Journal of Public Health",
"Australian Community Psychologist",
"Community Development",
"Community Development Journal",
"Community Mental Health Journal",
"Community Psychology in Global Perspective",
"Cultural Diversity \\& Ethnic Minority Psychology",
"Global Journal of Community Psychology Practice",
"Health Education \\& Behavior",
"Health Promotion Practice",
"Journal of Applied Social Psychology",
"Journal of Community \\& Applied Social Psychology",
"Journal of Community Practice",
"Journal of Health \\& Social Behavior",
"Journal of Prevention \\& Intervention",
"Journal of Primary Prevention",
"Journal of Rural Community Psychology",
"Journal of Social Issues",
"Journal of Community Psychology",
"Psychiatric Rehabilitation Journal",
"Psychology of Women Quarterly",
"Psychosocial Intervention",
"Social Science \\& Medicine",
"The Community Psychologist",
"Transcultural Psychiatry",
"Progress in Community Health Partnerships: Research, Education, \\& Action",
"Journal of Interpersonal Violence",
"Violence Against Women",
"Violence \\& Victims",
"Journal of Family Violence"),
cat = c(rep("Community Psychology", 31), rep("Violence", 4)),
yr1 = c(2003, 1973, 1986, 1930, 1985, 1971, 2006, 2005, 1966, 1965, 2015, 1995, 2010, 1997, 2000, 1971, 1991, 1994, 1967, 1996, 1981, 1980, 1997, 1973, 1996, 1976, 2011, 1967, 1975, 1997, 2007, 1989, 1995, 1986, 1986)
)
journals$yr2 <- rep(2017, nrow(journals))
journals$j <- sapply(as.character(journals$j), Rabbr)
timeline(journals, text.size = 3, text.color = NA) + scale_fill_manual(values = mpal(1:nrow(journals)), guide = FALSE) + thm_Rtft() + xlim(range(c(journals$yr1, journals$yr2)))
bibkey <- MAP$bibkey
scat <- MAP$scat %>% factor()
jrnl <- MAP$jrnl %>% factor()
codes.tp <- ctbl.m[ctbl.m$cat == "TOPIC", "code"] %>% droplevels()
tl <- data.frame(jrnl, scat)
yr1.s3 <- min(MAP[MAP$scat == "S3", "year"])
yr1.s4 <- min(MAP[MAP$scat == "S4", "year"])
yr2.s3 <- max(MAP[MAP$scat == "S3", "year"])
yr2.s4 <- max(MAP[MAP$scat == "S4", "year"])
tl <- within(tl, {
yr1 <- ifelse(scat == "S3", yr2.s3, yr2.s4)
yr2 <- ifelse(scat == "S3", yr1.s3, yr1.s4)
})
<file_sep>/_comps_docs/_zmisc/CPM-MethodDefinitions.Rmd
---
title: "Community Methods Reading Notes - Definitions of Each Method"
date: "3 May 2017"
---
\Frule
\newpage
# Community-Based Participatory Research & Participatory Action Research
> "Participatory action research represents a stance within qualitative research methods --- an epistemology that assumes knowledge is rooted in social relations and most powerful when produced collaboratively through action" [@fine2003participatory, p. 173].
> > "PAR ... has typically been practiced within community-based social action projects with a commitment to understanding, documenting, or evaluating the impact that social programs, social problems, or social movements bear on individuals and communities" [@fine2003participatory, p. 173].
> > "... at its core [PAR] articulates a recognition that knowledge is produced in collaboration and in action" [@fine2003participatory, p. 173].
> "[PAR] has been gradually gaining recognition in the social sciences promising strategy for actively involving research participants in the development and implementation of the research process while attempting to pursue socially relevant research issues" [@balcazar2004participatory, p. 17].
> "... [PAR] not only aims to empower individuals, but more important, it aims to facilitate higher order social, organizational, or political change" [@balcazar2004participatory, p. 17].
> "PAR combines social investigation, education, and social action to define and address social problems, particularly among disenfranchised and oppressed groups..." [@balcazar2004participatory, p. 17].
> "**[PAR] is both a research ideology and a strategy for conducting research**" [@balcazar2004participatory, p. 17; _emph. added_].
> > "As an ideology, PAR represents a set of beliefs regarding the role of social science research in alleviating social injustice and promoting community involvement in social change efforts" [@balcazar2004participatory, p. 17].
> "... [participatory] research was developed to change something about the specific situation right at that time, rather than, or as well as, later" [@senn2005you, p. 356].
> "Participatory research involves a very different level of involvement. A study can be said to be participatory when it requires the involvement of people from the group or community of interest in some or all stages of research" [@senn2005you, p. 360].
> > "\ @maguire1987doing suggested that 'participatory research combines three activities: investigation, education, and action' (p. 29)." [@senn2005you, p. 360].
> > "The _investigation_ part of the process is a 'social' investigation 'involving participation of oppressed and ordinary' people in problem posing and solving [@maguire1987doing, p. 29]" [@senn2005you, p. 360, _emph. in orig._].
> > "Both the participants in the study and the researchers are _educated_ in the process about the possible causes of the problem 'through collective discussion and interaction' [@maguire1987doing, p. 29]" [@senn2005you, p. 360, _emph. in orig._].
> > "... both the researchers and the participants 'join in solidarity to take collective _action_, both short and long term' [@maguire1987doing, p. 29, emphasis added]" [@senn2005you, p. 360, _emph. in orig._].
> > "The reasoning is clear. The people who are going to be affected by change efforts should be involved in directing that change, and mutual education will be necessary for that to occur" [@senn2005you, p. 360].
\SFrule
# Geographic Information Systems & Place-Based Methods
## Geographic Information Systems
> "Geographic information systems (GIS) are computer-based programs designed for the storage, visualization, analysis, and display of data that contain spatial components" [@lohmann2016geographic, p. 93].
> "The software for GIS allows for the _visual layering_ of geographic detail ... to assist in better understanding the relationships between spatial variables" [@lohmann2016geographic, p. 93, _emph. added_].
> > "The data generally take one of three forms: points ..., lines ..., and polygons. ... These categories contain some flexibility, however ..." [@lohmann2016geographic, p. 93].
> "GIS also has many analytic tools to extract information concerning the spatial variables. Among the more basic of these are the capacity to analyze the distance and area of any geographic variable" [@lohmann2016geographic, p. 93].
> > "More complex analytical operations involve _querying_ --- searching selected spacial variables for locating where specific criteria are met. ... By conducting queries for different spatial variables, areas of spacial correspondence can be located and analyzed" [@lohmann2016geographic, p. 93, _emph. added_].
## Place-Based Methods
> [An underlying assumption of place-based research is that\] "... the _development of self identity_ is not restricted to making distinctions between oneself * significant others, but _extends with no less importance to objects and things, and **the very spaces and places in which they are bound**_" [@proshansky1983place, p. 57, _emph. added_].
> [Place-based research methods\] "... consider the influence of the physical settings that are inherently part of any socialization context on self identity" [@proshansky1983place, p. 58].
> > "In a constantly changing technological society, it is imperative to ask the question, 'What are the effects of the built environment?' not only in regard to the personality development of the individual, but also in terms of how he defines himself within society" [@proshansky1983place, p. 58].
> [Place-based methods\] "... stress the importance of an ecological approach in which the person is seen as involved in _transactions_ with a changing world" [@proshansky1983place, p. 59, _emph. added].
> > "... the psychologically healthy state of a person's sense of self is not a static one, rather it is characterized by growth and change in response to a changing physical and social world" [@proshansky1983place, p. 59].
> [**Place-identity**\] "... is a sub-structure of the self-identity of the person consisting of, broadly conceived, cognitions about the physical world in which the individual lives" [@proshansky1983place, p. 59].
> > "These cognitions represent memories, ideas, feelings, attitudes, values, preferences, meanings, and conceptions of behavior and experience which relate to the variety and complexity of physical settings that define the day-to-day existence of every human being" [@proshansky1983place, p. 59].
> > "At the core of such physcial environment-related cognitions is the 'environmental past' of the person; a past consisting of places, spacing and their properties which have served instrumentally in the satisfaction of the person's biological, psychological, social, and cultural needs" [@proshansky1983place, p. 59].
\SFrule
# Program Evaluation
> [Program evaluators\] "... use social research methods to study, appraise, and help improve social programs, including the soundness of the programs' diagnoses of the social problems they address, the way the programs are conceptualized and implemented, the outcomes they achieve, and their efficiency" [@rossi2004aevaluation, p. 3].
> "Program evaluation is the use of social research methods to systematically investigate the effectiveness of social intervention programs in ways that are adapted to their political and organizational environments and are designed to inform social action to improve social conditions" [@rossi2004aevaluation, p. 16].
> "One aspect of evaluating a program ... is to assess how good the **program theory** is --- in particular, how well it is formulated and whether it presents a _plausible and feasible_ plan for improving the target social conditions" [@rossi2004bexpressing, p. 133, _emph. added_].
> "A **program's theory** is the conception of what must be done to bring about the intended social benefits. _As such it is the foundation on which every program rests_" [@rossi2004bexpressing, p. 133, _emph. added_].
> "For **program theory** to be assessed, ... it must first be _expressed clearly and completely_ enough to stand for review" [@rossi2004bexpressing, p. 133, _emph. added_].
> "... _evaluators often distinguish between **process (or implementation) evaluation** and **outcome (or impact) evaluation**_" [@rossi2004cassessing, p. 171, _emph. added_].
> "Program evaluation in Scheirer's (1994) words, 'verifies what the program is and whether or not it is delivered as intended to the targeted recipients'. It does not, however, attempt to assess the effects of the program on those recipients" [@rossi2004cassessing, p. 171].
> > "Where **process evaluation** is an ongoing function involving repeated measurements over time, it is referred to as **program monitoring**" [@rossi2004cassessing , p. 171, _emph. added_].
> > > "**Program process monitoring** [_emph. in orig_] is the continual measurement of intended outcomes of the program, usually of the social conditions it is intended to improve" [@rossi2004cassessing, p. 171].
> "The **changed conditions** are the **intended outcomes** or products of the programs. _Assessing the degree to which a program produces these outcomes is a core function of evaluators_" [@rossi2004dmeasuring, p. 203, _emph. added_].
> "A program's **intended outcomes** are ordinarily identified in the program's impact theory. _Sensitive and valid measurement of those outcomes_ is technically challenging but essential to assessing a program's success" [@rossi2004dmeasuring, p. 203, _emph. added_].
> > "... ongoing monitoring of outcomes can be critical to effective program management" [@rossi2004dmeasuring, p. 203].
> > "Interpreting the results of outcome measurement and monitoring ... presents a challenge to stakeholders because a given set of outcomes can be produced by factors other than program processes" [@rossi2004dmeasuring, p. 203].
\SFrule
# Mixed-Methods Research
> [One approach to mixed-methods research developed by @morgan1998practical and referred to here as the "**complimentary sequence**" approach, involves\] "... _combining_ qualitative and quantitative methods ..." [@morgan1998practical, p. 362, _emph. added_].
> "The core of [the **complimentary sequence**] approach is an effort to _integrate_ the complimentary strengths of different methods through a division of labor" [@morgan1998practical, p. 366, _emph. added_].
> > "This amounts to _using a qualitative and a quantitative method for different but well-coordinated purposes_ within the same overall research project" [@morgan1998practical, p. 366, _emph. added_].
> > "The division of labor is accomplished through _two basic decisions_ ..." [@morgan1998practical, p. 366, _emph. added_].
> > > [1\] "... a _priority_ decision that pairs a principal method with a complimentary method and ..." [@morgan1998practical, p. 366, _emph. added_].
> > > [2\] "... a _sequence_ decision that determines whether the complementary method precedes or follows the principal method" [@morgan1998practical, p. 366, _emph. added_].
> [_**Equal-status mixed-methods research designs**_ are those\] "... where _high quality_ qualitative and quantitative data are collected ... " [and] "... the qualitative and quantitative research paradigms are given equal weight" [@stefurak2016mixed, p. 347].
> > "Sometimes it is said that paradigms are incommensurable and cannot be mixed. _However, they can be, using a **dialectical and dialogic logic**. That is why **equal-status mixed methods designs** are also called **interactive mixed methods designs**_" [@stefurak2016mixed, p. 347, _emph. added_]
\newpage
`r tufte::newthought("\\large{Mixed-methods research, in general, is:}")`
\vspace*{1em}
\Large{``}
> > ... a research approach or methodology:
> > - focusing on research questions that call for real-life contextual understandings, multi-level perspectives, and cultural influences;
> > - employing rigourous quantitative research assessing magnitude and frequency of constructs and rigorous qualitative research exploring the meaning and understanding of constructs;
> > - utilizing multiple methods (e.g., intervention trials and in-depth interviews);
> > - _intentionally integrating or combining these methods to draw on the strengths of each_;
> > - framing the investigation within philosophical and theoretical positions
\vspace*{-1em}
> > `r tufte::quote_footer("\\Large{''}")`
> > `r tufte::quote_footer("@creswell2016best, (p. 4, _emph. added_)")`
\SFrule
# Qualitative Research Methods
> "Qualitative approaches to research reflect an underlying philosophy of science and set of methods that embody many of the values of community research and action (Banyard & Miller, 1998)" [@stein2004asking, p. 21].
> "Some community scholars advocate qualitative approaches as a way to better understand individual diversity and the nuance of social context" [@stein2004asking, p. 21].
> "By emphasizing detailed, first-hand descriptions of people and settings, qualitative approaches methods are thought to enhance the study of behavior embedded in a larger social world (Trickett, 1996)" [@stein2004asking, p. 21].
> "Qualitative methods are also used to arrive at more ecologically-sensitive constructs upon which quantitative measures can be based" [@stein2004asking, p. 21].
> "Qualitative findings are said to help dispel misconceptions about marginalized populations perpetuated by the use of quantitative measures originally developed with mainstream samples (Dumka [et al.], 1998; Maton [et al.], 1998)" [@stein2004asking, p. 21].
> [Qualitative research is comprised of a set of tools designed, in large part, to\] "... facilitate researchers' knowledge about the experiences and perspectives of the group under study, as well as the development of research instruments that are useful and relevant" [@hughes2002using, p. 776].
> "**Focus groups** are in-depth group interviews employing relatively homogenous groups to provide information around topics specified by researchers" [@hughes2002using, p. 776, _emph. added_].
> [Focus groups\] "... have several strengths that make them particularly useful for facilitating research that reflects the social realities of a cultural group" [@hughes2002using, p. 776].
> "Focus groups provide researchers with _direct access_ to the language and concepts participants use to _structure their experiences_ and to think and talk about a designated topic" [@hughes2002using, p. 776, _emph. added_].
> "Within-group homogeneity prompts focus group participants to elaborate stories and themes that help researchers understand how participants structure and organize their social world" [@hughes2002using, p. 776].
> "In their reliance on social interaction, focus groups can also help researchers identify cultural knowledge that is shared among group members as well as to appreciate the range of different experiences individuals within a group may have" [@hughes2002using, p. 776].
> [Qualitative methods bring\] "... researchers closer to a _phenomenological understanding_ of a cultural group. Such an understanding can help investigators ask better research questions and develop the measures needed to study them" [@hughes2002using, p. 776, _emph. added_].
\SFrule
# Quantitative Research Methods
> [Quantitative methods\] "... facilitate rigorous hypotheses testing, produce research that is both internally valid and externally generalizable, and assess cause-and-effect relationships between constructs" [@connell2016introduction, p. 121].
> "... the quantitative methods used by community-based researchers provide a strong framework for investigating complex and contextualized phenomena in their own right" [@connell2016introduction, p. 121].
> "To maintain pace with the field's complex theories of the 'interplay between people and contexts' [@shinn2000cross, p. 185], community researchers should use data-analytic methods that best represent the relationship of ecological and contextual domains to the phenomena being investigated. This means that community researchers need to adopt measurement approaches that do a better job of capturing contextual information, such as social network analysis (SNA) or geographic information systems (GIS) methods [@luke2005getting], or 'ecometric' approaches (Raudenbush & Sampson, 1999, p. 3)" [@connell2016introduction, pp. 121--122].
> > "Community researchers also must make greater use of data-analytic methods that incorporate contextual (i.e., setting-level) and cross-level (i.e., interactions between setting-level and individual-level) effects ..., as well as more complex processes (e.g., indirect or mediating effects, moderation effects) cross-sectionally, longitudinally, and across contextual settings ..." [@connell2016introduction, p. 122].
> > "... analytic methods should be dynamic and adaptable to the challenges of complex research designs and data structures" [@connell2016introduction, p. 122].
> > > "... previous examinations of the state of the field's statistical methods [e.g., @luke2005getting] revealed that community researchers continue to rely on more traditional data-analytic methods (e.g., analysis of variance [ANOVA], regression, and correlation), rather than methods permitting greater complexity (e.g., structural equation modeling [SEM], cluster analysis, and SNA) or contextualization (e.g., multilevel modeling [MLM] and GIS analysis)" [@connell2016introduction, p. 122].
\newpage
# References
\refs
<file_sep>/auxDocs/zTUFTE_TITLE_BLOCK.Rmd
---
title: " "
date: " "
---
# A Community Engaged Approach to Address Intimate Partner Violence among Sexual Minority Women
## by: <NAME>
```{r fig.fullwidth = TRUE, echo = FALSE, fig.width = 8, out.width = '\\linewidth'}
knitr::include_graphics('graphics/inputsPDF/intmodel.pdf')
```
\begin{center}
\Large{\textit{A thesis submitted in partial fulfillment of the}} \\
\Large{\textit{requirements for the degree of}} \\
\Large{\textit{Master of Science}} \\
\Large{\textit{in}} \\
\Large{\textit{Psychology}}
\end{center}
-----
\begin{center}
\textbf{\textit{Portland State University}} \\
\textit{`r format(Sys.Date(), '%d %b %Y')`}
\end{center}<file_sep>/_comps_docs/_zmisc/CCACE (nd)-Systematic rvws and meta-anaylyses-stepbystep guide.md
---
title: "Excerpts from 'Systematic reviews and meta-analyses: A step-by-step guide'"
author: "Center for Cognitive Ageing and Cognitive Epidemiology"
url: "http://www.ccace.ed.ac.uk/research/software-resources/systematic-reviews-and-meta-analyses"
---
A **systematic review** answers a defined research question by collecting and summarising all empirical evidence that fits pre-specified eligibility criteria.
Systematic reviews, just like other research articles, can be of varying quality. They are a significant piece of work (the Centre for Reviews and Dissemination at York estimates that a team will take 9-24 months), and to be useful to other researchers and practitioners they should have:
clearly stated objectives with pre-defined eligibility criteria for studies
explicit, reproducible methodology
a systematic search that attempts to identify all studies
assessment of the validity of the findings of the included studies (e.g. risk of bias)
systematic presentation, and synthesis, of the characteristics and findings of the included studies
It is essential that each review is approached rigorously and with careful attention to detail. Plan carefully, and document everything. The consensus reporting guidelines for different study designs proposed by EQUATOR (\url{http://www.equator-network.org/}) are a useful starting point. PRISMA provides guidance on what you should include when reporting a systematic review.
- \textsc{Step 1}: Why do a systematic review? \checkmark
- \textsc{Step 2}: Who will be involved? \checkmark
- \textsc{Step 3}: Formulate the problem. Has it been done before? Registering your review. \checkmark
- \textsc{Step 4}: Perform your search. \checkmark
- \textsc{Step 5}: _**Data extraction.**_
- \textsc{Step 6}: _**Critical appraisal of studies (quality assessment).**_
- \textsc{Step 7}: _**Data synthesis.**_
- \textsc{Step 8}: _**Presenting results (writing the report).**_
- \textsc{Step 9}: Archiving and updating.
\newpage
# \textsc{Step 5:} Data extraction.
Devise a form tailored to your research question to ensure you obtain all relevant information from each of the included studies. You will need to pilot and refine this form before your final search. Ideally this form should be electronic to minimise transcription errors.
This will generally include details of study characteristics, participant characteristics, intervention and setting, and results.
-----
# \textsc{Step 6}: Critical appraisal of studies (quality assessment).
There is no consensus on the best way to assess study quality, but most methods encompass issues such as:
- Appropriateness of study design to the research objective
- Risk of bias
- Other issues related to study quality:
- Choice of outcome measure
- Statistical issues
- Quality of reporting
- Quality of the intervention
- Generalisability
The consensus reporting guidelines for different study designs proposed by EQUATOR (\url{http://www.equator-network.org/} ) are a useful starting point, but note these are guidelines for reporting of original studies, NOT for assessment of study quality.
STROBE (\url{http://www.strobe-statement.org}) also provides useful guidelines for good reporting of observational research, including checklists of items that should be included in this type of research.
Useful resources for assessing quality of different study designs can be found here, and some specific examples are QUADAS for studies of diagnostic accuracy.
This article by Sanderson, Tatt and Higgins (2007) provides a review of the wide range of tools used to assess study quality. It does not recommend any specific tool for general use, but lists the domains which should be included [1) appropriate selection of participants 2) appropriate measurement of variables and 3) appropriate control of confounding, as well as considering design specific biases]. You may need to develop your own quality assessment tool, but do seek advice on the best method of quality assessment for your review.
This article by The Cochrane Collaboration describes a tool they developed for assessing risk of bias in random trials \url{http://www.bmj.com/content/343/bmj.d5928.full.pdf}
-----
# \textsc{Step 7}: Data synthesis
You can present the data from the studies narratively and/or statistically (a meta-analysis). If studies are very heterogenous it may be most appropriate to summarise the data narratively and not attempt a statistical (meta-analytic) summary.
There are guidelines as to how to present a narrative synthesis [here](http://www.york.ac.uk/inst/crd/SysRev/%21SSL%21/WebHelp/SysRev3.htm) (see section 1.3.5.1 - Narrative Synthesis). A statistical synthesis should include numerical and graphical presentations of the data, and also look at the strength and consistency of the evidence, and investigate reasons for any inconsistencies. See this [meta-analysis presentation](http://www.ccace.ed.ac.uk/sites/default/files/meta-analysis%20in%20cognitive%20ageing%20and%20epidemiology%20research.ppt?phpMyAdmin=UlK8xfSbayFQJAV7hgjO-sdYkp3) by <NAME>.
For guidance on how to review a diagnostic study see this [powerpoint presentation](http://www.ccace.ed.ac.uk/sites/default/files/Diagnostic_Studies_Systematic_Review_Chappell1.ppt?phpMyAdmin=UlK8xfSbayFQJAV7hgjO-sdYkp3) by <NAME>.
-----
# \textsc{Step 8}: Presenting results (writing the report)
It is essential that your review is presented clearly, and in accordance with current best practice. For general guidance see the Equator network site [here](http://www.equator-network.org/resource-centre/library-of-health-research-reporting/).
The [PRISMA statement](http://www.prisma-statement.org/index.htm) and this related article by [Liberati et al. (2009)](http://www.plosmedicine.org/article/info%3Adoi%2F10.1371%2Fjournal.pmed.1000100) provides very clear guidance on reporting of systematic reviews, including a flow chart of studies included, and there is useful advice on reporting meta-analysis of observational studies ([MOOSE](http://www.equator-network.org/index.aspx?o=1052)) at JAMA, 2000 PMID: [10789670](http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=pubmed&dr=abstract&list_uids=10789670).
For general guidance on scientific writing [click here](http://www.equator-network.org/resource-centre/library-of-health-research-reporting/guidance-on-scientific-writing/)
For a very useful guide on how to write a systematic review by Prof. <NAME> (2010) [click here](http://www.sbirc.ed.ac.uk/documents/advice%20on%20how%20to%20write%20a%20systematic%20review.pdf)
For examples of published systematic reviews and meta-analyses by researchers from CCACE [click here](http://www.ccace.ed.ac.uk/research/software-resources/ccace-publications-of-systematic-reviews-and-meta-analyses?phpMyAdmin=UlK8xfSbayFQJAV7hgjO-sdYkp3).
<file_sep>/_comps_docs/_MAP-untex.R
f1 <- "z.R"
f2 <- "zz.R"
yml <- "#' ---
#' title: \"Appendix C: Results from Qualitative Comparative Analyses\"
#' author: \"<NAME>\"
#' date: \"`r format(Sys.Date(), '%d %B %Y')`\"
#' ---"
ymlline <- 5
ex <- data.frame(
a = c("`\\{\\{(.*?)\\}\\}`",
"(\\\\)+chisq",
"(\\\\)+url\\{(.*?)\\}",
"(\\\\)+%",
"(\\\\)+refs",
"(\\\\)+Frule",
"\\.pdf",
"(\\\\)+rowgroup\\[.*?\\]\\{(.*?)\\}",
"\\\\part\\{(.*?)\\} <!\\-\\- (Part I{1,})\\. \\-\\->",
"(\\\\)+&",
"(\\\\)+tufteskip",
"`r tufte::newthought\\(\"(.*?)\")`",
"source\\(bibs\\.R\\)"
),
b = c("\\1",
"\\\\chi^{2}",
"\\1",
"%",
"",
"",
"\\.png",
"\\1",
"# \\2. \\1",
"&",
"",
"**\\1.**",
"source\\(z\\.R\\)"
))
# "\n> \\1\n"
# library(Riley)
source("../Riley/R/Rretex.R")
source("../Riley/R/Runtex.R")
Runtex(file = f1, addlexpr = ex, yml = yml, ymlline = ymlline, cat = TRUE, catFile = f2)
# .Rword(f2)
<file_sep>/data/RQDAQuery-ecoLvls.R
library(RQDA); openProject("data/RQDA/comps.rqda", updateGUI = FALSE)
s3 <- readLines("zs3.txt")
s4 <- readLines("zs4.txt")
# ys3 <- data.frame()
# ys4 <- data.frame()
ys3 <- vector(mode = "character", length = length(s3))
ys4 <- vector(mode = "character", length = length(s4))
for (i in 1:length(s3)){
ys3[i] <- RQDAQuery(s3[i])
}
for (i in 1:length(s4)){
ys4[i] <- as.character(RQDAQuery(s4[i]))
}
ys3df <- data.frame(unlist(ys3))
ys4df <- data.frame(unlist(ys4))
# library(dplyr)
# y$text <- gsub("c\\(\"(.*?)\"", "'\\1'", y$text)
# yy <- unlist(y$text) %>% as.character()
# yydf <- as.data.frame(yy)
write.csv(ys3df, "data/RQDA/RQDAQuery-MAPseltext-s3.csv")
write.csv(ys4df, "data/RQDA/RQDAQuery-MAPseltext-s4.csv")
closeProject()
<file_sep>/cdbk.R
catt <- Rtdf(cdbk$catlab, names = c("Information Category", "$N_{sub-codes}$"))
cdbk.ft1 <- with(cdbk, {
ftable(clab, catlab) %>% data.frame()
})
cdbk.ft1$Freq <- ifelse(cdbk.ft1$Freq == 0, NA, cdbk.ft1$Freq)
cdbk.ft <- na.omit(cdbk.ft1)[, 1:2]
rownames(cdbk.ft) <- NULL
cdbk.ft$catlab <- as.character(cdbk.ft$catlab)
cdbk.ft$catlab <- gsub("^0(\\d\\.)", "\\1", cdbk.ft$catlab)
cdbk.ft$catlab <- ifelse(duplicated(cdbk.ft$catlab), NA, paste0("**", cdbk.ft$catlab, "**"))
cdbk.ft <- cdbk.ft[, c("catlab", "clab"), drop = FALSE]
# kable(cdbk.ft)
cats <- unique(cdbk.ft$catlab) %>% as.character()
# ctime <- paste0("cat_", seq(1:length(cats)))
# cdbk.ft$catlab <- as.character(cdbk.ft$catlab)
# cdbk.ft$code <- as.character(cdbk.ft$code)
# y <- vector(mode = "list", length = length(cats))
# names(y) <- cats
# # for (i in length(cats)) {
# y[i] <- cdbk.ft[cdbk.ft$catlab == cats[i], "clab"]
# # }
#
# x <- vector(mode = "list", length = length(cats))
# names(x) <- cats
#
# for (i in length(cats)) {
# x <- dplyr::filter(cdbk.ft, catlab == cats[i])[, "clab"]
# }
<file_sep>/_comps_docs/_zmisc/flowChart.R
dims <- c(1, 11)
plot(dims, dims, type = 'n')
abline(h = 1:11, v = 1:11, lty = 3)
b1dim <- list(x = c(4, 8), y = c(8, 10))
segments(x0 = b1dim$x[1], y0 = b1dim$y[1], x1 = b1dim$x[2], y1 = b1dim$y[1])
segments(x0 = b1dim$x[1], y0 = b1dim$y[2], x1 = b1dim$x[2], y1 = b1dim$y[2])
segments(x0 = b1dim$x[1], y0 = b1dim$y[1], x1 = b1dim$x[1], y1 = b1dim$y[2])
segments(x0 = b1dim$x[2], y0 = b1dim$y[1], x1 = b1dim$x[2], y1 = b1dim$y[2])
text(x = 6, y = 10.25, labels = "1. Identification")
text(x = 5, y = 9.8, labels = "150 Initial hits")
text(x = 4.5, y = 8.8, labels = "IPV Interventions Research = 86 - 5 Duplicates ==> 81")
text(x = 4.5, y = 7.8, labels = "SMW-Inclusiv IPV Research = 64 - 12 Duplicates ==> 52")
text(x = 4.5, y = 6.8, labels = "Combined = 133 - 2 Duplicates ==> 131")
<file_sep>/_MAP-slides.Rmd
---
title: "A Methodological Review of Community-Based Research Related to Intimate Partner Violence"
author: "<NAME>"
date: "`r format(Sys.Date(), '%d %B %Y')`"
---
## Presentation Agenda {.shrink}
- \textsc{\textcolor{dkblue}{Introduction}} <!-- Part I. -->
- Research Questions
- Rationale
- Guiding Community-Psychology Theoretical Frameworks
- \textsc{\textcolor{dkblue}{Systematic Literature Search \& Review Methods}} <!-- Part II. -->
- Analytic Approach
- Initial Literature Screening, Assessment, \& Organization
- Synthesis & Methodological Evaluation
- \textsc{\textcolor{dkblue}{Literature Synthesis \& Review}} <!-- Part III. -->
- Summative Characteristics of the Included Literature
- Sampling Frame Definitions and Sampling Methods
- Methodologies & Methods Utilized
- Ecological Levels of Analysis Reflected in the Literature
- IPV Perpetration Interventions
- Perpetrator Intervention Programs' Efficacy
- Processes of Change
- Public Policy & Program Practices
- Prevention-Oriented IPV Intervention Programs
- IPV Prevention Program Implementation & Evaluation Methods
- Assessing Risk of IPV among Sexual Minority Women
- Police Responses to Same-Gender IPV
- \textsc{\textcolor{dkblue}{Summative Methodological Critique}} <!-- Part IV. -->
- Ecological-Validity
- \textsc{\textcolor{dkblue}{Discussion}} <!-- Part V. -->
- Limitations of This Review
- Implications
# Introduction <!-- PART I. -->
## Rationale
`r tufte::newthought("Intersecting Community-Psychology Theory \\& Research Methodology")`
## Guiding Community-Psychology Theoretical Frameworks
`r tufte::newthought("Ecological systems theory and the Social Ecological Model")`
`r tufte::newthought("Protective (versus risk) Factors")`
`r tufte::newthought("'The inextricable relationship of empowerment and politics'")` **[@riger1993what, p. 283]**.
# Systematic Literature Search \& Review Methods <!-- PART II. -->
## Analytic Approach
### Initial Literature Screening, Assessment, \& Organization
### Synthesis & Methodological Evaluation
`r tufte::newthought("Defining and Evaluating Methodological Rigor")`
# Literature Synthesis \& Review <!-- PART III. --> {.shrink}
## Summative Characteristics of the Included Literature
### Sampling Frame Definitions and Sampling Methods
### Methodologies & Methods Utilized
### Ecological Levels of Analysis Reflected in the Literature
`r tufte::newthought("Substantive Research Topics at Varying Levels of Ecological Analysis")`
## IPV Perpetration Interventions
### Perpetrator Intervention Programs' Efficacy
### Processes of Change
### Public Policy & Program Practices
## Prevention-Oriented IPV Intervention Programs
### IPV Prevention Program Implementation & Evaluation Methods
## IPV Research Specifically Inclusive of Sexual Minority Women
### Assessing Risk of IPV among Sexual Minority Women
`r tufte::newthought("IPV Risk Factors, Causes, \\& Consequences among Sexual Minority Youth")`
### Police Responses to Same-Gender IPV
# Summative Methodological Critique <!-- PART IV. -->
### Ecological-Validity
### Limitations of This Review
### Implications
# References {.allowframebreaks}
\refs
<file_sep>/data/sql/RQDA-MAP-SQL/RQDAmap-codingTbl-POP-s3.sql
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (28,1,"1737.0","4720.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (30,1,"4722.0","6544.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (28,1,"6546.0","8773.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (32,1,"10271.0","12246.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"12248.0","14009.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (28,1,"14011.0","16327.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (33,1,"16329.0","17957.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (37,1,"17959.0","20780.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (37,1,"20782.0","22705.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"24691.0","27049.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (36,1,"27051.0","29855.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (30,1,"29857.0","31667.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (32,1,"31669.0","33157.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (29,1,"33159.0","35143.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (38,1,"35145.0","37247.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (37,1,"37249.0","38956.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (39,1,"40875.0","42637.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"42639.0","44404.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"45819.0","48172.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"48174.0","50123.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"50125.0","51808.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"51810.0","53440.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"53442.0","55560.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (33,1,"55562.0","57701.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (33,1,"57703.0","39697.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (28,1,"59699.0","61313.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"61315.0","63457.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (32,1,"64926.0","67124.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (40,1,"67126.0","69107.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"69109.0","71029.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (28,1,"72217.0","73937.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (37,1,"73939.0","75437.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (29,1,"1737.0","4720.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (33,1,"10271.0","12246.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (35,1,"12248.0","14009.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (29,1,"14011.0","16327.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (36,1,"16329.0","17957.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (35,1,"24691.0","27049.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"35145.0","37247.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (28,1,"40875.0","42637.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (35,1,"42639.0","44404.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (35,1,"45819.0","48172.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (35,1,"48174.0","50123.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (36,1,"57703.0","39697.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (37,1,"61315.0","63457.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (40,1,"64926.0","67124.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (32,1,"67126.0","69107.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (35,1,"69109.0","71029.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (29,1,"72217.0","73937.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (34,1,"73939.0","75437.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (29,1,"16329.0","17957.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (35,1,"35145.0","37247.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (29,1,"40875.0","42637.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (29,1,"48174.0","50123.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (29,1,"57703.0","39697.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (35,1,"73939.0","75437.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (37,1,"16329.0","17957.0");
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`) VALUES (40,1,"73939.0","75437.0");
<file_sep>/_comps_docs/journal/journal-quote-lesbianIdentity.Rmd
---
title: "Lesbian Identity"
date: "2014-04-10"
---
> "Lesbian identity does not follow the well-worn ruts in the conventional road that lead from sex to gender to gender-role to gender-of-partner.In the same way, our families cannot be neatly mapped according to a conventional family tree, where connections are established by law (as in marriage) or by genetic connections. Invisible through those lenses, our families have thrived nonetheless."
>
> `r tufte::quote_footer("[@mitchell2010lesbian, p. 119]")`
-----
# References
<div class="refs">
<file_sep>/_comps_docs/journal/journal-nwlgbtq-projectGoals.Rmd
---
title: "NW LGBTQ Research Project Goals - Draft"
date: "2014-03-03"
---
This project is interested in examining how gender roles play out in lesbian relationships, and how gender and power dynamics influence IPV within these relationships. The goal of this research is ultimately to better inform IPV prevention efforts within this population. This research will necessarily shed light on the personal lives within an issue within an already marginalized population, and this ..?
Still in a block...
<file_sep>/data/summary-hendricks2006.md
A comparative evaluation was also conducted by @hendricks2006recidivism with two IPV perpetrator intervention programs in a small metropolitan Wisconsin county [@ingram2012nchs]. Although @hendricks2006recidivism ultimately describes the programs evaluated their investigation as two independent interventions, one of the programs, _"Reasoning & Rehabilitation (R&R)"_ is in fact evaluated as a `sort of nested or secondary` intervention within the county's larger IPV perpetrator intervention system, _"Stopping Abuse for Everyone (SAFE)"_ (p. 704). That is, individuals are referred to the _R&R_ program `if they are determined as in need of` greater levels of supervision based on a clinical assessment administered during the _SAFE_ program's intake process. Such individuals are expected to return to and complete the _SAFE_ program's intervention after completing the additional _R&R_ program. @hendricks2006recidivism\'s investigation also included an evaluation of the predictive validity of the _Level of Service Inventory–Revised_ [_LSI-R_; @andrews1994level], which is the assessment administed to determine intervention participants' levels of risk and need at intake for the _SAFE_ program. Regarding the latter, results from logistic regression analyses provided minimal support for the LSI-R scale's accuracy, sensitivity, and specificity in correctly classifying recidivating intervention participants (overall classification accuracy = 66% correct). However, while formal logistic regression analysis was not similarly conducted to examine the measure's predictive accuracy regarding program placement, comparisons<!-- via between-subjects factorial--> via cross-tabulations and chi-square ($\chisq$) analyses revealed significant differences in both LSI-R scores and recidivism rates among intervention participants. Specifically, participants who completed the _SAFE_ program without referral to the _R&R_ program (14.4% recidivated) had signficantly lower recidivism rates than those who completed both interventions (32.4% recidivated; $\chisq(1) = 6.26,~p < .05$). As @hendricks2006recidivism note, because participants were referred to the _R&R_ program on the basis of their LSI-R scores, these differences in recidivism rates do not necessarily inform comparisons regarding each interention program's individual effectiveness at reducing or preventing future violence pereptration among participants. However, a possibly missing point in @hendricks2006recidivism\'s report and analytic conclusions is that these observed differences may provide support for the discriminant validity of the LSI-R as a measure effective in determining the relative risk and needs levels of IPV pereptration intervention participants.
<file_sep>/_comps_docs/_zmisc/zDEPRECATED-maplvls.R
# tmaplvls <- t(maplvls[, -1]) %>% data.frame()
# rownames(tmaplvls) <- eco[, 1]
# mplvls$lvl <- ifelse(mplvls[, 1] == 1, lvls[1], NA)
# flvl <- function(x, lvls, yval = 1, nval = NA) {
# ## this is essentially a way to create a single (factor) variable/column
# ## from a set of dichotomous (1, 0) variables/columns
# ## - 'x' is the set of dichotomous vars;
# ## 'lvls' is the set of values to code each var in 'x' where x$var == 1
# ## thus, ncol(x) & length(lvls) should be the same length ##
# nvar <- max(apply(x, 1, sum))
# # y <- vector(mode = 'character', length = nvar)
# y <- x
# y[, 1] <- ifelse(x[, 1] == 1, lvls[1], NA)
# for (i in 1:length(lvls)) {
# # y[i] <- rep(NA, nrow(x))
# y[, i] <- ifelse(x[, i] == 1, lvls[i], y[, i])
# }
# return(y)
# }
# xlvls <- flvl(x = x, lvls = lvls)
# x$id <- rownames(x)
# xlong <- reshape(x, varying = 1:4, direction = 'long', sep = "")
# xlong <- dplyr::rename(xlong, lvl = time, ynlvl = l)
# l <- layout.sphere(xnetg)
# plot(xnetg, rescale = T, layout = l, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# ln <- layout.norm(l)#, ymin = -1.5, ymax = 2, xmin = -1.5, xmax = 2)
# plot(xnetg, rescale = F, layout = ln, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# l <- layout.mds(xnetg)
# plot(xnetg, rescale = T, layout = l, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# ln <- layout.norm(l)#, ymin = -1.5, ymax = 2, xmin = -1.5, xmax = 2)
# plot(xnetg, rescale = F, layout = ln, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# l <- layout.davidson.harel(xnetg)
# plot(xnetg, rescale = T, layout = l, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# ln <- layout.norm(l)#, ymin = -1.5, ymax = 2, xmin = -1.5, xmax = 2)
# plot(xnetg, rescale = F, layout = ln, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
#
# l <- layout.drl(xnetg)
# plot(xnetg, rescale = T, layout = l, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# ln <- layout.norm(l)#, ymin = -1.5, ymax = 2, xmin = -1.5, xmax = 2)
# plot(xnetg, rescale = F, layout = ln, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# l <- layout.kamada.kawai(xnetg)
# plot(xnetg, rescale = T, layout = l, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# ln <- layout.norm(l)#, ymin = -1.5, ymax = 2, xmin = -1.5, xmax = 2)
# plot(xnetg, rescale = F, layout = ln, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
#
# l <- layout.lgl(xnetg)
# plot(xnetg, rescale = T, layout = l, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# ln <- layout.norm(l)#, ymin = -1.5, ymax = 2, xmin = -1.5, xmax = 2)
# plot(xnetg, rescale = F, layout = ln, edge.arrow.size = .2, vertex.label.color = "#1a1e22")
# lnetm <- merge(lnet, lnetft, all.x = TRUE)
# V(lnetg)$label.size <- (V(lnetg)$Freq*0.02)*0.65
# plot(lnetg, rescale = TRUE)
# arcplot(as.matrix(llong))
#+ keysnet2, fig.fullwidth=TRUE
# library(igraph)
# lsys <- c("'Individual' = 'Micro'; 'Relationship' = 'Micro-Meso'; 'Community' = 'Meso-Exo'; 'Societal' = 'Exo-Macro'")
# slong <- within(llong1, {
# lvl <- car::recode(lvl, lsys)
# })
#
# slongv <- within(llongv, {
# x <- car::recode(x, lsys)
# })
#
# slongg <- graph_from_data_frame(slong, directed = FALSE, vertices = slongv)
#
# V(slongg)$size <- V(slongg)$Freq
# V(slongg)$color <- adjustcolor(V(slongg)$vclr, alpha.f = 0.5)
# V(slongg)$frame.color <- V(slongg)$border
# #mpal(1:length(unique(llongv3[, 1])))
#
# # lv <- cbind(names(V(llongg)), V(llongg)$Freq) %>% data.frame()
# # rep(V(llongg)$Freq, V(llongg)$Freq)
# # lv$Freq <- as.integer(lv$Freq)
# E(slongg)$width <- 0.35
#
# lsfr <- layout_with_fr(slongg)
# lsn <- norm_coords(lsfr)#, ymin = -1.5, ymax = 2, xmin = -1.5, xmax = 2)
# plot(slongg, rescale = T, layout = lsn, edge.arrow.size = 0.5, vertex.label.color = "#1a1e22", vertex.label.cex = log(V(slongg)$size)*0.35)
# llongv1$vclr <- ifelse(llongv1$lvl == "Individual", vclrs[1], llongv1$lvl)
# llongv1$vclr <- ifelse(llongv1$lvl == "Relationship", vclrs[2], llongv1$vclr)
# llongv1$vclr <- ifelse(llongv1$lvl == "Community", vclrs[3], llongv1$vclr)
# llongv1$vclr <- ifelse(llongv1$lvl == "Societal", vclrs[4], llongv1$vclr)
# llongv1$Freq <- ifelse(llongv1$Freq == 0, NA, llongv1$Freq)
# llongv <- na.omit(llongv1)
# llongv1$lvl <- car::recode(llongv1$lvl, llabs1)
# llongv2$key <- gsub("(\\w+)\\d{4}\\w+", "\\1", llongv2$key)
# llongv2$key <- sapply(llongv2$key, RtCap)
# llongv <- merge(llongv3, llong1, by.y = "id", by.x = "x", all = T)
# vclrs <- mpal(1:length(unique(llong[, 2])))
# llongv3 <- Rtdf(llong[, "scat"], names = c("x", "Freq"))
# scat <- car::recode(scat, sclabs)
# llongv$vclr <- ifelse(llongv$x == "Individual", vclrs[1], NA)
# llongv$vclr <- ifelse(llongv$x == "Relationship", vclrs[2], llongv$vclr)
# llongv$vclr <- ifelse(llongv$x == "Community", vclrs[3], llongv$vclr)
# llongv$vclr <- ifelse(llongv$x == "Societal", vclrs[4], llongv$vclr)
# llongv$vclr <- ifelse(llongv$x == "IPV Interventions Research", catpal[1], catpal[2])
# llongv$border <- ifelse(llongv$x == "Individual", vclrs[1], NA)
# llongv$border <- ifelse(llongv$x == "Relationship", vclrs[2], llongv$vclr)
# llongv$border <- ifelse(llongv$x == "Community", vclrs[3], llongv$vclr)
# llongv$border <- ifelse(llongv$x == "Societal", vclrs[4], llongv$vclr)
# llongv <- llongv[, c("id", "Freq", "vclr")]
#mpal(1:length(unique(llongv3[, 1])))
# lv <- cbind(names(V(llongg)), V(llongg)$Freq) %>% data.frame()
# rep(V(llongg)$Freq, V(llongg)$Freq)
# lv$Freq <- as.integer(lv$Freq)
# lvnames0 <- attributes(E(llongg))$vnames
# id <- gsub("(\\w+)\\d{4}\\w+", "\\1", id[])
# id <- sapply(id, RtCap)
#, ymin = -1.5, ymax = 2, xmin = -1.5, xmax = 2)
# MAPeco <- merge(MAP, mplvls1, by.x = "bibkey", by.y = "key", all = TRUE)[, c("bibkey", "jrnl", "year", "journal", "scat", "prop", "j.loc", "j.year", "SJR", "Hindex", "cpv", "l1", "l2", "l3", "l4", "exo_macro", "meso_exo", "micro", "nlvls", "nsys")]
# llongv01$cvclr <- ifelse(is.na(llongv01$cvclr), llongv01$vclr, llongv01$cvclr)
# llongbi <- rbind(llongbi1, llongbi2)
#
# llongbig <- graph_from_data_frame(llongbi, directed = T, vertices = llongv)
#
# lbivnames0 <- vertex_attr(llongbig, "name")
# lbivnames1 <- gsub("(\\w+)\\d{4}\\w+", "\\1", lbivnames0)
#
# lbivnames <- sapply(lbivnames1, RtCap, USE.NAMES = FALSE)
#
# V(llongbig)$name <- lbivnames
#
# V(llongbig)$size <- V(llongbig)$Freq+1
# V(llongbig)$color <- adjustcolor(V(llongbig)$vclr, alpha.f = 0.65)
# V(llongbig)$frame.color <- V(llongbig)$vclr
# E(llongbig)$width <- 0.35
#
# kindex.big <- V(llongbig)$name %>% length()-4 ## same as `kindex` above, but for the igraph data ##
# lbiblsize <- c(log(V(llongbig)$size[1:kindex.big])*0.45, log(V(llongbig)$size[-1:-kindex.big])*0.15) ## currently, this is actually identitcal, and tehrefore unneccessarily repetative of, to the llongg vertex attributes, but included here, as usual, for reusability/reproducibility purposes
#
# # PLOT - `llongbig` ---------------------------------------------------------
#
# lbfr <- layout_with_fr(llongbig)
# lbn <- norm_coords(lbfr)
# plot(llongbig, rescale = T, layout = lbn, edge.arrow.size = 0.075, vertex.label.color = V(llongbig)$cvclr, vertex.label.cex = lblsize)
# #+ keysnet_lvls2, fig.fullwidth = TRUE
# llongdg <- graph_from_data_frame(llong[, c(2, 1)], directed = T, vertices = llongv)
#
# ldvnames0 <- vertex_attr(llongdg, "name")
# ldvnames1 <- gsub("(\\w+)\\d{4}\\w+", "\\1", ldvnames0)
#
# ldvnames <- sapply(ldvnames1, RtCap, USE.NAMES = FALSE)
#
# V(llongdg)$name <- ldvnames
#
# V(llongdg)$size <- V(llongdg)$Freq+1
# V(llongdg)$color <- adjustcolor(V(llongdg)$vclr, alpha.f = 0.65)
# V(llongdg)$frame.color <- V(llongdg)$vclr
# E(llongdg)$width <- 0.35
#
# kindex.dg <- V(llongdg)$name %>% length()-4 ## same as `kindex` above, but for the igraph data ##
# ldblsize <- c(log(V(llongdg)$size[1:kindex.dg])*0.45, log(V(llongdg)$size[-1:-kindex.dg])*0.125) ## currently, this is actually identitcal, and tehrefore unneccessarily repetative of, to the llongg vertex attributes, but included here, as usual, for reusadlity/reproducidlity purposes
#
# # PLOT - `llongdg` ---------------------------------------------------------
#
# ldfr <- layout_with_fr(llongdg) %>% norm_coords()
# plot(llongdg, rescale = T, layout = ldfr, edge.arrow.size = 0.075, vertex.label.color = V(llongdg)$cvclr, vertex.label.cex = lblsize)
#
# plvl <- sapply(mplvls[, 1:4], table) %>% data.frame()
# apply(plvl, 2, Rbinom)
# sapply(mplvls[, c(1, 2)], table) %>% chisq.test
# sapply(mplvls[, c(1, 3)], table) %>% chisq.test
# sapply(mplvls[, c(1, 4)], table) %>% chisq.test
# sapply(mplvls[, c(2, 3)], table) %>% chisq.test
# sapply(mplvls[, c(2, 4)], table) %>% chisq.test
# sapply(mplvls[, c(3, 4)], table) %>% chisq.test
# aledges <- cbind(as.character(alnet$clab), alnet$to)
# allabs0 <- unique(aledges1[, 1])
# alrec <- paste0("'", allabs0, "' = '.", allabs0, "'; ", collapse = "")
# cbaft <- with(cba, {ftable(code, bibkey)}) %>% data.frame()
# cbaft <- cbaft[cbaft$Freq > 0, ]
# cbaft
# cbaft <- with(cba, {ftable(code, bibkey)}) %>% data.frame()
# cbaft <- cbaft[cbaft$Freq>0,]
# cbaft
# cbaft <- with(cba, {ftable(clab, bibkey)}) %>% data.frame()
# cbaft <- cbaft[cbaft$Freq>0,]
# cbaft
# reccb <- paste0("'", cbk$code, "' = '", seq(1:nrow(cbk)), "'", collapse = "; ")
# alrec <- c(alrec0, alrec)
# aln1 <- car::recode(alnet[, 1], alrec2) %>% as.character()
# aln <- cbind(aln1, alnet[, 2])
# aln[, 1] <- factor(aln[, 1])
# al$lvl <- as.character(al$lvl)
# allabs1 <- car::recode(allabs0, alreca)
# allabs2 <- car::recode(allabs1, alrec3)
# V(aledges0)$name <- av.ar
# allabs <- sort(c(unique(aledges[, 1]), unique(aledges[, 2])))
# allabs2 <- car::recode(allabs1, alrec3)
# allabs3 <- ifelse(grepl("\\(L\\d\\) \\w+", allabs1),
# gsub("\\((L\\d)\\) \\w+",
# "\\1", allabs1), allabs1)
# allabs2[1:4] <- sapply(allabs2, 1:4, noquote)
# avalsdf2 <- Rtdf(lcba.a$id)
# avnlvls <- apply(lcba.a[, 2:5], 1, sum)
# avalsdf <- data.frame(lcba.a, avnlvls) ## "nlvls" = number of eco levels each code crosses per case (bibkey) ##
# avals <- V(aledges0)$Freq
# aarcs <- .25 * (avals %>% matrix())
# aarcs <- ifelse(aarcs == 0, NA, aarcs) %>% na.omit()
# allabs <- c(unique(aledges[, 1]), unique(aledges[, 2]))
# av.all <- V(aledges0)$name
# av.lvl <- av.all[av.all %in% elvl]
# av.a <- av.all[!av.all %in% elvl]
# alreca <- paste0("'", av.a, "' = 'A-", seq(1:length(av.a)), "'", collapse = "; ")
# av.ar <- car::recode(av.a, alreca)
# allabs0 <- c(unique(aledges[, 1]), unique(aledges[, 2]))
# allabs1 <- car::recode(allabs0, reccb)
# alrec2 <- paste0("'", unique(alnet[, 2]), "' = '", elvl, "'", collapse = "; ")
# lvl <- gsub("\\.", "", lvl)
# alnet[, "clab"] <- gsub("\\n", "", alnet[, "clab"])
<file_sep>/_comps_docs/_zmisc/LitMap.R
#' ---
#' title: "Geography of Reviewed Research"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE
# SETUP --------------------------------------------------------------
source("../SETUP.R")
knitr::opts_chunk$set(
tidy = TRUE,
echo = TRUE,
fig.keep = 'high',
fig.show = 'hold',
results = 'asis',
tidy.opts = list(comment = FALSE),
echoRule = NULL,
echoRuleb = TRUE
)
options(scipen = 10)
# rpm()
#'
#'
# USMAP --------------------------------------------------------
# usmap <- read.csv("data/usmap.csv")[, -1]
# write.csv(usmap, "data/usmap.csv", row.names = FALSE) ## there was an extra column ("X") in the csv file (which contained the rownames from the first time I saved the file) that removed by not including that first column and then re-writing the file below ##
usmap <- read.csv("data/usmap.csv")
states = read.csv("data/states.csv", header = T, row.names = 1)
states <- data.frame(state = rownames(states), states)
snames <- aggregate(cbind(long, lat) ~ id, data = usmap,
FUN = function(x) mean(range(x)))
states <- merge(snames, states, by.x = "id", by.y = "state")
states$region <- c(3, 4, 4, 3, 4, 4, 1, 3, 3, 3, 3, 4, 4, 2, 2, 2, 2, 3, 3, 1, 3, 1, 2, 2, 3, 2, 4, 2, 4, 1, 1, 4, 1, 3, 2, 2, 3, 4, 1, 1, 3, 2, 3, 3, 4, 1, 3, 4, 3, 2, 4)
states$div <- c(6, 9, 8, 7, 9, 8, 1, 5, 5, 5, 5, 9, 8, 3, 3, 4, 4, 6, 7, 1, 5, 1, 3, 4, 6, 4, 8, 4, 8, 1, 2, 8, 2, 5, 4, 3, 7, 9, 2, 1, 5, 4, 6, 7, 8, 1, 5, 9, 5, 3, 8)
states.s <- states[, c("id", "ST", "region", "div")]
states.rg <- merge(usmap, states.s)
srg <- aggregate(cbind(long, lat) ~ region, data = states.rg,
FUN = function(x) mean(range(x)))
srg <- merge(srg, states.s)
srg <- srg[, c("id", "ST", "region", "long", "lat")]
regions <- c("Northeast", "Midwest", "South", "West")
srg <- within(srg, {
region <- factor(region, labels = regions)
})
sdv <- aggregate(cbind(long, lat) ~ div, data = states.rg,
FUN = function(x) mean(range(x)))
sdv <- merge(sdv, states.s)
sdv <- sdv[, c("id", "ST", "div", "long", "lat")]
divisions <- c("New England", "Middle Atlantic", "East North Central", "West North Central", "South Atlantic", "East South Central", "West South Central", "Mountain", "Pacific")
sdv <- within(sdv, {
div <- factor(div, labels = divisions)
})
## LABELING CENTROIDS =====================================================
states[10,2] <- 1841536
states[19,2] <- 706827
states[2,2] <- -1344021
states[2,3] <- -1974685
states[37,2] <- 181757
states[24,2] <- 400430
states[23,2] <- 1264168
states[23,3] <- -92122
states[13,2] <- -1174084
states[13,3] <- -0
states[5,2] <- -1750000
states[12,2] <- -350000
states[12,3] <- -2010000
states[21,3] <- -343925
states[21,2] <- 1955994
states[22,2] <- 2230000
states[7,3] <- -6
states[31,2] <- 2120364
states[31,3] <- -255347
states[30,3] <- 209979
states[46,3] <- 309355
states[8,3] <- -362274
states[47,2] <- 1881512
states[18,2] <- 1354662
states[49,2] <- 1657769
states[49,3] <- -520174
states[41,2] <- 1770243
states[41,3] <- -1015010
states[20,3] <- 497611
## Adjust hawaii ##
maxlong <- range(usmap[usmap$id == "California", "long"])[1]
usmap <- within(usmap, {
long <- ifelse(long <= maxlong, NA, long)
})
usmap <- na.omit(usmap)
# GGPLOT MAPS --------------------------------------------------------
library(ggplot2)
ggbase <- ggplot() +
geom_map(data = usmap, map = usmap,
aes(x = long, y = lat, map_id = id, group = group),
fill = "transparent", color = pal_my[19], size = 0.15)
gg <- ggbase + thm_Rcl_tft()
gg + geom_map(data = states, map = usmap,
aes(map_id = id, fill = ST),
color = pal_my[19], size = 0.15) +
scale_fill_manual(values = mpal(1:nlevels(states$ST)), guide=FALSE) +
geom_text(data = states, aes(long, lat, label = ST), size = 3)
## bibState ========================================================
bibState = list(
boal2014barriers = c("Oregon"),
boal2014impact = c("Oregon"),
contrino2007compliance = c("New York"),
enriquez2010development = c("Missouri"),
ermentrout2014this = c("North Carolina"),
feder2011need = c("Oregon"),
foshee2004assessing = c("North Carolina"),
gillum2008benefits = c("Massachusetts"),
gondolf1999comparison = c("Pennsylvania", "Texas", "Colorado"),
gregory2002effects = c("Ohio"),
hendricks2006recidivism = c("Wisconsin"),
hovell2006evaluation = c("California"),
howell2015strengthening = c("Michigan"),
muftic2007evaluation = c("North Dakota"),
potter2011bringing = c("New Hampshire"),
price2009batterer = c("Illinois"),
roffman2008mens = c("Washington"),
rumptz1991ecological = c("Michigan"),
silvergleid2006batterer = c("Oregon"),
sullivan2002findings = c("Illinois", "Michigan"),
thompson2000identification = c("Washington"),
welland2010culturally = c("California"))
bibState <- stack(bibState)
names(bibState) <- c("state", "bibkey")
bibState.t <- Rtdf(bibState$state, names = c("id", "Freq"))
bibSt <- merge(states, bibState.t, by = "id", all = TRUE)
bibRg <- merge(srg, bibState.t, by = "id", all = TRUE)
bibRg.t <- Rtdf(bibRg$region, names = c("region", "Freq"))
bibRg <- merge(srg, bibRg.t, by = "region", all = TRUE)
bibRg <- within(bibRg, {
lat <- ifelse(region == "West", lat/2, lat)
long <- ifelse(region == "West", long/1.5, long)
})
bibDv <- merge(sdv, bibState.t, by = "id", all = TRUE)
bibDv.t <- Rtdf(bibDv$div, names = c("div", "Freq"))
bibDv <- merge(sdv, bibDv.t, by = "div", all = TRUE)
## CHLOROPLETH MAPS ========================================================
frq.st <- 1:length(unique(bibSt$Freq))
frq.rg <- 1:length(unique(bibRg$Freq))
frq.dv <- 1:length(unique(bibDv$Freq))
grays2 <- colorRampPalette(pal_my[c(20, 1)])
### PLOT - cloropleths - states ####
ggchl.st <- ggbase + geom_map(data = bibSt, map = usmap,
aes(map_id = id, fill = Freq),
color = pal_my[19], size = 0, alpha = 0.5) +
scale_fill_gradientn(colours = grad(frq.st, p = grblues, alpha = 0.5),
na.value = NA, name = expression(N[studies])) +
guides(fill = guide_legend(barwidth = 2, alpha = 0.5)) +
geom_text(data = bibSt, aes(long, lat, label = ST),
size = 3, family = "serif", colour = pal_my[20]) + thm_Rcl_tft(ltitle = TRUE, lpos = "top", ldir = "horizontal") +
theme(legend.title.align = 0.5, legend.box.spacing = unit(-1, 'cm')) #+
ggchl.st
### ggchloro - regions ####
grblues2 <- colorRampPalette(pal_my[c(2, 16)], alpha = TRUE)
ggchl.rg <- gg + geom_map(data = bibRg, map = usmap,
aes(map_id = id, fill = Freq),
color = pal_my[19], size = 0, alpha = 0.5) +
scale_fill_gradientn(colours = grad(frq.rg, p = grblues2, alpha = 0.5),
na.value = NA, name = expression(N[studies])) +
guides(fill = guide_legend(barwidth = 2, alpha = 0.5)) +
geom_text(data = bibRg, aes(long, lat, label = region),
size = 10, family = "serif", colour = pal_my[20])
ggchl.rg
ggchl.dv <- ggplot() +
geom_map(data = states, map = usmap,
aes(x = long, y = lat, map_id = id),
color = NA, size = 0.15) +
geom_path(data = usmapDv,
aes(x = long, y = lat, group = group), size = 0.5)
# scale_fill_gradientn(colours = grad(frq.dv, p = grblues2, alpha = 0.5),
# na.value = NA, name = expression(N[studies])) +
# guides(fill = guide_legend(barwidth = 2, alpha = 0.5)) +
# geom_text(data = bibDv,
# aes(long, lat, label = div),
# size = 4, family = "serif", colour = pal_my[20])
ggchl.dv
bibDv.s <- bibDv[, c("div", "id", "ST", "Freq")]
usmapDv <- merge(usmap, bibDv.s)
# aggregate(cbind(long, lat) ~ div, data = bibDv,
# FUN = unique)
# divn <- Rtdf(usmapDv$div, names = c("div", "n"))
# f <- function(x) {
# y <- data.frame(id = 1:sum(x[, 2]))
# for (i in 1:nrow(x)) {y$id[1:x[i, 2]] <- paste0(x[i, 1], ".", 1:x[i, 2]))}
# }
# divgrp <- f(divn)
# names(divgrp) <- "divgrp"
# divgrp <- separate(divgrp, divgrp, c("div", "grpn"), remove = FALSE)
# usmapDv <- merge(usmapDv, divn, all = TRUE)
usmapDv$group2 <- paste0(usmapDv$div, ".", as.numeric(usmapDv$group))
ggbase + geom_map(data = bibDv, map = usmapDv,
aes(x = long, y = lat, map_id = id,
fill = div), size = 0.25, stat = "contour")
# geom_map(data = bibDv, map = usmap,
# aes(map_id = id, fill = Freq),
# color = pal_my[19], size = 0, alpha = 0.5) +
# geom_path(color = "black")
# scale_fill_hue(l = 40) +
# coord_equal()
ggplot() + geom_map(data = usmapDv, map = usmap,
aes(x = long, y = lat, map_id = id, group = group),
color = pal_my[19], size = 0, alpha = 0.5)
# scale_fill_gradientn(colours = grad(frq.dv, p = grblues2, alpha = 0.5),
# na.value = NA, name = expression(N[studies])) +
# guides(fill = guide_legend(barwidth = 2, alpha = 0.5)) +
# geom_text(data = bibDv, aes(long, lat, label = div),
# size = 4, family = "serif", colour = pal_my[20])
# ggchl.dv
### ggdensity - points ####
ggdens <- gg +
# geom_text(data = bibSt, aes(long, lat, label = ST), size = 2.5, colour = mypal[18]) +
geom_point(data = bibSt, aes(x = long, y = lat, colour = Freq)) +
geom_point(data = bibSt, aes(x = long, y = lat,
size = Freq, colour = Freq, alpha = Freq)) +
scale_size_continuous(range=c(1, 30), guide = FALSE) +
scale_fill_gradientn(colours = grad(frq, p = grblutr),
na.value = pal_my[1], guide = FALSE)
ggdens
#
# + geom_map(data = bibSt, map = usmap,
# aes(map_id = id),
# color = pal_my[19], size = 0.15, fill = pal_my[1]) +
<file_sep>/_comps_docs/_zmisc/cdbk_tp.R
source("MAPrqda.R")
cdbk_tp <- codecats[codecats$cat == "TOPIC", ]
Rdt(cdbk_tp[order(cdbk_tp$clab), c("cid", "clab")])
tp_filter <- c(25, 100, 11, 10, 99, 23, 18, 20, 19, 95,
24, 96, 14, 6, 15, 94, 97, 21, 22, 16, 17)
cdbk_tpFilter <- cdbk_tp[cdbk_tp$cid %in% tp_filter, ]
<file_sep>/_comps_docs/_zmisc/MAP-CPV.R
#+ results='hide', fig.keep='none', fig.show='none'
source("bibs.R")
#'
#' # IPV Interventions
#'
### [MAP-interventions.csv] ####
cpv.s3 <- MAP[MAP$scat == "S3", ]
# write.csv(cpv.s3, "data/MAP-interventions.csv", row.names = FALSE)
cpv.s3
#'
#' \newpage
#'
#' # LGBTQ-IPV Research
### [MAP-lgbtq.csv] ####
cpv.s4 <- MAP[MAP$scat == "S4", ]
# write.csv(cpv.s3, "data/MAP-lgbtq.csv", row.names = FALSE)
cpv.s4
#'
#' \newpage
#'
<file_sep>/_comps_docs/_cluster-topics.R
#' ---
#' title: "Cluster Analysis - Research Topics"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#' \Frule
#'
#+ echo=FALSE
knitr::opts_template$set(invisible = list(echo = FALSE, results = 'hide', message = FALSE, warning = FALSE, cache = FALSE, fig.keep = 'none', fig.show = 'none'))
knitr::opts_chunk$set(fig.path = "graphics/cluster/rplot-clust_tops-")
#'
#+ srcbibs, opts.label='invisible'
source("QCA.R")
#'
#' \newpage
#'
#' # Cluster - Topics
#'
#+ hclust_tops
top <- cb[cb$cat == "TOPIC", ] %>% droplevels()
top <- within(top, {
cid <- ifelse(top$cid %in% tpFilter, cid, NA)
})
top <- within(top, {
bibkey2 <- ifelse(bibkey == "boal2014barriers", "boala2014barriers", bibkey)
bibkey2 <- ifelse(bibkey2 == "boal2014impact", "boalb2014impact", bibkey2)
bibkey2 <- gsub("(\\w+)(\\d{4})\\w+", "\\1 (\\2)", bibkey2)
bibkey2 <- ifelse(bibkey2 == "boala (2014)", "boal (2014a)", bibkey2)
bibkey2 <- ifelse(bibkey2 == "boalb (2014)", "boal (2014b)", bibkey2)
bibkey2 <- sapply(bibkey2, RtCap, USE.NAMES = FALSE)
bibkey3 <- paste0("@", bibkey)
clab <- gsub(" \\(General\\) ", "", clab)
clab <- gsub(" \\(General\\)", "", clab)
clab <- gsub("IPV Victimization", "IPV - V", clab)
clab <- gsub("IPV Perpetration", "IPV - P", clab)
clab <- gsub("IPV Perpetrator", "IPV - P", clab)
clab <- gsub("Victims'/Survivors'", "IPV - V", clab)
clab <- gsub("IPV Intervention", "Intervention", clab)
clab <- gsub("Intervention Program", "Intervention", clab)
clab <- gsub("Intervention/Prevention", "Intervention", clab)
clab <- gsub("Evaluation", "Eval.", clab)
clab <- gsub("Interventions", "Intervention", clab)
clab <- gsub("Coordinated Community Response to IPV", "CCR", clab)
clab <- gsub("Key Stakeholders", "Stakeholders", clab)
})
rec.clab2cid2 <- paste0("\"", top$clab, "\" = \"", top$cid, "\"", collapse = "; ")
top <- na.omit(top)
# top$bibkey.pr <- paste0("@", top$bibkey)
# rec.key2pr <- paste0("\"", top$bibkey, "\" = \"", top$bibkey.pr, "\"", collapse = "; ")
Rtdf(top$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(align = c("l", "r"))
topmat <- ftable(top$bibkey2, top$cid) %>% as.matrix()
topmatpr <- ftable(top$bibkey3, top$clab) %>% as.matrix() ## "ks4" == "bibkeys - s4" ##
# topmatt <- t(topmat)
topmatt <- ftable(top$bibkey2, top$clab) %>% as.matrix() %>% t() ## "ks4" == "bibkeys - s4" ##
topmattpr <- ftable(top$bibkey3, top$clab) %>% as.matrix() %>% t() ## "ks4" == "bibkeys - s4" ##
kable(Rmsmm(as.data.frame(topmatpr)))
kable(Rmsmm(as.data.frame(topmattpr)))
topdist <- dist(topmat)
Rmsmm(topdist)
topclust <- hclust(topdist, method = "ward.D2")
# names(topclust)
# topclust$merge
# topclust$height
# topclust$order
# topclust$labels <- paste0("@", topclust$labels)
palette(pal_my)
par(mar = c(0,2,0.7,0))
plot(topclust, sub = ' ', xlab = ' ', main = "Bibkeys Clustered by Topics",
frame.plot = F, col = 20, col.main = 18, col.axis = 18,
cex = 0.8, cex.main = 1, cex.axis = 0.65, lwd = 1.5,
font.main = 3)
abline(a = 3, b = 0, lty = 3, lwd = 1.5,
col = adjustcolor(pal_my[19], alpha.f = 0.75))
rect.hclust(topclust, h = 3, border = "#3B0C67") -> rhcl
par(op)
topGrps <- cutree(topclust, 3)
barplot(table(topGrps), col = pal_sci[1], border = pal_sci[1], main = "Cluster Member Counts - Topics", xlab = ' ', cex = 1.25, cex.main = 1.15, cex.lab = 1, cex.axis = 0.85)
as.data.frame(table(topGrps)) %>%
dplyr::rename(Group = topGrps, Nmembers = Freq) %>% ## 'rename()' {dplyr} args: [output]=[input]
kable(caption = "3-Group Solution Membership Counts (Topics)")
topmembers <- sapply(unique(topGrps),function(g) paste(rownames(topmat)[topGrps == g]))
names(topmembers) <- paste0("Group.", seq_along(topmembers))
topmembers <- t(t(topmembers))
names(topmembers) <- "Group Members"
pander(topmembers, caption = "Group Memberships Resulting from 4-Group Hierarchical Cluster Solution (Topics)")
library(cluster)
topkfit <- kmeans(topmat, 3)
p <- pal_sci[c(1, 2, 3, 5, 8)]
clusplot(topmat, topkfit$cluster, main = '3-Cluster K-Means Solution (Topics)',
color = T, shade = T, plotchar = F, cex.txt = 0.5,
col.clus = p, pch = 21, bg = adjustcolor(pal_my[19], alpha.f = .25),
labels = 4, lines = 0, col.p = pal_my[19], font.main = 3, verbose = T, span = T)
pander(t(topkfit$centers), caption = "Per Variable Cluster Means ('centers') for 3-Cluster K-Means Solution (Topics)")
topkpam <- pam(topmat, 2) ## k = n-groups ##
topsil <- silhouette(topkpam)
plot(topsil, main = "Silhouette Plot of 3-Cluster Solution\n(Topics)", font.main = 3, do.n.k = T, col = mpal(1:4, p = grays), cex = 0.5)
topCluster <- c(seq(1:3))
topkpam.clus <- round(topkpam$clusinfo, 2)
topkpam.clus <- cbind(topCluster, topkpam.clus)
topkpam.cwidth <- topkpam$silinfo[2]
topkpam.cwidth <- cbind(topCluster, round(topkpam.cwidth[[1]], 2))
topkpam.sil <- round(topkpam$silinfo[[1]], 5)
topCase <- rownames(topkpam.sil)
topkpam.sil <- cbind(topCase, topkpam.sil)
kable(topkpam.clus, col.names = c("Cluster", "Size", "$Max_{Dissimilarity}$", "$\\mu_{Dissimilarity}$", "Diameter", "Separation"), align = c("c", rep("r", ncol(topkpam.clus) - 1)), caption = "K-pam Cluster Descriptives (Topics)")
names(topkpam$silinfo) <- c("Cluster Width", "$\\mu_{Cluster Width}", "\\mu_{Width_{Overall}}")
kable(topkpam.cwidth, caption = "Cluster Widths for 3-Cluster PAM Solution (Topics)", col.names = c("Cluster", "Width"), align = c("c", "r"))
kable(topkpam.sil, col.names = c("Case", "Cluster", "Neighbor", "Silhouette Width"), caption = "Silouette Information Per Case (Topics)", row.names = FALSE)
#'
#' -----
#'
#' # Which topics cluster with other topics?
#'
#'
top2dist <- dist(topmatt)
Rmsmm(top2dist)
top2clust <- hclust(top2dist, method = "ward.D2")
# names(top2clust)
# top2clust$merge
# top2clust$height
# top2clust$order
# top2clust$labels
palette(pal_my)
par(mar = c(0,2,0.7,0))
plot(top2clust, sub = ' ', xlab = ' ', main = "Topics Clustered by Bibkeys",
frame.plot = F, col = 20, col.main = 18, col.axis = 18,
cex = 0.65, cex.main = 1, cex.axis = 0.65, lwd = 1.5,
font.main = 3)
abline(a = 4, b = 0, lty = 3, lwd = 1.5,
col = adjustcolor(pal_sci[2], alpha.f = 0.75))
# rect.hclust(top2clust, h = 4,
# border = adjustcolor(pal_sci[2], alpha.f = 0.75)) -> rhcl.h4
abline(a = 3.5, b = 0, lty = 3, lwd = 1.5,
col = adjustcolor(pal_sci[4], alpha.f = 0.75))
# rect.hclust(top2clust, h = 3.5,
# border = adjustcolor(pal_sci[4], alpha.f = 0.75)) -> rhcl.h35
abline(a = 3, b = 0, lty = 3, lwd = 1.5,
col = adjustcolor(pal_sci[5], alpha.f = 0.75))
# rect.hclust(top2clust, h = 3,
# border = adjustcolor(pal_sci[5], alpha.f = 0.75)) -> rhcl.h3
abline(a = 2.8, b = 0, lty = 3, lwd = 1.5,
col = adjustcolor(pal_sci[8], alpha.f = 0.75))
rect.hclust(top2clust, h = 2.8,
border = adjustcolor(pal_sci[8], alpha.f = 0.75)) -> rhcl.h25
# names(rhcl.h25) <- paste0("c", seq_along(rhcl.h25))
# f <- function(x) { car::recode(x, rec.clab2cid2) }
par(op)
top2clusts <- list()
for (i in 1:length(rhcl.h25)) {
top2clusts[[i]] <- car::recode(names(rhcl.h25[[i]]), rec.clab2cid2)
}
# <- if
# for (i in 1:length(top2clusts)) {
# top2clusts[[i]] <- top[top$cid %in% top2clusts[[i]], "bibkey"] %>% unique()
# }
top2 <- within(top, {
tp_c1 <- ifelse(cid %in% top2clusts[[1]], 1, 0)
tp_c2 <- ifelse(cid %in% top2clusts[[2]], 1, 0)
tp_c3 <- ifelse(cid %in% top2clusts[[3]], 1, 0)
tp_c4 <- ifelse(cid %in% top2clusts[[4]], 1, 0)
tp_c5 <- ifelse(cid %in% top2clusts[[5]], 1, 0)
tp_clust <- ifelse(cid %in% top2clusts[[1]], "C-1", NA)
tp_clust <- ifelse(cid %in% top2clusts[[2]], "C-2", tp_clust)
tp_clust <- ifelse(cid %in% top2clusts[[3]], "C-3", tp_clust)
tp_clust <- ifelse(cid %in% top2clusts[[4]], "C-4", tp_clust)
tp_clust <- ifelse(cid %in% top2clusts[[5]], "C-5", tp_clust)
})
top2bib <- top2[, c("bibkey2", "code", paste0("tp_c", 1:5), "tp_clust")]
# top2bib <- top2bib[!duplicated(top2bib), ]
topmatbib <- ftable(top2bib$bibkey2, top2bib$tp_clust) %>% as.matrix()
barcol <- adjustcolor(pal_sci[c(2, 4, 5, 8)], alpha.f = 0.65)
top2Grps <- cutree(top2clust, 5)
barplot(table(top2Grps), col = barcol, border = pal_sci[c(2, 4, 5, 8)], main = "Cluster Member Counts - Topics", xlab = ' ', cex = 1.25, cex.main = 1.15, cex.lab = 1, cex.axis = 0.85)
# as.data.frame(table(top2Grps)) %>%
# dplyr::rename(Group = top2Grps, Nmembers = Freq) %>% ## 'rename()' {dplyr} args: [output]=[input]
# kable(caption = "3-Group Solution Membership Counts (Topics)")
# top2members <- sapply(unique(top2Grps),function(g) paste(car::recode(rownames(topmatt), rec.cid2clab)[top2Grps == g]))
# names(top2members) <- paste0("Group.", seq_along(top2members))
# top2members <- t(t(top2members))
# names(top2members) <- "Group Members"
# pander(top2members, caption = "Group Memberships Resulting from 4-Group Hierarchical Cluster Solution (Topics)")
# top2kpam <- pam(topmatt, 5) ## k = n-groups ##
# top2sil <- silhouette(top2kpam)
# plot(top2sil, main = "Silhouette Plot of 3-Cluster Solution\n(Topics)", font.main = 3, do.n.k = T, col = mpal(1:4, p = grays), cex = 0.5)
# top2Cluster <- c(seq(1:3))
# top2kpam.clus <- round(top2kpam$clusinfo, 2)
# top2kpam.clus <- cbind(top2Cluster, top2kpam.clus)
# top2kpam.cwidth <- top2kpam$silinfo[2]
# top2kpam.cwidth <- cbind(top2Cluster, round(top2kpam.cwidth[[1]], 2))
# top2kpam.sil <- round(top2kpam$silinfo[[1]], 5)
# top2Case <- rownames(top2kpam.sil)
# top2kpam.sil <- cbind(top2Case, top2kpam.sil)
# kable(top2kpam.clus, col.names = c("Cluster", "Size", "$Max_{Dissimilarity}$", "$\\mu_{Dissimilarity}$", "Diameter", "Separation"), align = c("c", rep("r", ncol(top2kpam.clus) - 1)), caption = "K-pam Cluster Descriptives (Topics)")
# names(top2kpam$silinfo) <- c("Cluster Width", "$\\mu_{Cluster Width}", "\\mu_{Width_{Overall}}")
# kable(top2kpam.cwidth, caption = "Cluster Widths for 3-Cluster PAM Solution (Topics)", col.names = c("Cluster", "Width"), align = c("c", "r"))
# kable(top2kpam.sil, col.names = c("Case", "Cluster", "Neighbor", "Silhouette Width"), caption = "Silouette Information Per Case (Topics)", row.names = FALSE)
#'
#' \newpage
#'
#+
topbibdist <- dist(topmatbib)
topbibclust <- hclust(topbibdist, method = "ward.D2")
palette(pal_my)
par(mar = c(0,2,0.7,0))
plot(topbibclust, sub = ' ', xlab = ' ', main = "Bibkey Clusters based on Topics Clusters",
frame.plot = F, col = 20, col.main = 18, col.axis = 18,
cex = 0.65, cex.main = 1, cex.axis = 0.65, lwd = 1.5,
font.main = 3)
abline(a = 2.8, b = 0, lty = 3, lwd = 1.5,
col = pal_sci[8])
# rect.hclust(top2clust, h = 2.8,
# border = adjustcolor(pal_my[18], alpha.f = 0.75))
rect.hclust(hclust(dist(topmatbib), method = "ward.D2"),
h = 2.8, border = pal_sci[8]) -> rhcl_bib
topmatbib2 <- ftable(top2$bibkey3, top2bib$tp_clust) %>% as.matrix()
# topmatbib2 <- ifelse(topmatbib2 == 0, topmatbib2)
kable(topmatbib2, caption = "Bibkey Clusters based on Topics Clusters", format.args = list(zero.print = ".") )
c1 <- names(rhcl.h25[[1]]) %>% as.list
c2 <- names(rhcl.h25[[2]]) %>% as.list
c3 <- names(rhcl.h25[[3]]) %>% as.list
c4 <- names(rhcl.h25[[4]]) %>% as.list
c5 <- names(rhcl.h25[[5]]) %>% as.list
cat(tufte::newthought("'C-1 Topics:"))
pander(c1)
cat(tufte::newthought("'C-2 Topics:"))
pander(c2)
cat(tufte::newthought("'C-3 Topics:"))
pander(c3)
cat(tufte::newthought("'C-4 Topics:"))
pander(c4)
cat(tufte::newthought("'C-5 Topics:"))
pander(c5)
topmatcodes <- ftable(top2$clab, top2$tp_clust) %>% as.matrix()
topmatcodespr <- ifelse(topmatcodes == 0, "$\\cdot$", "$\\checkmark$")
kable(topmatcodespr, caption = "Topic Clusters' Membership")
#'
#+ kclust_topics, fig.fullwidth=TRUE, figPath=TRUE
library(cluster)
topbib2fanny <- fanny(topmatbib, 2)
ktopbib <- kmeans(topmatbib, 2)
clusplot(topmatbib, ktopbib$cluster, main = '2-Cluster K-Means Solution (Topics)',
color = T, shade = T, plotchar = F, cex.txt = 0.5,
col.clus = p, pch = 21, bg = adjustcolor(pal_my[19], alpha.f = .25),
labels = 1, lines = 0, col.p = pal_my[19], font.main = 3, verbose = T, span = T)
pander(t(topkfit$centers), caption = "Per Variable Cluster Means ('centers') for 2-Cluster K-Means Solution (Topics)")
topmatbib3 <- ftable(top2$bibkey2, top2bib$tp_clust) %>% as.matrix()
tmb_c1 <- ktopbib$cluster[ktopbib$cluster == 1] %>% names()
tmb_c2 <- ktopbib$cluster[ktopbib$cluster == 2] %>% names()
tmb_c1mat <- topmatbib3[rownames(topmatbib3) %in% tmb_c1, ]
apply(tmb_c1mat, 2, sum)
tmb_c2mat <- topmatbib3[rownames(topmatbib3) %in% tmb_c2, ]
apply(tmb_c2mat, 2, sum)
# topmatbib2 <- ifelse(topmatbib2 == 0, topmatbib2)
kable(topmatbib3[rownames(topmatbib3) %in% tmb_c1, ], caption = "Cluster - 1 Bibkeys", format.args = list(zero.print = ".") )
kable(topmatbib3[rownames(topmatbib3) %in% tmb_c2, ], caption = "Cluster - 2 Bibkeys", format.args = list(zero.print = ".") )
levels(top2$scat) <- c("IPV Interventions", "SMW-Inclusive")
ftable(top2$tp_clust, top2$scat)
top2$tmb_clust <- ifelse(top2$bibkey2 %in% tmb_c1, "A", "B")
top2$tmb_c1 <- ifelse(top2$bibkey2 %in% tmb_c1, 1, 0)
top2$tmb_c2 <- ifelse(top2$bibkey2 %in% tmb_c2, 1, 0)
ftable(top2[top2$tmb_clust == "A", c("bibkey2", "code")]) %>% as.matrix() %>% pander()
ftable(top2[top2$tmb_clust == "B", c("bibkey2", "code")]) %>% as.matrix() %>% pander()
#'
#' \newpage
#'
#' # References
#'
#' \refs
<file_sep>/data/MAP-analyticApproaches.R
## AnalyticApproaches - S3 ========================================================
rumptz1991 <- data.frame(bibkey = "rumptz1991ecological", code = c("QTDESC"))
gondolf1999 <- data.frame(bibkey = "gondolf1999comparison", code = c("QTDESC", "X2D", "LGR"))
thompson2000 <- data.frame(bibkey = "thompson2000identification", code = c("QTDESC", "X2D", "TTEST", "ANOVA", "LNR", "CORR", "LGR", "OR"))
sullivan2002 <- data.frame(bibkey = "sullivan2002findings", code = c("QTDESC", "TTEST", "X2D", "MANCOVA", "ANCOVA", "RMANOVA", "MLTV"))
gregory2002 <- data.frame(bibkey = "gregory2002effects", code = c("CNTA"))
foshee2004 <- data.frame(bibkey = "foshee2004assessing", code = c("OR", "CORR", "MLTV", "LGR", "MOD"))
hendricks2006 <- data.frame(bibkey = "hendricks2006recidivism", code = c("QTDESC", "ANOVA", "X2D", "TTEST"))
silvergleid2006 <- data.frame(bibkey = "silvergleid2006batterer", code = c("GT-QL", "THMA"))
hovell2006 <- data.frame(bibkey = "hovell2006evaluation", code = c("X2D", "OR", "QTDESC"))
contrino2007 <- data.frame(bibkey = "contrino2007compliance", code = c("QTDESC", "CORR", "TTEST"))
muftic2007 <- data.frame(bibkey = "muftic2007evaluation", code = c("QTDESC", "X2D", "TTEST", "LGR"))
roffman2008 <- data.frame(bibkey = "roffman2008mens", code = c("QTDESC"))
gillum2008 <- data.frame(bibkey = "gillum2008benefits", code = c("CNTA", "GT-QL", "THMA", "XCASE"))
price2009 <- data.frame(bibkey = "price2009batterer", code = c("QTDESC"))
feder2011 <- data.frame(bibkey = "feder2011need", code = c("NOTAPPLICABLE"))
ermentrout2014 <- data.frame(bibkey = "ermentrout2014this", code = c("GT-QL", "THMA"))
boal2014 <- data.frame(bibkey = "boal2014barriers", code = c("THMA", "CNTA"))
kan2014 <- data.frame(bibkey = "kan2014can", code = c("MLM", "MLTV", "MEM", "MOD"))
boal2014 <- data.frame(bibkey = "boal2014impact", code = c("QTDESC", "MANOVA", "MLTV", "ANOVA"))
howell2015 <- data.frame(bibkey = "howell2015strengthening", code = c("QTDESC", "CORR", "MULTV", "LNR"))
sargent2016 <- data.frame(bibkey = "sargent2016evaluating", code = c("QTDESC", "TTEST", "X2D", "ANOVA", "MOD"))
enriquez2010 <- data.frame(bibkey = "enriquez2010development", code = c("QTDESC", "TTEST", "THMA"))
welland2010 <- data.frame(bibkey = "welland2010culturally", code = c("CCA", "THMA", "QTDESC"))
potter2011 <- data.frame(bibkey = "potter2011bringing", code = c("QTDESC", "TTEST", "OLSRG", "X2D", "ANOVA", "CNTA"))
portwood2011 <- data.frame(bibkey = "portwood2011evaluation", code = c("QTDESC", "MLM", "ANOVA", "PHCOMP", "THMA"))
s3codes <- rbind(rumptz1991, gondolf1999, thompson2000, sullivan2002, gregory2002, foshee2004, hendricks2006, silvergleid2006, hovell2006, contrino2007, muftic2007, roffman2008, gillum2008, price2009, feder2011, ermentrout2014, boal2014, kan2014, boal2014, howell2015, sargent2016, enriquez2010, welland2010, potter2011, portwood2011)
# write.csv(s3codes, file = "data/AnalyticApproaches-s3.csv")
## AnalyticApproaches - S4 ========================================================
balsam2005 <- data.frame(bibkey = "balsam2005relationship", code = c("QTDESC", "CORR", "PATH"))
blosnich2009 <- data.frame(bibkey = "blosnich2009comparisons", code = c("QTDESC", "X2D", "OR", "LGR", "WLSE"))
oswald2010 <- data.frame(bibkey = "oswald2010lesbian", code = c("QLDESC", "THMA", "THMA-GRP"))
mustanski2014 <- data.frame(bibkey = "mustanski2014syndemic", code = c("SEM", "OR", "MGM", "RRR", "CORR", "LVM", "CFA", "IRT", "WLSE", "MLR", "DESC", "X2D"))
lewis2014 <- data.frame(bibkey = "lewis2014sexual", code = c("DESC", "CFA", "BOOT", "MLE", "SEM", "SEM-FULL", "MED", "INDEFF"))
edwards2016 <- data.frame(bibkey = "edwards2016college", code = c("QTDESC", "CORR", "ANOVA", "X2D", "PHCOMP"))
glass2008 <- data.frame(bibkey = "glass2008risk", code = c("QLDESC", "GT-QL", "THMA", "CORR", "RRR", "QTDESC", "LGR"))
sylaska2015 <- data.frame(bibkey = "sylaska2015disclosure", code = c("QTDESC", "TTEST", "QLDESC", "THMA", "CNTA"))
s4codes <- rbind(balsam2005, blosnich2009, oswald2010, mustanski2014, lewis2014, edwards2016, glass2008, sylaska2015)
# write.csv(s4codes, file = "data/AnalyticApproaches-s4.csv")
## selpoints ========================================================
x <- read.csv("data/SQL/RQDA-MAP-SQL/selPoints.csv")
x <- dplyr::rename(x, "bibkey" = casename)
xs3 <- merge(s3codes, x, all = FALSE)
xs4 <- merge(s4codes, x, all = FALSE)
xs34 <- rbind(xs3, xs4)
xs34 <- xs34[, c("caseid", "bibkey", "scat", "code", "selfirst", "selend")]
# write.csv(xs34, file = "data/analyticApproaches-codings.csv", row.names = FALSE)
codings <- read.csv("data/analyticApproaches-codings.csv")
codes <- read.csv("data/analysisCodes.csv")
x <- merge(codings, codes, all = FALSE)
write.csv(x, file = "data/analyticApproaches-codings-2.csv", row.names = FALSE)
## RQDA ========================================================
# library(RQDA); openProject("data/RQDA/comps.rqda", updateGUI = FALSE)
#
# # ys3 <- data.frame()
# # ys4 <- data.frame()
# ys3 <- vector(mode = "character", length = length(s3))
# ys4 <- vector(mode = "character", length = length(s4))
#
# for (i in 1:length(s3)){
# ys3[i] <- RQDAQuery(s3[i])
# }
#
# for (i in 1:length(s4)){
# ys4[i] <- as.character(RQDAQuery(s4[i]))
# }
#
# ys3df <- data.frame(unlist(ys3))
#
# ys4df <- data.frame(unlist(ys4))
# # library(dplyr)
# # y$text <- gsub("c\\(\"(.*?)\"", "'\\1'", y$text)
# # yy <- unlist(y$text) %>% as.character()
# # yydf <- as.data.frame(yy)
#
# write.csv(ys3df, "data/RQDA/RQDAQuery-MAPseltext-s3.csv")
# write.csv(ys4df, "data/RQDA/RQDAQuery-MAPseltext-s4.csv")
#
#
# closeProject()
<file_sep>/MAPrqda.R
#' ---
#' title: "MAP - RQDA"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE
# source("../SETUP.R")
# knitr::opts_chunk$set(
# tidy = TRUE,
# echo = TRUE,
# fig.keep = 'high',
# fig.show = 'hold',
# results = 'asis'
# )
# rpm()
#'
#' \Frule
#'
#' # RQDA Project
#'
#+ openProj, echo=-2, results='hide'
# OPEN RQDA PROJECT --------------------------------------------------------
library(RQDA)
openProject("data/RQDA/comps.rqda")
# RQDA()
# openProject("data/RQDA/comps.RQDA", updateGUI = TRUE)
# openProject("data/RQDA/MAP-new.RQDA", updateGUI = TRUE)
# openProject("data/RQDA/MAP-new.RQDA")
#'
#' # Codings Retreival
#'
#+ misc, echo=FALSE, eval=FALSE
# cases <- RQDAQuery("SELECT `_rowid_`,* FROM `cases` ORDER BY `id`")
# library(Riley)
# Rdt(cases)
# closeProject(); RQDA(); openProject("data/RQDA/comps.RQDA", updateGUI = TRUE); caseAttr <- getAttr("case") ## "getAttr()" only works when GUI is open ##
#'
#'
#+ RQDAQueries, echo=TRUE
# RQDA SQL Queries --------------------------------------------------------
## ctbl1 & cbk ========================================================
ctbl1 <- getCodingTable()[, c("cid", "codename", "index1")] ## all codings (sans coded text) ##
names(ctbl1)[2] <- "code" ## for compatability later ##
cids.all <- RQDAQuery("SELECT `id`, `name` AS `code`
FROM `freecode`
WHERE `status` = 1") ## codelist only (without categories) ##
cbk <- RQDAQuery("SELECT `name` as `code`, `memo` AS `clab`
FROM `freecode`
WHERE `status` = 1") ## codelist only (without categories) ##
cbk <- within(cbk, {
code <- gsub("FG-\\w+", "FG", code)
# code <- gsub("EXP-\\w+", "EXP", code)
# code <- gsub("LT-\\w+", "LT", code)
code <- gsub("SVY-QL-MM", "SVY-QL", code)
code <- gsub("SVY-QT-MM", "SVY-QT", code)
# code <- gsub("XS-\\w+", "XS", code)
code <- gsub("IVW-\\w+", "IVW", code)
# code <- gsub("SMIN-\\w+", "SMIN", code)
code <- gsub("HET", NA, code)
})
# ctbl1 <- merge(ctbl1, cbk, all.y = FALSE, all.x = TRUE)
## cases ========================================================
cases1 <-
RQDAQuery("SELECT `name` AS `case`, `id` AS `caseid`
FROM `cases`
ORDER BY `caseid`")
caseids1 <-
RQDAQuery("SELECT `caseid`, `selfirst`
FROM `caselinkage`
ORDER BY `caseid`")
caseAttr.rm <-
RQDAQuery("SELECT `value` AS `RM`, `caseID` AS `caseid`
FROM `caseAttr`
WHERE `variable`='RMV'
ORDER BY `caseid`")
caseAttr.srch <-
RQDAQuery("SELECT `value` AS `scat`, `caseID` AS `caseid`
FROM `caseAttr`
WHERE `variable`='SEARCH'
ORDER BY `caseid`")
## codecats ========================================================
codecats1 <-
RQDAQuery("SELECT `name` AS `cat`, `catid`
FROM `codecat`
ORDER BY `catid`")
codecats2 <-
RQDAQuery(
"SELECT treecode.cid AS cid, treecode.catid AS catid,
freecode.name AS code, freecode.memo AS clab
FROM `treecode`
INNER JOIN `freecode` WHERE
freecode.id = treecode.cid AND treecode.status = 1 ORDER BY `catid`"
)
cdbk1 <-
RQDAQuery("SELECT `name` AS `cat`, `memo` AS `catlab`, `catid`
FROM `codecat`
ORDER BY `catid`")
cdbk2 <- RQDAQuery(
"SELECT treecode.cid AS cid, treecode.catid AS catid,
freecode.name AS code, freecode.memo AS clab
FROM `treecode`
INNER JOIN `freecode` WHERE
freecode.id = treecode.cid AND treecode.status = 1 ORDER BY `catid`"
)
#'
#' # Data Wrangling \& Cleaning
#'
#+ ctbl, echo=TRUE
# DATA WRANGLING --------------------------------------------------------
## ctbl ========================================================
## Could've used cbind() in the next 3 lines bc the combined dataframes
## all (1) have the same number of rows (1/case) *and*
## (2) are all ordered by "caseid" (see RQDAQueries for each above)...
## I use merge() instead bc this avoids inadvert duplicate columns ##
caseAttr <- merge(caseAttr.rm, caseAttr.srch, by = "caseid")
caseids2 <- merge(cases1, caseids1, by = "caseid")
caseids <- merge(caseids2, caseAttr, by = "caseid")
## I use merge() for the remaining df combinations below
## bc the two dfs have differing numbers of rows ##
ctbl2 <- merge(caseids, ctbl1, by.x = "selfirst", by.y = "index1")
## this only works because ALL codings were done at the case-level,
## so all codings for a given case have the same start- and end-points...
## Since "getCodingTable()" returns the start- and end-points by default
## I included the start-points ("selfirst") for codings retrieved via
## the case-specific see queries (see above) so that these could be
## used as merging-indices with the "index1" column in the table
## returned from "getCodingTable()" ("ctbl1"; see queries above) ##
codecats <- merge(codecats2, codecats1, by = "catid")
cdbk <- merge(cdbk2, cdbk1, by = "catid")
#'
## RECODE ALL THE THINGS! (using `car::recode()`) ##
rec.code2clab <- paste0("\"", cdbk$code, "\" = \"", cdbk$clab, "\"", collapse = "; ")
rec.clab2code <- paste0("\"", cdbk$clab, "\" = \"", cdbk$code, "\"", collapse = "; ")
rec.code2cid <- paste0("\"", cdbk$code, "\" = \"", cdbk$cid, "\"", collapse = "; ")
rec.cid2code <- paste0("\"", cdbk$cid, "\" = \"", cdbk$code, "\"", collapse = "; ")
rec.cid2clab <- paste0("\"", cdbk$cid, "\" = \"", cdbk$clab, "\"", collapse = "; ")
rec.clab2cid <- paste0("\"", cdbk$clab, "\" = \"", cdbk$cid, "\"", collapse = "; ")
rec.cat2catlab <- paste0("\"", cdbk$cat, "\" = \"", cdbk$catlab, "\"", collapse = "; ")
rec.catlab2cat <- paste0("\"", cdbk$catlab, "\" = \"", cdbk$cat, "\"", collapse = "; ")
rec.cat2catid <- paste0("\"", cdbk$cat, "\" = \"", cdbk$catid, "\"", collapse = "; ")
rec.catid2cat <- paste0("\"", cdbk$catid, "\" = \"", cdbk$cat, "\"", collapse = "; ")
rec.catid2catlab <- paste0("\"", cdbk$catid, "\" = \"", cdbk$catlab, "\"", collapse = "; ")
rec.catlab2catid <- paste0("\"", cdbk$catlab, "\" = \"", cdbk$catid, "\"", collapse = "; ")
ctbl <- merge(ctbl2, codecats, by = c("cid", "code"))
ctbl <-
ctbl[, c("caseid", "case", "RM", "scat", "cid", "code", "catid", "cat")] #"clab",
## reordering columns for data-organizational purposes ...
## also removed the "selfirst" column since it's no longer needed ##
# ct.scat <- ctbl[ctbl$cat == "SEARCH", ] ## for later ##
ctbl$cat <- ifelse(ctbl$cat == "SEARCH", NA_character_, ctbl$cat)
ctbl <- na.omit(ctbl)
## Removing any codings for codes in the "SEARCH" category since the
## values for those codes (i.e., "S3" & "S4") are already reflected
## in the "scat" attribute variable (see above) ##
#'
#' \newpage
#' ## Excluded Cases
#'
#' `r tufte::newthought("The below procedures")` are conducted to remove cases that will be excluded from the present review. Excluded cases include:
#'
#' 1. Non-empirical items, such as literature reviews, intervention descriptions or proposals (with no corresponding evaluation), etc.<!--(code = `"NON-EMPIRICAL"`)-->
#' 2. Empirical studies conducted with non-U.S. samples.<!--(code = `"NON-US"`)-->
#' 3. Items not available via Portland State University's library nor interlibrary loan.<!--(code = `"NOT_AVAILABLE"`)-->
#'
#' The above-described codes were included in a code-category (`"z"`) designated for excluded cases.
#'
#'
#+ exclude
# ctbl - EXCLUDE --------------------------------------------------------
t.cse <- table(caseids$RM) ## "0" = include; "1" = exclude ##
dimnames(t.cse)[[1]] <- c("Include", "Exclude")
t.cse
ctbl$RM <- as.numeric(ctbl$RM)
ctbl.z <- within(ctbl, {
RM2 <- ifelse(ctbl$RM == 1, NA_character_, 0)
})
ctbl.z1 <- ctbl.z[ctbl.z$RM == 1, -length(ctbl.z)]
## subsetted dataframe containing only excluded cases ("rmv1 == 1") ##
ctbl.z1 <- ctbl.z1[ctbl.z1$cat == "z", ]
## subsetted df containing only codings for the "z"
## category's codes, which I used to code for exclusion criteria ##
table(ctbl.z1$code) ## tabulated reasons for exclusion from review ##
ctbl <- na.omit(ctbl.z)[, c("caseid", "case", "scat", "cid", "code", "catid", "cat")]# "clab",
## remove NAs created in the new "RM2" column...and remove the
## "RM" and "RM2" columns bc they are no longer needed ##
#'
#' Below is for the final filtering/selection process conducted in _"`bibs.R`"_ & described "[here](https://eccriley.github.io/CommPsy-SysLitRvw/litSearchMethods.html)"
#'
tpFilter <- c(25, 100, 11, 10, 99, 23, 18, 20, 19, 95, 96, 14, 6, 15, 94, 97, 21, 22, 16, 17) ##"tpFilter" is a list of the code ids (cid) corresponding to the subset of "TOPICS" codes directly applicable to IPV intervention & prevention. ##
tpFilterdf <- cdbk[cdbk$cid %in% tpFilter, c("cid", "code", "clab")]
# labs_tpFilter <- tpFilter$clab %>% as.character()
keys_tpFilter <- ctbl[ctbl$cid %in% tpFilter, "case"] %>% unique() ## "cb" created in "MAPrqda.R" ##
# ctbl - DESCRIPTIVES --------------------------------------------------------
ntot <- length(unique(ctbl.z$case)) ## N_{total} ##
nexcl <- length(unique(ctbl.z1$case)) ## N_{excluded} ##
nincl <- length(unique(ctbl$case))## N_{included} ##
#'
#' \newpage
#'
#' # Descriptives
#'
#' \[ \scriptstyle{N_{total} = `r ntot`; ~~ N_{excluded} = `r nexcl`} \]
#' \[ \mathpzc{N_{included} = `r nincl`} \]
#'
#' -----
#'
#' \newpage
#'
#+ closeProj, results='hide'
# CLOSE RQDA PROJECT --------------------------------------------------------
CleanProject(); closeProject()
#'
<file_sep>/_comps_docs/_zmisc/MAParcdiagram.R
# ctbl.gr <- cb[, c("caseid", "bibkey", "scat", "cpv", "journal", "cat", "code", "year")]
source("bibs.R")
tp <- cb[cb$cat == "TOPIC", ]
# tp$code <- droplevels(tp$code)
# tp$clab <- droplevels(tp$clab)
# tp$bibkey <- droplevels(tp$bibkey)
edges.tp1 <- cbind(tp$scat, tp$code)
edges.tp2 <- cbind(tp$scat, tp$cpv)
library(arcdiagram)
arcplot(edges.tp1)
arcplot(edges.tp2)
source("MAPlvls.R")
sedges <- cbind(snet$from, snet$to)
svals <- V(snetg)$Freq
sdeg <- degree(snetg)
sarcs <- .5*(snetft %>% matrix())
sarcs <- ifelse(sarcs == 0, NA, sarcs) %>% na.omit()
arcplot(sedges, col.arcs = hsv(0, 0, 0.1, 0.06), pch.nodes = 21, bg.nodes = snetcol, cex.nodes = log(sdeg[c("Micro", "Meso-Exo", "Exo-Macro")])+1, col.nodes = snetcol, lwd.arcs = sarcs, line = 1, cex.labels = 0.8)
ledges <- cbind(lnet$from, lnet$to)
lvals <- V(lnetg)$Freq
ldeg <- degree(lnetg)
larcs <- .85*(lnetft %>% matrix())
larcs <- ifelse(larcs == 0, NA, larcs) %>% na.omit()
arcplot(ledges, col.arcs = hsv(0, 0, 0.1, 0.075), pch.nodes = 21, bg.nodes = lnetcol, cex.nodes = log(ldeg[c("Individual", "Relationship", "Community", "Societal")]), col.nodes = lnetcol, lwd.arcs = larcs, line = 1, cex.labels = 0.8)
MAPeco <- merge(MAP, mplvls1, by.x = "bibkey", by.y = "key", all = TRUE)[, c("bibkey", "jrnl", "year", "journal", "scat", "prop", "j.loc", "j.year", "SJR", "Hindex", "cpv", "l1", "l2", "l3", "l4", "exo_macro", "meso_exo", "micro", "nlvls", "nsys")]
<file_sep>/data/sql/RQDA-MAP-SQL/RQDAmap--codecat.sql
-- CREATE TABLE "codecat" (`name` TEXT,`cid` INTEGER,`catid` INTEGER,`owner` TEXT,`date` TEXT,`dateM` TEXT,`memo` TEXT,`status` INTEGER);
INSERT INTO `codecat`(`name`,`cid`,`catid`,`owner`,`date`,`dateM`,`memo`,`status`) VALUES ("TOPIC",?,1,"Riley","Wed Feb 22 13:01:00",?,?,1);
INSERT INTO `codecat`(`name`,`cid`,`catid`,`owner`,`date`,`dateM`,`memo`,`status`) VALUES ("POPULATION",?,2,"Riley","Wed Feb 22 13:01:00",?,?,1);
INSERT INTO `codecat`(`name`,`cid`,`catid`,`owner`,`date`,`dateM`,`memo`,`status`) VALUES ("M-OVERALL",?,3,"Riley","Wed Feb 22 13:01:00",?,?,1);
INSERT INTO `codecat`(`name`,`cid`,`catid`,`owner`,`date`,`dateM`,`memo`,`status`) VALUES ("M-QL",?,4,"Riley","Wed Feb 22 13:01:00",?,?,1);
INSERT INTO `codecat`(`name`,`cid`,`catid`,`owner`,`date`,`dateM`,`memo`,`status`) VALUES ("M-QT",?,5,"Riley","Wed Feb 22 13:01:00",?,?,1);
INSERT INTO `codecat`(`name`,`cid`,`catid`,`owner`,`date`,`dateM`,`memo`,`status`) VALUES ("M-MM",?,6,"Riley","Wed Feb 22 13:01:00",?,?,1);
INSERT INTO `codecat`(`name`,`cid`,`catid`,`owner`,`date`,`dateM`,`memo`,`status`) VALUES ("z",?,7,"Riley","Wed Feb 22 13:01:00",?,?,1);
INSERT INTO `codecat`(`name`,`catid`,`owner`,`date`,`status`) VALUES ("ECO",17,"Riley","Thu May 11 13:01:00",1);
INSERT INTO `codecat`(`name`,`catid`,`owner`,`date`,`status`) VALUES ("A-QT",18,"Riley","Thu May 11 13:01:00",1);
INSERT INTO `codecat`(`name`,`catid`,`owner`,`date`,`status`) VALUES ("A-QL",19,"Riley","Thu May 11 13:01:00",1);
INSERT INTO `codecat`(`name`,`catid`,`owner`,`date`,`status`) VALUES ("M-SAMPLING",20,"Riley","Thu May 11 13:01:00",1);
INSERT INTO `codecat`(`name`,`catid`,`owner`,`date`,`status`) VALUES ("M-SETTINGS",21,"Riley","Thu May 11 13:01:00",1);
<file_sep>/_comps_docs/_zmisc/MTHDSbibs.R
#' ---
#' title: "MAP - Bibliography"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE
# SETUP --------------------------------------------------------------
source("../SETUP.R")
knitr::opts_chunk$set(
tidy = TRUE,
echo = FALSE,
fig.keep = 'high',
fig.show = 'asis',
results = 'asis',
tidy.opts = list(comment = FALSE),
echoRule = NULL,
echoRuleb = NULL,
fig.height = 5,
fig.path = "graphics/bibs/rplot-")#, dev = 'png',
# fig.retina = 4
# rpm()
#+ bibdf
### FUN - 'Rbibkeys()' ####
Rbibkeys <- function(bib) {
keys <- bib[grep("\\@.*?\\{.*?,", bib, perl = TRUE)]
keys <- gsub("\\@\\w+\\{(.*?)", "\\1", keys, perl = TRUE)
keys <- keys[!grepl("\\%.*?,", keys, perl = TRUE)]
keys <- gsub(" ", NA_character_, keys)
keys <- gsub(",", "", keys)
return(keys)
}
# BIB --------------------------------------------------------------
bib <- readLines("MAP.bib")
BIBKEY <- Rbibkeys(bib)
library(bib2df)
bibdf <- bib2df("MAP.bib")
### n.init ####
n.init <- nrow(bibdf)
ID <- seq(1:nrow(bibdf))
MAP.au <- cbind(BIBKEY, bibdf[, "AUTHOR"])
## bibdf[,2] ##
#'
#+ MAP
# MAP ----------------------------------------------------------------
MAP <- cbind(ID,
BIBKEY,
bibdf[, c("YEAR", "TITLE", "JOURNAL", "ABSTRACT")]) %>%
as.data.frame()
## bibdf[c(3:5, 8)] ##
names(MAP)[-1] <- tolower(names(MAP)[-1])
#'
#+ MAP_RQDA, results='hide', fig.keep='none', fig.show='none'
# MAP-RQDA ----------------------------------------------------------------
source("MAPrqda.R", echo = FALSE)
#'
csid <- caseids[, c("caseid", "case", "RM", "scat")]
## caseids[, -3] ##
csid$case <- factor(csid$case)
<file_sep>/auxDocs/zrenderR.R
#
# RtufteB <- function(x, ...) {rmarkdown::render(x, output_format = "tufte::tufte_book", ...)}
# RtufteH <- function(x, ...) {rmarkdown::render(x, output_format = "tufte::tufte_handout", ...)}
# RtufteHtml <- function(x, ...) {rmarkdown::render(x, output_format = "tufte::tufte_html", ...)}
# Rbeam <- function(x, ...) {rmarkdown::render(x, output_format = "beamer_presentation", ...)}
# Rword <- function(x, ...) {rmarkdown::render(x, output_format = "word_document", ...)}
# Rpdf <- function(x, ...) {rmarkdown::render(x, output_format = "pdf_document", ...)}
# Rnb <- function(x, ...) {rmarkdown::render(x, output_format = "html_notebook", ...)}
# Rhtml <- function(x, ...) {rmarkdown::render(x, output_format = "html_document", ...)}
# Repub <- function(x, ...) { ## Rendering epubs requires a second step with the .epub output to generate the kindle .mobi format ##
# rmarkdown::render(x, output_format = "bookdown::epub_book", ...)
# p <- gsub("\\.Rmd", "\\.epub", x)
# bookdown::kindlegen(p)
# }
RtftB <- function(x, ...) {rmarkdown::render(x, output_format = "tufte::tufte_book", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
RtftH <- function(x, ...) {rmarkdown::render(x, output_format = "tufte::tufte_handout", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
RtftHt <- function(x, ...) {rmarkdown::render(x, output_format = "tufte::tufte_html", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
RtftHt2 <- function(x, ...) {rmarkdown::render(x, output_format = "bookdown::tufte_html2", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
Rbeam <- function(x, ...) {rmarkdown::render(x, output_format = "beamer_presentation", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
Rword <- function(x, ...) {rmarkdown::render(x, output_format = "word_document", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
Rpdf <- function(x, ...) {rmarkdown::render(x, output_format = "pdf_document", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
Rnb <- function(x, ...) {rmarkdown::render(x, output_format = "html_notebook", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
Rhtml <- function(x, ...) {rmarkdown::render(x, output_format = "html_document", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
Rhtml2 <- function(x, ...) {rmarkdown::render(x, output_format = "bookdown::html_document2", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
RhMat <- function(x, ...) {rmarkdown::render(x, output_format = "rmdformats::material", ...); print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))}
Repub <- function(x, ...) { ## Rendering epubs requires a second step with the .epub output to generate the kindle .mobi format ##
rmarkdown::render(x, output_format = "bookdown::epub_book", ...)
# p <- gsub("\\.Rmd", "\\.epub", x)
# bookdown::kindlegen(p)
# print(format(Sys.time(), '%n[%d %b. %I:%M%p]'))
}<file_sep>/auxDocs/gallery.js
function lb() {
var x = document.getElementByClassName('lightbox-target');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function closeModal() {
document.getElementByClassName('lightbox-target').style.display = "none";
}
<file_sep>/journals.R
### FUN - 'RtCap()' ####
RtCap <- function(x) {
s0 <- strsplit(x, " ")[[1]]
nocap <- c("a", "the", "to", "at", "in", "with", "and", "but", "or", "of")
s1 <- ifelse(!s0 %in% nocap, toupper(substring(s0, 1,1)), s0)
# s2 <- toupper(substring(s[!s %in% nocap], 1,1))
s2 <- ifelse(!s0 %in% nocap, substring(s0, 2), "")
s <- paste(s1, s2, sep="", collapse=" ")
return(s)
}
### FUN - 'Rabbr()' ####
Rabbr <- function(x) {
s0 <- strsplit(x, " ")[[1]]
ex <- c("a", "the", "to", "at", "in", "with", "and", "but", "or", "of", "\\&")
s1 <- s0[!s0 %in% ex]
s2 <- substring(s1, 1,1)
s <- paste(s2, sep = "", collapse = "")
s <- toupper(s)
return(s)
}
j.map <- c("Action Research",
"American Journal of Community Psychology",
"American Journal of Health Promotion",
"American Journal of Orthopsychiatry",
"American Journal of Preventive Medicine",
"American Journal of Public Health",
"Australian Community Psychologist",
"Community Development",
"Community Development Journal",
"Community Mental Health Journal",
"Community Psychology in Global Perspective",
"Cultural Diversity and Ethnic Minority Psychology",
"Global Journal of Community Psychology Practice",
"Health Education and Behavior",
"Health Promotion Practice",
"Journal of Applied Social Psychology",
"Journal of Community and Applied Social Psychology",
"Journal of Community Practice",
"Journal of Health and Social Behavior",
"Journal of Prevention and Intervention",
"Journal of Primary Prevention",
"Journal of Rural Community Psychology",
"Journal of Social Issues",
"Journal of Community Psychology",
"Psychiatric Rehabilitation Journal",
"Psychology of Women Quarterly",
"Psychosocial Intervention",
"Social Science and Medicine",
"The Community Psychologist",
"Transcultural Psychiatry",
"Progress in Community Health Partnerships: Research, Education, and Action",
"Journal of Interpersonal Violence",
"Violence Against Women",
"Violence and Victims",
"Journal of Family Violence")
j.map <- sapply(j.map, tolower, USE.NAMES = FALSE)
#'
#+ tidy=TRUE, echoRule=NULL, Rrule=NULL, Rerule=TRUE
j.loc <- c("UK", "US", "US", "US", "US", "US", "AU", "UK", "UK", "NL", "IT", "US", "US", "US", "US", "UK", "UK", "US", "US", "US", "US", "US", "UK", "US", "US", "UK", "ES", "UK", "US", "UK", "US", "US", "US", "US", "US")
j.year <- c(2003, 1973, 1986, 1930, 1985, 1971, 2006, 2005, 1966, 1965, 2015, 1995, 2010, 1997, 2000, 1971, 1991, 1994, 1967, 1996, 1981, 1980, 1997, 1973, 1996, 1976, 2011, 1967, 1975, 1997, 2007, 1986, 1995, 1986, 1986)
SJR <- c(0.33, 1.237, 0.821, 0.756, 2.764, 2.52, NA, NA, 0.47, 0.467, NA, NA, NA, 1.177, 0.769, 0.639, 0.855, 0.278, 1.727, 0.231, 0.64, NA, 1.467, 0.425, 0.692, 1.216, 0.331, 1.894, NA, 1.141, 0.427, 1.064, 0.851, 0.449, 0.639) ## SJR is for 2015 (most recent available on http://www.scimagojr.com) ##
Hindex <- c(15, 83, 72, 69, 154, 196, NA, NA, 28, 51, NA, NA, NA, 72, 32, 78, 44, 15, 93, 21, 36, NA, 89, 65, 48, 66, 8, 177, NA, 35, 15, 78, 66, 64, 56) ## also retrieved from http://www.scimagojr.com ##
jdat.all <- data.frame(journal = j.map, j.loc, j.year, SJR, Hindex)
jdat.v <- read.csv("data/ipvJournalsSearch.csv")[c(-1, -6, -7), ]
## Exclude Theses and Dissertations ##
m.cnt <- mean(jdat.v[, 2])
jdat.v$journal <- sapply(as.character(jdat.v$journal), tolower)
jdat.v$journal <- gsub(" & ", " and ", jdat.v$journal)
jv.sum <- sum(jdat.v$count)
jdat <- merge(jdat.v, jdat.all)[, c("journal", "j.loc", "j.year", "SJR", "Hindex")]
# jdat$jrnl <- sapply(as.character(jdat$journal), Rabbr)
# jdat.v$j <- as.numeric(factor(jdat.v$journal))
jfv.n <- jdat.v[3, 2]
jiv.n <- jdat.v[2, 2]
vaw.n <- jdat.v[4, 2]
jvv.n <- jdat.v[5, 2]
jv.n <- rbind(jiv.n, jfv.n, vaw.n, jvv.n)
jdat.v.m <- jdat.v[jdat.v[,2] >= m.cnt, ]
j.vpr <-c("Journal of Interpersonal Violence",
"Violence Against Women",
"Violence and Victims",
"Journal of Family Violence")
j.v <- sapply(j.vpr, tolower, USE.NAMES = FALSE)
j.cppr <- c("Action Research",
"American Journal of Community Psychology",
"American Journal of Health Promotion",
"American Journal of Orthopsychiatry",
"American Journal of Preventive Medicine",
"American Journal of Public Health",
"Australian Community Psychologist",
"Community Development",
"Community Development Journal",
"Community Mental Health Journal",
"Community Psychology in Global Perspective",
"Cultural Diversity and Ethnic Minority Psychology",
"Global Journal of Community Psychology Practice",
"Health Education and Behavior",
"Health Promotion Practice",
"Journal of Applied Social Psychology",
"Journal of Community and Applied Social Psychology",
"Journal of Community Practice",
"Journal of Community Psychology",
"Journal of Health and Social Behavior",
"Journal of Prevention and Intervention",
"Journal of Primary Prevention",
"Journal of Rural Community Psychology",
"Journal of Social Issues",
"Journal of Community Psychology",
"Psychiatric Rehabilitation Journal",
"Psychology of Women Quarterly",
"Social Science and Medicine",
"The Community Psychologist",
"Transcultural Psychiatry",
"Progress in Community Health Partnerships")
j.cp <- sapply(j.cppr, tolower, USE.NAMES = FALSE)
#'
#'
#+ pander_journals, echo=FALSE
j.cpp <- sapply(j.cp, RtCap, USE.NAMES = FALSE)
#'
#' \newpage
#'
jdat.v.m <- dplyr::rename(jdat.v.m, "Journal" = journal, "Count" = count)
rownames(jdat.v.m) <- NULL
kable(jdat.v.m[, 1:2], align = c("l", "r"), caption = "Violence-specific journals with article counts greater than or equal to the mean of all journal article counts in the 'broad-strokes' database search results set.")
j.vp <- sapply(j.v, RtCap, USE.NAMES = FALSE)
<file_sep>/data/RQDA/populations.R
source("MAPrqda.R")
openProject("data/RQDA/comps.rqda")
caseids2 <-
RQDAQuery("SELECT `caseid`, `selfirst`, `selend` FROM `caselinkage` ORDER BY `caseid`")
# ctbl2 <- RQDAQuery("SELECT `seltext`, `selfirst`, `selend` FROM `coding` ORDER BY `selfirst`")
# ctbl3 <- merge(ctbl2, cbk, by.x = "id")
# caseids3 <- merge(caseids2, ctbl3, by = c("selfirst", "selend"))
p1.s3 <- data.frame(caseid = c(1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 13,
14, 15, 16, 17, 18, 20, 21, 23, 24,
25, 26, 27, 28, 29, 30, 31, 33, 34,
35, 37, 38),
name = c("IPVV", "GENP", "IPVV", "PRAC", "IPVP",
"IPVV", "YC", "PRG", "PRG", "IPVP", "PRNT",
"GENP", "PRAC", "F", "LAT", "PRG", "AA",
"IPVP", "IPVP", "IPVP", "IPVP", "IPVP",
"IPVP", "YC", "YC", "IPVV", "IPVP", "PRAC",
"SYS", "IPVP", "IPVV", "PRG"))
# p1.s31$name <- as.character(p1.s31$name)
# p1.s32 <- merge(p1.s31, cbk, by.x = "name", by.y = "name")
# p1.s3 <- merge(caseids2, p1.s32, by = "caseid")
p2.s3 <- data.frame(caseid = c(1, 5, 6, 7, 8, 12, 17, 20, 21, 23,
24, 27, 29, 31, 33, 34, 35, 37, 38),
name = c("F", "YC", "M", "F", "PRNT", "M",
"IPVP", "IPVV", "M", "M", "M",
"PRAC-IPV", "PRNT", "PRG", "SYS",
"PRAC", "M", "F", "IPVP"))
# p2.s31$name <- as.character(p2.s31$name)
# p2.s32 <- merge(p2.s31, cbk, by.x = "name", by.y = "name")
# p2.s3 <- merge(caseids2, p2.s32, by = "caseid")
p3.s3 <- data.frame(caseid = c(8, 17, 20, 24, 29, 38),
name = c("F", "M", "F", "F", "F", "M"))
# p3.s31$name <- as.character(p3.s31$name)
# p3.s32 <- merge(p3.s31, cbk, by.x = "name", by.y = "name")
# p3.s3 <- merge(caseids2, p3.s32, by = "caseid")
p4.s3 <- data.frame(caseid = c(8, 38),
name = c("PRG", "PRAC-IPV"))
# p4.s31$name <- as.character(p4.s31$name)
# p4.s32 <- merge(p4.s31, cbk, by.x = "name", by.y = "name")
# p4.s3 <- merge(caseids2, p4.s32, by = "caseid")
p5.s3 <- data.frame(caseid = c(38), name = c("SYS"))
# p5.s31$name <- as.character(p5.s31$name)
# p5.s32 <- merge(p5.s31, cbk, by.x = "name", by.y = "name")
# p5.s3 <- merge(caseids2, p5.s32, by = "caseid")
p.s31 <- rbind(p1.s3, p2.s3, p3.s3, p4.s3, p5.s3)
p.s31$name <- as.character(p.s31$name)
p.s32 <- merge(p.s31, cbk, by = "name")
p.s3 <- merge(caseids2, p.s32, by = "caseid")
write.csv(p.s3, "data/sql/p_s3.csv")
p1.s4 <- data.frame(caseid = c(42, 43, 44, 45, 46, 49, 50, 52, 53, 54, 55, 56, 57, 59, 60, 61, 62, 66, 67, 68, 69, 70, 71, 73, 74, 75, 76, 77, 78, 81, 83, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 97, 98, 99, 102, 103, 104, 105, 106),
name = c("SML", "SML", "SML", "SM", "ASA", "PRNT", "PRNT", "PRACIPV", "SML", "SMG", "IPVV", "CLG", "SML", "IPVV", "SML", "GRD", "SML", "CLG", "CLG", "SM", "SM", "SMG", "SM", "SMG", "SML", "F", "ASA", "M", "M", "GENP", "SM", "SMG", "GENP", "SM", "CRMV", "IPVV", "YC", "SML", "YC", "IPVV", "IPVP", "SML", "YC", "SYS", "IPVV", "IPVV", "YC", "SYS", "SML"))
p2.s4 <- data.frame(caseid = c(42, 43, 44, 45, 46, 47, 49, 50, 53, 54, 57, 59, 60, 61, 62, 66, 68, 69, 70, 71, 73, 74, 76, 77, 78, 83, 85, 91, 92, 93, 97, 99, 102, 103, 106),
name = c("F", "CPL", "F", "YC", "F", "RM", "F", "F", "F", "SML", "F", "SML", "HET", "PRAC", "F", "F", "SMT", "CLG", "AA", "CLG", "YC", "F", "SMG", "SMG", "SMG", "YC", "SML", "CPL", "IPVP", "SML", "F", "PRAC", "SML", "SM", "SMB"))
p3.s4 <- data.frame(caseid = c(43, 46, 47, 49, 50, 54, 59, 60, 66, 68, 69, 70, 73, 76, 77, 78, 91, 92, 93, 97, 102, 103, 106),
name = c("F", "SML", "DA", "SML", "SML", "AR", "F", "F", "HET", "CIS", "IPVV", "CPL", "M", "RM", "SMB", "SMB", "IPVV", "AR", "F", "IPVP", "F", "HET", "F"))
p4.s4 <- data.frame(caseid = c(46, 47, 49, 59, 70, 76, 77, 91, 103),
name = c("SMQ", "SM", "SMB", "PRACIPV", "RM", "M", "HET", "F", "URBN"))
p5.s4 <- data.frame(caseid = c(46, 47, 70),
name = c("RM", "CLG", "M"))
p.s41 <- rbind(p1.s4, p2.s4, p3.s4, p4.s4, p5.s4)
p.s41$name <- as.character(p.s41$name)
p.s42 <- merge(p.s41, cbk, by = "name")
p.s4 <- merge(caseids2, p.s42, by = "caseid")
write.csv(p.s4, "data/sql/p_s4.csv")
<file_sep>/_comps_docs/_AppD-untex.Rmd
# Appendix D Clinician Rating Form [@gondolf2009clinician]
Date:
Subject Name:
Group Leader (initials): Site:
INSTRUCTIONS: Please rate the man named above on each of the listed criteria. Rate him using the 0 to 5 scale below based on your impressions and observations. Return the form immediately to the evaluation contact person. 5 = extremely present; 4 = very present; 3 = somewhat present; 2 = a little present; 1 = very little present; 0 = no opinion, uncertain, not applicable.
`_____` attendance: arrives at group session on time; socializes or lingers afterward; contacts program in advance about absence; has legitimate excuse for absences.
`_____` nonviolence: has not recently physically abused partner, children, or others; no apparent threats, intimidation, or manipulation.
`_____` sobriety: attends meeting sober; not high or drunk; no apparent abuse of alcohol or drugs during week; complying to ordered or referred drug and alcohol treatment.
`_____` acceptance: admits that violence and abuse exists; not minimizing, blaming, or excusing the problem; realizes responsibility for abuse; identifies contribution to problems
`_____` using techniques: takes conscious steps to avoid violence; refers to time-outs, self-talk, conflict resolution skills, etc.; does homework assignments or recommendations.
`_____` help seeking: seeks information about alternatives; discusses options with others in the group; calls other participants for help; open to referrals and future support.
`_____` process conscious: lets others speak one at time; acknowledges others’ contributions; asks questions of others without interrogating; heeds direction of counselors.
`_____` actively engaged: attentive body language and nonverbal response; maintains eye contact; speaks with feeling; follows topic of discussion in comments.
`_____` self-disclosure: reveals struggles, feelings, fears, and self-doubts; not withholding or evading issues; not sarcastic or defensive.
`_____` sensitive language: respectful of partner and women in general; nonsexist language and no pejorative slang; checks others who use sexist language.
-----
<file_sep>/data/sql/RQDA-cpm-SQL/RQDAcpm--freecode.sql
INSERT INTO `freecode`(`name`,`memo`,`owner`,`date`,`dateM`,`id`,`status`,`color`) VALUES ("CBPR",?,"Riley","Thu Apr 27 12:36:57 2017",?,1,1,?);
INSERT INTO `freecode`(`name`,`memo`,`owner`,`date`,`dateM`,`id`,`status`,`color`) VALUES ("PAR",?,"Riley","Thu Apr 27 12:36:57 2017",?,2,1,?);
INSERT INTO `freecode`(`name`,`memo`,`owner`,`date`,`dateM`,`id`,`status`,`color`) VALUES ("PBM",?,"Riley","Thu Apr 27 12:36:57 2017",?,3,1,?);
INSERT INTO `freecode`(`name`,`memo`,`owner`,`date`,`dateM`,`id`,`status`,`color`) VALUES ("GIS",?,"Riley","Thu Apr 27 12:36:57 2017",?,4,1,?);
INSERT INTO `freecode`(`name`,`memo`,`owner`,`date`,`dateM`,`id`,`status`,`color`) VALUES ("PEVAL",?,"Riley","Thu Apr 27 12:36:57 2017",?,5,1,?);
INSERT INTO `freecode`(`name`,`memo`,`owner`,`date`,`dateM`,`id`,`status`,`color`) VALUES ("QLM",?,"Riley","Thu Apr 27 12:36:57 2017",?,6,1,?);
INSERT INTO `freecode`(`name`,`memo`,`owner`,`date`,`dateM`,`id`,`status`,`color`) VALUES ("MMR",?,"Riley","Thu Apr 27 12:36:57 2017",?,7,1,?);
INSERT INTO `freecode`(`name`,`memo`,`owner`,`date`,`dateM`,`id`,`status`,`color`) VALUES ("QTM",?,"Riley","Thu Apr 27 12:36:57 2017",?,8,1,?);
UPDATE `freecode` SET `memo`="Community-Based Participatory Research" WHERE `id`=1;
UPDATE `freecode` SET `memo`="Participatory Action Research" WHERE `id`=2;
UPDATE `freecode` SET `memo`="Place-Based Methods" WHERE `id`=3;
UPDATE `freecode` SET `memo`="Geographic Information Systems" WHERE `id`=4;
UPDATE `freecode` SET `memo`="Program Evaluation" WHERE `id`=5;
UPDATE `freecode` SET `memo`="Qualitative Methods" WHERE `id`=6;
UPDATE `freecode` SET `memo`="Mixed-Methods" WHERE `id`=7;
UPDATE `freecode` SET `memo`="Quantiative Methods" WHERE `id`=8;
<file_sep>/_comps_docs/_zmisc/clabs.R
clabs <- cbk[, "clab"]
clabs <- c("African Americans",
"Approach Evaluation",
#"'At Risk' Populations",
"Secondary/Archival Data",
#"Asian Americans",
"IPV Perpetrator Interventions",
"Community Capacity",
"Coordinated Community Response",
#"Cis-Gender",
"College Students",
"IPV Consequences",
"Couples",
#"Non-IPV Crime Victims",
#"Case Study",
#"Disabled Persons",
#"IPV Dynamics",
"Experimental Design",
"Females/Women/Girls",
"Focus Groups",
"General Population",
#"Graduate Students",
"HIV Intervention/Prevention",
"Help-Seeking",
"Intervention/Prevention (General)",
"Intervention Description",
"Intervention Proposal",
"IPV-Perpetrators",
"IPV-Victims/Survivors",
"Interviews",
"Latinos/Latinas or Hispanic-Americans",
"Longitudinal",
"Males/Men/Boys",
"Measures",
"Multi-Method QuaLitative Design",
"Multi-Method QuaNTitative Design",
"Mixed-Methods",
"Research/Evaluation Methods",
#"Perpetrator Characteristics",
"Program/Policy Development",
"Outsiders' Perspectives",
"Practitioners' Perspectives",
#"Key Stakeholders' Persepctives",
"Victims'/Survivors' Perspectives",
"Program/Policy Evaluation",
#"Protective Factors",
"Public Policy",
"Non-IPV Community-Based Practitioners",
"IPV-Specific Community-Based Practitioners",
"IPV Prevention",
"IPV Prevalence",
"IPV Intervention Programs",
"Parents",
"QuaLitative",
"QuaNTitative",
"Client Records",
"Police/Court Records",
"Risk Factors",
"IPV Screening",
#"Racial Minorities",
"Sexual Minorities",
"QuaLitative Survey",
"QuaNTitative Survey",
"Non-IPV System Entities",
"System Response",
"Urban-Specific",
"IPV Victimization Interventions",
"Cross-Sectional",
"Children/Youth")
<file_sep>/_comps_docs/_zmisc/MAP-clust.R
#' ---
#' title: "MAP - Literature Description"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE
# SETUP --------------------------------------------------------------
source("bibs.R")
knitr::opts_chunk$set(
tidy = TRUE,
echo = TRUE,
fig.keep = 'high',
fig.show = 'hold',
results = 'asis',
tidy.opts = list(comment = FALSE),
echoRule = NULL,
echoRuleb = TRUE
)
rpm()
#'
#'
hca.s3F <- ctbl.m[ctbl.m$scat == "IPV Interventions", c("case", "cat", "caseid", "year", "jrnl", "cid")]
hca.s3F$jrnl <- as.numeric(factor(hca.s3F$jrnl))
hca.s3m <- hca.s3F[hca.s3F$cat == "M-OVERALL", -1:-2] %>% droplevels()
hca.s3m$caseid %in% hca.s3F$casid
hca.s3m <- apply(hca.s3m, 2, as.double)
means <- apply(hca.s3m,2,mean)
sds <- apply(hca.s3m,2,sd)
hca.s3m <- scale(hca.s3m,center = means,scale = sds)
head(hca.s3m) %>% round(2)
dist.s3m <- dist(hca.s3m)
Rmsmm(dist.s3m)
clust.s3m <- hclust(dist.s3m, method = "ward.D2")
names(clust.s3m)
clust.s3m$merge
clust.s3m$height
clust.s3m$order
clust.s3m$labels <- unique(hca.s3F[, 1])
# clust.s3m$labels
plot(clust.s3m)#, labels = unique(hca.s3F$case), sub = ' ', xlab = ' ', main = " ",
# frame.plot = F, col = 19, cex = .75, cex.main = 0.75,
# cex.lab = 0.75, cex.axis = 0.65)
abline(a = 9, b = 0, lty = 3, lwd = 1.5,
col = adjustcolor(pal_my[19], alpha.f = 0.75))
rect.hclust.s3m(clust.s3m, h = 9, border = "#3B0C67") -> rhcl
<file_sep>/graphicsGallery.Rmd
---
title: "<em><code>R</code></em> DataViz Gallery"
---
<style>
body {
background-color: rgba(0, 0, 0, 0.025);
width: 95%;
}
p {
width:95% !important;
}
h1:not(.title) {
text-align: center;
margin-top: 3em;
margin-bottom: 1.5em;
}
h1:not(.title)::after {
width : 100%;
/*margin-top : 21px;*/
/*margin-bottom : 21px;*/
border : 0;
height: 1px;
/*border-top : 2px solid #3f3f3f;*/
background-image: linear-gradient(to right, #e6e6e6, #333, #e6e6e6);
}
</style>
```{r setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE}
knitr::opts_chunk$set(echo = FALSE, results = 'asis')
g0 <- list.files(path = "graphics/", pattern = ".*?\\.svg$", recursive = TRUE)
g1 <- g0[!grepl("(zARCHIVE-)|(inputs/)|( copy)", g0)]
g2 <- paste0("graphics/", g1)
ginfo <- file.info(g2)[, c("ctime", "mtime", "atime")]
g <- g2[ginfo$ctime > "2017-05-31"]
glabs_ref <- gsub("(\\w+/){1,}rplot-(.*?)\\.svg", "\\2", g)
# glabs_id <- paste0("#", glabs_path)
# pathPrefix = "graphics/"
Rlightbox <- function(g, glabs) {
gl <- vector("character", length(g))
for (i in 1:length(g)) {
gl[i] <- paste0("<div class='lightbox' href=", glabs[i], "><img src=", g[i], " style=\"width=auto;\" /></div>")
# <div class='lightbox-target' id=", glabs2[i], "><span class='close cursor' onclick='closeModal()'>×</span><img src=", g[i], " /><a class='lightbox-close' href='#'></a></div><a class='prev' onclick='plusSlides(-1)'>❮</a><a class='next' onclick='plusSlides(1)'>❯</a>
}
return(gl)
}
library(pander)
panderOptions("p.sep", "\n")
panderOptions("p.copula", "\n")
panderOptions("p.wrap", "")
# pander(gl)
library(Riley); library(ggplot2); library(igraph); library(ggparallel); library(arcdiagram); library(ggthemes); library(Riley)
```
<hr class="Bold"/>
<div style="text-align:center;">
`r Riley::Rcite_r(file = "../auxDocs/REFs.bib", footnote = FALSE, Rnote = "Graphics on this page were created using")`
</div>
<hr class="SemiBold">
# Donut Plot via the **`ggplot2`** package
<div class="gallery cf">
```{r}
gdonut <- g[grepl("donut_", g)]
gdonutlabs2 <- gsub("(\\w+/){1,}(.*?)\\.svg", "\\2", gdonut)
gdonutlabs1 <- paste0("#", gdonutlabs2)
gldonut <- Rlightbox(gdonut, gdonutlabs1)
# for (i in 1:length(gdonut)) {
# gldonut[i] <- paste0("<a class='lightbox' href=", gdonutlabs1[i], "><img src=", gdonut[i], " /></a><div class='lightbox-target' id=", gdonutlabs2[i], "><img src=", gdonut[i], " /><a class='lightbox-close' href='#'></a></div>")
# }
pander(gldonut)
```
</div>
# Timelines via the **`ggplot2`** package
<div class="gallery cf">
```{r}
gtl <- g[grepl("tl_", g)]
gtllabs2 <- grep("rplot-tl_.*?\\.svg", gtl, value = T)
gtllabs1 <- paste0("#", gtllabs2)
gltl <- Rlightbox(gtl, gtllabs1)
# for (i in 1:length(gtl)) {
# gltl[i] <- paste0("<a class='lightbox' href=", gtllabs1[i], "><img src=", gtl[i], " /></a><div class='lightbox-target' id=", gtllabs2[i], "><img src=", gtl[i], " /><a class='lightbox-close' href='#'></a></div>")
# }
pander(gltl)
```
</div>
# Histogram Timeline via **`Base R Graphics`**
<div class="gallery cf">
```{r}
gtlhist <- g[grepl("hist_", g)]
gtlhistlabs2 <- grep("rplot-hist_.*?\\.svg", gtlhist, value = T)
gtlhistlabs1 <- paste0("#", gtlhistlabs2)
gltlhist <- Rlightbox(gtlhist, gtlhistlabs1)
# for (i in 1:length(gtlhist)) {
# gltlhist[i] <- paste0("<a class='lightbox' href=", gtlhistlabs1[i], "><img src=", gtlhist[i], " /></a><div class='lightbox-target' id=", gtlhistlabs2[i], "><img src=", gtlhist[i], " /><a class='lightbox-close' href='#'></a></div>")
# }
pander(gltlhist)
```
</div>
# Dot plots^[@robbins2006dot;@cleveland1984graphical] via My _in Progress_ **`Riley`** Package
<div class="gallery cf">
```{r}
gdot <- g[grepl("dot_", g)]
gdotlabs2 <- grep("rplot-dot_.*?\\.svg", gdot, value = T)
gdotlabs1 <- paste0("#", gdotlabs2)
gldot <- Rlightbox(gdot, gdotlabs1)
# for (i in 1:length(gdot)) {
# gldot[i] <- paste0("<a class='lightbox' href=", gdotlabs1[i], "><img src=", gdot[i], " onclick='openModal();' /></a><div class='lightbox-target' id=", gdotlabs2[i], "><span class='close cursor' onclick='closeModal()'>×</span><img src=", gdot[i], " /><a class='lightbox-close' href='#'></a></div><a class='prev' onclick='plusSlides(-1)'>❮</a><a class='next' onclick='plusSlides(1)'>❯</a>")
# }
pander(gldot)
```
</div>
# Parallel Sets via the **`ggplot2`** package
<div class="gallery cf">
```{r}
gparset <- g[grepl("parset_", g)]
gparsetlabs2 <- grep("rplot-parset_.*?\\.svg", gparset, value = T)
gparsetlabs1 <- paste0("#", gparsetlabs2)
glparset <- Rlightbox(gparset, gparsetlabs1)
# for (i in 1:length(gparset)) {
# glparset[i] <- paste0("<a class='lightbox' href=", gparsetlabs1[i], "><img src=", gparset[i], " /></a><div class='lightbox-target' id=", gparsetlabs2[i], "><img src=", gparset[i], " /><a class='lightbox-close' href='#'></a></div>")
# }
pander(glparset)
```
</div>
# Network Diagrams via the **`igraph`** & **`arcdiagram`**
<div class="gallery cf">
```{r}
garc0 <- list.files(path = "graphics/", pattern = ".*?\\.png$", recursive = TRUE)
garc1 <- garc0[!grepl("(zARCHIVE-)|(inputs/)|( copy)", garc0)]
garc2 <- paste0("graphics/", garc1)
garcinfo <- file.info(garc2)[, c("ctime", "mtime", "atime")]
garc3 <- garc2[garcinfo$ctime > "2017-05-31"]
gnet <- g[grepl("net_", g)]
garc <- garc3[grepl("arc_", garc3)]
gnets <- c(gnet, garc)
gnetslabs21 <- grep("rplot-net_.*?\\.svg", gnets, value = T)
gnetslabs22 <- grep("rplot-arc_.*?\\.png", gnets, value = T)
gnetslabs2 <- c(gnetslabs21, gnetslabs22)
gnetslabs1 <- paste0("#", gnetslabs2)
glnets <- Rlightbox(gnets, gnetslabs1)
# for (i in 1:length(gnets)) {
# glnets[i] <- paste0("<a class='lightbox' href=", gnetslabs1[i], "><img src=", gnets[i], " /></a><div class='lightbox-target' id=", gnetslabs2[i], "><img src=", gnets[i], " /><a class='lightbox-close' href='#'></a></div>")
# }
pander(glnets)
```
# Hierarchical Cluster Analysis Dendrograms & Related Barplots via **`Base R Graphics`**
```{r}
ghclust <- g[grepl("hclust_", g)]
ghclustlabs2 <- grep("rplot-hclust_.*?\\.svg", ghclust, value = T)
ghclustlabs1 <- paste0("#", ghclustlabs2)
glhclust <- Rlightbox(ghclust, ghclustlabs1)
pander(glhclust)
```
# K-Means & Fuzzy Analysis Clustering Graphics via the **`Cluster`** Package
```{r}
gkclust <- g[grepl("kclust_", g)]
gkclustlabs2 <- grep("rplot-kclust_.*?\\.svg", gkclust, value = T)
gkclustlabs1 <- paste0("#", gkclustlabs2)
glkclust <- Rlightbox(gkclust, gkclustlabs1)
pander(glkclust)
```
</div>
<hr class="Bold">
<h1 style="text-align:left;margin-top:-1em;">References</h1>
<div class="refs">
<file_sep>/_comps_docs/_zmisc/MTHDSrqda.R
#' ---
#' title: "CP Methods - RQDA"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE
# source("../SETUP.R")
# knitr::opts_chunk$set(
# tidy = TRUE,
# echo = TRUE,
# fig.keep = 'high',
# fig.show = 'hold',
# results = 'asis'
# )
# rpm()
#'
#' \Frule
#'
#' # RQDA Project
#'
#+ openProj, echo=-2, results='hide'
# OPEN RQDA PROJECT --------------------------------------------------------
library(RQDA)
openProject("data/RQDA/cpmethods.RQDA")
# RQDA()
# openProject("data/RQDA/cpmethods.RQDA", updateGUI = TRUE)
#'
#+ RQDAQueries, echo=TRUE
# RQDA SQL Queries --------------------------------------------------------
## ctbl1 & cbk ========================================================
ctbl1 <- getCodingTable()[, c("cid", "codename", "index1")] ## all codings (sans coded text) ##
names(ctbl1)[2] <- "code" ## for compatability later ##
cbk <- RQDAQuery("SELECT `name` as `code`, `memo` as `clab`
FROM `freecode`
WHERE `status` = 1") ## codelist only (without categories) ##
## cases ========================================================
cases1 <-
RQDAQuery("SELECT `name` AS `case`, `id` AS `caseid`
FROM `cases`
ORDER BY `caseid`")
caseids1 <-
RQDAQuery("SELECT `caseid`, `selfirst`
FROM `caselinkage`
ORDER BY `caseid`")
caseAttr.rm <-
RQDAQuery("SELECT `value` AS `RM`, `caseID` AS `caseid`
FROM `caseAttr`
WHERE `variable`='RMV'
ORDER BY `caseid`")
caseAttr.section <-
RQDAQuery("SELECT `value` AS `scat`, `caseID` AS `caseid`
FROM `caseAttr`
WHERE `variable`='SECTION'
ORDER BY `caseid`")
## codecats ========================================================
codecats1 <-
RQDAQuery("SELECT `name` AS `cat`, `catid`
FROM `codecat`
ORDER BY `catid`")
codecats2 <-
RQDAQuery(
"SELECT treecode.cid AS cid, treecode.catid AS catid,
freecode.name AS code, freecode.memo AS clab
FROM `treecode`
INNER JOIN `freecode` WHERE
freecode.id = treecode.cid AND treecode.status = 1 ORDER BY `catid`"
)
#'
#' # Data Wrangling \& Cleaning
#'
#+ ctbl, echo=TRUE
# DATA WRANGLING --------------------------------------------------------
## ctbl ========================================================
caseAttr <- merge(caseAttr.rm, caseAttr.srch, by = "caseid")
caseids2 <- merge(cases1, caseids1, by = "caseid")
caseids <- merge(caseids2, caseAttr, by = "caseid")
ctbl2 <- merge(caseids, ctbl1, by.x = "selfirst", by.y = "index1")
codecats <- merge(codecats2, codecats1, by = "catid")
ctbl <- merge(ctbl2, codecats, by = c("cid", "code"))
ctbl <-
ctbl[, c("caseid", "case", "cid", "code", "catid", "cat")] #"clab",
#'
#' \newpage
#'
#+ closeProj, results='hide'
# CLOSE RQDA PROJECT --------------------------------------------------------
CleanProject(); closeProject()
#'
<file_sep>/_comps_docs/_AppB-Untex.Rmd
---
title: NULL
author: NULL
date: NULL
---
```{r setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE}
## source("../SETUP.R")
knitr::opts_chunk$set(
tidy = FALSE,
echo = FALSE,
fig.keep = 'high',
fig.show = 'hold',
results = 'asis'
)
sm <- function(x) {
if (knitr:::is_latex_output()) {
sprintf("\\small{%s}", x)
} else {
sprintf("<span style=\"font-size:75%%;\">%s</span>", x)
}
}
```
## Citation
-------------------------------------------------------------
.
-------------------------------------------------------------
## Substantive Research Topic(s)
`r tufte::newthought("Study Purpose(s)")`
-------------------------------------------------------------
.
-------------------------------------------------------------
`r tufte::newthought("Research Question(s) (RQs)")`
-------------------------------------------------------------
.
-------------------------------------------------------------
_Including theoretical model(s) (if applicable)_
`r tufte::newthought("Hypotheses")`
-------------------------------------------------------------
.
-------------------------------------------------------------
_Including hypothesized/statistical model(s) (if applicable)_
-------------------------------------------------------------
.
-------------------------------------------------------------
## Target Population(s) & Sampling Frame(s)
-------------------------------------------------------------
.
-------------------------------------------------------------
### Target Population(s) _(By Level of Specificity)_
-------------------------------------------------------------
.
-------------------------------------------------------------
`r tufte::newthought("Includes")`
-------------------------------------------------------------
.
-------------------------------------------------------------
`r tufte::newthought("Excludes")`
-------------------------------------------------------------
.
-------------------------------------------------------------
### Sampling Frame Setting(s)
-------------------------------------------------------------
.
-------------------------------------------------------------
### Sampling Frame _(By Level of Specificity)_
-------------------------------------------------------------
.
-------------------------------------------------------------
`r tufte::newthought("Includes")`
-------------------------------------------------------------
.
-------------------------------------------------------------
`r tufte::newthought("Excludes")`
-------------------------------------------------------------
.
-------------------------------------------------------------
## Sampling Method(s) _(By Sampling Frame Level)_
❑ `r tufte::newthought("Probability/Random")`
❑ `r tufte::newthought("Purposive")`
❑ `r tufte::newthought("Convenience")`
## Study Design(s)
-------------------------------------------------------------
.
-------------------------------------------------------------
### Qua**L**itative Research Designs _(if applicable)_
❑ `r tufte::newthought("Grounded Theory")`
❑ `r tufte::newthought("Phenomenology")`
❑ `r tufte::newthought("Ethnography")`
❑ `r tufte::newthought("Case-Study")`
❑ `r tufte::newthought("Narrative/Descriptive")`
❑ _Biographical_
❑ _Historical_
### Qua**NT**itative Research Designs _(if applicable)_
❑ `r tufte::newthought("Experimental")`
❑ _Longitudinal_
❑ _Pre-Post_
❑ `r tufte::newthought("Randomized Control Trial (RCT)")`
❑ _RCT - Longitudinal_
❑ _RCT - Pre-Post_
❑ `r tufte::newthought("Quasi-Experimental")`
❑ `r tufte::newthought("Cross-Sectional")`
## Methodology
❑ `r tufte::newthought("Qualitative")`
❑ `r tufte::newthought("Quantitative")`
❑ `r tufte::newthought("Mixed-Methods")`
## Data Collection Method(s) / Data Source(s) _(By Sampling Frame Level & Methodology)_
-------------------------------------------------------------
.
-------------------------------------------------------------
`r tufte::newthought("Measure(s)")`
-------------------------------------------------------------
.
-------------------------------------------------------------
`r tufte::newthought("Archival / Secondary Data Source(s)")`
-------------------------------------------------------------
.
-------------------------------------------------------------
## Data Analytic Approach(es)
-------------------------------------------------------------
.
-------------------------------------------------------------
## Key Findings
`r tufte::newthought("Sample Characteristics")` _(By sampling frame level & methodology)_
-------------------------------------------------------------
.
-------------------------------------------------------------
`r tufte::newthought("Findings")` _(by methodology & hypothesis/RQ)_
-------------------------------------------------------------
.
-------------------------------------------------------------
## Social Ecological Levels of Analysis
❑ `r tufte::newthought("Individual")`
❑ `r tufte::newthought("Relationship")`
❑ `r tufte::newthought("Community")`
❑ `r tufte::newthought("Societal")`
## Miscellaneous Notes
-------------------------------------------------------------
.
-------------------------------------------------------------
<file_sep>/data/summary-contrino2007.md
@contrino2007compliance quantitatively examined intervention program participants' levels of compliance with program requirements (e.g., attendance, engagement with the program, maintaining sobriety, nonviolence, etc.) and the extent to which participants retain key components of the intervention's content (e.g., power and control dynamics versus non-controlling behaviors). This investigation's focus aligns with @silvergleid2006batterer\'s qualitative findings regarding key influences underlying and facilitating IPV perpetrator intervention program participants' change processes. Specifically,<!--both program participant and facilitator --> interviewees in @silvergleid2006batterer\'s sample emphasized the importance of learning new skills (e.g., taking a 'time-out') and engagement with program activities (e.g., reading required texts, journaling, acknowledging their past violent behaviors and the impact of those behaviors on others, etc.) in the change processes experienced by program participants:
> "The most emphasized aspect of awareness was the participant’s new understanding of the effects of their abuse on others. For many men, truly sit- ting with that understanding, the devastating impact of their actions on those around them, was a strong impetus for change" (@silvergleid2006batterer, p. 153).
Findings from @contrino2007compliance\'s process evaluation somewhat reiterate @silvergleid2006batterer\'s findings in that participants' recall of intervention content related to power and control dynamics levels of compliance with certain domains of program expectations, including (1) using techniques to avoid violence, (2) process-consciousness and communication skills, (3) self-disclosure of ones's feelings and non-defensiveness, and (4) use of respectful language. Other assessed program expectations including participants' program attendance, active engagement in group sessions, sobriety, nonviolence, and help-seeking were not associated with the number of forms of power and control they were able to recall [see @gondolf2009clinician].
<file_sep>/index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<!-- <meta name="viewport" content="width=device-width, initial-scale=1" /> -->
<link href="auxDocs/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="auxDocs/gallery.css" type="text/css" />
<link rel="stylesheet" href="auxDocs/reset.css" type="text/css" />
<link rel="stylesheet" href="auxDocs/et-book.css" type="text/css" />
<link rel="stylesheet" href="auxDocs/riley.css" type="text/css" />
<!-- <link rel="stylesheet" href="auxDocs/riley-navbar.css" type="text/css" /> -->
<style type="text/css">
/*h1 {*/
/*font-size: 34px;*/
/*}*/
/*h1.title {*/
/*font-size: 38px;*/
/*}*/
/*h2 {*/
/*font-size: 30px;*/
/*}*/
/*h3 {*/
/*font-size: 24px;*/
/*}*/
/*h4 {*/
/*font-size: 18px;*/
/*}*/
/*h5 {*/
/*font-size: 16px;*/
/*}*/
/*h6 {*/
/*font-size: 12px;*/
/*}*/
/*.table th:not([align]) {*/
/*text-align: left;*/
/*}*/
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
/*background-color: rgba(0, 0, 0, 0.04);*/
}
/*img {*/
/*max-width:100%;*/
/*height: auto;*/
/*}*/
/*.tabbed-pane {*/
/*padding-top: 12px;*/
/*}*/
/*button.code-folding-btn:focus {*/
/*outline: none;*/
/*}*/
/*</style>
<style type="text/css">*/
/* padding for bootstrap navbar */
body {
padding-top: 51px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 56px;
margin-top: -56px;
}
.section h2 {
padding-top: 56px;
margin-top: -56px;
}
.section h3 {
padding-top: 56px;
margin-top: -56px;
}
.section h4 {
padding-top: 56px;
margin-top: -56px;
}
.section h5 {
padding-top: 56px;
margin-top: -56px;
}
.section h6 {
padding-top: 56px;
margin-top: -56px;
}
</style>
<!-- <script> -->
<!-- // manage active state of menu based on current page -->
<!-- $(document).ready(function () { -->
<!-- // active menu anchor -->
<!-- href = window.location.pathname -->
<!-- href = href.substr(href.lastIndexOf('/') + 1) -->
<!-- if (href === "") -->
<!-- href = "index.html"; -->
<!-- var menuAnchor = $('a[href="' + href + '"]'); -->
<!-- -->
<!-- // mark it active -->
<!-- menuAnchor.parent().addClass('active'); -->
<!-- -->
<!-- // if it's got a parent navbar menu mark it active as well -->
<!-- menuAnchor.closest('li.dropdown').addClass('active'); -->
<!-- }); -->
<!-- </script> -->
<!-- </head> -->
<!-- <body> -->
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
<!-- CODEFOLDING SCRIPT -->
<!-- <script>
window.initializeCodeFolding = function(show) {
// handlers for show-all and hide all
$("#rmd-show-all-code").click(function() {
$('div.r-code-collapse').each(function() {
$(this).collapse('show');
});
});
$("#rmd-hide-all-code").click(function() {
$('div.r-code-collapse').each(function() {
$(this).collapse('hide');
});
});
// index for unique code element ids
var currentIndex = 1;
// select all R code blocks
var rCodeBlocks = $('pre.r');
rCodeBlocks.each(function() {
// create a collapsable div to wrap the code in
var div = $('<div class="collapse r-code-collapse"></div>');
if (show)
div.addClass('in');
var id = 'rcode-643E0F36' + currentIndex++;
div.attr('id', id);
$(this).before(div);
$(this).detach().appendTo(div);
// add a show code button right above
var showCodeText = $('<span>' + (show ? 'Hide' : 'Code') + '</span>');
var showCodeButton = $('<button type="button" class="btn btn-default btn-xs code-folding-btn pull-right"></button>');
showCodeButton.append(showCodeText);
showCodeButton
.attr('data-toggle', 'collapse')
.attr('data-target', '#' + id)
.attr('aria-expanded', show)
.attr('aria-controls', id);
var buttonRow = $('<div class="row"></div>');
var buttonCol = $('<div class="col-md-12"></div>');
buttonCol.append(showCodeButton);
buttonRow.append(buttonCol);
div.before(buttonRow);
// update state of button on show/hide
div.on('hidden.bs.collapse', function () {
showCodeText.text('Code');
});
div.on('show.bs.collapse', function () {
showCodeText.text('Hide');
});
});
}
</script> -->
<div class="container-fluid main-container">
<div class="navbar navbar-default navbar-fixed-top" role=
"navigation">
<div class="container">
<div class="navbar-header"><a class="navbar-brand" href="index.html"><i class="fa fa-home" aria-hidden="true"></i></a></div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav"></ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="litSearchMethods.html">Methods</a>
</li>
<li>
<a href="graphicsGallery.html">DataViz <!--& Tabulations--></a>
</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">< Source Code ></a>
<ul class="dropdown-menu" role="button">
<li><a href="QCA.nb.html"><code>R</code> Source Code & Output Notebook</a></li>
<li><a href="sourceCode.html"><code>R</code> & <code>SQL</code> Source Files & Data</a></li>
</ul>
</li>
<!-- <li> -->
<!-- <a target="_blank" href="auxDocs/_journal-Passcode.html"> [<i class="fa fa-lock" aria-hidden="true"></i>]</a> -->
<!-- </li> -->
<!-- </ul>
</li> -->
</ul>
</div>
<!--/.nav-collapse --></div>
<!--/.container --></div>
<!--/.navbar -->
<div class="fluid-row" id="header"></div>
</div>
<h1 class="title toc-ignore">Conducting a Community-Psychology-Focused & Action-Oriented Systematic Literature Review using R, SQL, & Git
<figure class="title">
<img src="graphics/inputs/bibkeys-ecoLvls-net.png" alt="Network visualization of ecological levels of analysis">
</figure></h1>
<hr class="Bold" />
<p>A newly implemented component of the doctoral comprehensive exam for <a href="!--TODO:%20link%20to%20psych%20grad%20program%20website--"><em>Applied Psychology</em> doctoral students majoring in <em>Community Psychology</em> at Portland State University</a> is writing a <em>Major Area Paper (MAP)</em> consisting of a systematic literature review focused around each student’s substantive research area. This repository contains procedural and analytic details, inputs, outputs, and resources from my personal process of completing this component of my comprehensive exam.</p>
<hr />
<p>The methodologically-focused critical review presented here provides a unique perspective of IPV-related empirical research by restricting the reviewed literature as a whole to only include studies published either in violence-specific journals determined by the primary author as being aligned with community-psychology or in journals endorsed by the Society for Community Research and Action as closely aligned with or related to community-psychology values, theory, and methods. This perspective therefore inherently incorporates applied research conducted within a range of action-oriented, community-based, participatory, and multilevel frameworks.</p>
<p>The process of conducting the community-psychology-focused systematic review of empirical research related to IPV and sexual minority women was arduous to say the least. Community Psychology, as a field, is overwhelmingly more multi-disciplinary than most scientific research domains, and is more so a methodologically- and values- focused field, rather than a field of study defined around a specific substantive area of research. That is, unlike disciplines such as medicine, or sub-fields of medicine such as Oncology, Community Psychology is primarily a field of social scientific research providing a range of general and specific values-based frameworks and ecologically-relevant methodologies. In addition, although intimate partner violence is increasingly recognized and treated as a public health issue, like many of the substantive research topics covered by community scientists, IPV is not exclusive to any one research discipline, such as Public Health, nor is it in and of itself a distinct research discipline. Rather, IPV-specific and related research is conducted out of a multitude of research and practice fields, including, but certainly not limited to, Psychology and its various sub-fields (e.g., Community, Social, Clinical, Organizational, and Cognitive Psychology), Sociology, Criminology, Public Policy, Economics, Public Health, Biology, Medicine, etcetera.</p>
<p>Given the multi-disciplinary and complex natures of both community-psychological and IPV-related research, as well as the specificity of the present systematic review’s focus, I was careful to maintain detailed records regarding each decision made throughout the article selection and review process (see <a href="litSearchMethods.html">Literature Search Methods</a>), as well as the rationale underlying each decision. The criteria and procedures used in the present review to determine the community-psychology relevance of research obtained from the literature database searches are provided in this repository for two purposes: (1) to ensure the transparency and reproducibility of the systematic review methods conducted for this review, and (2) as a potentially useful by-product of this process for future efforts to conduct similarly community-psychology-focused systematic literature reviews, including and beyond research related to intimate partner violence and sexual minority women.</p>
<hr class="Bold" />
<style>
</style>
<div style="width:25%;color:rgba(0, 0, 0, 0.6);text-align:left;font-size:0.75rem;float:right">
<!-- <div class="contactIcons"> -->
<span style="color:#404040;" class="lmText" id="lmText"></span><span id="lmDate" class="lmDate"></span>
<hr />
<a href="mailto:<EMAIL>" target="_blank" aria-label="Email: <EMAIL>" class="iconOnly"><i class="fa fa-envelope" aria-hidden="true"></i></a> <a href="https://www.linkedin.com/in/rachel-smith-9b8b2931/" target="_blank" aria-label="Linked In" class="iconOnly"><i class="fa fa-linkedin-square"></i></a> <a href="https://github.com/eccriley" target="_blank" aria-label="Github" class="iconOnly"><i class="fa fa-github-square" aria-hidden="true"></i></a> <a href="https://twitter.com/rileymsmith19" target="_blank" aria-label="Twitter" class="iconOnly"><i class="fa fa-twitter-square" aria-hidden="true"></i></a>
<!-- </div> -->
<hr />
<span>Design by <a href="EccRiley.github.io"><em><strong>Rachel ("Riley") Smith-Hunter</strong></em></a> based on the <a href="https://github.com/edwardtufte/tufte-css"><em><code>Tufte CSS</code></em></a> theme by <a href="https://github.com/daveliepmann"><em><NAME></em></a> & <a href="https://github.com/edwardtufte"><em><NAME></em></a></span>
<hr />
<a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Conducting a Community-Psychology-Focused & Action-Oriented Systematic Literature Review using R, SQL, & Git</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://eccriley.github.io/CommPsy-SysLitRvw/" property="cc:attributionName" rel="cc:attributionURL"><NAME></a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>. Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="EccRiley.github.io" rel="dct:source">EccRiley.github.io</a>.<br /><br />
<script src="auxDocs/lastModified.js"></script>
</div>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>
<file_sep>/data/sql/RQDA-MAP-SQL/RQDAmap-coding-ANALYSIS.sql
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (157,1,57703.0, 39697.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (155,1,4722.0, 6544.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (155,1,17959.0, 20780.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (155,1,64926.0, 67124.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (155,1,17959.0, 20780.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (155,1,29857.0, 31667.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (155,1,50125.0, 51808.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (155,1,129408.0, 131376.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (155,1,27051.0, 29855.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (166,1,141810.0, 143900.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (160,1,35145.0, 37247.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (164,1,141810.0, 143900.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (164,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (133,1,29857.0, 31667.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (133,1,40875.0, 42637.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (133,1,59699.0, 61313.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (133,1,133023.0, 134888.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (135,1,14011.0, 16327.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (135,1,55562.0, 57701.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (135,1,129408.0, 131376.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (135,1,45819.0, 48172.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (135,1,167673.0, 169471.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (135,1,187048.0, 188553.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (135,1,64926.0, 67124.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (135,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (142,1,16329.0, 17957.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (142,1,53442.0, 55560.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (142,1,167673.0, 169471.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (142,1,40875.0, 42637.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (169,1,141810.0, 143900.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (172,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (132,1,55562.0, 57701.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (132,1,64926.0, 67124.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (132,1,48174.0, 50123.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (132,1,167673.0, 169471.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (132,1,69109.0, 71029.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (132,1,183394.0, 184479.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (145,1,64926.0, 67124.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (145,1,14011.0, 16327.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (171,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (158,1,57703.0, 39697.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (156,1,17959.0, 20780.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (156,1,17959.0, 20780.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (138,1,141810.0, 143900.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (151,1,22707.0, 24689.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (170,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (167,1,141810.0, 143900.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (150,1,27051.0, 29855.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (150,1,22707.0, 24689.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (176,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (136,1,22707.0, 24689.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (136,1,55562.0, 57701.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (136,1,17959.0, 20780.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (136,1,57703.0, 39697.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (136,1,17959.0, 20780.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (137,1,4722.0, 6544.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (137,1,55562.0, 57701.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (137,1,22707.0, 24689.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (154,1,29857.0, 31667.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (140,1,64926.0, 67124.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (140,1,183394.0, 184479.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (140,1,51810.0, 53440.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (140,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (140,1,55562.0, 57701.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (163,1,187048.0, 188553.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (153,1,27051.0, 29855.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (153,1,129408.0, 131376.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (161,1,167673.0, 169471.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (161,1,97502.0, 99907.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (161,1,133023.0, 134888.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,29857.0, 31667.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,17959.0, 20780.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,48174.0, 50123.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,35145.0, 37247.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,45819.0, 48172.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,27051.0, 29855.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,4722.0, 6544.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,33159.0, 35143.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,183394.0, 184479.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,17959.0, 20780.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,167673.0, 169471.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,51810.0, 53440.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,37249.0, 38956.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,50125.0, 51808.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,57703.0, 39697.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,187048.0, 188553.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,14011.0, 16327.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,42639.0, 44404.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,72217.0, 73937.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,133023.0, 134888.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,64926.0, 67124.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,69109.0, 71029.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (130,1,129408.0, 131376.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (159,1,57703.0, 39697.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (162,1,167673.0, 169471.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (162,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (149,1,141810.0, 143900.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (149,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (168,1,141810.0, 143900.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,33159.0, 35143.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,35145.0, 37247.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,97502.0, 99907.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,53442.0, 55560.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,16329.0, 17957.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,167673.0, 169471.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,40875.0, 42637.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,133023.0, 134888.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,27051.0, 29855.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (177,1,97502.0, 99907.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (139,1,29857.0, 31667.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (139,1,33159.0, 35143.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (139,1,48174.0, 50123.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (139,1,45819.0, 48172.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (139,1,57703.0, 39697.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (139,1,50125.0, 51808.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (139,1,133023.0, 134888.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (139,1,64926.0, 67124.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (139,1,4722.0, 6544.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (174,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (174,1,183394.0, 184479.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,129408.0, 131376.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,50125.0, 51808.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,51810.0, 53440.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,69109.0, 71029.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,48174.0, 50123.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,147290.0, 148986.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,57703.0, 39697.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,4722.0, 6544.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,29857.0, 31667.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,183394.0, 184479.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (131,1,64926.0, 67124.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (144,1,40875.0, 42637.0,1);
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (141,1,20782.0, 22705.0); -- boal2014barriers;
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (133,1,20782.0, 22705.0); -- boal2014barriers;
INSERT INTO `coding` (`cid`,`fid`,`selfirst`,`selend`,`status`) VALUES (133,1,20782.0, 22705.0); -- boal2014barriers;
<file_sep>/data/summary-gondolf1999.md
Using naturalistic observations<!-- of program practices --> and key informant<!--(i.e., program participants' current romantic partners)--> reports of IPV perpetrators' reassault rates `during the first`<!-- over the course of--> 15 months following their initial intake into the `intervention program`, @gondolf1999comparison provides a<!--`foundational`--> comparative evaluation of four IPV perpetrator intervention systems in four U.S. cities (i.e., Pittsburg, PA; Houston, TX; Dallas, TX; and Denver, CO).<!-- EDIT: TOO LONG OF A SENTENCE--> Findings from this study are, however, somewhat mixed in that comparisons to evaluate differences in reassault rates across the four study sites, representing a continuum of least-to-most comprehensive IPV perpetration intervention systems, showed few meaningful differences across intervention sites. `Distinctions across the four sites are, however, more evident when individual perpetrator characteristics (e.g., psychopathology, substance abuse, previous arrests, etc.) and referral sources (e.g., court-mandated versus referral sources outside the court system) are also taken into account.` Further, while there was no significant effect of intervention site on reassault rates, the effect of the most comprehensive intervention system among the four included in the study `does tend toward significance`, particularly when this site's effect is compared with the least comprehensive intervention system included in this evaluation.
Overall, the total recidivism rate observed across all four programs was 32% (_n_ = 210) for physical reassault and 43-70% for non-physical forms of violence and abuse (i.e., controlling behaviors, 45%; verbal abuse, 70%; and threats, 43%). In addition, 72% (_n_ = 343) partner respondents reported that they "feel 'very safe'" and 66% (_n_ = 281) indicated that they were "'very unlikely' to be hit". However, only 12% (_n_ = 54) rated their overall quality of life following their partners' completion of the intervention as "better", another 12% rated their quality of life as "worse", while 22% (_n_ = 100) rated their quality of life as the "same" as it was prior to their partners' intervention participation (p. 53).
Despite these mixed findings, @gondolf1999comparison\'s, relatively, early investigation into the possible differential effects of IPV perpetrator intervention systems representing four distinct points along a continuum from least-to-most comprehensive systems informs questions regarding system-, dyadic-, and individual-level factors that may influence these systems' efficacy at reducing reassault among men who have perpetrated IPV toward one or more female intimate partners. In particular, @gondolf1999comparison\'s findings regarding differences across the four intervention systems were most informative to understanding the effectiveness of IPV perpetrator programs when multiple levels of analysis are considered. That is, the effects of intervention systems' characteristics (i.e., comprehensiveness of services and intervention program length) on reassault rates appears `rather` sensitive to the inclusion of system-level variables not specific to the IPV perpetrator intervention itself (e.g., referral sources) and dyadic- and individual-level variables (e.g., victim-perpetrator contact during the 15-month study period, perpetrators' IPV-related and non-IPV-related criminal backgrounds, perpetrators' substance use or abuse, etc.) in each analysis.
The primary data source for @gondolf1999comparison\'s study's outcome variables is key informant reports provided by participating IPV perpetrators' current romantic partners, `regardless of whether those partners were` the original victims leading to the men's intervention program participation<!-- EDIT -->. This sampling and data collection method is an interesting approach to evaluating IPV perpetrator interventions, and the use of key informant reports (e.g., victims', current and/or past romantic partners', and intervention program facilitators' perspectives used as primary or secondary reports of program participants' behavior) is `somewhat thematic across a subset of subsequently-published literature included in this review`<!-- EDIT --> [e.g., @gregory2002effects; @silvergleid2006batterer]. `An additionally notable characteristic of` @gondolf1999comparison\'s `evaluation report` is the transparency with which the study's results are presented. While the evaluation ultimately provided, at best, mixed support for more the effect of more comprehensive IPV perpetration intervention systems, the results are presented such a way that acknowledge the state of this specific practice's field, which, at the time of the study's publication, is possibly best characterized as disjointed and in need of a more concrete and consistent evidence-base.
<file_sep>/_comps_docs/_SETUP.R
options(prompt = "> ", continue = "... ", width = 60, scipen = 10, error = NULL, knitr.kable.NA = "-")
auto.loads <- c("Riley", "tidyr", "plyr", "dplyr", "devtools",
"rmarkdown", "knitr", "tufte", "formatR", "pander",
"bibtex", "knitcitations",
"scales", "sysfonts", "extrafont", "showtext")
sshhh <- function(a.package)
{
suppressWarnings(suppressPackageStartupMessages(library(a.package,
character.only = TRUE)))
}
invisible(sapply(auto.loads, sshhh))
library(extrafont)
library(sysfonts)
loadfonts(quiet = TRUE)
quartzFonts(serif = quartzFont(c("ETBembo-RomanOSF", "ETBembo-BoldLF",
"ETBembo-DisplayItalic", "ETBembo-SemiBoldOSF")))
options(bib.loc = "auxDocs/REFs.bib", citation_format = "pandoc", knitr.table.format = "pandoc",
xtable.floating = FALSE, scipen = 0, digits = 3, zero.print = ".",
formatR.arrow = TRUE, DT.options = list(pageLength = 200, language = list(search = "Filter:")),
bib.loc = "auxDocs/REFs.bib", citation_format = "pandoc", knitr.table.format = "pandoc",
formatR.arrow = TRUE, xtable.comment = FALSE, xtable.booktabs = TRUE,
xtable.caption.placement = "top", xtable.caption.width = "\\linewidth",
xtable.sanitize.text.function = function(x)
{
x
}, xtable.table.placement = "hb", xtable.floating = FALSE)
knitr::opts_chunk$set(warning = FALSE, message = FALSE, comment = ">>",
fig.showtext = TRUE, highlight = TRUE, background = "#f2f2f2", size = "footnotesize",
cache = FALSE, autodep = TRUE, fig.path = "graphics/rplot-", fig.width = 7,
fig.height = 7, out.width = "\\linewidth")
devtools::session_info()
seed <- 42
set.seed(seed)
panderOptions("digits", 3)
panderOptions("round", 3)
panderOptions("missing", "-")
panderOptions("keep.line.breaks", TRUE)
panderOptions("table.style", "multiline")
panderOptions("table.alignment.default", "left")
panderOptions("table.split.table", 160)
panderOptions("table.split.cells", 50)
panderOptions("table.continues", "")
panderOptions("p.copula", ", and ")
cite_options(citation_format = "pandoc", style = "pandoc", hyperlink = "to.bib",
max.names = 6, longnamesfirst = TRUE, check.entries = TRUE)
today <- format(Sys.Date(), "%d %B %Y")
origin.xls <- as.Date("1899-12-30")
origin.r <- as.Date("1970-01-01")
font.add("ETBembo", regular = "/Library/Fonts/ETBembo-RomanOSF.ttf", bold = "/Library/Fonts/ETBembo-SemiBoldOSF.ttf",
italic = "/Library/Fonts/ETBembo-DisplayItalic.ttf")
font.add("Palatino", "/Library/Fonts/Palatino")
library(showtext)
showtext.auto(enable = TRUE)
# pal_my <- c("#eef0f2", "#d1d6dc", "#da00d1", "#a700a0", "#74006f", "#dee800",
# "#adb500", "#00f485", "#00b965", "#006d3b", "#00d8d8", "#008b8b", "#003f3f",
# "#053efa", "#0434d4", "#021860", "#7a8998", "#56636f", "#2e363e", "#181C20")
options(palette = pal_my)
# mypal3 <- pal_my[3:16]
# mypal2 <- pal_my[c(4, 9, 12, 15)]
# mypal22 <- c("#29B78B", "#0434D4", "#00E6AE", "#01AFD7", "#A700A0")
# pal_my.a75 <- sapply(pal_my, adjustcolor, alpha.f = 0.75)
# pal_my.a50 <- sapply(pal_my, adjustcolor, alpha.f = 0.5)
# mb <- colorRampPalette(pal_my[c(5, 16)])
# magblu <- mb(10)
# pdxpal <- c("#8b9535", "#ffffff", "#373737")
# ynpal <- pal_my[c(10, 1, 2)]
# bmon_pal <- pal_my[c(16, 1, 17)]
# bmon_pal2 <- pal_my[c(16, 18, 17)]
# bstds_pal <- pal_my[c(5, 1, 17)]
# bstds_pal2 <- pal_my[c(5, 18, 17)]
# stmon_pal <- pal_my[c(17, 16, 5)]
# bmon_palX <- pal_my[c(17, 16)]
# bstds_palX <- pal_my[c(17, 5)]
R.adjCol <- function(x, a)
{
adjustcolor(x, alpha = a)
}
# stmon_pal2 <- as.character(lapply(stmon_pal, R.adjCol, a = 0.9))
# stmon_pal.ls <- list(Standards = pal_my[17], Monitoring = pal_my[16], `Standards \\&\nMonitoring` = pal_my[5])
# pal_HC <- c("#7cb5ec", "#434348", "#90ed7d", "#f7a35c", "#8085e9", "#f15c80",
# "#e4d354", "#8085e8", "#8d4653", "#91e8e1")
# pal_HCd <- c("#2b908f", "#90ee7e", "#f45b5b", "#7798BF", "#aaeeee", "#ff0066",
# "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee")
# pal_sci <- c("#0b2b4a", "#114477", "#44aa88", "#77112b", "#de1f51", "#ddd10a")
# pal_nord <- list(
# polar = c("#2e343f", "#2e343f", "#2e343f", "#2e343f"),
# snow = c("#d8dee8", "#e5e9ef", "#eceff4", "#eceff4"),
# frost = c("#8fbcbb", "#88c0ce", "#81a1be", "#5e81a8"),
# aurora = c("#bf606b", "#d08674", "#ebca93", "#a3be91", "#b48eab")
# )
# clrss <- colorRampPalette(pal_sci, alpha = T)
grad <- function(x, p = cols1, alpha = 1)
{
if (class(x) == "data.frame")
l <- nrow(x)
else l <- length(x)
adjustcolor(p(l), alpha.f = alpha)
}
Rformat <- function(x, big.mark = ",", ...)
{
format(x, big.mark = big.mark)
}
library(pander)
# capwords <- function(s, strict = FALSE)
# {
# cap <- function(s) paste(toupper(substring(s, 1, 1)), {
# s <- substring(s, 2)
# if (strict)
# tolower(s)
# else s
# }, sep = "", collapse = " ")
# sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
# }
Rformats <- list(big = ",", dgts = 0)
# mp <- function(..., plotlist = NULL, file, cols = 1, layout = NULL)
# {
# library(grid)
# plots <- c(list(...), plotlist)
# numPlots <- length(plots)
# if (is.null(layout))
# {
# layout <- matrix(seq(1, cols * ceiling(numPlots/cols)), ncol = cols,
# nrow = ceiling(numPlots/cols))
# }
# if (numPlots == 1)
# {
# print(plots[[1]])
# }
# else
# {
# grid.newpage()
# pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# for (i in 1:numPlots)
# {
# matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
# print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
# layout.pos.col = matchidx$col))
# }
# }
# }
# sedit <- function(x)
# {
# file.edit(x)
# source(x)
# }
# R.rrefs <- function(bib_main = "REFs.bib", bib_r = "rrefs.bib", perl = TRUE)
# {
# r_refs(file = bib_main, append = TRUE)
# r_refs(file = bib_r, append = FALSE)
# rrefs <- R.cite_r(file = bib_r)
# rrefs <- gsub(" and the R-packages", ";", rrefs, perl = perl)
# rrefs <- gsub("\\], and", "\\];", rrefs, perl = perl)
# rrefs <- gsub("\\],", "\\];", rrefs, perl = perl)
# rrefs <- strsplit(rrefs, "; ", perl = perl)
# rrefs <- data.frame(rrefs)
# names(rrefs) <- "R-References"
# return(kable(rrefs, col.names = ""))
# }
# R.percTEX <- function(x, n = 14)
# {
# if (length(x) == 0)
# return(character())
# y <- round(x/n, digits = getOption("digits"))
# paste0(comma(y * 100), "\\%")
# }
# R.Euvenn <- function(x, vcol, ...)
# {
# evenn <- venneuler(x)
# evenn$labels <- NA
# plot(evenn, col = vcol, alpha = 0.75, ...)
# text(evenn$centers, labels = colnames(x), col = "#c0c0c0", cex = 2)
# return(evenn)
# }
# R.Evenn <- function(x, vcol, labs = rev(names(x)), al = 0.5, lcex = 1,
# adj = NULL, ...)
# {
# A <- x[[2]]
# AB <- x[[1]]
# evenn <- venneuler(c(A = A, `A&B` = AB))
# evenn$labels <- c("", "")
# plot(evenn, col = vcol, alpha = al, ...)
# text(evenn$centers, labels = labs, col = pal_my[1], cex = lcex, adj = adj)
# return(evenn)
# }
is_html_output <- function(...) knitr:::is_html_output(...)
is_latex_output <- function(...) knitr:::is_latex_output(...)
# R.regTEX <- function(txt, op = 1)
# {
# if (op == 1)
# {
# TX <- gsub("\\*\\*(.*?)\\*\\*", "\\\\textbf\\{\\1\\}", txt, perl = TRUE)
# TX <- gsub("_(.*?)_", "\\\\textit\\{\\1\\}", TX, perl = TRUE)
# TX <- gsub("`(.*?)`", "\\\\texttt\\{\\1\\}", TX, perl = TRUE)
# }
# else
# {
# TX <- gsub("\\\\textbf\\{(.*?)\\}", "\\*\\*\\1\\*\\*", txt, perl = TRUE)
# TX <- gsub("\\\\textit\\{(.*?)\\}", "_\\1_", TX, perl = TRUE)
# TX <- gsub("\\\\texttt\\{(.*?)\\}", "`\\1`", TX, perl = TRUE)
# }
# return(TX)
# }
# R.rspss <- function(x, vlabs = FALSE, df = TRUE, ...)
# {
# read.spss(x, use.value.labels = vlabs, to.data.frame = df)
# }
# knitr::knit_hooks$set(Rplot = function(before, options, envir)
# {
# if (before)
# {
# palette(pal_my)
# par(bg = "transparent", font.main = 3, family = "ETBembo")
# }
# })
knitr::knit_hooks$set(Rrule = function(before, options, envir)
{
if (is_latex_output())
{
if (before)
{
if (!is.null(options$Rrule))
{
"\\Rrule\n\n"
}
}
else
{
if (!is.null(options$Rerule))
{
"\n\n\\Rerule"
}
}
}
})
knitr::opts_hooks$set(echoRule = function(options)
{
if (options$echo == FALSE)
{
options$Rrule <- NULL
options$Rerule <- NULL
}
else
{
options$Rrule <- TRUE
options$Rerule <- TRUE
}
options
})
knitr::opts_chunk$set(Rplot = TRUE, echoRule = TRUE)
knitr::knit_hooks$set(Rruleb = function(before, options, envir)
{
if (is_latex_output())
{
if (before)
{
"\\Rruleb\n\n"
}
else
{
"\n\n\\Reruleb"
}
}
})
knitr::opts_hooks$set(echoRuleb = function(options)
{
if (options$echo == FALSE)
{
options$Rruleb <- NULL
}
else
{
options$Rruleb <- TRUE
}
options
})
knitr::opts_chunk$set(echoRuleb = NULL)
RtftB <- function(x, ...)
{
rmarkdown::render(x, output_format = "tufte::tufte_book", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
RtftH <- function(x, ...)
{
rmarkdown::render(x, output_format = "tufte::tufte_handout", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
RtftHt <- function(x, ...)
{
rmarkdown::render(x, output_format = "tufte::tufte_html", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
RtftHt2 <- function(x, ...)
{
rmarkdown::render(x, output_format = "bookdown::tufte_html2", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
Rbeam <- function(x, ...)
{
rmarkdown::render(x, output_format = "beamer_presentation", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
Rword <- function(x, ...)
{
rmarkdown::render(x, output_format = "word_document", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
Rpdf <- function(x, ...)
{
rmarkdown::render(x, output_format = "pdf_document", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
Rnb <- function(x, ...)
{
rmarkdown::render(x, output_format = "html_notebook", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
Rhtml <- function(x, ...)
{
rmarkdown::render(x, output_format = "html_document", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
Rhtml2 <- function(x, ...)
{
rmarkdown::render(x, output_format = "bookdown::html_document2", ...)
print(format(Sys.time(), "%n[%d %b. %I:%M%p]"))
}
<file_sep>/_comps_docs/_zmisc/appb_appc.Rmd
# Appendix B. Literature Description \& Data Extraction Template
\Frule
## Citation:
\tufteskip
\SFrule
## Substantive Research Topic(s):
\tufteskip
\SFrule
\medskip
\SFrule
## \textsc{Study Purpose(s):}
\tufteskip
\SFrule
\medskip
\SFrule
`r tufte::newthought("Research Question(s) (RQs)")`:
\hspace*{2em} \small{Including theoretical model(s) (if applicable)}
\tufteskip
\SFrule
\medskip
\SFrule
`r tufte::newthought("Hypotheses")`:
\hspace*{2em} \small{Including hypothesized model(s) (if applicable)}
\tufteskip
\SFrule
\medskip
\SFrule
\tufteskip
## Target Population(s) (By Level of Specificity):
`r tufte::newthought("Includes")`:
\medskip
\SFrule
\medskip
\SFrule
`r tufte::newthought("Excludes")`:
\medskip
\SFrule
\medskip
\SFrule
## Sampling Frame (By Level of Specificity)
`r tufte::newthought("Includes")`
\medskip
\SFrule
\medskip
\SFrule
`r tufte::newthought("Excludes")`
\medskip
\SFrule
\medskip
\SFrule
## Sampling Method(s) (By Sampling Frame Level):
\Frule
\tufteskip
\hspace*{2em} $\square$ Probability/Random
\hspace*{2em} $\square$ Purposive
\hspace*{2em} $\square$ Convenience
## \textsc{Sampling \& Recruitment Setting(s)}
\medskip
\SFrule
\medskip
\SFrule
## Study Design(s)
\Frule
## \textsc{Qua\LARGE{L}itative Research Designs (if applicable):}
\hspace*{2em} $\square$ \textsc{Grounded Theory}
\parindent=1em\ $\square$ \textsc{Phenomenology}
\parindent=1em\ $\square$ \textsc{Ethnography}
\parindent=1em\ $\square$ \textsc{Case-Study}
\parindent=1em\ $\square$ \textsc{Narrative/Descriptive}
\parindent=2.25em\ $\square$ Biographical
\parindent=2.25em\ $\square$ Historical
## \textsc{Qua\LARGE{NT}itative Research Designs (if applicable):}
\parindent=1em\ $\square$ \textsc{Experimental}
\parindent=2.5em\ $\square$ Longitudinal
\parindent=2.5em\ $\square$ Pre-Post
\parindent=2.25em\ $\square$ \textsc{Randomized Control Trial (RCT)}
\parindent=3.25em\ $\square$ RCT - Longitudinal
\parindent=3.25em\ $\square$ RCT - Pre-Post
\parindent=1em\ $\square$ \textsc{Quasi-Experimental}
\parindent=1em\ $\square$ \textsc{Cross-Sectional}
## Methodology:
\Frule
\parindent=1em\ $\square$ \textsc{Qualitative}
\parindent=1em\ $\square$ \textsc{Quantitative}
\parindent=1em\ $\square$ \textsc{Mixed-Methods}
\tufteskip
## \textsc{Data Collection Method(s) \& Data Source(s) (By Sampling Frame Level \& Methodology):}
\Frule
`r tufte::newthought("Measure(s)")`
`r tufte::newthought("Archival / Secondary Data Source(s)")`
\tufteskip
## Data Analytic Approach(es):
\Frule
\tufteskip
\tufteskip
## Key Findings
\Frule
`r tufte::newthought("Sample Characteristics (by sampling frame level \\& methodology)")`:
\medskip
\SFrule
\medskip
\SFrule
`r tufte::newthought("Findings (by methodology \\& hypothesis/RQ)")`:
\medskip
\SFrule
\medskip
\SFrule
\tufteskip
## Social Ecological Levels of Analysis:
\Frule
\parindent=1em\ $\square$ \textsc{Individual}
\parindent=1em\ $\square$ \textsc{Relationship}
\parindent=1em\ $\square$ \textsc{Community}
\parindent=1em\ $\square$ \textsc{Societal}
Social-Ecological Model](graphics/inputs/sem.pdf){#fig:sem}
> `r tufte::quote_footer("--- @centers2015social; @dahlberg2002violence")`
# Appendix C. Qualitative Comparative Analysis
<!-- TODO: INCLUDE APPENDIX C CONTENT -->
<file_sep>/_comps_docs/_zmisc/bibkeys_cp.R
#' ---
#' title: "MAP - Bibliography (Bibkeys - CP Only)"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', fig.keep='none', fig.show='none', message=FALSE, warning=FALSE, cache=FALSE
# SETUP --------------------------------------------------------------
source("bibs_cp.R", echo = FALSE, print.eval = FALSE, verbose = FALSE)
knitr::opts_chunk$set(fig.path = "graphics/bibkeys_cp/rplot-", dev = 'pdf')
# options(warn = -1)
#'
#' \Frule
#'
#'
#+ maptl, fig.fullwidth=TRUE, fig.height=3, out.width='\\linewidth'
MAPtl <- within(MAP, { ## making a copy so i don't mess up anything already written below that may depend on the original version of "MAP" ##
scat2 <- factor(scat, labels = c("IPV Interventions Reserach", "SMW-Inclusive Research"))
bibkey2 <- as.integer(factor(bibkey))
})
MAPtl$bibkey2 <- gsub("(\\w+)\\d{4}\\w+", "\\1", MAPtl$bibkey)
MAPtl$bibkey2 <- sapply(MAPtl$bibkey2, RtCap, USE.NAMES = FALSE)
MAPtl$pos <- sample(seq(1, nrow(MAPtl), by = 1), size = nrow(MAPtl), replace = FALSE)
pcpv <- mpal(1:2) %>% rev()
gg.tl <- ggplot(MAPtl, aes(x = year, y = 0, colour = scat2)) +
thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE, ptitle = TRUE) +
theme(legend.text = element_text(size = rel(0.65)),
legend.title = element_text(size = rel(0.75), face = "bold"),
plot.title = element_text(size = rel(0.8))) +
labs(colour = "Research Category") +
scale_colour_manual(values = pcpv) + #, guide = FALSE) +
geom_hline(yintercept = mean(MAPtl$pos), size = 0.25, color = pal_my[19], alpha = 0.5) +
geom_segment(aes(y = mean(MAPtl$pos), yend = pos, x = year, xend = year),
colour = pal_my[19], alpha = 0.45,
na.rm = TRUE, size = 0.15) +
##, position = position_dodge(width = 1)) +
geom_text(aes(y = pos, x = year, label = bibkey2),#, position = position_jitter(),
vjust = "outward", angle = 0, size = 2.5, fontface = "bold"); gg.tl +
ggtitle("Timeline of Reviewed Community-Psychology (CP)-Specific Research")
#'
#' \newpage
#'
#' # \textsc{IPV Interventions Research}
#'
#' \Frule
#'
# reclab(cb$scat) --------------------------------------------------------
levels(cb$scat) <- c(1, 2)
cb$clab <- factor(cb$clab)
#'
# s3cb --------------------------------------------------------
s3cb <- cb[cb$scat == 1, ] %>% droplevels()
# s3cb.keys <- paste0("_**", levels(s3cb$bibkey), "**_ [@", levels(s3cb$bibkey), "]")
s3cb.keys <- paste0("@", levels(s3cb$bibkey))
# s3cb.keys %>% as.list() %>% pander()
#'
#'
#+ inv, fig.fullwidth=TRUE, fig.height=2, out.width='\\linewidth'
inv <- MAP[MAP$scat == "S3", ]
# inv.a <- cb[as.character(cb$bibkey) %in% as.character(inv$bibkey), ]
tl.inv <- inv[order(inv$year), c("bibkey", "year", "journal", "title")] %>% droplevels()
tl.inv$bibkey <- paste0("@", tl.inv$bibkey)
tl.inv <- dplyr::rename(tl.inv, "Study" = bibkey, "Journal" = journal, "Year Published" = year)
rownames(tl.inv) <- NULL
tl.inv[, c(1, 3, 2)] %>% kable(caption = "CP-Specific IPV Interventions Research Timeline")
bibkey.inv <- gsub("(\\w+)\\d{4}\\w+", "\\1", inv$bibkey)
bibkey.inv <- sapply(bibkey.inv, RtCap, USE.NAMES = FALSE)
inv$bibkey <- bibkey.inv
# tl.inv$pos <- runif(nrow(tl.inv), min = -1, max = 1)#*1.5
# tl.inv$pos <- ifelse(abs(tl.inv$pos) < 0.25, tl.inv$pos*10, tl.inv$pos)
# probs1 <- seq(1, nrow(inv), by = 1)
# probs2 <- mean(probs1)
inv$pos <- sample(seq(1, nrow(inv), by = 1), size = nrow(inv), replace = FALSE)
# inv$yrjt <- jitter(tl.inv$year, amount = 1.5)
# jitter(tl.inv$pos, amount = 2)
pinv <- pal_sci[1:length(unique(inv$journal))]
inv$bibkey2 <- as.integer(factor(inv$bibkey))
gg.tlinv <- ggplot(inv, aes(x = year, y = 0, colour = journal)) +
thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE, ptitle = TRUE) +
theme(legend.text = element_text(size = rel(0.65)),
legend.title = element_text(size = rel(0.75), face = "bold"),
plot.title = element_text(size = rel(0.8))) +
labs(colour = "Journal Title") +
scale_colour_manual(values = pinv) + #, guide = FALSE) +
geom_hline(yintercept = mean(inv$pos), size = 0.25, color = pal_my[19], alpha = 0.5) +
geom_segment(aes(y = mean(inv$pos), yend = pos, x = year, xend = year),
colour = pal_my[19], alpha = 0.45,
na.rm = TRUE, size = 0.15) +
##, position = position_dodge(width = 1)) +
geom_text(aes(y = pos, x = year, label = bibkey),#, position = position_jitter(),
vjust = "outward", angle = 0, size = 2.25, fontface = "bold"); gg.tlinv +
ggtitle("CP-Specific IPV-Interventions Research Timeline")
#'
#' ## Research Topics
#'
## s3cb - TOPICS ========================================================
s3top <- s3cb[s3cb$cat == "TOPIC", ] %>% droplevels()
# Rtdf(s3top$clab, names = c(" ", "$N_{Articles}$")) %>%
# pander(caption = "Primary Topics", justify = c("left", "right"))
lvlsn.tp <-paste0(seq(1:nlevels(s3top$clab)), " = ", levels(s3top$clab))
s3top$clabn <- factor(s3top$clab, labels = seq(1:nlevels(s3top$clab)))
ks3tp <- ftable(s3top$bibkey, s3top$clabn) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3tp <- ifelse(ks3tp >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3tp) <- paste0("@", rownames(ks3tp))
kable(ks3tp, caption = "Research Topics")
# library(kableExtra)
# kable(ks3tp, format = "latex", booktabs = T, escape = FALSE) %>%
# kable_styling(latex_options = c("scale_down"))
pander(lvlsn.tp)
#'
#' \newpage
#'
#' ## Target Populations/Sampling Frames
#'
## s3cb - POPULATIONS ========================================================
s3pop <- s3cb[s3cb$cat == "POPULATION" & s3cb$scat == 1, ] %>% droplevels()
# ftable(s3pop$clab, s3pop$jrnl)
# Rtdf(s3pop$clab, names = c(" ", "$N_{Articles}$")) %>%
# kable(caption = "Populations Included", align = c("l", "r"))
lvlsn.pop <-paste0(seq(1:nlevels(s3pop$clab)), " = ", levels(s3pop$clab))
s3pop$clabn <- factor(s3pop$clab, labels = seq(1:nlevels(s3pop$clab)))
ks3pop <- ftable(s3pop$bibkey, s3pop$clabn) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3pop <- ifelse(ks3pop >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3pop) <- paste0("@", rownames(ks3pop))
kable(ks3pop)
pander(lvlsn.pop)
#'
#' ## Methodologies
#'
## s3cb - METHODS ========================================================
s3mo <- s3cb[s3cb$cat == "METHODS", ] %>% droplevels()
# ftable(s3mo$clab, s3mo$jrnl)
# Rtdf(s3mo$clab, names = c(" ", "$N_{Articles}$")) %>%
# kable(caption = "Overarching Methodology", align = c("l", "r"))
lvlsn.mo <-paste0(seq(1:nlevels(s3mo$clab)), " = ", levels(s3mo$clab))
s3mo$clabn <- factor(s3mo$clab, labels = seq(1:nlevels(s3mo$clab)))
ks3mo <- ftable(s3mo$bibkey, s3mo$clabn) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3mo <- ifelse(ks3mo >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3mo) <- paste0("@", rownames(ks3mo))
kable(ks3mo)
pander(lvlsn.mo)
#'
#' ## QuaNTitative Methods
#'
## s3cb - QUANT ========================================================
s3qt <- s3cb[s3cb$cat == "M-QT", ] %>% droplevels()
# ftable(s3qt$clab, s3qt$jrnl)
# Rtdf(s3qt$clab, names = c(" ", "$N_{Articles}$")) %>%
# kable(caption = "Qua**NT**itative Methods", align = c("l", "r"))
lvlsn.qt <-paste0(seq(1:nlevels(s3qt$clab)), " = ", levels(s3qt$clab))
s3qt$clabn <- factor(s3qt$clab, labels = seq(1:nlevels(s3qt$clab)))
ks3qt <- ftable(s3qt$bibkey, s3qt$clabn) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3qt <- ifelse(ks3qt >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3qt) <- paste0("@", rownames(ks3qt))
kable(ks3qt)
pander(lvlsn.qt)
#'
#' \newpage
#'
## s3cb - MIXED-MTHDS (NA) ========================================================
# s3mm <- s3cb[s3cb$cat == "M-MM", ] %>% droplevels()
# # ftable(s3mm$clab, s3mm$jrnl)
# Rtdf(s3mm$clab, names = c(" ", "$N_{Articles}$")) %>%
# kable(caption = "Mixed-Methods", align = c("l", "r"))
#
# lvlsn.mm <-paste0(seq(1:nlevels(s3mm$clab)), " = ", levels(s3mm$clab))
# s3mm$clabn <- factor(s3mm$clab, labels = seq(1:nlevels(s3mm$clab)))
# ks3mm <- ftable(s3mm$bibkey, s3mm$clabn) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
# ks3mm <- ifelse(ks3mm >= 1, "\\checkmark", "$\\cdot$")
# rownames(ks3mm) <- paste0("@", rownames(ks3mm))
# kable(ks3mm)
# pander(lvlsn.mm)
#'
#' # \textsc{SMW-Inclusive IPV Research}
#'
#' \Frule
#'
#+ s4cb
# s4cb --------------------------------------------------------
s4cb <- cb[cb$scat == 2, ] %>% droplevels
s4cb.keys <- paste0("@", levels(s4cb$bibkey))
# s4cb.keys %>% as.list() %>% pander
#'
#'
#+ smw, fig.fullwidth=TRUE, fig.height=3, out.width='\\linewidth', fig.show='asis'
smw <- MAP[MAP$scat == "S4", ]
# inv.a <- cb[as.character(cb$bibkey) %in% as.character(inv$bibkey), ]
tl.smw <- smw[order(smw$year), c("bibkey", "year", "journal", "title")] %>% droplevels()
tl.smw$bibkey <- paste0("@", tl.smw$bibkey)
tl.smw <- dplyr::rename(tl.smw, "Study" = bibkey, "Journal" = journal, "Year Published" = year)
rownames(tl.smw) <- NULL
tl.smw[, c(1, 3, 2)] %>% kable(caption = "SMW-Inclusive Research Timeline")
bibkey.smw <- gsub("(\\w+)\\d{4}\\w+", "\\1", smw$bibkey)
bibkey.smw <- sapply(bibkey.smw, RtCap, USE.NAMES = FALSE)
smw$bibkey <- bibkey.smw
smw$pos <- sample(seq(1, nrow(smw), by = 1), size = nrow(smw), replace = FALSE) %>% jitter(amount = 2)
psmw <- pal_sci[1:length(unique(smw$journal))]
gg.tlsmw <- ggplot(smw, aes(x = year, y = 0, colour = journal)) +
thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE, ptitle = TRUE) +
theme(legend.text = element_text(size = rel(0.65)),
legend.title = element_text(size = rel(0.75), face = "bold"),
plot.title = element_text(size = rel(0.8))) +
labs(colour = "Journal Title") +
scale_colour_manual(values = psmw) + #, guide = FALSE) +
geom_hline(yintercept = mean(smw$pos), size = 0.25, color = pal_my[19], alpha = 0.5) +
geom_segment(aes(y = mean(smw$pos), yend = pos, x = year, xend = year),
colour = pal_my[19], alpha = 0.45,
na.rm = TRUE, size = 0.15) +
geom_text(aes(y = pos, x = year, label = bibkey),#, position = position_jitter(),
vjust = "outward", angle = 0, size = 2.5, fontface = "bold"); gg.tlsmw +
ggtitle("CP-Specific SMW-Inclusive Research Timeline")
#'
#' \newpage
#'
#' ## Research Topics
#'
## s4cb - TOPICS ========================================================
s4top <- s4cb[s4cb$cat == "TOPIC", ] %>% droplevels()
# Rtdf(s4top$clab, names = c(" ", "$N_{Articles}$")) %>%
# kable(caption = "Primary Topics", align = c("l", "r"))
# s4jtp <- ftable(s4top$clab, s4top$jrnl) %>% as.matrix
# dimnames(s4jtp) <- list("Topic" = dimnames(s4jtp)[[1]], "Journal" = dimnames(s4jtp)[[2]])
# ks4jtp <- ifelse(s4jtp >= 1, "\\checkmark", "$\\cdot$")
# lvlsn.jtp <- paste0(levels(factor(s4top$jrnl)), " = ", levels(factor(s4top$journal)))
# kable(ks4jtp)
# pander(lvlsn.jtp)
lvlsn.tp <- paste0(seq(1:nlevels(s4top$clab)), " = ", levels(s4top$clab))
s4top$clabn <- factor(s4top$clab, labels = seq(1:nlevels(s4top$clab)))
# s4top$clabn <- factor(s4top$clab, labels = seq(1:nlevels(s4top$clab)))
ks4tp <- ftable(s4top$bibkey, s4top$clabn) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4tp <- ifelse(ks4tp >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4tp) <- paste0("@", rownames(ks4tp))
kable(ks4tp)
pander(lvlsn.tp)
#'
#' ## Target Populations/Sampling Frames
#'
## s4cb - POPULATIONS ========================================================
s4pop <- s4cb[s4cb$cat == "POPULATION", ] %>% droplevels()
# lvls.pop <-levels(s4pop$clab)
# ftable(s4pop$clab, s4pop$jrnl)
# Rtdf(s4pop$clab, names = c(" ", "$N_{Articles}$")) %>%
# kable(caption = "Populations Included", align = c("l", "r"))
#
lvlsn.pop <- paste0(seq(1:nlevels(s4pop$clab)), " = ", levels(s4pop$clab))
s4pop$clabn <- factor(s4pop$clab, labels = seq(1:nlevels(s4pop$clab)))
# s4pop$clabn <- factor(s4pop$clab, labels = seq(1:nlevels(s4pop$clab)))
fts4pop <- ftable(s4pop$bibkey, s4pop$clabn) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
fts4pop <- ifelse(fts4pop >= 1, 1, 0)
# ts4pop <- cbind(levels(s4pop$clab), apply(fts4pop, 2, sum))
# colnames(ts4pop) <- c(" ", "$N_{Articles}$")
# kable(ts4pop, caption = "Populations Included in Sampling Frame", align = c("l", "r"))
ks4pop <- Rdich(fts4pop, values = c("\\checkmark", "$\\cdot$"))
rownames(ks4pop) <- paste0("@", rownames(ks4pop))
kable(ks4pop)
pander(lvlsn.pop)
#'
#' \newpage
#'
#' ## Methodology
#'
## s4cb - METHODS ========================================================
s4mo <- s4cb[s4cb$cat == "METHODS", ] %>% droplevels()
# ftable(s4mo$clab, s4mo$jrnl)
# Rtdf(s4mo$clab, names = c(" ", "$N_{Articles}$")) %>%
# kable(caption = "Overarching Methodology", align = c("l", "r"))
lvlsn.mo <-paste0(seq(1:nlevels(s4mo$clab)), " = ", levels(s4mo$clab))
s4mo$clabn <- factor(s4mo$clab, labels = seq(1:nlevels(s4mo$clab)))
ks4mo <- ftable(s4mo$bibkey, s4mo$clabn) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4mo <- ifelse(ks4mo >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4mo) <- paste0("@", rownames(ks4mo))
kable(ks4mo)
pander(lvlsn.mo)
#'
#' ## QuaLitative Methods
#'
## s4cb - QUAL
s4ql <- s4cb[s4cb$cat == "M-QL", ] %>% droplevels()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s4ql$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**L**itative Methods", align = c("l", "r"))
lvlsn.ql <-paste0(seq(1:nlevels(s4ql$clab)), " = ", levels(s4ql$clab))
s4ql$clabn <- factor(s4ql$clab, labels = seq(1:nlevels(s4ql$clab)))
ks4ql <- ftable(s4ql$bibkey, s4ql$clabn) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4ql <- ifelse(ks4ql >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4ql) <- paste0("@", rownames(ks4ql))
kable(ks4ql)
pander(lvlsn.ql)
#'
#' ## QuaNTitative Methods
#'
## s4cb - QUANT ========================================================
s4qt <- s4cb[s4cb$cat == "M-QT", ] %>% droplevels()
# ftable(s4qt$clab, s4qt$jrnl)
# Rtdf(s4qt$clab, names = c(" ", "$N_{Articles}$")) %>%
# kable(caption = "Qua**NT**itative Methods", align = c("l", "r"))
lvlsn.qt <-paste0(seq(1:nlevels(s4qt$clab)), " = ", levels(s4qt$clab))
s4qt$clabn <- factor(s4qt$clab, labels = seq(1:nlevels(s4qt$clab)))
ks4qt <- ftable(s4qt$bibkey, s4qt$clabn) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4qt <- ifelse(ks4qt >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4qt) <- paste0("@", rownames(ks4qt))
kable(ks4qt)
pander(lvlsn.qt)
#'
#' ## Mixed-Methods
#'
## s4cb - MIXED-MTHDS ========================================================
s4mm <- s4cb[s4cb$cat == "M-MM", ] %>% droplevels()
# ftable(s4mm$clab, s4mm$jrnl)
# Rtdf(s4mm$clab, names = c(" ", "$N_{Articles}$")) %>%
# kable(caption = "Mixed-Methods", align = c("l", "r"))
lvlsn.mm <-paste0(seq(1:nlevels(s4mm$clab)), " = ", levels(s4mm$clab))
s4mm$clabn <- factor(s4mm$clab, labels = seq(1:nlevels(s4mm$clab)))
ks4mm <- ftable(s4mm$bibkey, s4mm$clabn) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4mm <- ifelse(ks4mm >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4mm) <- paste0("@", rownames(ks4mm))
kable(ks4mm)
pander(lvlsn.mm)
#'
#' \newpage\onehalfspacing
#'
#' # References
<file_sep>/cluster-sampling.R
#' ---
#' title: "Cluster Analysis - Sampling Settings \\& Methods"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#' \Frule
#'
#+ echo=FALSE
knitr::opts_template$set(invisible = list(echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE, fig.keep='none', fig.show='none'))
knitr::opts_chunk$set(fig.path="graphics/cluster/rplot-")
#'
#+ srcbibs, opts.label='invisible'
source("QCA.R")
#'
#' \newpage
#'
#' # Cluster - Sampling Methods
#'
#+ hclust_smthds
sm <- cb[cb$cat == "M-SAMPLING", ] %>% droplevels()
# sm2 <- cb[cb$cat == "M-SETTINGS", ] %>% droplevels()
# sm <- rbind(sm1, sm2)
sm$bibkey <- paste0("@", sm$bibkey)
Rtdf(sm$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(align = c("l", "r"))
smmat <- ftable(sm$bibkey, sm$cid) %>% as.matrix
smmatpr <- ftable(sm$bibkey, sm$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
smmatt <- t(smmat)
kable(Rmsmm(as.data.frame(smmatpr)))
kable(Rmsmm(as.data.frame(smmatt)))
smdist <- dist(smmat)
Rmsmm(smdist)
smclust <- hclust(smdist, method = "ward.D2")
# names(smclust)
# smclust$merge
# smclust$height
# smclust$order
# smclust$labels
palette(pal_my)
par(mar = c(0,2,2,1))
plot(smclust, sub = ' ', xlab = ' ', main = "Sampling Methods Clusters",
frame.plot = F, col = 19, cex = .75, cex.main = 0.75,
cex.lab = 0.75, cex.axis = 0.65)
abline(a = 3, b = 0, lty = 3, lwd = 1.5,
col = adjustcolor(pal_my[19], alpha.f = 0.75))
rect.hclust(smclust, h = 3, border = "#3B0C67") -> rhcl
smGrps <- cutree(smclust, 3)
barplot(table(smGrps), col = pal_sci[1], border = pal_sci[1], main = "Cluster Member Counts - Sampling Methods", xlab = ' ', cex = 1.25, cex.main = 1.15, cex.lab = 1, cex.axis = 0.85)
as.data.frame(table(smGrps)) %>%
dplyr::rename(Group = smGrps, Nmembers = Freq) %>% ## 'rename()' {dplyr} args: [output]=[input]
kable(caption = "3-Group Solution Membership Counts (Sampling Methods)")
smmembers <- sapply(unique(smGrps),function(g) paste(rownames(smmat)[smGrps == g]))
names(smmembers) <- paste0("Group.", seq_along(smmembers))
smmembers <- t(t(smmembers))
names(smmembers) <- "Group Members"
pander(smmembers, caption = "Group Memberships Resulting from 4-Group Hierarchical Cluster Solution (Sampling Methods)")
#'
#+ kclust_smthds
library(cluster)
smkfit <- kmeans(smmat, 3)
palette(pal_sci)
clusplot(smmat, smkfit$cluster, main = '3-Cluster K-Means Solution (Sampling Methods)',
color = T, shade = T,
labels = 0, lines = 1, col.p = pal_my[19], font.main = 3, verbose = T, span = T)
pander(t(smkfit$centers), caption = "Per Variable Cluster Means ('centers') for 3-Cluster K-Means Solution (Sampling Methods)")
smkpam <- pam(smmat, 3) ## k = n-groups ##
smsil <- silhouette(smkpam)
plot(smsil, main = "Silhouette Plot of 3-Cluster Solution\n(Sampling Methods)", font.main = 3, do.n.k = T, col = mpal(1:4, p = grays), cex = 0.5)
smCluster <- c(seq(1:3))
smkpam.clus <- round(smkpam$clusinfo, 2)
smkpam.clus <- cbind(smCluster, smkpam.clus)
smkpam.cwidth <- smkpam$silinfo[2]
smkpam.cwidth <- cbind(smCluster, round(smkpam.cwidth[[1]], 2))
smkpam.sil <- round(smkpam$silinfo[[1]], 5)
smCase <- rownames(smkpam.sil)
smkpam.sil <- cbind(smCase, smkpam.sil)
kable(smkpam.clus, col.names = c("Cluster", "Size", "$Max_{Dissimilarity}$", "$\\mu_{Dissimilarity}$", "Diameter", "Separation"), align = c("c", rep("r", ncol(smkpam.clus) - 1)), caption = "K-pam Cluster Descriptives (Sampling Methods)")
names(smkpam$silinfo) <- c("Cluster Width", "$\\mu_{Cluster Width}", "\\mu_{Width_{Overall}}")
kable(smkpam.cwidth, caption = "Cluster Widths for 3-Cluster PAM Solution (Sampling Methods)", col.names = c("Cluster", "Width"), align = c("c", "r"))
kable(smkpam.sil, col.names = c("Case", "Cluster", "Neighbor", "Silhouette Width"), caption = "Silouette Information Per Case (Sampling Methods)", row.names = FALSE)
#'
#' \newpage
#'
#' # References
#'
#' \refs
#'
<file_sep>/data/MAP-selpoints.R
source("bibs.R")
x <- read.csv("data/SQL/RQDA-MAP-SQL/selPoints.csv")
# x <- dplyr::rename(x, "bibkey" = casename)
# xm <- merge(MAP, x)
# xm <- xm[, c("caseid", "bibkey", "selfirst", "selend", "scat")]
# write.csv(xm, "data/SQL/RQDA-MAP-SQL/MAP-selPoints.csv")
<file_sep>/data/summary-silvergleid2006.md
In general, research on the effectiveness of IPV perpetrator intervention programs in the late 1990s and early 2000s, including the above-reviewed research, provides a mixture of evidence in favor and not in favor of these programs' effectiveness [@feder2005meta]. The above-reviewed subset of the IPV-related literature reiterates the general ambiguity regarding effective approaches to IPV interventions. Nonetheless, it is important to understand the processes underlying successful outcomes (e.g., reduced or eliminated recidivism among participants) in these interventions. @silvergleid2006batterer provide one such exploration of the key processes facilitating positive change among men who successfully completed an IPV perpetrator intervention program in Portland, Oregon.
@silvergleid2006batterer conducted in-depth, semi-structured, one-on-one interviews with ten intervention group facilitators and nine men who were within two-weeks of having completed their participation in the intervention and who were nominated by group facilitators. Four levels of change processes were identified through inductive thematic analysis of the interview data: (1) "community and extratherapeutic influences", (2) "organizational influences", (3) "group processes", and (4) "individual psychological development" (p. 144). The group-level processes seem especially influential in terms of facilitating a _process_ of change, in that this level of influence is further categorized into three sub-processes that appear to build from one another: (1) balancing support and confrontation, (2) sharing and hearing stories, and (3) modeling and mentoring. Facilitators' accounts further emphasized the group-level influences as instrumental in the process underlying intervention participants' "'resocialization' into a new manhood" (p. 151).
<file_sep>/_comps_docs/_bibkeys.R
#' ---
#' title: "Appendix C: Results from Qualitative Comparitive Analyses"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', fig.keep='none', fig.show='none', message=FALSE, warning=FALSE, cache=FALSE
# SETUP --------------------------------------------------------------
source("bibs.R", echo = FALSE, print.eval = FALSE, verbose = FALSE)
knitr::opts_chunk$set(fig.path = "graphics/bibkeys/rplot-",
fig.show = 'asis')#, echo = TRUE)
# options(warn = -1)
#'
#' \Frule
#'
#' \newpage
#'
#+ maptl, fig.fullwidth=TRUE, fig.height=4, out.width='\\linewidth', fig.align='center'
# MAPtl -------------------------------------------------------------------
MAP <- MAP[, c("bibkey", "year", "journal", "caseid", "scat", "jrnl", "cpv", "j.loc", "j.year", "SJR", "Hindex", "title")]
MAPtl <- within(MAP, {
## - making a copy so i don't mess up anything already
## written below that may depend on the original
## version of "MAP" ##
bibkey2 <- as.integer(factor(bibkey))
bibkey2 <- gsub("(\\w+)\\d{4}\\w+", "\\1", bibkey)
bibkey2 <- sapply(bibkey2, RtCap, USE.NAMES = FALSE)
yrv <- ifelse(cpv == "V", year, 0)
yrcp <- ifelse(cpv == "CP", year, 0)
cpv <- factor(cpv, labels = c("Community-Psychology", "Violence"))
})
MAPtl <- MAPtl[order(MAPtl$yrv), , drop = FALSE] %>% within({
posv <- sequence(rle(sort(yrv))$lengths)
posv <- ifelse(yrv == 0, 0, posv)
posv <- posv * -1
})
MAPtl <- MAPtl[order(MAPtl$yrcp), , drop = FALSE] %>% within({
poscp <- sequence(rle(sort(yrcp))$lengths)
poscp <- ifelse(yrcp == 0, 0, poscp)
pos <- posv + poscp
## could've achieved the same in the previous line,
## but wanted to preserve the separate pos* columns just in case ##
})
## !!!! THANKS TO THIS SO ANSWER FOR THE "sequence(rle())" solution:
## http://stackoverflow.com/a/19998876/5944560
## (i spent HOURS trying to figure out how to do this,
## only to find that the geniuses behind R
## [specifically the {utils} pkg] had already developed
## an effecient, vectorized, solution) ##
# grays_nord <- colorRampPalette(pal_nord$polar[c(8, 1)]) ## add to pkg::Riley (in "Rpals.R")##
vawa <- 1994 ## year original VAWA was passed ##
vawaclr <- grays_nord(12)[7]
# yrcnt <- Rtdf(MAPtl$year, names = c("year", "yrcnt"))#[, 1, drop == FALSE]
# as.integer(MAPtl$year) %>% min() -> yrmin
# as.integer(MAPtl$year) %>% max()+1 -> yrmax
# GGPLOT - tl -------------------------------------------------------------
gg.tl <- ggplot(MAPtl, aes(x = year, y = 0, colour = cpv)) +
thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE,
ptitle = TRUE, xtext = FALSE, xticks = FALSE) +
theme(legend.text = element_text(size = rel(0.55)),
legend.title = element_text(size = rel(0.65), face = "bold"),
legend.justification = c(1, 0.635),
legend.box.spacing = unit(0, "cm")) +
labs(colour = "Journal Category", title = "Timeline of Reviewed Research\n") +
scale_colour_manual(values = pcpv) + #, guide = FALSE) +
geom_hline(yintercept = 0, size = 0.25, color = pal_nord$polar[7], alpha = 0.5) +
geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
colour = pal_my[19], alpha = 0.45,
na.rm = TRUE, size = 0.15) +
geom_text(aes(y = pos, x = year, label = bibkey2), hjust = 0.5, vjust = 0,
angle = 45, size = 2.5, fontface = "bold") +
# geom_vline(xintercept = vawa, size = 0.45, color = pal_nord$polar[1], linetype = 3) +
geom_text(aes(y = 0, x = vawa, label = "1994 Violence Against Women Act"),
alpha = 0.5, angle = 90, colour = vawaclr, size = 3,
nudge_x = -0.25,
family = "serif", fontface = "italic") +
geom_text(aes(y = 0, x = year, label = year), check_overlap = TRUE,
vjust = 0.5, hjust = 0.5, angle = 0, colour = pal_my[20],
size = 2.5, family = "serif", fontface = "bold")
gg.tl
#'
#' \newpage
#'
#' # \textsc{IPV Interventions Research}
#'
#' \Frule
#'
# reclab(cb$scat) --------------------------------------------------------
levels(cb$scat) <- c(1, 2)
cb$clab <- factor(cb$clab)
#'
# s3cb --------------------------------------------------------
s3cb <- cb[cb$scat == 1, ] %>% droplevels
s3cb.keys <- paste0("@", levels(s3cb$bibkey))
#'
#'
#+ tl_inv, fig.fullwidth=TRUE, fig.height=2.75, out.width='\\linewidth'
inv <- MAPtl[MAPtl$scat == "S3", ]
tl.inv <- inv[order(inv$year), c("bibkey", "year", "cpv", "journal", "title"), drop = FALSE] %>% droplevels()
tl.inv$bibkey <- paste0("@", tl.inv$bibkey)
tl.inv$journal <- paste0("_", tl.inv$journal, "_")
tl.inv <- dplyr::rename(tl.inv, "Study" = bibkey, "Journal" = journal, "Year Published" = year)
rownames(tl.inv) <- NULL
# GGPLOT - invtl ----------------------------------------------------------
gg.invtl <- ggplot(inv, aes(x = year, y = 0, colour = cpv)) +
thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE,
ptitle = FALSE, xtext = FALSE, xticks = FALSE) +
theme(legend.text = element_text(size = rel(0.55)),
legend.title = element_text(size = rel(0.65), face = "bold"),
legend.justification = c(1, 0.8),
legend.box.spacing = unit(0, "cm")) +
# plot.margin = unit(c(1, rep(0.15, 3)), "cm")) +
ylim(min(inv$pos) - 0.5, max(inv$pos) + 0.5) +
labs(colour = "Journal Category", title = "IPV-Interventions Research Timeline") +
scale_colour_manual(values = pcpv) + #, guide = FALSE) +
geom_hline(yintercept = 0, size = 0.25, color = pal_nord$polar[7], alpha = 0.5) +
geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
colour = pal_my[19], alpha = 0.45,
na.rm = TRUE, size = 0.15) +
geom_text(aes(y = pos, x = year, label = bibkey2), hjust = 0.5, vjust = 1,
angle = 45, size = 2.5, fontface = "bold") + #, nudge_y = -0.05) +
# geom_vline(xintercept = vawa, size = 0.45, color = pal_nord$polar[1], linetype = 3) +
geom_text(aes(y = 0, x = vawa, label = "1994 Violence Against Women Act"),
alpha = 0.5, angle = 90, colour = vawaclr, size = 2.5,
nudge_x = -0.25, family = "serif", fontface = "italic") +
geom_text(aes(y = 0, x = year, label = year), check_overlap = TRUE,
vjust = 0.5, hjust = 0.5, angle = 0, colour = pal_my[20],
size = 2.5, family = "serif", fontface = "bold")
gg.invtl
tl.inv[, c(1, 4, 2)] %>% kable(caption = "IPV Interventions Research Timeline")
#'
#' \newpage
#'
#' ## Research Topics
#'
#+ topics_s3
## s3cb - TOPICS ========================================================
# levels(droplevels(cb[cb$cat == "TOPIC", "clab"])) %>% as.list() %>% pander()
# l1tops <-levels(droplevels(cb[cb$cat == "TOPIC", "clab"]))[c(12, 16, )]
s3top <- s3cb[s3cb$cat == "TOPIC", ] %>% droplevels()
s3top <- s3top[!duplicated(s3top), ]
# x <- s4qt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3top$clab, s3top$jrnl)
Rtdf(s3top$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Primary Topics Distribution (IPV Interventions Research)", align = c("l", "r"))
lvls3.tp <- paste0(seq(1:length(unique(s3top$clab))), " = ", levels(s3top$clab))
levels(s3top$clab) <- seq(1:length(unique(s3top$clab)))
ks3tp <- ftable(s3top$bibkey, s3top$clab) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3tp <- ifelse(ks3tp >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3tp) <- paste0("@", rownames(ks3tp))
#'
#' \newpage
#'
# panderOptions("table.split.table", 120)
kable(ks3tp[, 1:9], caption = "Primary Topics by Study (IPV Interventions Research [1/2])")
pander(lvls3.tp[1:9])
#'
#' \newpage
#'
kable(ks3tp[, 10:ncol(ks3tp)], caption = "Primary Topics by Study (IPV Interventions Research [2/2])")
pander(lvls3.tp[10:length(lvls3.tp)])
#'
#' \newpage
#' ## Target Populations/Sampling Frames
#'
#+ pop_s3
## s3cb - POPULATIONS ========================================================
s3pop <- s3cb[s3cb$cat == "POPULATION", ] %>% droplevels()
s3pop <- s3pop[!duplicated(s3pop), ]
# x <- s3pop[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3pop$clab, s3pop$jrnl)
Rtdf(s3pop$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Populations Included (IPV Interventions Research)", align = c("l", "r"))
lvla3.pop <- paste0(seq(1:length(unique(s3pop$clab))), " = ", levels(s3pop$clab))
levels(s3pop$clab) <- seq(1:length(unique(s3pop$clab)))
ks3pop <- ftable(s3pop$bibkey, s3pop$clab) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3pop <- ifelse(ks3pop >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3pop) <- paste0("@", rownames(ks3pop))
kable(ks3pop, caption = "Populations Included by Study (IPV Interventions Research)")
pander(lvla3.pop)
#'
#'
#' \newpage
#'
#' ## Sampling Settings
#'
#'
#+ setLvls_s3
s3set <- s3cb[s3cb$cat == "M-SETTINGS", ] %>% droplevels()
s3set <- s3set[!duplicated(s3set), ]
# x <- s3set[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s3set$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Sampling Settings (IPV Interventions Research)", align = c("l", "r"))
lvla3.set <- paste0(seq(1:length(unique(s3set$clab))), " = ", levels(s3set$clab))
levels(s3set$clab) <- seq(1:length(unique(s3set$clab)))
ks3set <- ftable(s3set$bibkey, s3set$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks3set <- ifelse(ks3set >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3set) <- paste0("@", rownames(ks3set))
kable(ks3set[, 1:10], caption = "Sampling Settings by Study (IPV Interventions Research [1/2])")
pander(lvla3.set[1:9])
#'
#' \newpage
#'
kable(ks3set[, 11:ncol(ks3set)], caption = "Sampling Settings by Study (IPV Interventions Research [2/2])")
pander(lvla3.set[10:length(lvla3.set)])
#'
#'
#' \newpage
#'
#' ## Sampling Methods
#'
#'
#+ smthds_s3
s3smthds <- s3cb[s3cb$cat == "M-SAMPLING", ] %>% droplevels()
s3smthds <- s3smthds[!duplicated(s3smthds), ]
# x <- s3smthds[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s3smthds$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Ecological Levels of Analysis (IPV Interventions Research)", align = c("l", "r"))
lvla3.smthds <- paste0(seq(1:length(unique(s3smthds$clab))), " = ", levels(s3smthds$clab))
levels(s3smthds$clab) <- seq(1:length(unique(s3smthds$clab)))
ks3smthds <- ftable(s3smthds$bibkey, s3smthds$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks3smthds <- ifelse(ks3smthds >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3smthds) <- paste0("@", rownames(ks3smthds))
kable(ks3smthds, caption = "Sampling Methods by Study (IPV Interventions Research)")
pander(lvla3.smthds)
#'
#'
#' \newpage
#' ## Overarching Methodology
#'
#+ mthds_s3
## s3cb - METHODS ========================================================
s3mo <- s3cb[s3cb$cat == "METHODS", ] %>% droplevels()
s3mo <- s3mo[!duplicated(s3mo), ]
# x <- s3mo[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3mo$clab, s3mo$jrnl)
Rtdf(s3mo$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Overarching Methodology (IPV Interventions Research)", align = c("l", "r"))
lvla3.mo <- paste0(seq(1:length(unique(s3mo$clab))), " = ", levels(s3mo$clab))
levels(s3mo$clab) <- seq(1:length(unique(s3mo$clab)))
ks3mo <- ftable(s3mo$bibkey, s3mo$clab) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3mo <- ifelse(ks3mo >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3mo) <- paste0("@", rownames(ks3mo))
kable(ks3mo, caption = "Methodology by Study (IPV Interventions Research)")
pander(lvla3.mo)
#'
#' \newpage
#' ## QuaLitative Methods
#'
#+ QL_s3
## s3cb - QUAL ========================================================
s3ql <- s3cb[s3cb$cat == "M-QL", ] %>% droplevels()
s3ql <- s3ql[!duplicated(s3ql), ]
# x <- s3ql[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3ql$clab, s3ql$jrnl)
Rtdf(s3ql$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**L**itative Methods (IPV Interventions Research)", align = c("l", "r"))
lvla3.ql <- paste0(seq(1:length(unique(s3ql$clab))), " = ", levels(s3ql$clab))
levels(s3ql$clab) <- seq(1:length(unique(s3ql$clab)))
ks3ql <- ftable(s3ql$bibkey, s3ql$clab) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3ql <- ifelse(ks3ql >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3ql) <- paste0("@", rownames(ks3ql))
kable(ks3ql, caption = "Qua**L**itative Methods by Study (IPV Interventions Research)")
pander(lvla3.ql)
#'
#' ## QuaLitative Analytic Appraoches
#'
#+ AQL_s3
## s3cb - QUAL ========================================================
s3aqt <- s3cb[s3cb$cat == "A-QT", ] %>% droplevels()
# s3aqt <- s3ql[!duplicated(s3aqt), ]
# x <- s3aqt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3aqt$clab, s3aqt$jrnl)
Rtdf(s3aqt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**L**itative Methods (IPV Interventions Research)", align = c("l", "r"))
lvla3.ql <- paste0(seq(1:length(unique(s3aqt$clab))), " = ", levels(s3aqt$code))
levels(s3aqt$clab) <- seq(1:length(unique(s3aqt$clab)))
ks3aqt <- ftable(s3aqt$bibkey, s3aqt$clab) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3aqt <- ifelse(ks3aqt >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3aqt) <- paste0("@", rownames(ks3aqt))
kable(ks3aqt, caption = "Qua**L**itative Analytic Approaches by Study (IPV Interventions Research)")
pander(lvla3.ql)
#'
#' \newpage
#' ## QuaNTitative Methods
#'
#+ QT_s3
## s3cb - QUANT ========================================================
s3qt <- s3cb[s3cb$cat == "M-QT", ] %>% droplevels()
s3qt <- s3ql[!duplicated(s3qt), ]
# x <- s3qt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3qt$clab, s3qt$jrnl)
Rtdf(s3qt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**NT**itative Methods (IPV Interventions Research)", align = c("l", "r"))
lvla3.qt <- paste0(seq(1:length(unique(s3qt$clab))), " = ", levels(s3qt$clab))
levels(s3qt$clab) <- seq(1:length(unique(s3qt$clab)))
ks3qt <- ftable(s3qt$bibkey, s3qt$clab) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3qt <- ifelse(ks3qt >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3qt) <- paste0("@", rownames(ks3qt))
kable(ks3qt, caption = "Qua**NT**itative Methods by Study (IPV Interventions Research)")
pander(lvla3.qt)
#'
#' ## QuaNTitative Analytic Approaches
#'
#+ AQT_s3
## s3cb - QUANT - ANALYSIS ========================================================
s3aqt <- s3cb[s3cb$cat == "A-QT", ] %>% droplevels()
# s3aqt <- s3ql[!duplicated(s3aqt), ]
# x <- s3aqt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3aqt$clab, s3aqt$jrnl)
Rtdf(s3aqt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**NT**itative Methods (IPV Interventions Research)", align = c("l", "r"))
lvls3.aqt <- paste0(seq(1:length(unique(s3aqt$clab))), " = ", as.character(levels(s3aqt$clab)))
levels(s3aqt$clab) <- seq(1:length(unique(s3aqt$clab)))
ks3aqt <- ftable(s3aqt$bibkey, s3aqt$clab) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3aqt <- ifelse(ks3aqt >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3aqt) <- paste0("@", rownames(ks3aqt))
kable(ks3aqt, caption = "Qua**NT**itative Methods by Study (IPV Interventions Research)")
pander(lvls3.aqt)
#'
#' \newpage
#' ## Mixed-Methods
#'
#+ mmr_s3
## s3cb - MIXED-MTHDS ========================================================
s3mm <- s3cb[s3cb$cat == "M-MM", ] %>% droplevels()
s3mm <- s3mm[!duplicated(s3mm), ]
# x <- s3mm[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s3mm$clab, s3mm$jrnl)
Rtdf(s3mm$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Mixed-Methods (IPV Interventions Research)", align = c("l", "r"))
lvls3.mm <- paste0(seq(1:length(unique(s3mm$clab))), " = ", levels(s3mm$clab))
levels(s3mm$clab) <- seq(1:length(unique(s3mm$clab)))
ks3mm <- ftable(s3mm$bibkey, s3mm$clab) %>% as.matrix ## "ks3" == "bibkeys - s3" ##
ks3mm <- ifelse(ks3mm >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3mm) <- paste0("@", rownames(ks3mm))
kable(ks3mm, caption = "Mixed-Methods by Study (IPV Interventions Research)")
pander(lvls3.mm)
#'
#'
#' \newpage
#'
#' ## Ecological Levels of Analysis
#'
#'
#+ ecoLvls_s3
s3eco <- s3cb[s3cb$cat == "ECO", ] %>% droplevels()
s3eco <- s3eco[!duplicated(s3eco), ]
# x <- s3eco[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s3eco$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Ecological Levels of Analysis (IPV Interventions Research)", align = c("l", "r"))
lvls3.eco <- paste0(seq(1:length(unique(s3eco$clab))), " = ", levels(s3eco$clab))
levels(s3eco$clab) <- seq(1:length(unique(s3eco$clab)))
ks3eco <- ftable(s3eco$bibkey, s3eco$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks3eco <- ifelse(ks3eco >= 1, "\\checkmark", "$\\cdot$")
rownames(ks3eco) <- paste0("@", rownames(ks3eco))
kable(ks3eco, caption = "Levels of Analysis by Study (IPV Interventions Research)")
pander(lvls3.eco)
#'
#' \newpage
#'
#' # \textsc{SMW-Inclusive Research}
#'
#' \Frule
#'
#+ s4cb
# s4cb --------------------------------------------------------
s4cb <- cb[cb$scat == 2, ] %>% droplevels
s4cb.keys <- paste0("@", levels(s4cb$bibkey))
# s4cb.keys %>% as.list() %>% pander
#'
#+ tl_smw, fig.fullwidth=TRUE, fig.height=2, out.width='\\linewidth', fig.show='asis'
smw <- MAPtl[MAPtl$scat == "S4", ]
tl.smw <- smw[order(smw$year), c("bibkey", "year", "cpv", "journal", "title")] %>% droplevels()
tl.smw$bibkey <- paste0("@", tl.smw$bibkey)
tl.smw$journal <- paste0("_", tl.smw$journal, "_")
tl.smw <- dplyr::rename(tl.smw, "Study" = bibkey, "Journal" = journal, "Year Published" = year)
rownames(tl.smw) <- NULL
psmw <- pal_sci[1:length(unique(smw$journal))]
smw$pos <- rep_len(c(1, -1), length(smw$pos))
# GGPLOT - smwtl ----------------------------------------------------------
gg.smwtl <- ggplot(smw, aes(x = year, y = 0, colour = journal)) +
thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE,
ptitle = FALSE, xtext = FALSE, xticks = FALSE) +
theme(legend.text = element_text(size = rel(0.55)),
legend.title = element_text(size = rel(0.65), face = "bold"),
legend.justification = c(1, 0.635),
legend.box.spacing = unit(0, "cm")) +
# plot.margin = unit(c(1, rep(0.15, 3)), "cm")) +
ylim(min(smw$pos) - 0.5, max(smw$pos) + 0.5) +
labs(colour = "Journal Title", title = "SMW-Inclusive IPV Research Timeline\n") +
scale_colour_manual(values = psmw) + #, guide = FALSE) +
geom_hline(yintercept = 0, size = 0.25, color = pal_nord$polar[7], alpha = 0.5) +
geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
colour = pal_my[19], alpha = 0.45,
na.rm = TRUE, size = 0.15) +
geom_text(aes(y = pos, x = year, label = bibkey2), hjust = 0.5, vjust = 0,
angle = 45, size = 2.5, fontface = "bold") + #, nudge_y = -0.05) +
geom_text(aes(y = 0, x = year, label = year), check_overlap = TRUE,
vjust = 0.5, hjust = 0.5, angle = 0, colour = pal_my[20],
size = 2.5, family = "serif", fontface = "bold")
gg.smwtl
tl.smw[, c(1, 4)] %>% kable(caption = "SMW-Inclusive Research Timeline")
#'
#' \newpage
#'
#' ## Research Topics
#'
#+ topics_s4
## s4cb - TOPICS ========================================================
s4top <- s4cb[s4cb$cat == "TOPIC", ] %>% droplevels()
s4top <- s4top[!duplicated(s4top), ]
# x <- s4top[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4top$clab, s4top$jrnl)
Rtdf(s4top$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Primary Topics (SMW-Inclusive Research)", align = c("l", "r"))
lvls4.tp <- paste0(seq(1:length(unique(s4top$clab))), " = ", levels(s4top$clab))
levels(s4top$clab) <- seq(1:length(unique(s4top$clab)))
ks4tp <- ftable(s4top$bibkey, s4top$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4tp <- ifelse(ks4tp >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4tp) <- paste0("@", rownames(ks4tp))
kable(ks4tp, caption = "Primary Topics by Study (SMW-Inclusive Research)")
pander(lvls4.tp)
#'
#' \newpage
#' ## Target Populations/Sampling Frames
#'
#+ pop_s4
## s4cb - POPULATIONS ========================================================
s4pop <- s4cb[s4cb$cat == "POPULATION", ] %>% droplevels()
s4pop <- s4pop[!duplicated(s4pop), ]
# x <- s4pop[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4pop$clab, s4pop$jrnl)
Rtdf(s4pop$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Populations Included (SMW-Inclusive Research)", align = c("l", "r"))
lvla4.pop <- paste0(seq(1:length(unique(s4pop$clab))), " = ", levels(s4pop$clab))
levels(s4pop$clab) <- seq(1:length(unique(s4pop$clab)))
ks4pop <- ftable(s4pop$bibkey, s4pop$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4pop <- ifelse(ks4pop >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4pop) <- paste0("@", rownames(ks4pop))
kable(ks4pop, caption = "Populations Included by Study (SMW-Inclusive Research)")
pander(lvla4.pop)
#'
#'
#' \newpage
#'
#' ## Sampling Settings
#'
#'
#+ setLvls_s4
s4set <- s4cb[s4cb$cat == "M-SETTINGS", ] %>% droplevels()
s4set <- s4set[!duplicated(s4set), ]
# x <- s4set[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s4set$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Sampling Settings (SMW-Inclusive Research)", align = c("l", "r"))
lvla4.set <- paste0(seq(1:length(unique(s4set$clab))), " = ", levels(s4set$clab))
levels(s4set$clab) <- seq(1:length(unique(s4set$clab)))
ks4set <- ftable(s4set$bibkey, s4set$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4set <- ifelse(ks4set >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4set) <- paste0("@", rownames(ks4set))
kable(ks4set, caption = "Sampling Settings by Study (SMW-Inclusive IPV Research)")
pander(lvla4.set)
#'
#'
#' \newpage
#'
#' ## Sampling Methods
#'
#'
#+ smthdsLvls_s4
s4smthds <- s4cb[s4cb$cat == "M-SAMPLING", ] %>% droplevels()
s4smthds <- s4smthds[!duplicated(s4smthds), ]
# x <- s4smthds[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s4smthds$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Sampling Methods (SMW-Inclusive Research)", align = c("l", "r"))
lvla4.smthds <- paste0(seq(1:length(unique(s4smthds$clab))), " = ", levels(s4smthds$clab))
levels(s4smthds$clab) <- seq(1:length(unique(s4smthds$clab)))
ks4smthds <- ftable(s4smthds$bibkey, s4smthds$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4smthds <- ifelse(ks4smthds >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4smthds) <- paste0("@", rownames(ks4smthds))
kable(ks4smthds, caption = "Sampling Methods by Study (SMW-Inclusve Research)")
pander(lvla4.smthds)
#'
#' \newpage
#' ## Overarching Methodology
#'
#+ mthds_s4
## s4cb - METHODS ========================================================
s4mo <- s4cb[s4cb$cat == "METHODS", ] %>% droplevels()
s4mo <- s4mo[!duplicated(s4mo), ]
# x <- s4mo[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4mo$clab, s4mo$jrnl)
Rtdf(s4mo$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Overarching Methodology (SMW-Inclusive Research)", align = c("l", "r"))
lvla4.mo <- paste0(seq(1:length(unique(s4mo$clab))), " = ", levels(s4mo$clab))
levels(s4mo$clab) <- seq(1:length(unique(s4mo$clab)))
ks4mo <- ftable(s4mo$bibkey, s4mo$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4mo <- ifelse(ks4mo >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4mo) <- paste0("@", rownames(ks4mo))
kable(ks4mo, caption = "Methodology by Study (SMW-Inclusive Research)")
pander(lvla4.mo)
#'
#' \newpage
#' <!-- ## QuaLitative Methods -->
#'
#+ QL_s4
## s4cb - QUAL ========================================================
s4ql <- s4cb[s4cb$cat == "M-QL", ] %>% droplevels()
s4ql <- s4ql[!duplicated(s4ql), ]
# x <- s4ql[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s4ql$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**L**itative Methods (SMW-Inclusive Research)", align = c("l", "r"))
lvla4.ql <- paste0(seq(1:length(unique(s4ql$clab))), " = ", levels(s4ql$clab))
levels(s4ql$clab) <- seq(1:length(unique(s4ql$clab)))
ks4ql <- ftable(s4ql$bibkey, s4ql$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4ql <- ifelse(ks4ql >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4ql) <- paste0("@", rownames(ks4ql))
kable(ks4ql, caption = "Qua**L**itative Methods by Study (SMW-Inclusive Research)")
pander(lvla4.ql)
#'
#' ## QuaLitative Analytic Appraoches
#'
#+ AQL_s4
## s4cb - QUAL ========================================================
s4aqt <- s4cb[s4cb$cat == "A-QT", ] %>% droplevels()
# s4aqt <- s4ql[!duplicated(s4aqt), ]
# x <- s4aqt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4aqt$clab, s4aqt$jrnl)
Rtdf(s4aqt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**L**itative Methods (IPV Interventions Research)", align = c("l", "r"))
lvla4.ql <- paste0(seq(1:length(unique(s4aqt$clab))), " = ", levels(s4aqt$code))
levels(s4aqt$clab) <- seq(1:length(unique(s4aqt$clab)))
ks4aqt <- ftable(s4aqt$bibkey, s4aqt$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4aqt <- ifelse(ks4aqt >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4aqt) <- paste0("@", rownames(ks4aqt))
kable(ks4aqt, caption = "Qua**L**itative Analytic Approaches by Study (IPV Interventions Research)")
pander(lvla4.ql)
#'
#' \newpage
#' ## QuaNTitative Methods
#'
#+ QT_s4
## s4cb - QUANT ========================================================
s4qt <- s4cb[s4cb$cat == "M-QT", ] %>% droplevels()
s4qt <- s4qt[!duplicated(s4qt), ]
# x <- s4qt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4qt$clab, s4qt$jrnl)
Rtdf(s4qt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**NT**itative Methods (SMW-Inclusive Research)", align = c("l", "r"))
lvla4.qt <- paste0(seq(1:length(unique(s4qt$clab))), " = ", levels(s4qt$clab))
levels(s4qt$clab) <- seq(1:length(unique(s4qt$clab)))
ks4qt <- ftable(s4qt$bibkey, s4qt$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4qt <- ifelse(ks4qt >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4qt) <- paste0("@", rownames(ks4qt))
kable(ks4qt, caption = "Qua**NT**itative Methods by Study (SMW-Inclusive Research)")
pander(lvla4.qt)
#'
#' ## QuaNTitative Analytic Appraoches
#'
#+ AQT_s4
## s4cb - QUANT ========================================================
s4aqt <- s4cb[s4cb$cat == "A-QT", ] %>% droplevels()
# s4aqt <- s4ql[!duplicated(s4aqt), ]
# x <- s4aqt[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4aqt$clab, s4aqt$jrnl)
Rtdf(s4aqt$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Qua**NT**itative Methods (IPV Interventions Research)", align = c("l", "r"))
lvla4.qt <- paste0(seq(1:length(unique(s4aqt$clab))), " = ", levels(s4aqt$code))
levels(s4aqt$clab) <- seq(1:length(unique(s4aqt$clab)))
ks4aqt <- ftable(s4aqt$bibkey, s4aqt$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4aqt <- ifelse(ks4aqt >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4aqt) <- paste0("@", rownames(ks4aqt))
kable(ks4aqt, caption = "Qua**NT**itative Analytic Approaches by Study (IPV Interventions Research)")
pander(lvla4.qt)
#'
#' \newpage
#' ## Mixed-Methods
#'
#+ mmr_s4
## s4cb - MIXED-MTHDS ========================================================
s4mm <- s4cb[s4cb$cat == "M-MM", ] %>% droplevels()
s4mm <- s4mm[!duplicated(s4mm), ]
# s4ql <- s4ql[!duplicated(s4ql), ]
# x <- s4ql[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4mm$clab, s4mm$jrnl)
Rtdf(s4mm$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Mixed-Methods (SMW-Inclusive Research)", align = c("l", "r"))
lvla4.mm <- paste0(seq(1:length(unique(s4mm$clab))), " = ", levels(s4mm$clab))
levels(s4mm$clab) <- seq(1:length(unique(s4mm$clab)))
ks4mm <- ftable(s4mm$bibkey, s4mm$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4mm <- ifelse(ks4mm >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4mm) <- paste0("@", rownames(ks4mm))
kable(ks4mm, caption = "Mixed-Methods by Study (SMW-Inclusive Research)")
pander(lvla4.mm)
#'
#'
#' \newpage
#'
#' ## Ecological Levels of Analysis
#'
#'
#+ ecoLvls_s4
s4eco <- s4cb[s4cb$cat == "ECO", ] %>% droplevels()
s4eco <- s4eco[!duplicated(s4eco), ]
# x <- s4eco[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4ql$clab, s4ql$jrnl)
Rtdf(s4eco$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(caption = "Ecological Levels of Analysis (SMW-Inclusive Research)", align = c("l", "r"))
lvla4.eco <- paste0(seq(1:length(unique(s4eco$clab))), " = ", levels(s4eco$clab))
levels(s4eco$clab) <- seq(1:length(unique(s4eco$clab)))
ks4eco <- ftable(s4eco$bibkey, s4eco$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
ks4eco <- ifelse(ks4eco >= 1, "\\checkmark", "$\\cdot$")
rownames(ks4eco) <- paste0("@", rownames(ks4eco))
kable(ks4eco, caption = "Levels of Analysis by Study (SMW-Inclusive Research)")
pander(lvla4.eco)
#'
#' \newpage\onehalfspacing
#'
#' # References
#'
#' \refs
#'
<file_sep>/cluster.R
#' ---
#' title: "Cluster Analysis - Full Codebook"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#' \Frule
#'
#+ echo=FALSE
knitr::opts_template$set(invisible = list(echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE, fig.keep='none', fig.show='none'))
knitr::opts_chunk$set(fig.path="graphics/cluster/rplot-")
#'
#+ srcbibs, opts.label='invisible'
source("bibs_html.R", verbose = FALSE)
#'
dat <- cb[!duplicated(cb), ]
dat <- within(dat, {
})
dat$bibkey <- paste0("@", dat$bibkey)
Rtdf(dat$clab, names = c(" ", "$N_{Articles}$")) %>%
kable(align = c("l", "r"))
mat <- ftable(dat$bibkey, dat$cid) %>% as.matrix
matpr <- ftable(dat$bibkey, dat$clab) %>% as.matrix ## "ks4" == "bibkeys - s4" ##
matt <- t(mat)
kable(Rmsmm(as.data.frame(matpr)))
kable(Rmsmm(as.data.frame(matt)))
dist <- dist(matt)
Rmsmm(dist)
clust <- hclust(dist, method = "ward.D2")
names(clust)
clust$merge
clust$height
clust$order
clust$labels
#+ hclust_all, fig.fullwidth=TRUE
palette(pal_my); par(mar = c(0, 2, 2, 1))
plot(clust, sub = ' ', xlab = ' ', main = " ",
frame.plot = F, col = 19, cex = .75, cex.main = 0.75,
cex.lab = 0.75, cex.axis = 0.65)
abline(a = 7, b = 0, lty = 3, lwd = 1.5,
col = adjustcolor(pal_my[19], alpha.f = 0.75))
rect.hclust(clust, h = 7, border = "#3B0C67") -> rhcl
Grps <- cutree(clust, 4)
barplot(table(Grps), col = , border = 18, main = " ", xlab = ' ', cex = 1.25, cex.main = 1.15, cex.lab = 1, cex.axis = 0.85)
#'
#' \newpage
#'
as.data.frame(table(Grps)) %>%
dplyr::rename(Group = Grps, Nmembers = Freq) %>% ## 'rename()' {dplyr} args: [output]=[input]
kable(caption = "4-Group Solution Membership Counts")
members <- sapply(unique(Grps),function(g) paste(car::recode(rownames(matt), rec.cid2clab)[Grps == g]))
names(members) <- paste0("Group.", seq_along(members))
members <- t(t(members))
names(members) <- "Group Members"
#'
#'
#+ echo=FALSE
kable(data.frame(members[1, ]), caption = "Group-1 Members")
kable(data.frame(members[2, ]), caption = "Group-2 Members")
kable(data.frame(members[3, ]), caption = "Group-3 Members")
kable(data.frame(members[4, ]), caption = "Group-4 Members")
#'
#' \newpage
#'
#+ kclust_all
library(cluster)
kfit <- kmeans(matt, 4)
palette(pal_sci)
clusplot(matt, kfit$cluster, main = '4-Cluster K-Means Solution',
color = T, shade = T,
labels = 0, lines = 1, col.p = pal_my[19], font.main = 3, verbose = T, span = T)
kable(t(kfit$centers), caption = "Per Variable Cluster Means ('centers') for 4-Cluster K-Means Solution")
#'
#' \newpage
#'
#' # References
#'
#' \refs
#'
<file_sep>/data/summary-gregory2002.md
# @gregory2002effects
`In a separate effort to` inform the question of IPV perpetrator intervention effectiveness from the victims'/survivors' perspectives, @gregory2002effects conducted in-depth one-on-one interviews with 33 women identified via police reports as having experienced IPV victimization perpetrated by men referred to a local IPV perpetrator intervention program in a rural Ohio county. Interview questions sought information regarding the offenders' behaviors before, during, and after their participation in the intervention. Regarding survivors' accounts of offenders' behaviors prior to being referred to the intervention, the authors found that many of the men entering the intervention had also been physically violent with past romantic partners, close relatives, and male friends. In addition, a substantial proportion of survivor respondents indicated that jealousy, substance abuse, and family-related issues (e.g., issues related to children, finances, household chores, etc.) were apparent causes of conflict leading to the perpetrators' use of violence. Survivors' also provided insights into their assessments of more underlying causes of abuse, including issues related to power and control, their partners' low self-esteem, and conflict related to sexual/intimacy issues and the perpetrators' infidelity in the relationship. Regarding program participants' partners' accounts of the intervention's effectiveness, the majority of the 33 respondents in @gregory2002effects\'s evaluation indicated either a decrease or complete elimination of violence in their relationships, while a third of the partners reported that the intervention program in fact became a new source of conflict in their relationship, and 19% reported abuse during or following the offenders' program completion.
A particularly notable descriptive finding from @gregory2002effects\'s investigation is that, on average, over seven years lapsed between the first occurrence of IPV in the relationships accounted for by the study's survivor respondents and the IPV incident resulting in the perpetrators' referrals to the intervention program. Although not explicitly connected in the study's findings report nor discussion, this finding may inform survivor respondents' apparent consensus that jail time should be an immediate and/or unconditional sanction imposed against individuals found guilty and/or under investigation for IPV perpetration. Further, an average time-lapse of this magnitude indicates a potentially critical flaw in the implantation of any form of a coordinated community response to IPV [@hart1995coordinated].
@gregory2002effects\'s evaluation is restricted to female survivors' accounts of male IPV perpetrators court-mandated, either as part of post-sentencing probationary requirements or deferred-sentencing conditions, to complete the intervention, and therefore does not include accounts of the intervention programs' participants who are not referred to the program by the courts. @gregory2002effects\'s sample further excludes accounts of same-gender IPV perpetration and/or victimization, as well as IPV perpetrated by female-identified individuals toward male-identified partners. This sampling frame is similar to that defined in @gondolf1999comparison\'s investigation (summarized above) both in terms of the specific included and excluded populations, as well as the fact that the sampling restrictions in both studies are, at least to some degree, a function of the populations served by the study sites themselves. That is, at the time the studies were conducted, the intervention programs evaluated in both investigations provided IPV perpetrator intervention services only to male-identified individuals who perpetrated IPV toward female-identified partners.
<file_sep>/sourceCode.Rmd
---
title: "Source Code used for Systematic Literature Review & Analyses<br /><figure class=\"title\"><img src=\"Rlogo.png\" height=\"20%\" width=\"20%\" /></figure>"
---
<blockquote style="text-align: right;">"People who love statistics are damned to hell for all eternity, people who like R even more so."</blockquote>
<blockquote style="text-align: right;">`r tufte::quote_footer("A. Field, Miles, & Field (2012), p. xxv")`</blockquote>
<hr class="Bold" />
# `R` Code
```{r echo=FALSE, results='asis'}
p_r <- list.files(path = ".", pattern = ".*?\\.R$")
rsrcDocs <- paste0("[", p_r, "](", p_r, ")")
pander::pander(as.list(rsrcDocs))
```
# `SQL` Queries
```{r echo=FALSE, results='asis'}
p_sql <- list.files(path = "data/sql/RQDA-MAP-SQL/", pattern = ".*?\\.sql$")
sqlsrcDocs <- paste0("[", p_sql, "](data/sql/", p_sql, ")")
pander::pander(as.list(sqlsrcDocs))
```
# Data Files Generated from/for `R` code, `RQDA`, & `SQL` queries
```{r echo=FALSE, results='asis'}
p_dat <- list.files(path = "data/", pattern = ".*?\\.csv$")
datsrcDocs <- paste0("[", p_dat, "](", p_dat, ")")
pander::pander(as.list(datsrcDocs))
```
<file_sep>/_comps_docs/journal/journal-challengingGenderBinary.Rmd
---
title: "Challenging the Gender Binary"
date: "2014-04-10"
---
> "Yet it is important to note that the majority of existing risk models, risk assessment instruments, and prevention and intervention strategies were primarily developed with heterosexual samples and then applied to FSSIPV. It is only recently that researchers have begun to examine the role of minority stress (e.g., internalized homophobia and discrimination) as risk factors for IPV in same-sex relationships [@balsam2005relationship]."
>
> `r tufte::quote_footer("[@hassouneh2008influence, p. 311]")`
>
> "Historically, heterosexual discourse has engendered persons as being feminine or masculine. This duality has created gender role stereotypes that many view as immutable biological categories rather than social constructions. Perper and Cornog (2000) describe this form of biological categorization:"
>
> > "Western cultural traditions have created two idealized categories, called Man and Woman, that co-align gender roles, sexual activities, and anatomy. In everyday and vivid words, Men enact masculine gender roles, have sex with women, and have big muscles, penises, and testicles. Women enact feminine gender roles, have sex with men, and have breats, vaginas, and clitorises. (p.101)."
>
> In addition to focusing on women’s anatomy and sexual behavior, traditional gender role stereotyping has portrayed women as being innately nonviolent, caretaking, and nurturing [@gilbert2002discourses; @girshick2002no; @perilla2003working]. This perception has significant implications for women who behave in ways that are incongruent with traditional gender stereotypical roles, such as women who perpetrate violence and women who have sex with women. Such women may be viewed as being unnatural, deviant, a threat to the status quo of existing gender relations in families and society.
>
> > `r tufte::quote_footer("[@hassouneh2008influence, p. 312]")`
-----
# References
<div class="refs">
<file_sep>/_comps_docs/_zmisc/alnetg_arc.R
#+ setup, echo=1, results='hide', message=FALSE, warning=FALSE, cache=FALSE, fig.keep='none', fig.show='none'
source("bibs.R")
knitr::opts_chunk$set(
echo = TRUE,
tidy = FALSE,
fig.height = 7,
fig.fullwidth = TRUE,
out.width = '1.05\\linewidth'
)
# options(width = 80)
#'
elvl <- c("(L1) Individual", "(L2) Relationship", "(L3) Community", "(L4) Societal")
eLVL <- c("L1", "L2", "L3", "L4")
alrec <- paste0("'", alfrq$lvl[1:4], "' = '", elvl, "'", collapse = "; ") ## "alfrq" is from "bibs.R" ##
alrec1 <- paste0("'", elvl, "' = '", eLVL, "'", collapse = "; ")
aln <- alnet[, 1:2] ## "alnet" is from "bibs.R" ##
aln[, 2] <- car::recode(aln[, 2], alrec)
aln[, 1] <- car::recode(aln[, 1], rec.code2cid) ## "rec.code2cid" is from "bibs.R ##
al <- within(alfrq, {
lvl <- car::recode(lvl, alrec)
lvl <- car::recode(lvl, rec.code2cid)
})
# aledges ----------------------------------------------------------------
aledges0 <- graph_from_data_frame(aln, directed = FALSE, vertices = al)
aledges <- get.edgelist(aledges0)
alnetcol <- mpal(alfrq, p = sci, a = 0.5)[-1:-4]
avbrdrs <- c(vclrs[1:4], alnetcol) ## "vclrs" is from "bibs.R" ##
avclrs <-
c(adjustcolor(vclrs[1:4], alpha.f = 0.35),
adjustcolor(alnetcol, alpha.f = 0.25))
adeg <- degree(aledges0)*.25
alstrength <- strength(aledges0)
allabs0 <- car::recode(al[, 1], rec.cid2clab)
allabs <- paste0(al[, 1], " = ", allabs0)
allabs1 <- paste0("**", al[-1:-4, 1], "**", " = _", allabs0[-1:-4], "_", collapse = ", ")
allabs.p <- gsub(" & ", " \\\\& ", allabs)
# alcap0 <- paste0("\\textit{", allabs.p[-1:-4], "}", collapse = ", ")
# alcap0 <- paste0("\\textbf{", allabs.p[-1:-4], "}", collapse = ", ")
# ARCPLOT - Analytic Approaches (`alnetg_arc`) -------------------------------------------------
#'
#'
#+ alnetg_arc, fig.show='asis', fig.cap="Network Diagram Showing Relations among Analytic Approaches (numbered graph nodes) used and Ecological Levels of Analysis (named graph nodes) Invovled among the Reviewed Literature"
arcplot(
aledges,
vertices = al[, 1],
col.arcs = hsv(0, 0, 0.1, 0.15),
pch.nodes = 21,
bg.nodes = avclrs,
col.nodes = avbrdrs,
lwd.nodes = 0,
cex.nodes = log(adeg)+1*1.25,
lwd.arcs = alstrength-3, #adeg,
line = 0,
cex.labels = 0.85,
font = 1,
col.labels = pal_my[20],
horizontal = T,
sorted = FALSE,
# ordering = allabs,
family = "serif"
)
#':
#'
#' `r allabs1`
#'
#' \newpage
#'
#'
arcplot(
aledges,
vertices = al[, 1],
col.arcs = hsv(0, 0, 0.1, 0.15),
pch.nodes = 21,
bg.nodes = avclrs,
col.nodes = avbrdrs,
lwd.nodes = 0,
cex.nodes = log(adeg)+1*1.25,
lwd.arcs = adeg, #adeg,
line = 0,
cex.labels = 0.85,
font = 1,
col.labels = pal_my[20],
horizontal = T,
sorted = FALSE,
# ordering = allabs,
family = "serif"
)
#'
#' \newpage
#'
#' # The data "under the hood" of that arc diagram
#'
#' `r tufte::newthought("Potentially useful for later/someday")` (primarily in terms of `R-programming`, not so much with regards to the actual current analysis)
#'
#+ alarc_df, fig.keep=c(2, 4, 8), fig.show=c(2, 4, 8), fig.height=7
#
# xy.alarc <- xynodes(length(allabs), order(allabs), allabs)
# locs.alarc <-
# arc_radius_locs(aledges, al[, 1], xy.alarc) %>% data.frame()
# locs.alarc$edgeID <- rownames(locs.alarc) %>% as.integer()
#
# alarc.df1 <- aledges %>% data.frame()
# names(alarc.df1) <- c("ecoLvls", "analysis")
# alarc.df1$edgeID <- rownames(alarc.df1) %>% as.integer()
#
# alarc.df <- merge(alarc.df1, locs.alarc)
# avclrs2 <- c(vclrs, mpal(alfrq, p = sci)[-1:-4])
# cor(alarc.df[, "locs"], alarc.df[, "radios"])
# # plot(alarc.df[, "locs"], alarc.df[, "radios"], type='l', col = avclrs2)
#
# adeg2 <- ifelse(adeg > 1, log1p(adeg)/1.75, log1p(adeg))
#
# plot(alarc.df[, "radios"], alarc.df[, "locs"], type = 'n', ##p1
# xaxt = 'n', yaxt = 'n')
#
# points(alarc.df[, "radios"], alarc.df[, "locs"], type = 'p', ## p2 - KEEP
# pch = 19, col = adjustcolor(avclrs2, alpha.f = 0.75))
#
# plot(alarc.df[, "radios"], alarc.df[, "locs"], type = 'n', ## p3
# xaxt = 'n', yaxt = 'n')
#
# lines(alarc.df[, "radios"], alarc.df[, "locs"], ## p4 - KEEP
# col = pal_my[19])
#
# plot(alarc.df[, "radios"], alarc.df[, "locs"], type = 'n', ## p5
# xaxt = 'n', yaxt = 'n')
#
# points(alarc.df[, "radios"], alarc.df[, "locs"], type = 'p', ## p6
# pch = 19, col = adjustcolor(avclrs2, alpha.f = 0.75))
#
# lines(alarc.df[, "radios"], alarc.df[, "locs"], type = 'h', ## p7
# lwd = 3, col = adjustcolor(avclrs2, alpha.f = 0.27))
#
# text(alarc.df[, "radios"], alarc.df[, "locs"], al[, 1], ## p8 - KEEP
# cex = adeg2) #, srt = 41)
# text(jitter(alarc.df[, "radios"]), alarc.df[, "locs"] + c(0.005, -0.007),
# allabs2, ## p8 - KEEP
# cex = adeg2) #, srt = 41)
<file_sep>/netwrk-topics.R
source("QCA.R")
cbt <- cb[cb$cat == "TOPIC",
c("bibkey", "scat", "cat", "code", "clab")] %>% droplevels()
cbt <- cbt[!duplicated(cbt), ]
tlabs <- paste0(seq(1:length(levels(cbt$clab))), " = ", levels(cbt$clab))
lt <- mplvls[, 1:4]
lt$id <- rownames(lt)
lcbt <- merge(lt, cbt, by.x = "id", by.y = "bibkey", all = FALSE)
lcbt.t <- lcbt[, c("code", "l1", "l2", "l3", "l4")] %>% dplyr::rename("id" = code)
lcbt.t.nd <- lcbt.t[!duplicated(lcbt.t), ]
tlnet1 <- lcbt.t[, 1:2] %>% Rtdf(names = c(names(lcbt.t[,1:2]), "Freq"))
tlnet1$l1 <- as.numeric(tlnet1$l1)
tlnet1$l1 <- ifelse(tlnet1$l1 == 1, NA, "l1")
tlnet1$Freq <- ifelse(tlnet1$Freq == 0, NA, tlnet1$Freq)
tlnet1 <- na.omit(tlnet1)
# tlnet1 <- tlnet1[!duplicated(tlnet1$id), ]
names(tlnet1) <- c("from", "to", "Freq")
tlnet2 <- lcbt.t[, c(1, 3)] %>% Rtdf(names = c(names(lcbt.t[, c(1, 3)]), "Freq"))
tlnet2$l2 <- as.numeric(tlnet2$l2)
tlnet2$l2 <- ifelse(tlnet2$l2 == 1, NA, "l2")
tlnet2$Freq <- ifelse(tlnet2$Freq == 0, NA, tlnet2$Freq)
tlnet2 <- na.omit(tlnet2)
names(tlnet2) <- c("from", "to", "Freq")
tlnet3 <- lcbt.t[, c(1, 4)] %>% Rtdf(names = c(names(lcbt.t[,c(1, 4)]), "Freq"))
tlnet3$l3 <- as.numeric(tlnet3$l3)
tlnet3$l3 <- ifelse(tlnet3$l3 == 1, NA, "l3")
tlnet3$Freq <- ifelse(tlnet3$Freq == 0, NA, tlnet3$Freq)
tlnet3 <- na.omit(tlnet3)
names(tlnet3) <- c("from", "to", "Freq")
tlnet4 <- lcbt.t[, c(1, 5)] %>% Rtdf(names = c(names(lcbt.t[,c(1, 5)]), "Freq"))
tlnet4$l4 <- as.numeric(tlnet4$l4)
tlnet4$l4 <- ifelse(tlnet4$l4 == 1, NA, "l4")
tlnet4$Freq <- ifelse(tlnet4$Freq == 0, NA, tlnet4$Freq)
tlnet4 <- na.omit(tlnet4)
names(tlnet4) <- c("from", "to", "Freq")
tlnet0 <- rbind(tlnet1, tlnet2, tlnet3, tlnet4)
tlnet0$clab <- recode(tlnet0$from, rec.code2clab) ## "rec.code2clab" is from "MAPrqda.R"
# tlnet <- tlnet0[!duplicated(tlnet0), c("from", "to", "clab", "Freq")]
#+ tlnet_llabs
library(car)
llabs <- c("'l1' = '.Individual'; 'l2' = '.Relationship'; 'l3' = '.Community'; 'l4' = '.Societal'")
tlnet$to <- car::recode(tlnet$to, llabs)
#+ tlfrq
# tlfrq ----------------
tlfrq1 <- tlnet[, 1] %>% as.character()
tlfrq2 <- tlnet[, 2]
tlfrq3 <- c(tlfrq1, tlfrq2)
tlfrq <- Rtdf(tlfrq3, names = c("lvl", "Freq"))
tv1 <- tlnet[, 3] %>% as.character()
tv2 <- tlnet[, 2]
tv3 <- c(tv1, tv2)
tv <- Rtdf(tv3, names = c("id", "Freq"))
tv[, 1] <- as.character(tv[, 1])
# `tlnetg` ----------------
library(igraph)
tlnetg <- graph_from_data_frame(tlnet[, 1:2], directed = FALSE, vertices = tlfrq)
V(tlnetg)$size <- V(tlnetg)$Freq*3
tlnetcol <- mpal(tlfrq, a = 0.8)[-1:-4] %>% adjustcolor(alpha.f = 0.5)
tvclrs <- c(adjustcolor(vclrs[1:4], alpha.f = 0.65), tlnetcol)
V(tlnetg)$color <- tvclrs
# E(tlnetg)$width <- 0.25
E(tlnetg)$frq <- tlnet$Freq
E(tlnetg)$width <- log(tlnet$Freq) + 1
# V(tlnetg)$name[-1:-4] <- seq(1:length(tv[-1:-4, 1]))
V(tlnetg)$name[1:4] <- gsub("\\.", "", V(tlnetg)$name[1:4])
tindex.g <- V(tlnetg)$name %>% length()
tlblsize <- c(log(V(tlnetg)$size[1:4])*0.125, log(V(tlnetg)$size[5:tindex.g])*0.325)
#'
#'
#+ echo=FALSE
# panderOptions("p.wrap", "")
# tlabs <- gsub("\\n", "", tlabs)
tlabs <- gsub("&", "\\\\&", tlabs)
# tlabs1 <- paste0(tlabs[1:length(tlabs)-1], sep = ", ")
# deparse(tlabs1)
tlabs <- paste(tlabs, collapse = ", ")
tlnetg_cap <- paste0("Network Diagram Showing Relations among Substantive Research Topics (numbered graph nodes) Covered & Ecological Levels of Analysis (named graph nodes) Involved among the Reviewed Literature: \\textit{", tlabs, "}")
# PLOTS - `tlnetg` (layout-0 & layout-2) ----------------
#'
#+ arc_tlnetg, out.height='4in', fig.cap=tlnetg_cap
par(mar = rep(0, 4))
ltl <- layout_with_fr(tlnetg) %>% norm_coords()
plot(tlnetg, rescale = T, layout = ltl, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = c(vclrs[1:4], rep(NA, length(tlnetcol))), vertex.label.cex = tlblsize)
l1tpsum <- tlnet[tlnet$to == "l1", "Freq"] %>% sum()
l2tpsum <- tlnet[tlnet$to == "l2", "Freq"] %>% sum()
l3tpsum <- tlnet[tlnet$to == "l3", "Freq"] %>% sum()
l4tpsum <- tlnet[tlnet$to == "l4", "Freq"] %>% sum()
l1tpWgtMu <- l1tpsum / length(unique(tlnet$from))
l2tpWgtMu <- l2tpsum / length(unique(tlnet$from))
l3tpWgtMu <- l3tpsum / length(unique(tlnet$from))
l4tpWgtMu <- l4tpsum / length(unique(tlnet$from))
l1tpRawMu <- tlnet[tlnet$to == "l1", "Freq"] %>% mean()
l2tpRawMu <- tlnet[tlnet$to == "l2", "Freq"] %>% mean()
l3tpRawMu <- tlnet[tlnet$to == "l3", "Freq"] %>% mean()
l4tpRawMu <- tlnet[tlnet$to == "l4", "Freq"] %>% mean()
tpMuAll <- mean(tlnet$Freq)
l1tpRawMu/tpMuAll
l1tpWgtMu/tpMuAll
l2tpRawMu/tpMuAll
l2tpWgtMu/tpMuAll
<file_sep>/_comps_docs/_zmisc/zDEPRECATED-MAPtl.R
# SOLUTION ----------------------------------------------------------------
## FINALLY FOUND ON SO: http://stackoverflow.com/a/19998876/5944560
x <- MAPtl$year
sequence(rle(x)$lengths)
# OTHER ATTEMPTS ----------------------------------------------------------
# MAPtl$pos2 <- ifelse(duplicated(MAPtl$year), jitter(MAPtl$pos2, factor = 2.5), MAPtl$pos2)
# MAPtl <- MAPtl[order(MAPtl$year), , drop = FALSE]# %>% data.frame()
# x <- MAPtl$year
# xtbl <- Rtdf(x, names = c("year", "yrcnt"))
# x[duplicated(x)]
# MAPtl2 <- merge(MAPtl, xtbl, by = "year", all = TRUE)
# MAPtl2$yrcnt <- ifelse(MAPtl2$yrcnt > 1, MAPtl2$yrcnt + 1, MAPtl2$yrcnt)
# yrdup <- duplicated(x)
# yrdupsum <- yrdup %>% sum()
# xd <- x[yrdup]
# y <- vector(mode = mode(x), length = length(x))
# repeat{
# for (i in 2:length(x)) {
# if (x[i] != x[i - 1]) {
# y[i] <- x[i]
# } else {
# if (x[i] == x[i - 1]) {
# y[i] <- x[i - 1] + 1
# } #else {
# # if (sum(duplicated(x) == 0)) {
# # break
# }
# }
# # }
# # }
# # }
#
# for (i in 2:length(x)) {
# repeat {
# if(x[i] == x[i-1]) {y[i] <- x[i-1] + 1
# } else {
#
# if (sum(duplicated(x) == 0)) break
# }
# }
# }
# # if(x[i] != x[i - 1]) next
# # }
# #; if (x[i] != x[i - 1]) break}
# # }
#
# # ifelse(x[14] == lag(x, 1)[14-1], x[14] + 1, x[i])
#
# MAPtl$y <- group_by(MAPtl, year) %>% tally()
# yc <- count
# if (x[i] == x[i-1]) {
# y[i] <- y[i-1] + 1
# }
# y[i] <- ifelse(
# MAPtl$pos <- sample(seq(1, nrow(MAPtl), by = 1), size = nrow(MAPtl), replace = FALSE)
# posmu <- mean(MAPtl$pos)
# MAPtl$pos <- ifelse(MAPtl$cpv == "Violence", MAPtl$pos*-1, MAPtl$pos)
# MAPtl$pos <- ifelse(MAPtl$cpv == "Violence" & MAPtl$pos > posmu, MAPtl$pos-posmu, MAPtl$pos)
MAPtl$pos2 <- ifelse(MAPtl$cpv == "Violence", MAPtl$pos1*-1, MAPtl$pos1)
# pos2mu <- mean(MAPtl$pos2)
<file_sep>/auxDocs/Rtwee.R
#' # Generating a plain-text directory map
#'
#' Below is a minimally-modified version of [@jennybc's](https://gist.github.com/jennybc) ["twee()" function](https://gist.github.com/jennybc/2bf1dbe6eb1f261dfe60). Specific modifications are commented inline, but in short, the only difference between "`twee2()`" (below) and the original "`twee()`" (further below and available [@jennybc's original gist](https://gist.github.com/jennybc/2bf1dbe6eb1f261dfe60)) is the added option to write the output to either or both the "`R-console`" (or save as an object) or a specified "`file`".
#'
#' The added output args/options were motivated by my attempts to make my own project management workflow more efficient. Specifically, I typically include a directory map in the README's I create in any shared project directories for which I am the primary administrator, and this made the whole process of constructing README's SO much easier.
#'
#+ modTwee
twee2 <- function(dir = getwd(), level = Inf, f = NULL, quiet = FALSE) {
## ^changed "path" arg to "dir" to avoid confusion (mostly as part of my own workflow)^ ##
## ^added "file = """ to args list for use in later "cat(...)" line^ ##
fad <-
list.files(path = dir, recursive = TRUE, no.. = TRUE, include.dirs = TRUE)
fad_split_up <- strsplit(fad, "/")
too_deep <- lapply(fad_split_up, length) > level
fad_split_up[too_deep] <- NULL
jfun <- function(x) {
n <- length(x)
if(n > 1)
x[n - 1] <- "|__"
if(n > 2)
x[1:(n - 2)] <- " "
x <- if(n == 1) c("-- ", x) else c(" ", x)
x
}
fad_subbed_out <- lapply(fad_split_up, jfun)
y <- unlist(lapply(fad_subbed_out, paste, collapse = "")) ## saved main output to a new object ##
if (!is.null(f)) { ## added conditional step to write output to a specified file ("f") ##
cat(y, sep = "\n", file = f)
}
if (!quiet) { ## added option to return the output quietly (i.e., if writing to a file and not wanting the output to also print to the console) ##
return(y) ## return output/print to console only if "quiet == FALSE" ##
}
}
#'
#' ## Example usage
#'
#+ twee2_example
twee2()
twee2(f = "dirMap.txt")
twee2(f = "dirMap.txt", quiet = TRUE)
dirmap <- twee2()
dirmap
dirmap <- twee2(f = "dirMap.txt")
dirmap
dirmap <- twee2(f = "dirMap.txt", quiet = TRUE)
dirmap ## yields NULL, but output still written to file ##
readLines("dirMap.txt")
#'
#' -----
#'
#' # Original `FUN` Description:
> "quick-and-dirty ersatz Unix tree command in R inspired by this one-liner: `ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'` found here (among many other places): http://serverfault.com/questions/143954/how-to-generate-an-ascii-representation-of-a-unix-file-hierarchy"
#' ## Original `FUN`:
#'
#+ origTwee
# twee <- function(path = getwd(), level = Inf) {
#
# fad <-
# list.files(path = path, recursive = TRUE,no.. = TRUE, include.dirs = TRUE)
#
# fad_split_up <- strsplit(fad, "/")
#
# too_deep <- lapply(fad_split_up, length) > level
# fad_split_up[too_deep] <- NULL
#
# jfun <- function(x) {
# n <- length(x)
# if(n > 1)
# x[n - 1] <- "|__"
# if(n > 2)
# x[1:(n - 2)] <- " "
# x <- if(n == 1) c("-- ", x) else c(" ", x)
# x
# }
# fad_subbed_out <- lapply(fad_split_up, jfun)
#
# cat(unlist(lapply(fad_subbed_out, paste, collapse = "")), sep = "\n")
# }
#'<file_sep>/_comps_docs/_zmisc/zDEPRECATED.R
# DEPRECATED - litSummaries.R ---------------------------------------------------------
# print("## Location(s)\n\n"); pander(sf.locations); print("\n\n")
# print("## Level-1 Frame:\n\n"); print(L1.sf); print("\n\n")
#
# print("## Level-2 Frame:\n\n"); print(L2.sf); print("\n\n")
#
# print("## Level-3 Frame:\n\n"); print(L3.sf); print("\n\n")
# print("## Level-2 Frame Includes:\n\n"); print(L2.sf.incl); print("\n\n")
# print("## Level-2 Frame Excludes:\n\n"); print(L2.sf.excl); print("\n\n")
# print("## Level-3 Frame Includes:\n\n"); print(L3.sf.incl); print("\n\n")
# print("## Level-3 Frame Excludes:\n\n"); print(L3.sf.excl); print("\n\n")
#'
# L1.criteria <- c("Complies with state BIP standards", "collaborates with victim services", "empoloys cognitive-behavioral approach according to evidence-based standards", "40-50+ referrals per month", "operating for 5+ years", "provide training and supervision to new programs")
# L1.scriteria2 <- c("", "Range of Intervention System Components")
# L1.sm <- list("L1-Sampling Methods" = L1.smethods,
# # "L1-Program Criteria" = L1.criteria,
# "L1-Intervention Components Continuum" = L1.scontinuum) %>% stack()
#
# L2.scriteria <- c("First 20-25 men appearing for intake each month at each of the four research sites")
# L2.sm <- list("L2-Sampling Methods" = L2.smethods)
# # "L2-Participant Criteria" = L2.scriteria) %>% stack()
# L3.scriteria <- c("L3-sampling probability depends on L2 participants")
# L3.sm <- list("L3-Sampling Methods" = L3.smethods)
# # "L3-Participant Criteria" = L3.scriteria) %>% stack()
# methods.w <- reshape(methods, v.names = c("value"), idvar = c("L"), timevar = "V", direction = "wide")
# methods.ww <- reshape(methods.w, v.names = c("value.L1", "value.L2", "value.L3"), idvar = "id", timevar = "V", direction = "wide")
# methods <- cbind(id = seq(1:nrow(methods)), methods[, c(2, 1)])
# vars <- gsub("L\\d\\-(\\w+)", "\\1", vars, perl = TRUE)
# vars <- gsub("[ ]+", ".", vars, perl = TRUE)
#
# slvls <- methods$var
# slvls <- gsub("[ ]+", "", slvls, perl = TRUE)
# slvls <- gsub("-\\w+", "", slvls, perl = TRUE)
#
# methods$V <- vars
# methods$L <- slvls
# kable(sf[, c(2, 1)], align = c("r", "l"), col.names = c(names(sf)[1], "S[note]") %>% add_footnote("'S' = Sub-Samples", threeparttable = TRUE)
# kable(sf.incl[, c(2, 1)], align = c("r", "l"), format = 'latex', booktabs = TRUE, escape = FALSE, caption = "Populations Included in Sampling Frame") %>% kable_styling(full_width = TRUE, latex_options = c("scale_down"))
# kable(sf.excl[, c(2, 1)], align = c("r", "l"), format = 'latex', booktabs = TRUE, escape = FALSE, caption = "Populations Excluded from Sampling Frame") %>% kable_styling(full_width = TRUE, latex_options = c("scale_down"))
# kable(sf[sf$S == samples[2], c(2, 1)], align = c("r", "l"), caption = paste0("'", samples[2], "' Sub-Sample Definition"))
#
# kable(sf[sf$S == samples[3], c(2, 1)], align = c("r", "l"), caption = paste0("'", samples[3], "' Sub-Sample Definition"))
#
# ### LOOP - sf[2:3, ] kables (no footnotes) ####
# for (i in 1:length(samples[-1])) {
# print(kable(sf[sf$S == samples[-1][i], c(2, 1)], align = c("r", "l"), caption = paste0("'", samples[-1][i], "' Sub-Sample Definition")))
# }
#' `r tufte::newthought("States:")`
#'
#' `r unique(sf.locations[sf.locations$ind == "State", "values"]) %>% pander()`
#'
#' `r tufte::newthought("Counties:")`
#'
#' `r sf.locations[sf.locations$ind == "County", "values"] %>% pander()`
#'
#' `r tufte::newthought("Cities:")`
#'
#' `r sf.locations[sf.locations$ind == "City", "values"] %>% pander()`
#'
#'
# for (i in 1:length(samples)) {
# print(
# kable(sf.incl[sf.incl$S == samples[i], c(2, 1)], align = c("r", "l"),
# caption = paste0("Populations \\textit{Included} in '\\textbf{",
# samples[i], "}' Sub-Sample"),
# format = 'latex', booktabs = TRUE, escape = FALSE, row.names = FALSE) %>%
# kable_styling(full_width = TRUE, latex_options = c("scale_down"))
# )
# }
# DEPRECATED - gondolf-crosstab.R ------------------------------------
# ra.PB <- c(rep(1, reassault[1]), rep(0, noReassault[1]))
# ra.DL <- c(rep(1, reassault[2]), rep(0, noReassault[2]))
# ra.HT <- c(rep(1, reassault[3]), rep(1, noReassault[3]))
# ra.DV <- c(rep(1, reassault[4]), rep(1, noReassault[4]))
# n <- list(PT = 180, Dallas = 144, Houston = 160, Denver = 174)
# f <- function(x) {n - x}
# reassault <- list(PB = 63, DL = 52, HT = 48, DV = 47)
# noReassault <- lapply(reassault, f)
# severe <- list(PB = 41, DL = 38, HT = 33, DV = 21)
# noSevere <- n - severe
# repeated <- list(PB = 43, DL = 34, HT = 25, DV = 19)
# noRepeated <- n - repeated
# injury<- list(PB = 35, DL = 37, HT = 33, DV = 23)
# noInjury <- n - injury
# controlling <- list(PB = 78, DL = 67, HT = 75, DV = 79)
# noControlling <- n - controlling
# verbal <- list(PB = 140, DL = 101, HT = 102, DV = 117)
# noVerbal <- n - verbal
# threats <- list(PB = 81, DL = 60, HT = 72, DV = 70)
# noThreats <- n - threats
# ra.PB <- c(ra.PB, rep(NA, maxN - length(ra.PB)))
# frq.s3 <- seq(0, max(hist(cpv.s3$year, plot = FALSE)$counts), by = 2)
# frq.s3 <- frq.s3[-length(frq.s3)]
# hist(MAP$year[MAP$scat == "S3"], col = pal_my.a75[16], border = pal_my[19],
# main = "IPV Interventions Research", xlab = " ", ylab = expression(N[Articles]),
# lwd = .5, right = F)#, breaks = seq(1990, 2018, by = 4));
# lines(density(cpv.s3$year), lwd = 2, col = pal_my[19], lty = 3);
# axis(side = 2, at = axTicks(side = 2), labels = frq.s3);
# frq.s4 <- seq(0,max(hist(cpv.s4$year, plot = FALSE)$counts),by = 6)
# hist(MAP$year[MAP$scat == "S4"], col = pal_my.a75[12], border = pal_my[19],
# main = "LGBTQ-Specific IPV Research", xlab = " ", ylab = " ",
# lwd = .5, right = F)
# lines(density(cpv.s4$year), lwd = 2, col = pal_my[19], lty = 3);
# axis(side = 2, at = c(0, .02, .04, .06, .8), labels = frq.s4)
#+ yr_hist1, echo=FALSE, fig.fullwidth=TRUE, fig.width=7, fig.height=5
# publication years ============================================================
### PLOT - year ####
# par(cex = 0.9)
# frq <- seq(0, max(hist(MAP$year, plot = FALSE)$counts), by = 5)[1:4]
# hist(MAP$year, freq = FALSE, col = pal_my.a75[17], border = pal_my[18],
# main = " ", xlab = "Year Published", ylab = expression(N[Articles]),
# lwd = .5, yaxt = 'n', right = T, breaks = seq(1990, 2018, by = 4));
# lines(density(MAP$year), lwd = 2, col = pal_my[18], lty = 3);
# axis(side = 2, at = axTicks(side = 2), labels = frq)
# LitMap.R -----------------------------------------------------------
# states2 <- merge(states, bibState, by.x = "id", by.y = "state", all = TRUE)
# states2.t <- Rtdf(states2$id)
# bibSt$Freq <- sapply(bibSt$Freq, Rna)
# scale_colour_gradientn(colours = grad(frq.st, p = grays2),
# na.value = pal_my[20], guide = FALSE)
# divngrp <- list()
# for (i in 1:nrow(divn)) {divngrp <- paste0(divn[i, 1], ".", seq(1:divn[i, 2]))}
# bibs.R -------------------------------------------------------------
# DEPRECATED ---------------------------------------------------------
# yr <- cbind(density(MAP$year)$x, density(MAP$year)$y*350)
# hist(MAP$year, col = pal_my.a50[17], border = pal_my[18], main = " ", xlab = "Year Published", lwd = .5); lines(yr, lwd = 2, col = pal_my[18], lty = 3)
# hist(cpv.s3$year, col = pal_my.a50[16], border = pal_my[18], lwd = .5, main = "IPV Interventions Research", xlab = "Year Published"); lines(yr.s3, lwd = 2, col = pal_my[18], lty = 3)
# hist(cpv.s4$year, col = pal_my.a50[16], border = pal_my[18], main = "LGBTQ-Specific IPV Research", xlab = "Year Published", lwd = .5); lines(yr.s4, lwd = 2, col = pal_my[18], lty = 3)
# wt$n <- Rdich(wt$n, min = 1)
# table(ct.mo$code[21 | 20 | 17 | 14 | 5])
# scale_x_discrete(breaks = c("code", "scat"),
# labels = c("Primary Topics", "Category")) +
# wt <- group_by(ct.top, case) %>% dplyr::count()
# names(wt) <- c("scat", "wt")
# wt2 <- group_by(ct.top, scat) %>% dplyr::count()
# names(wt2) <- c("scat", "wt2")
# ct.top <- merge(ct.top, wt, by = "case")
# ct.top <- merge(ct.top, wt2, by = "scat")
# library(kableExtra)
# kable(yrt, align = rep('c', ncol(yrt)),
# caption = "Summary of Number of Articles Published Per Year",
# format = 'latex', booktabs = TRUE, escape = FALSE) %>%
# kable_styling(full_width = TRUE)
#
#
# kable(yrt.s3, align = rep('c', ncol(yrt)), caption = "Summary Statistics for Amount of IPV Interventions Research Articles Published Each Year", format = 'latex', booktabs = TRUE) %>%
# kable_styling(position = "float_left")
# kable(yrt.s4, align = rep('c', ncol(yrt)), caption = "Summary Statistics for Amount of LGBTQ-Specific IPV Research Articles Published Each Year", format = 'latex', booktabs = TRUE) %>%
# kable_styling(position = "float_right")
# t.top <- Rtdf(ctbl.m[ctbl.m$cat == "TOPIC", "code"] %>%
# droplevels(),
# names = c("Topic", "$N_{Articles}$"))
# ftm.top <- ftable(ctbl.m[ctbl.m$cat == "TOPIC",
# c("code", "scat")] %>%
# droplevels(),
# row.vars = 1) %>%
# matrix(nrow = nrow(t.top),
# byrow = FALSE)
# dimnames(ftm.top) <-
# list(Topic = levels(ctbl.m[ctbl.m$cat == "TOPIC", "code"] %>% droplevels()),
# c("IPV Interventions", "LGBTQ-IPV Research"))
# ftm.top <- ifelse(ftm.top == 0, NA, ftm.top)
#
# t.top
# t.s3bibkey <- Rtdf(cpv.s3$bibkey)
# ft.s3jrnl <- with(cpv.s3, {
# ftable(bibkey, jrnl) %>%
# matrix(nrow = nrow(t.s3bibkey),
# byrow = FALSE)
# })
# dimnames(ft.s3jrnl) <- list("Case" = levels(cpv.s3$bibkey), "Publication Title" = levels(cpv.s3$jrnl))
# ft.s3jrnl <- ifelse(ft.s3jrnl == 0, NA, ft.s3jrnl)
# ft.s3jrnl %>% pander(caption = "Publication Title per Case")
# t.s4bibkey <- Rtdf(cpv.s4$bibkey)
# ft.s4jrnl <- with(cpv.s4, {
# ftable(bibkey, jrnl) %>%
# matrix(nrow = nrow(t.s4bibkey),
# byrow = FALSE)
# })
# dimnames(ft.s4jrnl) <- list("Case" = levels(cpv.s4$bibkey), "Publication Title" = levels(cpv.s4$jrnl))
# ft.s4jrnl
# yr <- Rmsmm(MAP$year) %>% t() %>% as.data.frame()
#
# yrt <- Rtdf(MAP$year)[, 2] %>% Rmsmm() %>% t() %>% as.data.frame()
# yrt[, c(1, 3:4)] <- apply(yrt[, c(1, 3:4)], 2, round, digits = 0)
# yrt$M <- paste0(yrt$M, " (\\textit{", yrt$SD, "})")
# yrt <- yrt[c(1, 3:4)]
# names(yrt) <- c("Mean (\\textit{SD})", "Minimum", "Maximum")
# #'
# #+ yrt, echo=FALSE
# yrt.s3 <- Rtdf(cpv.s3$year)[, 2] %>% Rmsmm() %>% t() %>% as.data.frame()
# yrt.s3[, c(1, 3:4)] <- apply(yrt.s3[, c(1, 3:4)], 2, round, digits = 0)
# yrt.s3$M <- paste0(yrt.s3$M, " (\\textit{", yrt.s3$SD, "})")
# yrt.s3 <- yrt.s3[c(1, 3:4)]
# names(yrt.s3) <- c("Mean (\\textit{SD})", "Minimum", "Maximum")
#
# yrt.s4 <- Rtdf(cpv.s4$year)[, 2] %>% Rmsmm() %>% t() %>% as.data.frame()
# yrt.s4[, c(1, 3:4)] <- apply(yrt.s4[, c(1, 3:4)], 2, round, digits = 0)
# yrt.s4$M <- paste0(yrt.s4$M, " (\\textit{", yrt.s4$SD, "})")
# yrt.s4 <- yrt.s4[c(1, 3:4)]
# names(yrt.s4) <- c("Mean (\\textit{SD})", "Minimum", "Maximum")
#'
### PLOT - populations - 3 ####
# cutoff <- group_by(ct.pop, code) %>% dplyr::count()
# names(cutoff) <- c("code", "cutoff.score")
# ct.pop <- merge(ct.pop, cutoff, by = "code")
# ct.pop <- ct.pop[ct.pop$cutoff.score > 1, ]
# cutoff2 <- with(ct.pop, {ftable(code, scat)}) %>% data.frame()
# names(cutoff2)[3] <- "co2.freq"
# ct.pop <- merge(ct.pop, cutoff2, by = c("code", "scat"))
# ct.pop <- ct.pop[ct.pop$cutoff.score > 1, ]
# ct.pop <- ct.pop[ct.pop$co2.freq > 2, ]
# ct.pop$code <- droplevels(ct.pop$code)
# nlabs <- length(unique(ct.pop$code))
# ppop <- mpal(1:(length(unique(ct.pop$code))), p = sci)
# pscat <- pal_my[c(2, 17)]
# ct.pop <- rename(ct.pop, c(code = "Included Populations",
# scat = "Research Category"))
#
# pop.ps2 <- ggparset2(list("Included Populations",
# "Research Category"),
# data = ct.pop, method = "parset", label = TRUE,
# label.size = 3.5, text.angle = 0, order = c(1,-1)) +
# scale_fill_manual(values = c(adjustcolor(ppop, alpha.f = 0.55), pscat),
# guide = FALSE) +
# scale_colour_manual(values = c(ppop, pscat), guide = FALSE) +
# thm_Rtft(ticks = FALSE, ytext = FALSE)
# pop.ps2
### PLOT - mixed-methods - 1 ####
# mosaic(
# ftm.mm,
# labeling_args = list(
# gp_labels = gpar(fontsize = 7),
# gp_varnames = gpar(fontsize = 10, fontface = 2),
# pos_labels = c("center", "center"),
# just_labels = c("center", "right")
# ),
# rot_varnames = c(0, -90, 0, -90),
# rot_labels = rep(0, 4),
# alternate_labels = c(F, F),
# tl_labels = c(T, F),
# tl_varnames = c(F, T),
# highlighting = 2,
# highlighting_fill = catpal,
# margins = unit(5, "lines"),
# main = "Mixed-Methods by Research Category"
# )
### PLOT - quantitative - 1 ####
# mosaic(ftm.qt,
# labeling_args = list(gp_labels = gpar(fontsize = 7),
# gp_varnames = gpar(fontsize = 10,
# fontface = 2),
# pos_labels = c("center", "center"),
# just_labels = c("center", "right")),
# rot_varnames = c(0, -90, 0, -90), rot_labels = rep(0, 4),
# alternate_labels = c(F, F), tl_labels = c(T, F),
# tl_varnames = c(F, T), highlighting = 2,
# highlighting_fill = catpal, margins = unit(5, "lines"))
### PLOT - qualitative - 1 ####
# mosaic(ftm.ql,
# labeling_args = list(gp_labels = gpar(fontsize = 7),
# gp_varnames = gpar(fontsize = 10,
# fontface = 2),
# pos_labels = c("center", "center"),
# just_labels = c("center", "right")),
# rot_varnames = c(0, -90, 0, -90), rot_labels = rep(0, 4),
# alternate_labels = c(F, F), tl_labels = c(T, F),
# tl_varnames = c(F, T), highlighting = 2, highlighting_fill = catpal,
# margins = unit(5, "lines"))
#
# mosaic(ftm.mo,
# labeling_args = list(gp_labels = gpar(fontsize = 9),
# gp_varnames = gpar(fontsize = 11,
# fontface = 2),
# pos_labels = c("center", "center"),
# just_labels = c("center", "right"),
# rot_varnames = c(0, -90, 0, -90),
# rot_labels = rep(0, 4),
# alternate_labels = c(F, F),
# tl_labels = c(T, F),
# tl_varnames = c(F, T)),
# highlighting = 2, highlighting_fill = catpal)
# map.v <- MAP[vlc && MAP$scat == "S3", , drop = FALSE]
# map.v <- map.v[!map.v$scat == "S4", ]
# levels(map.v$journal) <- c(levels(map.v$journal),
# j.v[!j.v %in% levels(map.v$journal)])
# Ms3 <- MAP[cp | vlc, , drop = FALSE]
# Ms4 <- MAP[cp, , drop = FALSE]
# mpyr$scat <- factor(mpyr$scat) %>% as.integer()
# mpyr$scat <- sapply(mpyr$scat, Rna, v = 0)
# mpyr$scat <- ifelse(mpyr$scat == 1, -1, mpyr$scat)
# mpyr$scat <- ifelse(mpyr$scat == 2, 1, mpyr$scat)
# ggyrt + geom_freqpoly(aes(y = yrFrq), stat = "identity")
# geom_line(aes(y = yrFrq))
# ggyr <- ggplot(MAP, aes(x = year, colour = scat), alpha = 0.6) + thm_Rtft() +
# geom_freqpoly(binwidth = 2, closed = "left", size = 1) +
# scale_colour_manual(values = catpal,
# breaks = c("S3", "S4"),
# labels = c("IPV Interventions Research",
# "LGBTQ-IPV CP Research"))
# ggyr
#
# yrts3 <- Rtdf(MAP[MAP$scat == "S3", "year"], names = c("Year", "Freq"))
# yrts3$scat <- "S3"
# yrts4 <- Rtdf(MAP[MAP$scat == "S4", "year"], names = c("Year", "Freq"))
# yrts4$scat <- "S4"
# yrt2 <- rbind(yrts3, yrts4)
# yrt <- Rtdf(MAP$year, names = c("year", "Frq"))
# yrt$year <- as.character(yrt$year) %>% as.integer()
# yrtyr <- yrt$year %>% range()
# yr.seq <- data.frame(year = seq(yrtyr[1], yrtyr[2]))
# yrt <- merge(yrt, yr.seq, by = "year", all = TRUE)
# yrt$Frq <- sapply(yrt$Frq, Rna)
#
# mpyr <- merge(yrt, MAP, by = "year", all = TRUE)[, c("year", "Frq", "scat", "bibkey", "jrnl")]
#
#
#
# # catpal2 <- c(sci(20)[2], pal_my[20], sci(20)[10])
# catpal2 <- c(sci(20)[c(2, 10)])
#
# mpyr$Frq <- ifelse(mpyr$Frq == 0, NA, mpyr$Frq)
# ggyrt <- ggplot(mpyr, aes(x = year, fill = factor(scat)), na.rm = TRUE) + thm_Rtft() + scale_fill_manual(values = catpal2)
# ggyrt + geom_area(aes(y = (Frq)), alpha = 0.5, color = pal_my[20], size = 0.25)
# ggyrt + geom_ribbon(aes(ymin = 0, ymax = Frq),
# alpha = 0.5, color = pal_my[20])
#
# ggyrt +
# geom_ribbon(aes(ymin = Frq, ymax = Frq + 1), fill = pal_my[2]) +
# geom_line(aes(y = Frq)) + thm_Rtft()
# hist(MAP$year, freq = FALSE, col = pal_my.a75[17], border = pal_my[18],
# main = " ", xlab = "Year Published", ylab = expression(N[Articles]),
# lwd = .5, yaxt = 'n', right = T, breaks = seq(1990, 2018, by = 4));
# #+ wt
# scattdf <- Rtdf(MAP$scat)
# ps4 <- scattdf[2,2]/sum(scattdf[, 2])
# ps3 <- scattdf[1,2]/sum(scattdf[, 2])
# wts4 <- ps4
# wts3 <- ps4/ps3
# ctbl.m$wt <- ifelse(ctbl.m$scat == "LGBTQ-IPV Research", 1, wts3-1)
#+ populations2, fig.fullwidth=TRUE
### PLOT - populations - 2 ####
# cutoff <- group_by(ct.pop, code) %>% dplyr::count()
# names(cutoff) <- c("code", "cutoff.score")
# ct.pop <- merge(ct.pop, cutoff, by = "code")
# ct.pop <- ct.pop[ct.pop$cutoff.score > 3, ]
# nlabs <- length(unique(ct.pop$code))
# ppop <- mpal(1:(length(unique(ct.pop$code))), p = sci)
#
# ct.pop <-
# rename(ct.pop,
# c(code = "Sampling_Frame", scat = "Category"))
#
# pop.ps <- ggparset2(list("Category", "Sampling_Frame"),
# data = ct.pop,
# method = "parset", label = TRUE,
# label.size = 3.5, text.angle = 0, order = c(-1,1)) +
# scale_fill_manual(values = c(pscat, adjustcolor(ppop, alpha.f = 0.55)),
# guide = FALSE) +
# scale_colour_manual(values = c(pscat, ppop), guide = FALSE) +
# thm_Rtft(ticks = FALSE, ytext = FALSE)
# pop.ps
# cutoff <- group_by(ct.mm, code) %>% dplyr::count()
# names(cutoff) <- c("code", "cutoff.score")
# ct.mm <- merge(ct.mm, cutoff, by = "code")
# ct.mm <- ct.mm[ct.mm$cutoff.score > 1, ]
# ### PLOT - topic - 2 ####
# library(ggparallel)
# ct.tp <- ctbl.m[ctbl.m$cat == "TOPIC", ] %>% droplevels()
# cutoff <- group_by(ct.tp, code) %>% dplyr::count()
# names(cutoff) <- c("code", "cutoff.score")
# ct.tp <- merge(ct.tp, cutoff, by = "code")
# # ct.tp <- ct.tp[ct.tp$cutoff > 2, ]
# # ct.tp <- ct.tp[ct.tp$cutoff > mean(ct.tp$cutoff), ]
#
# nlabs <- length(unique(ct.tp$code))
# ptop <- mpal(1:(length(unique(ct.tp$code))), p = sci)
# pscat <- c("#a6afbb", pal_my[17])
#
# library(reshape)
# ct.tp <- rename(ct.tp, c(scat = "Category", code = "Topics"))
#
# top.ps <- ggparset2(list("Category", "Topics"),
# data = ct.tp,
# method = "parset", label = TRUE,
# label.size = 3.5, text.angle = 0, order = c(1, 1)) +
# scale_fill_manual(values = c(pscat, adjustcolor(ptop, alpha.f = 0.55)),
# guide = FALSE) +
# scale_colour_manual(values = c(pscat, ptop), guide = FALSE) +
# thm_Rtft(ticks = FALSE, ytext = FALSE)
# # top.ps
# catpal <- c(pal_my[16], pal_my[18])
# catpal <- colorRampPalette(pal_my[c(2, 16)])(20)[c(12, 20)]
# MAPrqda.R ----------------------------------------------------------
#+ echo=FALSE
# DEPRECATED ---------------------------------------------------------
# knitr::opts_chunk$set(echo = FALSE)
# library(vcd);
# library(kableExtra);
# library(dplyr)
# #'
# #' `r tufte::newthought("\\large{Search Categories}")`
# #'
# ct.scat$scat <- ifelse(ct.scat$scat == "S3", "IPV Interventions", "LGBTQ-IPV Research")
#
# t.scat <- Rtdf(ct.scat$scat, names = c("Category", "$N_{Articles}$"))
# t.scat
# scat.t <- table(ct.scat$scat)
# prop.test(scat.t)
#'
#'
#+ out.width=".5\\linewidth"
# # catpal <- c(adjustcolor(pal_my[16], alpha.f = 0.8), adjustcolor(pal_my[18], alpha.f = 0.9)) ## muted dark blue and muted medium gray ##
#
# barplot(t.scat[, 2], names.arg = t.scat[, 1], pch = 19, col = catpal, ylab = "Frequency", xlab = "Category")
#'
#' \newpage
#' `r tufte::newthought("\\large{Topics}")`
#'
# labs <- list(
# top = c("Approach Eval.", "Community Capacity", "CCR", "IPV-Consequences", "IPV-Dynamics", "Help-Seeking", "Int. - General", "Int. - Descriptions", "Int. - Efficay", "Int. - Proposal", "Measures", "Eval. Methods", "Perp. Char.", "Program/Policy Devel.", "Outsiders' Persp.", "Key Stakeholders' Persp.", "Victims' Persp.", "Program Eval.", "Protective Factors", "Policy", "Prevalence", "Risk Factors", "System Response"),
# mo = c("MTA", "MM", "QL", "QT"),
# ql = c("Case Study", "Focus Groups", "Group Interviews", "1-on-1 Interviews", "Multiple QL Methods", "Participant Obsv.", "QL Survey"),
# qt = c("Secondary Data", "Experimental", "Longitudinal", "Multiple QT Methods", "Client Records", "Police Records", "QT Survey", "Cross-Sectional"),
# mm = c("Experimental", "Focus Groups", "1-on-1 Interviews", "Longitudinal", "QL Survey", "QT Survey", "Cross-Sectional"),
# pop = c("African Americans", "'At Risk' Populations", "Asian Americans", "Cis-Gender", "College Students", "Couples", "Non-IPV Crime Victims", "Disabled Persons", "Female/Women/Girls", "General Population", "Graduate Students", "Heterosexuals", "IPV-Perpetratords", "IPV-Victims/Survivors", "Latin*/Hispanic", "Males/Men/Boys", "CB Practitioners", "CB Practitioners - IPV", "Int. Programs" , "Parents", "Racial Minorities", "Sexual Minorities (SM)", "SM - Bisexuals", "SM - Gay", "SM - Lesbian", "SM - Queer", "SM - Transgender", "System Entities", "Urban-Specific", "Children/Youth")
# )
# labs2 <- list(
# top = c("Intervention Approach Evaluation (Eval.)", "Community Capacity", "Coordinated Community Response (CCR)", "IPV Consequences", "IPV Dynamics", "Help-Seeking", "IPV Interventions (Int.) - General", "IPV Interventions (Int.) - Description", "IPV Interventions (Int.) - Efficay", "IPV Interventions (Int.) - Proposal", "Measures", "Program Evaluation (Eval.) Methods", "Perpetrator (Perp.) Characteristics (Char.)", "Program/Policy Development (Devel.)", "Outsiders' Perspectives (Persp.)", "Key Stakeholders' Perspectives (Persp.)", "Victims' Perspectives (Persp.)", "Program/Policy Evaluation (Eval.) - General", "Protective Factors", "Policy", "IPV Prevalence", "Risk Factors", "System Response"),
# mo = c("Meta-Analysis (MTA)", "Mixed-Methods (MM)", "Qualitative (QL)", "Quantitative (QT)"),
# ql = c("Case Study", "Focus Groups", "Group Interviews", "1-on-1 Interviews", "Multiple Qualitative (QL) Methods", "Participant Observation (Obsv.)", "Qualitative (QL) Survey"),
# qt = c("Secondary Data", "Experimental", "Longitudinal", "Multiple Quantitative (QT) Methods", "Client Records", "Police Records", "Quantitative (QT) Survey", "Cross-Sectional"),
# mm = c("Experimental", "Focus Groups", "1-on-1 Interviews", "Longitudinal", "Qualitative (QL) Survey", "Quantitative (QT) Survey", "Cross-Sectional"),
# pop = c("African Americans", "'At Risk' Populations", "Asian Americans", "Cis-Gender", "College Students", "Couples", "Non-IPV Crime Victims", "Disabled Persons", "Female/Women/Girls", "General Population", "Graduate Students", "Heterosexuals", "IPV-Perpetrators", "IPV-Victims/Survivors", "Latinos/Latinas and/or Hispanic-Americans (Latin*/Hispanic)", "Males/Men/Boys", "Community-Based (CB) Practitioners", "CB Practitioners - IPV-Specific", "IPV Intervention (Int.) Programs" , "Parents", "Racial Minorities", "Sexual Minorities (SM)", "SM - Bisexuals", "SM - Gay", "SM - Lesbian", "SM - Queer", "SM - Transgender", "System Entities", "Urban-Specific", "Children/Youth")
# )
# ct.top <- ctbl[ctbl$cat == "TOPIC",]
# t.top <- Rtdf(ct.top$code, names = c("Topic", "Frequency"))
# t.top[, 1] <- labs2$top
# kable(t.top, booktabs = T, format = "latex") %>% kable_styling(position = "float_right")
#
# ft.top <- ftable(ct.top[, c("code", "scat")], row.vars = 1)
# ftm.top <- matrix(ft.top, nrow = length(unique(t.top[, 1])), byrow = FALSE)
# dimnames(ftm.top) <- list(Topic = labs$top, scat = c("IPV Interventions", "LGBTQ-IPV Research"))
# #'
# #+ out.width=".55\\linewidth"
# # dotchart(t.top[, 2], labels = labs$top, pch = 19, lcolor = pal_my[20], xlab = "Frequency", cex = 0.8, xlim = c(1, 24))
#
# Rdotchart(ftm.top, labels = labs$top, pch = 19, gcolor = pal_my[20], xlab = "Frequency", cex = 0.7, gcex = 0.75, gfont = 2, pt.cex = 1.125, color = c(rep(catpal[1], nrow(ftm.top)), rep(catpal[2], nrow(ftm.top))))
#
# #'
# #' \newpage
# #' `r tufte::newthought("\\large{Overarching Methododology}")`
# #'
# ct.mo <- ctbl[ctbl$cat == "M-OVERALL", ]
# t.mo <- Rtdf(ct.mo$code, names = c("Method(s)", "Frequency"))
# t.mo[, 1] <- labs2$mo
# kable(t.mo, align = c("l", "r"))
#
# ft.mo <- ftable(ct.mo[, c("code", "scat")], row.vars = 1)
# ftm.mo <- matrix(ft.mo, nrow = length(unique(t.mo[, 1])), byrow = FALSE)
# dimnames(ftm.mo) <- list(Methodology = labs$mo, scat = c("IPV Interventions", "LGBTQ-IPV Research"))
#
# # barplot(t.mo[, 2], names.arg = labs$mo, pch = 19, main = "Overarching Methodology", cex.names = 0.9)
#
# mosaic(ftm.mo, labeling_args = list(gp_labels = gpar(fontsize = 9), gp_varnames = gpar(fontsize = 11, fontface = 2), set_varnames = c(scat = "Search Category"), pos_labels = c("center", "center"), just_labels = c("center", "right")), rot_varnames = c(0, -90, 0, -90), rot_labels = rep(0, 4), alternate_labels = c(F, F), tl_labels = c(T, F), tl_varnames = c(F, T), highlighting = 2, highlighting_fill = catpal)#, margins = unit(6, "lines"))
# #'
# #' \newpage
# #' `r tufte::newthought("\\large{Qualitative Methods}")`
# #'
# ct.ql <- ctbl[ctbl$cat == "M-QL", ]
# t.ql <- Rtdf(ct.ql$code, names = c("Qualitative Method", "Frequency"))
# ft.ql <- ftable(ct.ql[, c("code", "scat")], row.vars = 1)
# ftm.ql <- matrix(ft.ql, nrow = length(unique(t.ql[, 1])), byrow = FALSE)
# dimnames(ftm.ql) <- list("Qualitative Method(s)" = labs$ql, scat = c("IPV Interventions", "LGBTQ-IPV Research"))
#
# t.ql[, 1] <- labs2$ql
# t.ql
#
# mosaic(ftm.ql, labeling_args = list(gp_labels = gpar(fontsize = 7), gp_varnames = gpar(fontsize = 10, fontface = 2), set_varnames = c(scat = "Search Category"), pos_labels = c("center", "center"), just_labels = c("center", "right")), rot_varnames = c(0, -90, 0, -90), rot_labels = rep(0, 4), alternate_labels = c(F, F), tl_labels = c(T, F), tl_varnames = c(F, T), highlighting = 2, highlighting_fill = catpal, margins = unit(6, "lines"))
# #'
# #' \newpage
# #' `r tufte::newthought("\\large{Quantitative Methods}")`
# #'
# ct.qt <- ctbl[ctbl$cat == "M-QT", ]
# t.qt <- Rtdf(ct.qt$code, names = c("Quantitative Method", "Frequency"))
# ft.qt <- ftable(ct.qt[, c("code", "scat")], row.vars = 1)
# ftm.qt <- matrix(ft.qt, nrow = length(unique(t.qt[, 1])), byrow = FALSE)
# dimnames(ftm.qt) <- list("Quantitative Method(s)" = labs$qt, scat = c("IPV Interventions", "LGBTQ-IPV Research"))
#
# t.qt[, 1] <- labs2$qt
# t.qt
#
# mosaic(ftm.qt, labeling_args = list(gp_labels = gpar(fontsize = 7), gp_varnames = gpar(fontsize = 10, fontface = 2), set_varnames = c(scat = "Search Category"), pos_labels = c("center", "center"), just_labels = c("center", "right")), rot_varnames = c(0, -90, 0, -90), rot_labels = rep(0, 4), alternate_labels = c(F, F), tl_labels = c(T, F), tl_varnames = c(F, T), highlighting = 2, highlighting_fill = catpal, margins = unit(5, "lines"))
# #'
# #' \newpage
# #' `r tufte::newthought("\\large{Mixed-Methods}")`
# #'
# ct.mm <- ctbl[ctbl$cat == "M-MM", ]
# t.mm <- Rtdf(ct.mm$code, names = c("Methods", "Frequency"))
# ft.mm <- ftable(ct.mm[, c("code", "scat")], row.vars = 1)
# ftm.mm <- matrix(ft.mm, nrow = length(unique(t.mm[, 1])), byrow = FALSE)
# dimnames(ftm.mm) <- list("Mixed-Methods" = labs$mm, scat = c("IPV Interventions", "LGBTQ-IPV Research"))
#
# t.mm[, 1] <- labs2$mm
# t.mm
#
# mosaic(ftm.mm, labeling_args = list(gp_labels = gpar(fontsize = 7), gp_varnames = gpar(fontsize = 10, fontface = 2), set_varnames = c(scat = "Search Category"), pos_labels = c("center", "center"), just_labels = c("center", "right")), rot_varnames = c(0, -90, 0, -90), rot_labels = rep(0, 4), alternate_labels = c(F, F), tl_labels = c(T, F), tl_varnames = c(F, T), highlighting = 2, highlighting_fill = catpal, margins = unit(5, "lines"))
# #'
# #' \newpage
# #' `r tufte::newthought("\\large{Populations}")`
# #'
# ct.pop <- ctbl[ctbl$cat == "POPULATION", ]
# t.pop <- Rtdf(ct.pop$code, names = c("Population", "Frequency"))
# ft.pop <- ftable(ct.pop[, c("code", "scat")], row.vars = 1)
# ftm.pop <- matrix(ft.pop, nrow = length(unique(t.pop[, 1])), byrow = FALSE)
# dimnames(ftm.pop) <- list("Populations" = labs$pop, scat = c("IPV Interventions", "LGBTQ-IPV Research"))
#
# t.pop[, 1] <- labs2$pop
# t.pop
# Rdotchart(ftm.pop, labels = labs$pop, pch = 19, gcolor = pal_my[20], xlab = "Frequency", cex = 0.7, gcex = 0.75, gfont = 2, pt.cex = 1.125, color = c(rep(catpal[1], nrow(ftm.pop)), rep(catpal[2], nrow(ftm.pop))))
# pop.df <- ft.pop %>% as.data.frame
# lrm <- glm(Freq ~ scat + , data = pop.df)
# dat.p1 <- with(pop.df,
# data.frame(Freq = mean(Freq), scat = factor(scat)))
# # dat.p1
# dat.p1$frqP <- predict(lrm, newdata = dat.p1, type = "response")
# # dat.p1
# dat.p2 <- with(pop.df, data.frame(Freq = rep(seq(from = 0, to = 65, length.out = 30), 2), scat = factor(scat)))
# dat.p3 <- cbind(dat.p2, predict(lrm, newdata = dat.p2, type = "link", se = TRUE))
# dat.p3 <- within(dat.p3, {
# PredictedProb <- plogis(fit)
# LL <- plogis(fit - (1.96 * se.fit))
# UL <- plogis(fit + (1.96 * se.fit))
# })
# library(ggplot2); library(ggthemes)
# ggplot(dat.p3, aes(x = Freq, y = PredictedProb)) +
# geom_ribbon(aes(ymin = LL, ymax = UL, fill = scat), alpha = 0.2) +
# geom_line(aes(colour = scat), size = 1) + scale_fill_manual(values = catpal) + scale_colour_manual(values = catpal) + thm_Rtft()
#
#'
#'
#'
# gg.tlinv <- ggplot(inv, aes(x = year, y = 0, colour = journal)) +
# thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE) +
# theme(legend.text = element_text(size = rel(0.65)),
# legend.title = element_text(size = rel(0.75), face = "bold")) +
# labs(colour = "Journal") +
# scale_colour_manual(values = mpal(1:length(unique(inv$jrnl))))) + #, guide = FALSE) +
# geom_hline(yintercept = 0, size = 0.5, color = pal_my[19]) +
# geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
# colour = pal_my[19], alpha = 0.5,
# na.rm = TRUE, size = 0.25) +
# # position = position_dodge(width = 1)) +
# geom_text(aes(y = pos, x = year, label = bibkey),
# vjust = "center", angle = 0, size = 2.65, fontface = "bold"); gg.tlinv
# gg.tlinv <- ggplot(tl.inv, aes(x = year, y = 0)) + thm_Rtft() +
# geom_hline(yintercept = 0, size = 1, color = pal_my[19]) +
# geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
# colour = pal_my[19], na.rm = TRUE, size = 0.5) + #,
# # position = position_dodge(width = 1)) +
# geom_text(aes(y = pos, x = year, label = bibkey), angle = 45, size = 1.75)#, position = position_jitter(height = 1.5))
#, position = position_jitter(), vjust = "outward",
##, position = position_dodge(width = 1)) +
# bibkey.inv <- gsub("(\\w+)\\d{4}\\w+", "\\1", inv$bibkey)
# bibkey.inv <- sapply(bibkey.inv, RtCap, USE.NAMES = FALSE)
# inv$bibkey <- bibkey.inv
# tl.inv$pos <- runif(nrow(tl.inv), min = -1, max = 1)#*1.5
# tl.inv$pos <- ifelse(abs(tl.inv$pos) < 0.25, tl.inv$pos*10, tl.inv$pos)
# probs1 <- seq(1, nrow(inv), by = 1)
# probs2 <- mean(probs1)
# inv$pos <- sample(seq(1, nrow(inv), by = 1), size = nrow(inv), replace = FALSE)
# inv$yrjt <- jitter(tl.inv$year, amount = 1.5)
# jitter(tl.inv$pos, amount = 2)
# inv$cpv <- factor(inv$cpv, labels = c("Community-Psychology", "Violence"))
# inv$bibkey2 <- as.integer(factor(inv$bibkey))
# gg.tlinv <- ggplot(inv, aes(x = year, y = 0, colour = cpv)) +
# thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE, ptitle = TRUE) +
# theme(legend.text = element_text(size = rel(0.65)),
# legend.title = element_text(size = rel(0.75), face = "bold")) +
# labs(colour = "Journal Category") +
# scale_colour_manual(values = pcpv) + #, guide = FALSE) +
# geom_hline(yintercept = mean(inv$pos), size = 0.25, color = pal_my[19], alpha = 0.5) +
# geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
# colour = pal_my[19], alpha = 0.45,
# na.rm = TRUE, size = 0.15) +
# ##, position = position_dodge(width = 1)) +
# geom_text(aes(y = pos, x = year, label = bibkey),#, position = position_jitter(),
# vjust = "outward", angle = 0, size = 2.5, fontface = "bold"); gg.tlinv +
# ggtitle("IPV-Interventions Research Timeline")
# gg.tlinv <- ggplot(inv, aes(x = year, y = 0, colour = journal)) +
# thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE) +
# theme(legend.text = element_text(size = rel(0.65)),
# legend.title = element_text(size = rel(0.75), face = "bold")) +
# labs(colour = "Journal") +
# scale_colour_manual(values = mpal(1:length(unique(inv$jrnl))))) + #, guide = FALSE) +
# geom_hline(yintercept = 0, size = 0.5, color = pal_my[19]) +
# geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
# colour = pal_my[19], alpha = 0.5,
# na.rm = TRUE, size = 0.25) +
# # position = position_dodge(width = 1)) +
# geom_text(aes(y = pos, x = year, label = bibkey),
# vjust = "center", angle = 0, size = 2.65, fontface = "bold"); gg.tlinv
# gg.tlinv <- ggplot(tl.inv, aes(x = year, y = 0)) + thm_Rtft() +
# geom_hline(yintercept = 0, size = 1, color = pal_my[19]) +
# geom_segment(aes(y = 0, yend = pos, x = year, xend = year),
# colour = pal_my[19], na.rm = TRUE, size = 0.5) + #,
# # position = position_dodge(width = 1)) +
# geom_text(aes(y = pos, x = year, label = bibkey), angle = 45, size = 1.75)#, position = position_jitter(height = 1.5))
# gg.tlinv
# bibkey.smw <- gsub("(\\w+)\\d{4}\\w+", "\\1", smw$bibkey)
# bibkey.smw <- sapply(bibkey.smw, RtCap, USE.NAMES = FALSE)
# smw$bibkey <- bibkey.smw
#
# smw$pos <- sample(seq(1, nrow(smw), by = 1), size = nrow(smw), replace = FALSE)
# gg.tlsmw <- ggplot(smw, aes(x = year, y = 0, colour = journal)) +
# thm_Rtft(yticks = FALSE, ytext = FALSE, ytitle = FALSE, ltitle = TRUE, ptitle = TRUE) +
# theme(legend.text = element_text(size = rel(0.65)),
# legend.title = element_text(size = rel(0.75), face = "bold")) +
# labs(colour = "Journal Title") +
# scale_colour_manual(values = psmw) + #, guide = FALSE) +
# geom_hline(yintercept = mean(smw$pos), size = 0.25, color = pal_my[19], alpha = 0.5) +
# geom_segment(aes(y = mean(smw$pos), yend = pos, x = year, xend = year),
# colour = pal_my[19], alpha = 0.45,
# na.rm = TRUE, size = 0.15) +
# geom_text(aes(y = pos, x = year, label = bibkey),#, position = position_jitter(),
# vjust = "outward", angle = 0, size = 2.5, fontface = "bold"); gg.tlsmw +
# ggtitle("SMW-Inclusive Research Timeline")
# inv.a <- cb[as.character(cb$bibkey) %in% as.character(inv$bibkey), ]
<file_sep>/_comps_docs/journal/journal.Rmd
---
title: "Research & Comps Journal"
---
<hr class="Bold" />
```{r echo=FALSE, results='asis'}
p <- list.files(pattern = "^journal\\-.*?\\.Rmd")
pt <- lapply(p, readLines)
names(pt) <- p
Rpt <- function(x) {
grep("title: \"(.*?)\"", x, value = TRUE, perl = T)
}
ptitle <- lapply(pt, Rpt)
Rptsub <- function(x) {
res <- gsub("title: ", "", x)
res <- gsub("\\\"", "", res)
res <- gsub("#' ", "", res)
return(res)
}
ptitle <- lapply(ptitle, Rptsub)
Rpht <- function(x) {
res <- gsub("\\.Rmd", ".html", x)
res <- gsub("\\.R", ".html", res)
return(res)
}
pht <- lapply(p, Rpht)
posts <- paste0("[", ptitle, "](", pht, ")")
pander::pander(as.list(posts))
```
<file_sep>/_comps_docs/_zmisc/bibs_cp.R
#' ---
#' title: "MAP - Bibliography (CP-Only)"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE
# SETUP --------------------------------------------------------------
source("../SETUP.R")
knitr::opts_chunk$set(
tidy = TRUE,
echo = FALSE,
fig.keep = 'high',
fig.show = 'asis',
results = 'asis',
tidy.opts = list(comment = FALSE),
echoRule = NULL,
echoRuleb = NULL,
fig.height = 5,
fig.path = "graphics/bibs_cp/rplot-")#, dev = 'png')
panderOptions("table.emphasize.rownames", FALSE)
# fig.retina = 4
# rpm()
#'
#' \Frule
#'
#' \newpage
#'
#'
#+ journals
# JOURNALS -----------------------------------------------------------
jdat <- read.csv("data/ipvJournalsSearch.csv")[c(-1, -6, -7), ]
## Exclude Theses and Dissertations ##
m.cnt <- mean(jdat[, 2])
s.cnt <- sd(jdat[, 2])
jdat$j <- as.integer(jdat$journal)
jv.sum <- sum(jdat$count)
jdat$prop <- jdat$count/jv.sum
jfv.n <- jdat[jdat$j == 59, 2]
jiv.n <- jdat[jdat$j == 61, 2]
vaw.n <- jdat[jdat$j == 94, 2]
jvv.n <- jdat[jdat$j == 96, 2]
jv.n <- rbind(jiv.n, jfv.n, vaw.n, jvv.n)
jdat.m <- jdat[jdat[,2] >= m.cnt, ]
jdat.s <- jdat[jdat[,2] >= s.cnt, ]
j.vpr <-c("Journal of Interpersonal Violence",
"Violence Against Women",
"Violence and Victims",
"Journal of Family Violence")
j.v <- sapply(j.vpr, tolower, USE.NAMES = FALSE)
j.cppr <- c("Action Research",
"American Journal of Community Psychology",
"American Journal of Health Promotion",
"American Journal of Orthopsychiatry",
"American Journal of Preventive Medicine",
"American Journal of Public Health",
"Australian Community Psychologist",
"Community Development",
"Community Development Journal",
"Community Mental Health Journal",
"Community Psychology in Global Perspective",
"Cultural Diversity and Ethnic Minority Psychology",
"Global Journal of Community Psychology Practice",
"Health Education and Behavior",
"Health Promotion Practice",
"Journal of Applied Social Psychology",
"Journal of Community and Applied Social Psychology",
"Journal of Community Practice",
"Journal of Community Psychology",
"Journal of Health and Social Behavior",
"Journal of Prevention and Intervention",
"Journal of Primary Prevention",
"Journal of Rural Community Psychology",
"Journal of Social Issues",
"Journal of Community Psychology",
"Psychiatric Rehabilitation Journal",
"Psychology of Women Quarterly",
"Social Science and Medicine",
"The Community Psychologist",
"Transcultural Psychiatry",
"Progress in Community Health Partnerships")
j.cp <- sapply(j.cppr, tolower, USE.NAMES = FALSE)
#'
#'
#+ pander_journals, echo=FALSE
### FUN - 'RtCap()' ####
RtCap <- function(x) {
s0 <- strsplit(x, " ")[[1]]
nocap <- c("a", "the", "to", "at", "in", "with", "and", "but", "or", "of")
s1 <- ifelse(!s0 %in% nocap, toupper(substring(s0, 1,1)), s0)
# s2 <- toupper(substring(s[!s %in% nocap], 1,1))
s2 <- ifelse(!s0 %in% nocap, substring(s0, 2), "")
s <- paste(s1, s2, sep="", collapse=" ")
return(s)
}
j.cpp <- sapply(j.cp, RtCap, USE.NAMES = FALSE)
cat(tufte::newthought("Community-psychology journals"), "included in database searches:\n\n")
j.cpp %>% as.list() %>% pander()
#'
#' \newpage
#'
#' # \LARGE{\textsc{Results of Systematic Database Searches:}}
#'
#' \Frule
#'
#+ bibdf
### FUN - 'Rbibkeys()' ####
Rbibkeys <- function(bib) {
keys <- bib[grep("\\@.*?\\{.*?,", bib, perl = TRUE)]
keys <- gsub("\\@\\w+\\{(.*?)", "\\1", keys, perl = TRUE)
keys <- keys[!grepl("\\%.*?,", keys, perl = TRUE)]
keys <- gsub(" ", NA_character_, keys)
keys <- gsub(",", "", keys)
return(keys)
}
# BIB --------------------------------------------------------------
bib <- readLines("MAP.bib")
BIBKEY <- Rbibkeys(bib)
library(bib2df)
bibdf <- bib2df("MAP.bib")
### n.init ####
n.init <- nrow(bibdf)
ID <- seq(1:nrow(bibdf))
MAP.au <- cbind(BIBKEY, bibdf[, "AUTHOR"])
## bibdf[,2] ##
#'
#+ MAP
# MAP ----------------------------------------------------------------
MAP <- cbind(ID,
BIBKEY,
bibdf[, c("YEAR", "TITLE", "JOURNAL", "ABSTRACT")]) %>%
as.data.frame()
## bibdf[c(3:5, 8)] ##
names(MAP)[-1] <- tolower(names(MAP)[-1])
#'
#+ MAP_RQDA, results='hide', fig.keep='none', fig.show='none'
# MAP-RQDA ----------------------------------------------------------------
source("MAPrqda.R", echo = FALSE)
#'
csid <- caseids[, c("caseid", "case", "RM", "scat")]
## caseids[, -3] ##
csid$case <- factor(csid$case)
MAP <- merge(MAP, csid, by.x = "bibkey", by.y = "case")
#'
#'
#+ MAP_CPV
# MAP-CPV ----------------------------------------------------------------
## (map.cp & map.v) ============================================================
MAP$journal <- sapply(MAP$journal, tolower)
MAP$journal <- gsub(" & ", " and ", MAP$journal)
MAP$journal <- factor(MAP$journal)
cp <- MAP$journal %in% j.cp
map.cp <- MAP[cp, , drop = FALSE]
levels(map.cp$journal) <- c(levels(map.cp$journal),
j.cp[!j.cp %in% levels(map.cp$journal)])
levels(map.cp$journal) <- sapply(levels(map.cp$journal), RtCap)
MAP <- map.cp
#'
#'
MAP$RM <- ifelse(MAP$RM == 1, NA_character_, 0)
MAPrm <- MAP[is.na(MAP$RM), "bibkey"] %>% droplevels() %>% as.character()
MAP <- na.omit(MAP)
MAP <- droplevels(MAP)
#'
#'
## map-jrnl ============================================================
MAP$journal <- factor(MAP$journal)
levels(MAP$journal) <- sapply(levels(MAP$journal), RtCap)
MAP$journal <- droplevels(MAP$journal)
### FUN - 'Rabbr()' ####
Rabbr <- function(x) {
s0 <- strsplit(x, " ")[[1]]
ex <- c("a", "the", "to", "at", "in", "with", "and", "but", "or", "of", "\\&")
s1 <- s0[!s0 %in% ex]
s2 <- substring(s1, 1,1)
s <- paste(s2, sep = "", collapse = "")
s <- toupper(s)
return(s)
}
MAP$jrnl <- sapply(as.character(MAP$journal), Rabbr)
#'
#'
#+ cb
# CTBL ---------------------------------------------------------------
cb <- merge(MAP, ctbl, by = c("caseid", "scat"))
cb <- within(cb, {
journal <- droplevels(journal)
jrnl <- sapply(as.character(journal), Rabbr)
code <- gsub("FG-\\w+", "FG", code)
# code <- gsub("EXP-\\w+", "EXP", code)
# code <- gsub("LT-\\w+", "LT", code)
code <- gsub("SVY-QL-MM", "SVY-QL", code)
code <- gsub("SVY-QT-MM", "SVY-QT", code)
# code <- gsub("XS-\\w+", "XS", code)
code <- gsub("IVW-\\w+", "IVW", code)
code <- ifelse(code == "HET", NA, code) ## have not coded all cases for this ##
code <- ifelse(code == "F", NA, code) ## have not coded all cases for this ##
code <- ifelse(code == "M", NA, code) ## have not coded all cases for this ##
# code <- gsub("SMIN-\\w+", NA, code) ## previously done to save space
scat <- factor(scat, labels = c("IPV Interventions", "SMW-Inclusive Research"))
})
cb <- na.omit(cb) %>% droplevels()
# cbk$clab <- ifelse(cbk$code %in% cb$code, cbk$clab, NA)
# cbk <- na.omit(cbk) %>% droplevels()
cbk <- within(cbk, {
clab <- ifelse(code == "SMIN-L", "Sexual Minorities - Lesbian", clab)
clab <- ifelse(code == "SMIN-G", "Sexual Minorities - Gay", clab)
clab <- ifelse(code == "SMIN-B", "Sexual Minorities - Bisexual", clab)
clab <- ifelse(code == "SMIN-T", "Sexual Minorities - Transgender", clab)
clab <- ifelse(code == "SMIN-Q", "Sexual Minorities - Queer", clab)
})
cb <- merge(cb, cbk, by = "code")
cb$code <- factor(cb$code)
cb$clab <- factor(cb$clab)
#'
#'
#+ FUN_Rftm
### FUN - 'Rftm()' ####
Rftm <- function(x1, x2, dnn = NULL, zero.action = NA, zero.qt = FALSE) {
if (!is.null(dnn)) {
tx <- Rtdf(x1, names = dnn[[1]])
ftm <- ftable(x1, x2, row.vars = 1) %>%
matrix(nrow = nrow(tx), byrow = FALSE)
dimnames(ftm) <- list(levels(x1), dnn[[2]])
} else {
tx <- Rtdf(x1)
ftm <- ftable(x1, x2, row.vars = 1) %>%
matrix(nrow = nrow(tx), byrow = FALSE)
dimnames(ftm) <- list(levels(x1))
}
if (!is.null(zero.action)) {
if (zero.qt == 0 | zero.qt == 1) {
zero.qt <- as.logical(zero.qt)
}
if (zero.qt == TRUE) {
ftm <- ifelse(ftm == 0, quote(zero.action), ftm)
} else {
ftm <- ifelse(ftm == 0, noquote(zero.action), ftm)
}
}
y <- list(tx, ftm)
names(y) <- c(paste0("Tabulation of ", deparse(substitute(x1))),
paste0("Cross-Tabulation of ",
deparse(substitute(x1)),
" & ",
deparse(substitute(x2))))
return(y)
}
#'
#' # General Research Categories
#'
#' \Frule
#'
#+ desc
### catpal ####
catpal <- c(adjustcolor(pal_my[16], alpha.f = 0.9), adjustcolor(pal_my[5], alpha.f = 0.9))
# DESCRIPTIVES ---------------------------------------------------------------
## search categories ============================================================
### [MAP-abstracts-S3.csv] ####
cpv.s3 <- MAP[MAP$scat == "S3", ]; ## write.csv(cpv.s3[order(cpv.s3$year), c("bibkey", "year", "title", "journal", "abstract")], "data/MAP-abstracts-S3.csv", row.names = FALSE)
### [MAP-abstracts-S4.csv] ####
cpv.s4 <- MAP[MAP$scat == "S4", ]; ## write.csv(cpv.s4[order(cpv.s4$year), c("bibkey", "year", "title", "journal", "abstract")], "data/MAP-abstracts-S4.csv", row.names = FALSE)
ct.scat <- within(MAP, {
scat <- ifelse(scat == "S3", "IPV Interventions", "SMW-Inclusive Research")
})
t.scat <- Rtdf(ct.scat$scat, names = c("Category", "N"))
## "ct.scat" created in "MAPrqda.R" ##
t.scat %>% kable()
scat.t <- table(ct.scat$scat)
scat.bn <- Rbinom(scat.t)
scat.bn %>% pander(caption = "Binomial Test of the Difference in Search Category Proportions")
t.scat$prop = t.scat$N / sum(t.scat$N)
t.scat <- t.scat[order(t.scat$prop), ]
t.scat$ymax <- cumsum(t.scat$prop)
t.scat$ymin <- c(0, head(t.scat$ymax, n = -1))
### PLOT - scat ####
library(ggplot2)
scat.p <- ggplot(t.scat, aes(fill = Category,
ymax = ymax,
ymin = ymin,
xmax = 4,
xmin = 3)) +
scale_fill_manual(values = catpal) +
geom_rect() +
coord_polar(theta = "y") +
xlim(c(0, 4)) +
annotate("text", x = 0, y = 0, label = "Category Proportions") +
labs(title = "") +
thm_Rtft(ytitle = FALSE) +
theme(axis.text = element_blank(),
axis.ticks = element_blank(),
legend.text = element_text(size = rel(1)),
legend.key.width = unit(0.5, "cm"),
legend.key.height = unit(0.5, "cm"))
scat.p
#'
#'
#' \newpage
#'
#' # Publication Titles
#' \Frule
#'
#+ pub_titles
## publication titles ============================================================
t.jrnl <- Rtdf(MAP$journal)
ft.jrnl <- with(MAP, {
ftable(journal, scat) %>%
matrix(nrow = nrow(t.jrnl),
byrow = FALSE)
})
dimnames(ft.jrnl) <- list("Publication Title" = levels(MAP$journal),
Category = c("IPV Interventions", "SMW-Inclusive Research"))
ft.jrnl <- ifelse(ft.jrnl == 0, NA, ft.jrnl)
# ft.jrnl %>% pander(caption = "Number of Publications in Each Research Category per Journal",
# justify = c("left", "right", "right"))
cpv.s3$jrnl <- sapply(as.character(cpv.s3$journal), Rabbr) %>% factor()
cpv.s4$jrnl <- sapply(as.character(cpv.s4$journal), Rabbr) %>% factor()
j.cp <- sapply(j.cp, Rabbr, USE.NAMES = FALSE)
#'
#' <!--## Research Category by Journal & Journal Category-->
#'
#+ scat_x_journal, fig.height=4, fig.fullwidth=TRUE
cj.dnn <- c("Journal", "$N_{Articles}$")
sj.dnn <- c("IPV Interventions", "SMW-Inclusive Research")
journals <- Rftm(MAP$journal, MAP$scat, dnn = list(cj.dnn, sj.dnn))
t.j <- journals[[1]]
ftm.j <- journals[[2]]
ftm.j2 <- Rna(ft.jrnl)
sum.j <- apply(ftm.j2, 1, sum)
ftm.jp <- cbind(ft.jrnl, "**Total**" = sum.j)
ftm.jp %>% pander(justify = c("left", "right", "right", "right"),
caption = "$N_{articles}$ in Each Research Category per Journal")
Rdotchart(
ftm.j,
pch = 19,
gcolor = pal_my[20],
xlab = expression(N[Articles]),
cex = 0.7,
gcex = 0.75,
gfont = 2,
pt.cex = 1.125,
color = c(rep(catpal[1], nrow(ftm.j)),
rep(catpal[2], nrow(ftm.j))),
xaxt = 'n'
); axis(1, at = seq(range(ftm.j, na.rm = TRUE)[1],
range(ftm.j, na.rm = TRUE)[2], by = 1))
MAP.j <- MAP[, c("scat", "journal")]
names(MAP.j) <- c("Category", "Journal")
MAP.j$Category <- ifelse(MAP.j$Category == "S3",
"IPV Interventions",
"SMW-Inclusive Research")
pj <- mpal(1:length(unique(MAP$jrnl)), p = sci)
library(ggparallel)
pscat <- c("#a6afbb", pal_my[17])
j.ps <- ggparset2(list("Category", "Journal"),
data = MAP.j,
method = "parset", label = TRUE,
label.size = 2.75, text.angle = 0, order = c(1, 1)) +
scale_fill_manual(values = c(pscat, adjustcolor(pj, alpha.f = 0.55)),
guide = FALSE) +
scale_colour_manual(values = c(pscat, pj), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
# j.ps
#'
#' \tufteskip
#'
#'
#+ echo=FALSE
#### NO MORE ECHO ####
## knitr::opts_chunk$set(echo = FALSE)
#'
#' \newpage
#'
#' # Research Topics, Sampling Frames, and Methodologies
#'
#' \Frule
#'
#' ## Primary Topics
#'
#+ topics, fig.fullwidth=TRUE, fig.height = 7.5
## topics ============================================================
# cb$clab <- factor(cb$clab)
codes.tp <- cb[cb$cat == "TOPIC", "clab"] %>% droplevels()
ctp.dnn <- c("Topic", "$N_{Articles}$")
scats.tp <- cb[cb$cat == "TOPIC", "scat"] %>% droplevels()
stp.dnn <- c("IPV Interventions", "SMW-Inclusive Research")
topics <- Rftm(codes.tp, scats.tp, dnn = list(ctp.dnn, stp.dnn))
t.tp <- topics[[1]]
ftm.tp <- topics[[2]]
ftm.tp2 <- Rna(ftm.tp)
sum.tp <- apply(ftm.tp2, 1, sum)
ftm.tpp <- cbind(ftm.tp, "**Total**" = sum.tp)
ftm.tpp %>% pander(justify = c("left", "right", "right", "right"),
caption = "Research Topics")
### PLOT - topic - 1 ####
Rdotchart(
ftm.tp,
pch = 19,
gcolor = pal_my[20],
xlab = expression(N[Articles]),
cex = 0.7,
gcex = 0.75,
gfont = 2,
pt.cex = 1.125,
color = c(rep(catpal[1], nrow(ftm.tp)), rep(catpal[2], nrow(ftm.tp))))
## xaxt = 'n'
#; axis(1, at = seq(range(ftm.tp, na.rm = TRUE)[1],
## range(ftm.tp, na.rm = TRUE)[2], by = 3))
#'
#' \newpage
#'
#+ topics2, fig.fullwidth=TRUE
dfm.tp2 <- data.frame(ftm.tp)
names(dfm.tp2) <- c("s3", "s4")
top.s3 <- data.frame(dfm.tp2$s3, row.names = rownames(dfm.tp2))
top.s3 <- na.omit(top.s3)
# top.s3
top.s4 <- data.frame(dfm.tp2$s4, row.names = rownames(dfm.tp2))
top.s4 <- na.omit(top.s4)
# top.s4
tp.s3 <- cb[cb$scat == levels(cb$scat)[1] &
cb$cat == "TOPIC", ] %>%
droplevels()
tp.s4 <- cb[cb$scat == levels(cb$scat)[2] &
cb$cat == "TOPIC", ] %>%
droplevels()
#'
#' \newpage
#' ## Research Designs
#'
#+ designs, fig.fullwidth=TRUE
## designs ============================================================
ct.d <- cb[cb$cat == "DESIGN", ] %>% droplevels()
t.d <- Rtdf(ct.d$clab)
ct.d$clab <- gsub(" Design", "", ct.d$clab) %>% factor()
ft.d <- ftable(ct.d[, c("clab", "scat")], row.vars = 1)
ftm.d <- matrix(ft.d, nrow = nrow(t.d), byrow = FALSE)
dimnames(ftm.d) <- list(Design = levels(ct.d$clab),
Category = c("IPV Interventions",
"SMW-Inclusive Research"))
sum.d <- apply(ftm.d, 1, sum)
ftm.d <- ifelse(ftm.d == 0, NA, ftm.d)
ftm.d <- cbind(ftm.d, "**Total**" = sum.d)
ftm.d %>% pander(justify = c("left", "right", "right", "right"),
caption = "Overarching Research Designs")
nlabs <- length(unique(ct.d$clab))
pmo <- mpal(1:length(unique(ct.d$clab)), p = sci)
ct.d <- dplyr::rename(ct.d, "Category" = scat, "Design" = clab)
### PLOT - designs ####
library(ggparallel)
pscat <- c("#a6afbb", pal_my[17])
d.ps <- ggparset2(list("Category", "Design"),
data = ct.d,
method = "parset", label = TRUE,
label.size = 3.5, text.angle = 0, order = c(1, 1)) +
scale_fill_manual(values = c(pscat, adjustcolor(pmo, alpha.f = 0.55)),
guide = FALSE) +
scale_colour_manual(values = c(pscat, pmo), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
d.ps
#'
#' \newpage
#' `r tufte::newthought("\\Large{Experimental Research Designs}")`
#'
#+ exp, fig.fullwidth=TRUE
## experimental designs ============================================================
ct.exp <- cb[cb$cat == "DESIGN-EXP", ] %>% droplevels()
t.exp <- Rtdf(ct.exp$clab)
ct.exp$clab <- gsub(" Design", "", ct.exp$clab) %>% factor()
ct.exp$clab <- gsub(" \\(", " \n\\(", ct.exp$clab) %>% factor()
ft.exp <- ftable(ct.exp[, c("clab", "scat")], row.vars = 1)
ftm.exp <- matrix(ft.exp, nrow = nrow(t.exp), byrow = FALSE)
dimnames(ftm.exp) <- list("Experimental Design" = levels(ct.exp$clab),
Category = c("IPV Interventions",
"SMW-Inclusive Research"))
sum.exp <- apply(ftm.exp, 1, sum)
ftm.exp <- ifelse(ftm.exp == 0, NA, ftm.exp)
ftm.exp <- cbind(ftm.exp, "**Total**" = sum.exp)
ftm.exp %>% pander(justify = c("left", "right", "right", "right"),
caption = "Experimental Research Designs")
nlabs <- length(unique(ct.exp$clab))
pmo <- mpal(1:length(unique(ct.exp$clab)), p = sci)
ct.exp <- dplyr::rename(ct.exp, "Category" = scat, "Experimental Design" = clab)
### PLOT - experimental designs ####
library(ggparallel)
pscat <- c("#a6afbb", pal_my[17])
exp.ps <- ggparset2(list("Category", "Experimental Design"),
data = ct.exp,
method = "parset", label = TRUE,
label.size = 3, text.angle = 0, order = c(1, 1)) +
scale_fill_manual(values = c(pscat, adjustcolor(pmo, alpha.f = 0.55)),
guide = FALSE) +
scale_colour_manual(values = c(pscat, pmo), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
exp.ps
#'
#' \newpage
#' ## Data Collection Methodologies
#'
#+ methodologies, fig.fullwidth=TRUE
## methodologies ============================================================
### PLOT - methodologies - 1 ####
ct.mo <- cb[cb$cat == "METHODS", ] %>% droplevels()
t.mo <- Rtdf(ct.mo$clab)
ft.mo <- ftable(ct.mo[, c("clab", "scat")], row.vars = 1)
ftm.mo <- matrix(ft.mo, nrow = nrow(t.mo), byrow = FALSE)
dimnames(ftm.mo) <- list(Methodology = levels(ct.mo$clab),
Category = c("IPV Interventions",
"SMW-Inclusive Research"))
sum.mo <- apply(ftm.mo, 1, sum)
ftm.mo <- ifelse(ftm.mo == 0, NA, ftm.mo)
ftm.mo <- cbind(ftm.mo, "**Total**" = sum.mo)
ftm.mo %>% pander(justify = c("left", "right", "right", "right"),
caption = "Methodologies")
### PLOT - methodologies ####
nlabs <- length(unique(ct.mo$clab))
pmo <- mpal(1:length(unique(ct.mo$clab)), p = sci)
ct.mo <- dplyr::rename(ct.mo, "Category" = scat, "Methodology" = clab)
library(ggparallel)
pscat <- c("#a6afbb", pal_my[17])
mo.ps <- ggparset2(list("Category", "Methodology"),
data = ct.mo,
method = "parset", label = TRUE,
label.size = 3.5, text.angle = 0, order = c(1, 1)) +
scale_fill_manual(values = c(pscat, adjustcolor(pmo, alpha.f = 0.55)),
guide = FALSE) +
scale_colour_manual(values = c(pscat, pmo), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
mo.ps
#'
#' \newpage
#' `r tufte::newthought("\\large{QuaLitative \\textit{Methods}}")`
#'
#+ qual, fig.fullwidth=TRUE
## qualitative ============================================================
ct.ql <- cb[cb$cat == "M-QL", ] %>% droplevels()
t.ql <- Rtdf(ct.ql$clab)
ft.ql <- ftable(ct.ql[, c("clab", "scat")], row.vars = 1)
ftm.ql <- matrix(ft.ql, nrow = nrow(t.ql), byrow = FALSE)
dimnames(ftm.ql) <- list("Qua**L**itative Method(s)" = levels(ct.ql$clab),
Category = c(#"IPV Interventions",
"SMW-Inclusive Research"))
sum.ql <- apply(ftm.ql, 1, sum)
ftm.ql <- ifelse(ftm.ql == 0, NA, ftm.ql)
ftm.ql <- cbind(ftm.ql, "**Total**" = sum.ql)
ftm.ql %>% pander(justify = c("left", "right", "right"),
caption = "Qua**L**itative Method(s)")
### PLOT - qualitative ####
pql <- mpal(1:length(unique(ct.ql$clab)), p = sci)
ct.ql <- dplyr::rename(ct.ql, "QuaLitative Methods" = clab, "Category" = scat)
ql.ps <- ggparset2(list("Category", "QuaLitative Methods"),
data = na.omit(ct.ql),
method = "parset", label = TRUE,
label.size = 3.5, text.angle = 0, order = c(1, 1)) +
scale_fill_manual(values = c(pscat[1], adjustcolor(pql, alpha.f = 0.55)),
guide = FALSE) +
scale_colour_manual(values = c(pscat[1], pql), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
ql.ps
#'
#' \newpage
#'
#' `r tufte::newthought("\\Large{QuaNTitative Research \\textit{Designs}}")`
#'
#+ quaNT_designs, fig.fullwidth=TRUE
ct.dqt <- cb[cb$cat == "D-QT", ] %>% droplevels()
t.dqt <- Rtdf(ct.dqt$clab)
ft.dqt <- ftable(ct.dqt[, c("clab", "scat")], row.vars = 1)
ftm.dqt <- matrix(ft.dqt, nrow = nrow(t.dqt), byrow = FALSE)
dimnames(ftm.dqt) <- list("Qua**NT**itative Design" = levels(ct.dqt$clab),
Category = c("IPV Interventions",
"SMW-Inclusive Research"))
# t.dqt
sum.dqt <- apply(ftm.dqt, 1, sum)
ftm.dqt <- ifelse(ftm.dqt == 0, NA, ftm.dqt)
ftm.dqt <- cbind(ftm.dqt, "**Total**" = sum.dqt)
ftm.dqt %>% pander(justify = c("left", "right", "right", "right"),
caption = "Qua**NT**itative Designs")
### PLOT - quantitative ####
nlabs <- length(unique(ct.dqt$clab))
pqt <- mpal(1:length(unique(ct.dqt$clab)), p = sci)
ct.dqt <- dplyr::rename(ct.dqt, "QuaNTitative Design" = clab, "Category" = scat)
dqt.ps <- ggparset2(list("Category", "QuaNTitative Design"),
data = ct.dqt,
method = "parset", label = TRUE,
label.size = 3.5, text.angle = 0, order = c(1, 1)) +
scale_fill_manual(values = c(pscat, adjustcolor(pqt, alpha.f = 0.55)),
guide = FALSE) +
scale_colour_manual(values = c(pscat, pqt), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
dqt.ps
#'
#'
#' \newpage
#' `r tufte::newthought("\\large{QuaNTitative \\textit{Methods}}")`
#'
#+ quant, fig.fullwidth=TRUE, fig.height=6
### quantitative ============================================================
ct.qt <- cb[cb$cat == "M-QT", ] %>% droplevels()
t.qt <- Rtdf(ct.qt$clab)
ft.qt <- ftable(ct.qt[, c("clab", "scat")], row.vars = 1)
ftm.qt <- matrix(ft.qt, nrow = nrow(t.qt), byrow = FALSE)
dimnames(ftm.qt) <- list("Qua**NT**itative Method" = levels(ct.qt$clab),
Category = c("IPV Interventions",
"SMW-Inclusive Research"))
# t.qt
sum.qt <- apply(ftm.qt, 1, sum)
ftm.qt <- ifelse(ftm.qt == 0, NA, ftm.qt)
ftm.qt <- cbind(ftm.qt, "**Total**" = sum.qt)
ftm.qt %>% pander(justify = c("left", "right", "right", "right"),
caption = "Qua**NT**itative Methods")
### PLOT - quantitative ####
nlabs <- length(unique(ct.qt$clab))
pqt <- mpal(1:length(unique(ct.qt$clab)), p = sci)
ct.qt <- dplyr::rename(ct.qt, "QuaNTitative Methods" = clab, "Category" = scat)
qt.ps <- ggparset2(list("Category", "QuaNTitative Methods"),
data = ct.qt,
method = "parset", label = TRUE,
label.size = 3.5, text.angle = 0, order = c(1, 1)) +
scale_fill_manual(values = c(pscat, adjustcolor(pqt, alpha.f = 0.55)),
guide = FALSE) +
scale_colour_manual(values = c(pscat, pqt), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
qt.ps
#'
#' \newpage
#' `r tufte::newthought("\\large{Archival/Secondary Data Sources}")`
#'
#+ m_rcrd, fig.fullwidth=TRUE
### archival/secondary data sources ####
ct.rcrd <- cb[cb$cat == "M-RCRD", ] %>% droplevels()
t.rcrd <- Rtdf(ct.rcrd$clab)
ft.rcrd <- ftable(ct.rcrd[, c("clab", "scat")], row.vars = 1)
ftm.rcrd <- matrix(ft.rcrd, nrow = nrow(t.rcrd), byrow = FALSE)
dimnames(ftm.rcrd) <- list("Archival Data Source" = levels(ct.rcrd$clab),
Category = c(#"IPV Interventions",
"SMW-Inclusive Research"))
# t.rcrd
sum.rcrd <- apply(ftm.rcrd, 1, sum)
ftm.rcrd <- ifelse(ftm.rcrd == 0, NA, ftm.rcrd)
ftm.rcrd <- cbind(ftm.rcrd, "**Total**" = sum.rcrd)
ftm.rcrd %>% pander(justify = c("left", "right", "right"),
caption = "Archival Data Sources")
### PLOT - archival/secondary data sources ####
nlabs <- length(unique(ct.rcrd$clab))
prcrd <- mpal(1:length(unique(ct.rcrd$clab)), p = sci)
ct.rcrd <- dplyr::rename(ct.rcrd, "Archival Data Source" = clab, "Category" = scat)
rcrd.ps <- ggparset2(list("Category", "Archival Data Source"),
data = ct.rcrd,
method = "parset", label = TRUE,
label.size = 3.5, text.angle = 0, order = c(1, 1)) +
scale_fill_manual(values = rev(c(rev(pscat), adjustcolor(prcrd, alpha.f = 0.55))),
guide = FALSE) +
scale_colour_manual(values = rev(c(rev(pscat), prcrd)), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
rcrd.ps
#'
#' \newpage
#'
#' `r tufte::newthought("\\Large{Mixed-Methodological \\textit{Designs}}")`
#'
#+ mm_designs, fig.fullwidth=TRUE
## mixed-methods designs ========================================================
ct.dmm <- cb[cb$cat == "D-MM", ] %>% droplevels()
t.dmm <- Rtdf(ct.dmm$clab)
ft.dmm <- ftable(ct.dmm[, c("clab", "scat")], row.vars = 1)
ftm.dmm <- matrix(ft.dmm, nrow = nrow(t.dmm), byrow = FALSE)
dimnames(ftm.dmm) <- list("Mixed-Methodological Design" = levels(ct.dmm$clab),
scat = c(#"IPV Interventions",
"SMW-Inclusive Research"))
# t.dmm
sum.dmm <- apply(ftm.dmm, 1, sum)
ftm.dmm <- ifelse(ftm.dmm == 0, NA, ftm.dmm)
ftm.dmm <- cbind(ftm.dmm, "**Total**" = sum.dmm)
ftm.dmm %>% pander(justify = c("left", "right", "right"),
caption = "Mixed-Methodological Designs")
### PLOT - mixed-methods ####
nlabs <- length(unique(ct.dmm$clab))
pmm <- mpal(1:length(unique(ct.dmm$clab)), p = sci)
ct.dmm <- dplyr::rename(ct.dmm, "Mixed-Methodological Design" = clab, "Category" = scat)
dmm.ps <- ggparset2(list("Category", "Mixed-Methodological Design"),
data = ct.dmm,
method = "parset", label = TRUE,
label.size = 3.5, text.angle = 0, order = c(-1,-1)) +
scale_fill_manual(values = c(pscat, adjustcolor(pmm, alpha.f = 0.55)),
guide = FALSE) +
scale_colour_manual(values = c(pscat, pmm), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
dmm.ps
#' \newpage
#' `r tufte::newthought("\\large{Mixed (QuaLitative \\& QuaNTitative) \\textit{Methods}}")`
#'
#+ mm_methods, fig.fullwidth=TRUE
## mixed-methods ============================================================
ct.mm <- cb[cb$cat == "M-MM", ] %>% droplevels()
t.mm <- Rtdf(ct.mm$clab)
ft.mm <- ftable(ct.mm[, c("clab", "scat")], row.vars = 1)
ftm.mm <- matrix(ft.mm, nrow = nrow(t.mm), byrow = FALSE)
dimnames(ftm.mm) <- list("Mixed-Methods" = levels(ct.mm$clab),
scat = c("IPV Interventions",
"SMW-Inclusive Research"))
# t.mm
sum.mm <- apply(ftm.mm, 1, sum)
ftm.mm <- ifelse(ftm.mm == 0, NA, ftm.mm)
ftm.mm <- cbind(ftm.mm, "**Total**" = sum.mm)
ftm.mm %>% pander(justify = c("left", "right", "right", "right"),
caption = "Research Topics")
### PLOT - mixed-methods ####
nlabs <- length(unique(ct.mm$clab))
pmm <- mpal(1:length(unique(ct.mm$clab)), p = sci)
ct.mm <- dplyr::rename(ct.mm, "Mixed-Methods" = clab, "Category" = scat)
mm.ps <- ggparset2(list("Category", "Mixed-Methods"),
data = na.omit(ct.mm),
method = "parset", label = TRUE,
label.size = 3.5, text.angle = 0, order = c(-1,-1)) +
scale_fill_manual(values = c(pscat, adjustcolor(pmm, alpha.f = 0.55)),
guide = FALSE) +
scale_colour_manual(values = c(pscat, pmm), guide = FALSE) +
thm_Rtft(ticks = FALSE, ytext = FALSE)
mm.ps
#'
#' \newpage
#' ## Target Populations & Sampling Frames
#'
#+ populations, fig.fullwidth=TRUE, fig.height = 7.5
## populations ============================================================
ct.pop <- cb[cb$cat == "POPULATION", ] %>% droplevels()
t.pop <- Rtdf(ct.pop$clab)
ft.pop <- ftable(ct.pop[, c("clab", "scat")], row.vars = 1)
ftm.pop <- matrix(ft.pop, nrow = nrow(t.pop), byrow = FALSE)
dimnames(ftm.pop) <-
list(
"Populations" = levels(ct.pop$clab),
scat = c("IPV Interventions", "SMW-Inclusive Research")
)
sum.pop <- apply(ftm.pop, 1, sum)
ftm.pop <- ifelse(ftm.pop == 0, NA, ftm.pop)
ftm.popp <- cbind(ftm.pop, "**Total**" = sum.pop)
ftm.popp %>% pander(justify = c("left", "right", "right", "right"),
caption = "Research Topics")
### PLOT - populations - 1 ####
Rdotchart(
ftm.pop,
pch = 19,
gcolor = pal_my[20],
xlab = expression(N[Articles]),
cex = 0.7,
gcex = 0.75,
gfont = 2,
pt.cex = 1.125,
color = c(rep(catpal[1], nrow(ftm.pop)), rep(catpal[2], nrow(ftm.pop))))
#'
#' \newpage
#'
#' # References`r Rcite_r(file = "../auxDocs/REFs.bib", footnote = TRUE)`
#'
#'
#' \parindent=-1.75em
#'
#' \setlength{\parskip}{0.25\baselineskip}
#'
<file_sep>/_comps_docs/_zmisc/MAPlvls.R
#' ---
#' title: "MAP - Levels of Analysis"
#' author: "<NAME>"
#' date: "`r format(Sys.Date(), '%d %B %Y')`"
#' ---
#'
#+ setup, echo=FALSE, results='hide', fig.keep='none', fig.show='none', message=FALSE, warning=FALSE, cache=FALSE
# SETUP --------------------------------------------------------------
source("bibs.R", echo = FALSE, print.eval = FALSE, verbose = FALSE)
knitr::opts_chunk$set(
tidy = TRUE,
echo = FALSE,
fig.keep = 'high',
fig.show = 'asis',
results = 'asis',
tidy.opts = list(comment = FALSE),
echoRule = NULL,
echoRuleb = NULL,
fig.width = 7,
fig.height = 7,
out.width = '0.75\\linewidth',
fig.path = "graphics/EcoLvls/rplot-")#,
# dev = 'png', fig.retina = 6)
knitr::opts_template$set(invisible = list(echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE, fig.keep='none', fig.show='none'))
#'
#+ ecoLvlsData
# DATA - ECO-LEVELS -------------------------------------------------------
mpeco0 <- read.csv("data/mapeco.csv")
mplvls0 <- read.csv("data/maplvls.csv")
mplvls1 <- within(mplvls0, {
micro <- ifelse(l1 | l2 == 1, 1, 0)
meso_exo <- ifelse(l3 == 1, 1, 0)
exo_macro <- ifelse(l4 == 1, 1, 0)
})
mplvls1$nlvls <- apply(mplvls1[, 2:5], 1, sum)
mplvls1$nsys <- apply(mplvls1[, 6:8], 1, sum)
rownames(mplvls1) <- mplvls1[, 1]
mplvls <- mplvls1[, -1, drop = FALSE]
#'
#' # Levels of Analysis
#'
#+ clrs_labs
# COLORS & LABELS ---------------------------------------------------------
vclrs <- rev(grad(1:10, p = nord_polar))[4:7]
vtclrs <- rev(grad(1:10, p = nord_polar))[6:9]
catpal85 <- adjustcolor(catpal, alpha.f = 0.85)
lcvclrs <- c("1 = vclrs[1]; 2 = vclrs[2]; 3 = vclrs[3]; 4 = vclrs[4]; 'S3' = catpal85[1]; 'S4' = catpal85[2]") ## `catpal85` is from 'bibs.R' ##
ltclrs <- c("1 = vtclrs[1]; 2 = vtclrs[2]; 3 = vtclrs[3]; 4 = vtclrs[4]")
llabs1 <- c("1 = 'Individual'; 2 = 'Relationship'; 3 = 'Community'; 4 = 'Societal'")
sclabs <- c("'S3' = 'IPV Interventions Research'; 'S4' = 'SMW-Inclusive IPV Research'")
#'
#+ l_MAP
# MERGE - MAP+l -------------------------------------------------------------
l <- mplvls[, 1:4]
l$id <- rownames(l)
mpjscat <- MAP[, c("bibkey", "scat", "journal")]
l <- merge(l, mpjscat, by.x = "id", by.y = "bibkey", all = TRUE)
# `llong` -------------------------------------------------------------------
llong0 <- reshape(l, varying = 2:5, direction = 'long', sep = "")
llong1 <- dplyr::rename(llong0, lvl = time, ynlvl = l)
rownames(llong1) <- NULL
llong1$ynlvl <- ifelse(llong1$ynlvl == 0, NA, llong1$ynlvl)
llong2 <- na.omit(llong1)[, c("id", "scat", "journal", "lvl")]
llong2$lvclr <- car::recode(llong2$lvl, lcvclrs)
llong2$cvclr <- car::recode(llong2$scat, lcvclrs)
llongv1 <- Rtdf(llong2[, "id"], names = c("x", "Freq"))
llongv1 <- merge(llongv1, llong2[, c("id", "cvclr")], all = FALSE, by.x = "x", by.y = "id")
llongv2 <- Rtdf(llong2[, "lvl"], names = c("x", "Freq"))
llongv2$cvclr <- rep(NA, nrow(llongv2))
llongv0 <- rbind(llongv1, llongv2) #, llongv3)
llongv01 <- within(llongv0, {
vclr <- car::recode(x, lcvclrs)
x <- car::recode(x, llabs1)
# x <- gsub("(\\w+)\\d{4}\\w+", "\\1", x)
# x <- sapply(x, RtCap)
})
kindex <- nrow(llongv01)-4 ## `kindex` = bibkey row-indexes in `llongv` (i.e., all rows minus the last four, which are the 4 eco levels of analysis) ##
llongv01$vclr[1:kindex] <- gsub("\\w+\\d{4}\\w+", NA, llongv01$vclr[1:kindex])
llongv01$vclr <- as.character(llongv01$vclr)
# llongv01$cvclr[-1:-kindex] <- vtclrs
# llongv01$cvclr[-1:-kindex] <- rev(llongv01$vclr[-1:-kindex])
llongv01$cvclr[-1:-kindex] <- pal_my[18]
llongv <- llongv01[!duplicated(llongv01), ]
llong <- within(llong2[, c("id", "lvl")], { ## 2 birds - 1 line of code: (1) select only the `id` and `lvl` cols from `llong2` (which correspond to the "from" & "to" cols in a network df) & (2) recode the levels of `lvl` ("to") from numbers to character strings ##
lvl <- car::recode(lvl, llabs1)
})
llongbi1 <- dplyr::rename(llong, "from" = id, "to" = lvl)
llongbi2 <- llongbi1[, c(2, 1)] %>% dplyr::rename("from" = to, "to" = from)
#+ llongg_net
# GRAPH DATA - LVLS -------------------------------------------------------
library(igraph)
llongg <- graph_from_data_frame(llong, directed = F, vertices = llongv)
lvnames0 <- vertex_attr(llongg, "name")
lvnames1 <- gsub("(\\w+)\\d{4}\\w+", "\\1", lvnames0)
lvnames <- sapply(lvnames1, RtCap, USE.NAMES = FALSE)
V(llongg)$name <- lvnames
V(llongg)$size <- V(llongg)$Freq+1
V(llongg)$color <- adjustcolor(V(llongg)$vclr, alpha.f = 0.65)
V(llongg)$frame.color <- V(llongg)$vclr
E(llongg)$width <- 0.35
kindex.g <- V(llongg)$name %>% length()-4 ## same as `kindex` above, but for the igraph data ##
lblsize <- c(log(V(llongg)$size[1:kindex.g])*0.45, log(V(llongg)$size[-1:-kindex.g])*0.125)
#'
#+ keysnet_lvls, fig.fullwidth=TRUE
# PLOT - `llongg` ---------------------------------------------------------
lfr <- layout_with_fr(llongg) %>% norm_coords()
plot(llongg, rescale = T, layout = lfr, vertex.label.color = V(llongg)$cvclr, vertex.label.cex = lblsize)
l2 <- layout_with_graphopt(llongg) %>% norm_coords()
plot(llongg, rescale = T, layout = l2, vertex.label.color = V(llongg)$cvclr, vertex.label.cex = lblsize)
plot(llongg, rescale = T, vertex.label.color = V(llongg)$cvclr, vertex.label.cex = lblsize)
#+ lvls_lnet
# `lnet` --------------------------------------------------------------------
lnet12 <- within(l, {
from <- Rdich(l1, values = c(NA, "l1"))
to <- Rdich(l2, values = c(NA, "l2"))
})
lnet12 <- na.omit(lnet12)
lnet13 <- within(l, {
from <- Rdich(l1, values = c(NA, "l1"))
to <- Rdich(l3, values = c(NA, "l3"))
})
lnet13 <- na.omit(lnet13)
lnet14 <- within(l, {
from <- Rdich(l1, values = c(NA, "l1"))
to <- Rdich(l4, values = c(NA, "l4"))
})
lnet14 <- na.omit(lnet14)
lnet23 <- within(l, {
from <- Rdich(l2, values = c(NA, "l2"))
to <- Rdich(l3, values = c(NA, "l3"))
})
lnet23 <- na.omit(lnet23)
lnet24 <- within(l, {
from <- Rdich(l2, values = c(NA, "l2"))
to <- Rdich(l4, values = c(NA, "l4"))
})
lnet24 <- na.omit(lnet24)
lnet34 <- within(l, {
from <- Rdich(l3, values = c(NA, "l3"))
to <- Rdich(l4, values = c(NA, "l4"))
})
lnet34 <- na.omit(lnet34)
lnet0 <- rbind(lnet12, lnet13, lnet14, lnet23, lnet24, lnet34)[, c("id", "from", "to")]
lnet <- lnet0[, -1]
#+ lnet_llabs
# llabs -------------------------------------------------------------------
library(car)
llabs <- c("'l1' = 'Individual'; 'l2' = 'Relationship'; 'l3' = 'Community'; 'l4' = 'Societal'")
lnet$from <- car::recode(lnet$from, llabs)
lnet$to <- car::recode(lnet$to, llabs)
#+ lfrq
# lfrq --------------------------------------------------------------------
lfrq1 <- lnet[, 1]
lfrq2 <- lnet[, 2]
lfrq3 <- c(lfrq1, lfrq2)
lfrq <- Rtdf(lfrq3, names = c("lvl", "Freq"))
# `lnetg` ------------------------------------------------------------------
library(igraph)
lnetg <- graph_from_data_frame(lnet, directed = FALSE, vertices = lfrq)
V(lnetg)$size <- V(lnetg)$Freq*1.5
lnetcol <- mpal(lfrq, p = nord_aurora, a = 0.8)
V(lnetg)$color <- lnetcol
E(lnetg)$width <- 0.25
#'
#+ lnetg_random
# PLOTS - `lnetg` (layout-1 : layout-4) -----------------------------------
plot(lnetg, rescale = T, edge.arrow.size = 0.35, vertex.label.color = "#1a1e22", vertex.frame.color = adjustcolor(pal_my[17], alpha.f = 0.25))
#'
#+ lnetg_fr
ll1 <- layout_with_fr(lnetg)
ll1n <- norm_coords(ll1, ymin = -2, ymax = 2, xmin = -2, xmax = 2)
plot(lnetg, rescale = T, layout = ll1n, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = NA)
#'
#+ lnetg_circle
ll2 <- layout.circle(lnetg)
ll2n <- norm_coords(ll2)#, ymin = -2, ymax = 2, xmin = -2, xmax = 2)
plot(lnetg, rescale = T, layout = ll2n, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = NA)
#'
#+ lnetg_gem
ll3 <- layout.gem(lnetg)
ll3n <- norm_coords(ll2)
plot(lnetg, rescale = T, layout = ll3n, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = NA)
#'
#+ lnetg_rt
ll4 <- layout.reingold.tilford(lnetg)
ll4n <- norm_coords(ll4)
plot(lnetg, rescale = T, layout = ll4n, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = NA)
#'
#' \newpage
#'
#+ lnetft
# `lnetft` -----------------------------------------------------------------
lnetft <- ftable(lnet)# %>% matrix(nrow = nrow(lfrq), byrow = FALSE)
# dimnames(lnetft) <- list(levels(factor(lnet$to)), levels(factor(lnet$from)))
llvls <- c("Individual", "Relationship", "Community", "Societal")
lnetp <- within(lnet, {
from <- factor(from, ordered = FALSE)
to <- factor(to, ordered = FALSE)
levels(from) <- c(levels(from), llvls[!llvls %in% levels(from)])
levels(to) <- c(levels(to), llvls[!llvls %in% levels(to)])
}) ## NOTE: in both of the factor() calls above,
## the second arg is not necessarily essential,
## since the default for the 'ordered' arg in 'factor()'
## is to check whether the variable being factored is ordered
## (i.e., 'is.ordered(x)' - see '?factor') ...
## ... but, like most of my coding habits/conventions,
## i tend to specify it explicitly for programmatic
## and reproducibility/reusability purposes ##
lnetftp <- ftable(lnetp) %>% matrix(nrow = nrow(lfrq), byrow = FALSE)
dimnames(lnetftp) <- list("Level-1" = levels(lnetp$to), "Level-2" = levels(lnetp$from))
lnetftp <- ifelse(lnetftp == 0, NA, lnetftp)
pander(lnetftp, justify = c("left", "centre", "centre", "center", "center"))
library(arcdiagram)
ledges <- cbind(lnet$from, lnet$to)
lvals <- V(lnetg)$Freq
ldeg <- degree(lnetg)
larcs <- .35*(lnetft %>% matrix())
larcs <- ifelse(larcs == 0, NA, larcs) %>% na.omit()
#+ arc_lvls, fig.height=3.75, fig.fullwidth=TRUE
# PLOT - `lnet - arcplot()` -----------------------------------------------
arcplot(ledges, col.arcs = hsv(0, 0, 0.1, 0.075), pch.nodes = 21, bg.nodes = adjustcolor(lnetcol, alpha.f = 0.75), cex.nodes = log(ldeg[c("Individual", "Relationship", "Community", "Societal")])*0.37, col.nodes = lnetcol, lwd.nodes = 0.75, lwd.arcs = larcs, line = 1.25, cex.labels = 0.5, font = 1, col.labels = pal_my[20])
#'
#' \newpage
#'
#' # Ecological Systems
#'
#+ sysnet
# `snet` -----------------------------------------------------------------
sys <- names(mplvls[, 5:7])
slabs <- c("'micro' = 'Micro-system'; 'meso_exo' = 'Meso- & Exo-system'; 'exo_macro' = 'Exo- & Macro-system'")
slabs2 <- c("'micro' = 'Micro'; 'meso_exo' = 'Meso-Exo'; 'exo_macro' = 'Exo-Macro'")
s <- mplvls[, 5:7]
s$id <- rownames(s)
## exo_macro, meso_exo, micro
snet12 <- within(s, {
from <- Rdich(micro, values = c(NA, "micro"))
to <- Rdich(micro, values = c(NA, "micro"))
})
snet12 <- na.omit(snet12)
snet13 <- within(s, {
from <- Rdich(micro, values = c(NA, "micro"))
to <- Rdich(meso_exo, values = c(NA, "meso_exo"))
})
snet13 <- na.omit(snet13)
snet14 <- within(s, {
from <- Rdich(micro, values = c(NA, "micro"))
to <- Rdich(exo_macro, values = c(NA, "exo_macro"))
})
snet14 <- na.omit(snet14)
snet23 <- within(s, {
from <- Rdich(micro, values = c(NA, "micro"))
to <- Rdich(meso_exo, values = c(NA, "meso_exo"))
})
snet23 <- na.omit(snet23)
snet24 <- within(s, {
from <- Rdich(micro, values = c(NA, "micro"))
to <- Rdich(exo_macro, values = c(NA, "exo_macro"))
})
snet24 <- na.omit(snet24)
snet34 <- within(s, {
from <- Rdich(meso_exo, values = c(NA, "meso_exo"))
to <- Rdich(exo_macro, values = c(NA, "exo_macro"))
})
snet34 <- na.omit(snet34)
snet0 <- rbind(snet12, snet13, snet14, snet23, snet24, snet34)[, c("id", "from", "to")]
snet <- snet0[, -1]
snet$from <- car::recode(snet$from, slabs2)
snet$to <- car::recode(snet$to, slabs2)
# `sfrq` ------------------------------------------------------------------
sfrq1 <- snet[, 1]
sfrq2 <- snet[, 2]
sfrq3 <- c(sfrq1, sfrq2)
sfrq <- Rtdf(sfrq3, names = c("lvl", "Freq"))
# GRAPH DATA - ECO SYS ------------------------------------------------------------------
library(igraph) ## not necessary - but included as reminder and in case I move/copy the code later ##
snetg <- graph_from_data_frame(snet, directed = FALSE, vertices = sfrq)
V(snetg)$size <- V(snetg)$Freq*1.5
# V(snetg)$label.size <- (V(snetg)$Freq*0.85
snetcol <- mpal(sfrq, p = nord_aurora, a = 0.8)
V(snetg)$color <- snetcol
E(snetg)$width <- 0.25
#'
#+ snetg_random
# PLOTS - `snetg` (layout-1 : layout-4) -----------------------------------
plot(snetg, rescale = T, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = NA)
#'
#+ snetg_fr
ls1 <- layout.fruchterman.reingold(snetg)
ls1n <- norm_coords(ls1)
plot(snetg, rescale = T, layout = ls1n, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = NA)
#'
#+ snetg_circle
ls2 <- layout.circle(snetg)
ls2n <- norm_coords(ls2)
plot(snetg, rescale = T, layout = ls2n, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = NA)
#'
#+ snetg_gem
ls3 <- layout.gem(snetg)
ls3n <- norm_coords(ls3)
plot(snetg, rescale = T, layout = ls3n, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = NA)
#'
#+ snetg_rt
ls4 <- layout.reingold.tilford(snetg)
ls4n <- norm_coords(ls4)
plot(snetg, rescale = T, layout = ls4n, edge.arrow.size = .2, vertex.label.color = "#1a1e22", vertex.frame.color = NA)
#'
#' \newpage
#'
#+ snetft
# `snetft` ----------------------------------------------------------------
snetft <- ftable(snet) %>% matrix(nrow = nrow(sfrq), byrow = FALSE)
dimnames(snetft) <- list(levels(factor(snet$to)), levels(factor(snet$from)))
snetp <- within(snet, {
from <- factor(from, ordered = FALSE)
to <- factor(to, ordered = FALSE)
levels(from) <- c(levels(to)[!levels(to) %in% levels(from)], levels(from))
levels(to) <- c(levels(from)[!levels(from) %in% levels(to)], levels(to))
})
snetftp <- ftable(snetp) %>% matrix(nrow = nrow(sfrq), byrow = FALSE)
dimnames(snetftp) <- list("Ecological System-1" = levels(snetp$to), "Ecological System-2" = levels(snetp$from))
snetftp <- ifelse(snetft == 0, NA, snetft)
pander(snetftp, justify = c("left", "centre", "centre"))
sedges <- cbind(snet$from, snet$to)
svals <- V(snetg)$Freq
sdeg <- degree(snetg)
sarcs <- .15*(snetft %>% matrix())
sarcs <- ifelse(sarcs == 0, NA, sarcs) %>% na.omit()
#+ arc_sys, fig.height=3.5, fig.fullwidth=TRUE
# PLOT - `snetft-arcplot` -------------------------------------------------
arcplot(sedges, col.arcs = hsv(0, 0, 0.1, 0.06), pch.nodes = 21, bg.nodes = adjustcolor(snetcol, alpha.f = 0.5), cex.nodes = log(sdeg[c("Micro", "Meso-Exo", "Exo-Macro")])*0.3, col.nodes = snetcol, lwd.nodes = 0.75, lwd.arcs = sarcs, line = 1.25, cex.labels = 0.5, font = 1, col.labels = pal_my[20])
#
#'
#' \newpage\onehalfspacing
#'
#' # References
#'
#' \refs
#'
<file_sep>/_comps_docs/_zmisc/s4all.R
#+ setup, echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE
knitr::opts_template$set(invisible = list(echo=FALSE, results='hide', message=FALSE, warning=FALSE, cache=FALSE, fig.keep='none', fig.show='none'))
#'
#+ src_bibs, opts.label='invisible'
source("bibs.R")
#'
s4all <- MAP2[MAP2$scat == "S4", ]
s4all$bibkey <- as.character(s4all$bibkey)
s4excl <- s4all[!s4all$bibkey %in% MAP$bibkey, ]
# Rdt(s4excl[, c("bibkey", "journal")])
#
cb_s4x <- merge(s4excl, ctbl, by = c("caseid", "scat"))
cb_s4x <- within(cb_s4x, {
jrnl <- sapply(as.character(journal), Rabbr)
code <- gsub("FG-\\w+", "FG", code)
# code <- gsub("EXP-\\w+", "EXP", code)
# code <- gsub("LT-\\w+", "LT", code)
code <- gsub("SVY-QL-MM", "SVY-QL", code)
code <- gsub("SVY-QT-MM", "SVY-QT", code)
# code <- gsub("XS-\\w+", "XS", code)
code <- gsub("IVW-\\w+", "IVW", code)
code <- gsub("SMIN-\\w+", NA, code)
code <- gsub("HET", NA, code)
})
cb_s4x <- na.omit(cb_s4x) %>% droplevels()
cb_s4x <- cb_s4x[, c("caseid", "scat", "journal", "bibkey", "year", "RM", "case", "cid", "code", "catid", "cat")]
cb_s4x <- merge(cb_s4x, cbk, by = "code")
cb_s4x$code <- factor(cb_s4x$code)
cb_s4x$clab <- factor(cb_s4x$clab)
# x <- s4xtp[, c("bibkey", "clab")] %>% ftable() %>% data.frame()
# x[, 3] %>% unique()
# ftable(s4xql$clab, s4xql$jrnl)
#'
#' \newpage
#'
#+ echo=FALSE
#'
s4xtp <- cb_s4x[cb_s4x$cat == "TOPIC", ] %>% droplevels()
s4xtp <- s4xtp[!duplicated(s4xtp), ]
#
# rec.clab2code <- paste0("\"", s4xtp$clab, "\" = \"", s4xtp$code, "\"", collapse = "; ")
# rec.code2clab <- paste0("\"", s4xtp$code, "\" = \"", s4xtp$clab, "\"", collapse = "; ")
# lvla4.tp <- paste0(seq(1:length(unique(s4xtp$clab))), " = ", car::recode(levels(s4xtp$clab), rec.clab2code))
s4xtp$codelabs <- paste0("**`", car::recode(s4xtp$clab, rec.clab2code), "`** = _", car::recode(s4xtp$code, rec.code2clab), "_")
Rtdf(s4xtp$codelabs, names = c(" ", "$N_{Articles}$")) %>%
kable(align = c("l", "r"), row.names = TRUE)
cda4.tp <- paste0(seq(1:length(unique(s4xtp$code))), " = ", levels(s4xtp$code))
levels(s4xtp$code) <- seq(1:length(unique(s4xtp$code)))
ks4xtp <- ftable(s4xtp$bibkey, s4xtp$code) %>% as.matrix ## "ks4x" == "bibkeys - s4x" ##
ks4xtp <- ifelse(ks4xtp >= 1, "$\\checkmark$", "$\\cdot$")
z <- paste0("@", rownames(ks4xtp))
ks4xtp <- cbind(z, ks4xtp)
rownames(ks4xtp) <- NULL
#'
#+ eval=FALSE, echo=FALSE
dt4xtp <- ftable(s4xtp$bibkey, s4xtp$code) %>% as.matrix ## "ks4x" == "bibkeys - s4x" ##
dt4xtp <- ifelse(dt4xtp >= 1, "✓", ".")
z <- paste0("@", rownames(dt4xtp))
dt4xtp <- cbind(z, dt4xtp)
rownames(dt4xtp) <- NULL
Rdt(dt4xtp, escape = FALSE, filter = 'top', class = 'cell-border hover')
#'
#' \newpage
#'
#+ echo=FALSE
kable(ks4xtp[, 1:7])
#'
#' \newpage
#'
#+ echo=FALSE
kable(ks4xtp[, 8:13])
# pander(lvla4.tp)
#'
#' \newpage
#'
#' # References
#'
#' \refs
#'
<file_sep>/_comps_docs/_zmisc/circle.R
#'
#' # First, some basic geometry
#'
#' ## Area of a circle ("$A$"):
#' \[ A = \pi r^{2} \]
#'
#' where $r$ is the radius.
#'
#' ## Radius of a circle ("$r$"):
#'
#' \[ r = \sqrt{\frac{A}{\pi}} \]
#'
#' # Now a circle (drawn in base `R` graphics):
#'
radius <- 1
cir <- c(-1, 1)
theta <- seq(0, 2*pi, length = 200)
plot(cir, cir*2, type = 'n')
lines(x = radius*cos(theta), y = radius*sin(theta))
#'
#'
# MAPtl <- read.csv("http://datasets.flowingdata.com/crimeRatesByState2005.tsv", header = TRUE, sep = "\t")
radius <- sqrt(MAP$SJR/pi)
symbols(MAP$year, jitter(MAP$prop, amount = sd(MAP$prop)), circles = radius, inches = 0.35, fg = NA, bg = mpal(MAPtl, a = 0.25))
symbols(MAP$year, circles = radius, inches = 0.5, fg = NA, bg = mpal(MAPtl, a = 0.25))
plot(MAPtl$year, jitter(MAPtl$prop, amount = sd(MAPtl$prop)))
text(MAPtl$year, MAPtl$prop, MAPtl$state, cex=0.5)
jitter(MAPtl$prop, amount = sd(MAPtl$prop))
<file_sep>/_comps_docs/_dbsrch.R
library(scales)
library(knitr)
s1psy <- 4386
s1wos <- 3376
s1mn <- min(c(s1psy = s1psy, s1wos = s1wos))
s1mx <- max(c(s1psy = s1psy, s1wos = s1wos))
s1 <- range(c(s1psy = s1psy, s1wos = s1wos))
s2psy <- 337
s2wos <- 686
s2mn <- min(c(s2psy = s2psy, s2wos = s2wos))
s2mx <- max(c(s2psy = s2psy, s2wos = s2wos))
s2 <- range(c(s2psy = s2psy, s2wos = s2wos))
s3psy <- 32
s3wos <- 46
s3mn <- min(c(s3psy = s3psy, s3wos = s3wos))
s3mx <- max(c(s3psy = s3psy, s3wos = s3wos))
s3 <- range(c(s3psy = s3psy, s3wos = s3wos))
s4psy <- 18
s4wos <- 34
s4mn <- min(c(s4psy = s4psy, s4wos = s4wos))
s4mx <- max(c(s4psy = s4psy, s4wos = s4wos))
s4 <- range(c(s4psy = s4psy, s4wos = s4wos))
s5psy <- 0
s5wos <- 4
s5mn <- min(c(s5psy = s5psy, s5wos = s5wos))
s5mx <- max(c(s5psy = s5psy, s5wos = s5wos))
s5 <- range(c(s5psy = s5psy, s5wos = s5wos))
s6psy <- 0
s6wos <- 2
s6mn <- min(c(s6psy = s6psy, s6wos = s6wos))
s6mx <- max(c(s6psy = s6psy, s6wos = s6wos))
s6 <- range(c(s6psy = s6psy, s6wos = s6wos))
n <- c(s1psy, s1wos, s2psy, s2wos, s3psy, s3wos, s4psy, s4wos, s5psy, s5wos, s6psy, s6wos)
srch.n <- sort(rep(1:6, 2))
names(n) <- paste0("s", srch.n, c("psy", "wos"))
db <- ifelse(grepl("psy", names(n)), "psy", "wos")
srch.mn <- c(s1mn, s1mn, s2mn, s2mn, s3mn, s3mn, s4mn, s4mn, s5mn, s5mn, s6mn, s6mn)
srch.mx <- c(s1mx, s1mx, s2mx, s2mx, s3mx, s3mx, s4mx, s4mx, s5mx, s5mx, s6mx, s6mx)
srchdf <- data.frame(srch.n, db, n, srch.mn, srch.mx)
db.n <- data.frame(wos = c(s1wos, s2wos, s3wos, s4wos, s5wos, s6wos), psy = c(s1psy, s2psy, s3psy, s4psy, s5psy, s6psy))
db.n$mn <- apply(db.n, 1, min)
db.n$mx <- apply(db.n, 1, max)
db.n$whchmn <- apply(db.n[, 1:2], 1, which.min)
db.n$whchmx <- apply(db.n[, 1:2], 1, which.max)
db.n <- within(db.n, {
whchmn <- ifelse(whchmn == 1, "WoS", "PI")
whchmx <- ifelse(whchmx == 1, "WoS", "PI")
})
dbsrch <- data.frame(n = c("1.", "2.", "3.", "4.", "5.", "6."),
srch = c("\\textsc{IPV - General}",
"--- \\textit{Interventions}",
"--- \\textit{Intervention Evaluations}",
"\\textsc{Female Same-Sex/Same-Gender IPV - General}",
"--- \\textit{Interventions}",
"--- \\textit{Intervention Evaluations}"),
nres = c(
paste0(comma(db.n$mn[1]), ", ", comma(db.n$mx[1]),
" \\textit{\\footnotesize{(", db.n$whchmx[1], ")}}"),
paste0(comma(db.n$mn[2]), ", ", comma(db.n$mx[2]),
" \\textit{\\footnotesize{(", db.n$whchmx[2], ")}}"),
paste0(comma(db.n$mn[3]), ", ", comma(db.n$mx[3]),
" \\textit{\\footnotesize{(", db.n$whchmx[3], ")}}"),
paste0(comma(db.n$mn[4]), ", ", comma(db.n$mx[4]),
" \\textit{\\footnotesize{(", db.n$whchmx[4], ")}}"),
paste0(comma(db.n$mn[5]), ", ", comma(db.n$mx[5]),
" \\textit{\\footnotesize{(", db.n$whchmx[5], ")}}"),
paste0(comma(db.n$mn[6]), ", ", comma(db.n$mx[6]),
" \\textit{\\footnotesize{(", db.n$whchmx[6], ")}}"))) #,
# mxdb = c(db.n$whchmx))
names(dbsrch) <- c(" ",
"Database Search",
"$Range_{N_{Results}}$\\newline(Database with most results)") #,
# "Database with most results")
# names(dbsrch) <- c("", "Database Search", "$Range_{N_{Results}}$")
# kable(dbsrch, caption = "Descriptions of database searches conducted with corresponding ranges of the number of results returned {#tbl:dbsrch}", align = c("r", "l", "c"), escape = T)
# pander(dbsrch, caption = "Descriptions of database searches conducted with corresponding ranges of the number of results returned {#tbl:dbsrch}", justify = c("right", "left", "left"), escape = T)
|
7f2d3d1f4ec4e90d7e757b4753cfec9c4e819c4e
|
[
"SQL",
"HTML",
"Markdown",
"JavaScript",
"R",
"RMarkdown"
] | 72
|
R
|
EccRiley/CommPsy-SysLitRvw
|
cb5001741c8525d7516c4ecb6a9ff730f8062627
|
93c3b3aa54fc12f2d8bf8494d92a4675d94dd8b9
|
refs/heads/master
|
<file_sep># -*- coding:utf-8 -*-
import cv2
import numpy as np
import time
import os
import glob
from calibrater import calibrater
def checkPath(path):
if os.path.isdir(path):
pass
else:
os.mkdir(path)
#计算存放在./results/bin文件夹里的标定内参和畸变参数的平均值,
#weight表示是否按照图片数加权计算平均,默认为True
def avgMtx(weight = True):
c = calibrater()
amtx = np.zeros((3,3))
adist = np.zeros((1,5))
aerror = 0
fname = glob.glob('./results/bin/*.npz')
imageNum = 0
for f in fname:
c.loadMtx(f,False)
c.calError()
if weight == True:
imageNum += c.imageNum
amtx += c.mtx * c.imageNum
adist += c.dist * c.imageNum
aerror += c.total_error * c.imageNum
else:
amtx += c.mtx
adist += c.dist
aerror += c.total_error
if weight == True:
amtx = amtx / imageNum
adist = adist / imageNum
aerror = aerror / imageNum
else:
amtx = amtx / len(fname)
adist = adist / len(fname)
aerror = aerror / len(fname)
return [amtx,adist,aerror,len(fname)]
#.npz转.txt
def npz2txt(filename,path = './results/text'):
checkPath(path)
c = calibrater()
c.loadMtx(filename)
c.calError()
filename = path + filename[13:-4] + '.txt'
f = open(filename,'w')
f.write('ret:'+ str(c.ret) + '\nnumber of images:' + str(c.imageNum) + '\nmtx:\n')
f.close()
f = open(filename,'ab')
np.savetxt(f,c.mtx,fmt='%.6f')
f.close()
f = open(filename,'a')
f.write('\ndist:\n')
f.close()
f = open(filename,'ab')
np.savetxt(f,c.dist,fmt='%.6f')
f = open(filename,'a')
f.write('\ntotal-error:' + str(c.total_error) + '\n')
f.close()
#将存放在./results/bin文件夹里的二进制文件全部转为文本文件并放入对应的text文件夹
def npzall2txt(path = './results/text'):
fname = glob.glob('./results/bin/*.npz')
for f in fname:
npz2txt(f,path)
<file_sep># -*- coding:utf-8 -*-
import sys
from tools import *
from calibrater import calibrater
if __name__ == '__main__':
#相机标定
c = calibrater()
c.calibrate(0)
#标定结束之后计算平均结果
m,d,e,n = avgMtx()
print '\nTotal number of data:' + str(n)
print 'Average mtx:\n',m
print 'Average dist:\n',d
print 'Average re-projection error:\n',e<file_sep># -*- coding:utf-8 -*-
import cv2
import numpy as np
import time
import os
def checkPath(path):
if os.path.isdir(path):
pass
else:
os.mkdir(path)
class calibrater:
#初始化标定状态
def __init__(self):
self.cal = False
self.__tr = False
self.__sf = True
checkPath('results')
checkPath('results/text')
checkPath('results/bin')
checkPath('undistortion')
checkPath('undistortion')
self.__mtx = False
#设置外参和输出
def setTr(self,tr = False, sf = True):
self.__tr = tr
self.__sf = sf
#更新格的宽高
def update(self,x):
self.numWidth = cv2.getTrackbarPos('棋盘格宽','capture')
self.numHeight = cv2.getTrackbarPos('棋盘格高','capture')
#初始化标定
def initCalibration(self):
#获取格的宽高
self.update(0)
#清空世界坐标点和图像坐标点
self.objpoints = [] #世界坐标点
self.imgpoints = [] #图像坐标点
self.pointCounts = [] #图片的角点数
#图片数置零
self.imageNum = 0
print 'Start calibrating...'
#为标定工作拍摄图片
def shotBoards(self):
#获取内部的格点数目
w = self.numWidth - 1
h = self.numHeight - 1
self.pointCounts.append(w*h)
# 设置寻找亚像素角点的参数,最大循环次数30和最大误差容限0.001
criteria = (cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_EPS, 30, 0.001)
#获取标定板角点的位置
objp = np.zeros((w*h,3), np.float32)
objp[:,:2] = np.mgrid[0:w,0:h].T.reshape(-1,2)
ret, corners = cv2.findChessboardCorners(self.gray, (w,h),None)
if ret == True:
#获取亚像素角点
cv2.cornerSubPix(self.gray,corners,(11,11),(-1,-1),criteria)
#添加世界坐标点和图像坐标点
self.objpoints.append(objp)
self.imgpoints.append(corners)
# 将角点在图像上显示
img = self.frame.copy()
cv2.drawChessboardCorners(img, (w,h), corners, ret)
cv2.imshow('findCorners',img)
self.imageNum = self.imageNum + 1
print 'Picture shot for calibration. Current image count:',self.imageNum
else:
print 'Cannot find corners'
#打印结果,tr表示是否打印外参数,sf表示是否保存内参信息至文件
def printResult(self,tr = False,sf = True):
print "ret:",self.ret
print "number of images:",self.imageNum
print "mtx:\n",self.mtx # 内参数矩阵
print "dist:\n",self.dist # 畸变系数 distortion cofficients = (k_1,k_2,p_1,p_2,k_3)
print "totol-error:\n",self.total_error
if tr == True:
print "rvecs:\n",self.rvecs # 旋转向量
print "tvecs:\n",self.tvecs # 平移向量
if sf == True: #保存内参至文件
t = time.strftime('%Y%m%d%H%M%S')
fileName = 'results/text/' + t + '.txt'
f = open(fileName,'w')
f.write('ret:'+ str(self.ret) + '\nnumber of images:' + str(self.imageNum) + '\nmtx:\n')
f.close()
f = open(fileName,'ab')
np.savetxt(f,self.mtx,fmt='%.6f')
f.close()
f = open(fileName,'a')
f.write('\ndist:\n')
f.close()
f = open(fileName,'ab')
np.savetxt(f,self.dist,fmt='%.6f')
f = open(fileName,'a')
f.write('\ntotal-error:' + str(self.total_error) + '\n')
f.close()
fileName = 'results/bin/' + t + '.npz'
np.savez(fileName,mtx=self.mtx,dist=self.dist,objpoints=self.objpoints, \
imgpoints=self.imgpoints,pointCounts=self.pointCounts, \
rvecs=self.rvecs,tvecs=self.tvecs,imageNum=self.imageNum,ret=self.ret)
#加载内参
def loadMtx(self,filename,printlog = True):
if os.path.isfile(filename) == False:
print 'Cannot find file'
else:
f = open(filename,'rb')
self.__mtx = True
data = np.load(f)
self.ret = data['ret']
self.mtx = data['mtx']
self.dist = data['dist']
self.objpoints = data['objpoints']
self.imgpoints = data['imgpoints']
self.pointCounts = data['pointCounts']
self.rvecs = data['rvecs']
self.tvecs = data['tvecs']
self.imageNum = data['imageNum']
if printlog == True:
print 'Loading calibration data......'
print 'ret:\n',self.ret
print 'mtx:\n',self.mtx
print 'dist:\n',self.dist
# print 'objpoints\n',self.objpoints
# print 'pointCounts\n',self.pointCounts
print 'Calibration data loaded!'
self.calError()
print 'total-error:',self.total_error
#去除畸变
def undisort(self):
if self.__mtx == False:
return
h,w = self.frame.shape[:2] #获取形状
#获取优化后的参数矩阵以及ROI
newcameramtx,roi = cv2.getOptimalNewCameraMatrix(self.mtx,self.dist,(w,h),1,(w,h))
#设定输出的图片
t = time.strftime('%Y%m%d%H%M%S')
os.mkdir('undistortion/' + t)
srcName = 'undistortion/' + t + '/origin_' + t + '.png'
dstName1 = 'undistortion/' + t + '/result1_' + t + '.png'
dstName2 = 'undistortion/' + t + '/result2_' + t + '.png'
#方法一:直接使用undistort函数
dst1 = cv2.undistort(self.frame,self.mtx,self.dist,None,newcameramtx)
#方法二:使用重映射方法
mapx, mapy = cv2.initUndistortRectifyMap(self.mtx, self.dist, None, newcameramtx, (w,h), 5)
dst2 = cv2.remap(self.frame, mapx, mapy, cv2.INTER_LINEAR)
#截取ROI
x,y,w,h = roi
dst1 = dst1[y:y+h,x:x+w]
dst2 = dst2[y:y+h,x:x+w]
#显示去畸变前后的图像
cv2.imshow('origin',self.frame)
cv2.imshow('result1',dst1)
cv2.imshow('result2',dst2)
#保存去畸变前后的图像
cv2.imwrite(srcName,self.frame)
cv2.imwrite(dstName1,dst1)
cv2.imwrite(dstName2,dst2)
#计算重投影误差
def calError(self):
self.total_error = 0
for i in xrange(len(self.objpoints)):
imgpoints2, _ = cv2.projectPoints(self.objpoints[i],self.rvecs[i],self.tvecs[i],self.mtx,self.dist)
error = cv2.norm(self.imgpoints[i],imgpoints2,cv2.NORM_L2) / len(imgpoints2)
self.total_error += error
#计算平均误差(之前忘了orz)
self.total_error /= len(self.objpoints)
#标定过程
def calibrate(self,source):
#获取摄像头信息
vc = cv2.VideoCapture(source)
#建立窗口
cv2.namedWindow('capture')
cv2.createTrackbar('棋盘格宽','capture',10,30,self.update)
cv2.createTrackbar('棋盘格高','capture',7,30,self.update)
while(1):
ret,self.frame = vc.read() #读取当前帧
cv2.imshow('capture',self.frame)
#计算灰度图
self.gray = cv2.cvtColor(self.frame,cv2.COLOR_BGR2GRAY)
#获取按键
key = cv2.waitKey(1) & 0xFF
if key == ord('q'): #q键退出
self.cal = False
break
elif key == ord('c'): #c键开始/结束标定
self.cal = not self.cal #切换状态
#开始初始化标定
if self.cal == True:
self.initCalibration()
#结束是计算标定结果并输出
else:
if self.imageNum == 0:
print 'Calibration failed: No image shot for calibration'
else:
self.ret, self.mtx, self.dist, self.rvecs, self.tvecs = cv2.calibrateCamera(self.objpoints, self.imgpoints, self.gray.shape[::-1], None, None)
self.__mtx = True
self.calError()
self.printResult(self.__tr,self.__sf)
print 'Calibration finished!'
elif key == ord('s'): #s键拍照
if self.cal == True:
self.shotBoards()
elif key == ord('d'): #d键去畸
self.undisort()
elif key == ord('l'):
print 'input the file path:'
filename = raw_input()
self.loadMtx(filename)
vc.release()
cv2.destroyAllWindows()
|
71eea000bac16cce66e7d4accc521198d86d9baa
|
[
"Python"
] | 3
|
Python
|
TonitruiAula/disparity-estimation
|
47ec97369d719153fb05cbce863bf26047fa0e7c
|
8ee2997031e694fd9c85cc09e2fe4f00950e9b62
|
refs/heads/master
|
<file_sep># App Store
https://itunes.apple.com/us/app/suu-laundry/id1441195559?mt=8
# SUU Laundry Calculator
iOS utility app that lets students know how many laundry loads they can make with the money they have on their account.
The app uses AutoLayout.
# UI

<file_sep>//
// ViewController.swift
// SUU Laundry Calculator
//
// Created by <NAME> on 18/08/2018.
// Copyright © 2018 ToualbiApps. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var calculateBtn: UIButton!
@IBOutlet weak var enteredAmount: UITextField!
public var amount : Double = 0
//Pass data between views.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let dormViewController = segue.destination as! DormViewController
dormViewController.budget = amount
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Makes circle button with shadow.
calculateBtn.layer.shadowColor = UIColor.black.cgColor
calculateBtn.layer.shadowOffset = CGSize(width: 0, height: 2.0)
calculateBtn.layer.masksToBounds = false
calculateBtn.layer.shadowRadius = 1.0
calculateBtn.layer.shadowOpacity = 0.5
calculateBtn.layer.cornerRadius = 15
//Checks for tap & applies fct dismissKeyboard.
let outsideTap = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard(recognizer:)))
//Add gesture to the view.
self.view.addGestureRecognizer(outsideTap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func calculatePressed(_ sender: Any) {
if(enteredAmount.text != ""){
//Format 21,7 to 21.7 for instance.
let number = NumberFormatter().number(from: enteredAmount.text!)
if let number = number {
amount = Double(truncating: number)
}
print(amount)
performSegue(withIdentifier: "toDormChoice", sender: self)
}
else{
//TODO: Some way of telling user to enter data.
}
}
@objc func dismissKeyboard(recognizer : UITapGestureRecognizer){
view.endEditing(true)
}
}
<file_sep>//
// SecondViewController.swift
// SUU Laundry Calculator
//
// Created by <NAME> on 02/09/2018.
// Copyright © 2018 ToualbiApps. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var newAmount: UIButton!
@IBOutlet weak var budgetLabel: UITextView!
@IBOutlet weak var dryLabel: UILabel!
@IBOutlet weak var washLabel: UILabel!
@IBOutlet weak var washPriceLabel: UILabel!
@IBOutlet weak var dryPriceLabel: UILabel!
@IBOutlet weak var changeLabel: UITextView!
var budget : Double = 0
var budgetAmount : Int = 0
var washPrice : Double = 0
var dryPrice : Double = 0
var dormChoice : String = ""
var washNbr : Double = 0
var dryNbr : Double = 0
var washBudget : Double = 0
var dryBudget : Double = 0
var change : Double = 0
override func viewDidLoad() {
super.viewDidLoad()
//Circle button.
newAmount.layer.shadowColor = UIColor.black.cgColor
newAmount.layer.shadowOffset = CGSize(width: 0, height: 2.0)
newAmount.layer.masksToBounds = false
newAmount.layer.shadowRadius = 1.0
newAmount.layer.shadowOpacity = 0.5
newAmount.layer.cornerRadius = 15
budgetLabel.text = "Budget: $" + (String(format: "%.2f", budget))
//Set prices.
if(dormChoice == "Cedar"){
washPrice = 1.00
dryPrice = 0.75
}
else{
washPrice = 1.00
dryPrice = 1.00
}
let roundedBudget : Double = floor(budget)
// print(budget)
// print(roundedBudget)
washBudget = roundedBudget / 2
dryBudget = roundedBudget / 2
// print("Wash budget = " + String(washBudget))
// print("Dry budget = " + String(dryBudget))
washNbr = floor(washBudget / washPrice)
dryNbr = floor(dryBudget / dryPrice)
// print("Wash nbr = \(washNbr)")
// print("Dry nbr = \(dryNbr)")
// print("dryNbr * dryPrice = \(dryNbr*dryPrice)")
// // print(Double(washNbr*washPrice))
// //print(dryNbr*dryPrice)
change = budget - (washNbr * washPrice + dryNbr * dryPrice)
print("BUDGET IS " + String(budget))
print ("CHANGE IS " + String(change))
changeLabel.text = " Change: $" + (String(format: "%.2f", change))
washLabel.text = String(Int(washNbr))
dryLabel.text = String(Int(dryNbr))
washPriceLabel.text = "Wash = $" + (String(format: "%.2f", washPrice))
dryPriceLabel.text = "Dry = $" + (String(format: "%.2f", dryPrice))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>//
// DormViewController.swift
// SUU Laundry Calculator
//
// Created by <NAME> on 04/09/2018.
// Copyright © 2018 ToualbiApps. All rights reserved.
//
import UIKit
class DormViewController: UIViewController {
@IBOutlet weak var newAmount: UIButton!
@IBOutlet weak var cedarBtn: UIButton!
@IBOutlet weak var ecclesBtn: UIButton!
@IBOutlet weak var foundersBtn: UIButton!
@IBOutlet weak var ponderosaBtn: UIButton!
var myDorm : String = ""
var goBack : Bool = false
var budget : Double = 0
override func viewDidLoad() {
super.viewDidLoad()
//Circle button.
newAmount.layer.shadowColor = UIColor.black.cgColor
newAmount.layer.shadowOffset = CGSize(width: 0, height: 2.0)
newAmount.layer.masksToBounds = false
newAmount.layer.shadowRadius = 1.0
newAmount.layer.shadowOpacity = 0.5
newAmount.layer.cornerRadius = 15
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func dormChoice(_ sender: Any) {
if (sender as AnyObject).tag == 1{
print("CEDAR")
myDorm = "Cedar"
performSegue(withIdentifier: "goToSecond", sender: self)
}
else if ((sender as AnyObject).tag == 2){
print("ECCLES")
myDorm = "Eccles"
performSegue(withIdentifier: "goToSecond", sender: self)
}
else if ((sender as AnyObject).tag == 3){
print("PONDEROSA")
myDorm = "Ponderosa"
performSegue(withIdentifier: "goToSecond", sender: self)
}
else if ((sender as AnyObject).tag == 4){
print("FOUNDERS")
myDorm = "Founders"
performSegue(withIdentifier: "goToSecond", sender: self)
}
else if((sender as AnyObject).tag == 5){
performSegue(withIdentifier: "goToFirst", sender: self)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "goToFirst"){
let viewController = segue.destination as! ViewController
}
else if(segue.identifier == "goToSecond"){
let secondViewController = segue.destination as! SecondViewController
secondViewController.dormChoice = myDorm
secondViewController.budget = budget
}
}
}
|
4250727294d714572f62903fd4923c11616e16a5
|
[
"Markdown",
"Swift"
] | 4
|
Markdown
|
AmineToualbi/SUU-Laundry-Calculator
|
725c15f0515afe380b4a2ce61e47b144bc169e63
|
352d1bc28cad7a8a47ffd5c0ad5c550170ee89ce
|
refs/heads/master
|
<file_sep>export declare class JsonWebToken {
static SECRET: string;
static encode(payload: any): string;
static decode(token: string): string | object;
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Base = void 0;
var Base_1 = require("./Base");
Object.defineProperty(exports, "Base", { enumerable: true, get: function () { return Base_1.Base; } });
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Lettuce = void 0;
const express = require("express");
const http = require("http");
const common_1 = require("@lettuce/common");
const AppUtil_1 = require("./AppUtil");
const ServerUtil_1 = require("./ServerUtil");
const action_1 = require("@lettuce/action");
const error_1 = require("@lettuce/error");
class Lettuce extends common_1.Base {
constructor(config) {
super();
this.appConfig = config;
this.preInitialize();
}
preInitialize() {
this.app = express();
AppUtil_1.AppUtil.configureApp(this.app);
}
initialize() {
action_1.ControllerUtil.configureController(this.appConfig.appRoot + '/controller', this.app);
error_1.ErrorUtil.configureExceptionHandler(this.appConfig.appRoot + '/error', this.app);
}
setup() {
this.server = http.createServer(this.app);
ServerUtil_1.ServerUtil.configureServer(this.server);
}
startup() {
this.initialize();
this.setup();
ServerUtil_1.ServerUtil.startServer(this.server);
}
}
exports.Lettuce = Lettuce;
<file_sep>import { Logger } from '@lettuce/logger';
import { Injector } from '@lettuce/inject';
export class Base {
public log: any;
public name: string;
public injects: Array<any>;
public injectable: boolean;
public static NAME: string;
constructor() {
this.name = this.constructor.name;
this.log = msg => Logger.print(msg, undefined, `${this.name}`);
this.injects = this.injects || [];
console.log(this.name);
console.log(this.injects);
this.injects.map(x => {
this[x.injectName] = Injector.resolve(x.source.name);
});
this.injectable && Injector.add(this, this.name);
}
}
<file_sep>import { ActionDecoratorUtil } from './ActionDecoratorUtil';
import { InjectUtil } from '@lettuce/inject';
const { ROUTE_PREFIX } = ActionDecoratorUtil;
export interface IRouteProps {
method: string;
url: string;
middlewareList: [];
actionName: string;
}
export const Route = (args: string) => {
const ctrlPath = ActionDecoratorUtil.DestructApiDecorator(args).path;
return target => {
const proto = target.prototype;
let routes: any[] = Object.getOwnPropertyNames(proto).filter(prop => prop.indexOf(ROUTE_PREFIX) === 0);
routes = routes.map(prop => {
const { method, path, middlewareList } = proto[prop];
// const url = `${ctrlPath}${path}`;
const url = `${path}`;
const actionName = prop.substring(ROUTE_PREFIX.length);
const routeProps: IRouteProps = {
method: method === 'del' ? 'delete' : method,
url,
middlewareList,
actionName,
};
return routeProps;
});
target.prototype.path =
target.prototype.path && target.prototype.path !== '/' ? target.prototype.path + ctrlPath : ctrlPath;
target.prototype.routes = routes;
InjectUtil.configureInject(target);
};
};
function route(method, ...args) {
if (typeof method !== 'string') {
throw new Error('The first argument must be an HTTP method');
}
const { path, middlewareList } = ActionDecoratorUtil.DestructRouteDecorator(args);
return function (target: any, name: string, descriptor: PropertyDescriptor) {
target[`${ROUTE_PREFIX}${name}`] = {
method,
path,
middlewareList,
};
};
}
const Head = route.bind(null, 'head');
const Options = route.bind(null, 'options');
const Get = route.bind(null, 'get');
const Post = route.bind(null, 'post');
const Put = route.bind(null, 'put');
const Patch = route.bind(null, 'patch');
const Delete = route.bind(null, 'delete');
const Del = route.bind(null, 'del');
const All = route.bind(null, 'all');
export { Head, Options, Get, Post, Put, Patch, Delete, Del, All };
<file_sep>export interface IRouteProps {
method: string;
url: string;
middlewareList: [];
actionName: string;
}
export declare const Route: (args: string) => (target: any) => void;
declare const Head: (...args: any[]) => (target: any, name: string, descriptor: PropertyDescriptor) => void;
declare const Options: (...args: any[]) => (target: any, name: string, descriptor: PropertyDescriptor) => void;
declare const Get: (...args: any[]) => (target: any, name: string, descriptor: PropertyDescriptor) => void;
declare const Post: (...args: any[]) => (target: any, name: string, descriptor: PropertyDescriptor) => void;
declare const Put: (...args: any[]) => (target: any, name: string, descriptor: PropertyDescriptor) => void;
declare const Patch: (...args: any[]) => (target: any, name: string, descriptor: PropertyDescriptor) => void;
declare const Delete: (...args: any[]) => (target: any, name: string, descriptor: PropertyDescriptor) => void;
declare const Del: (...args: any[]) => (target: any, name: string, descriptor: PropertyDescriptor) => void;
declare const All: (...args: any[]) => (target: any, name: string, descriptor: PropertyDescriptor) => void;
export { Head, Options, Get, Post, Put, Patch, Delete, Del, All };
<file_sep>export class Injector {
private static _Map: any = {};
static add(target, key) {
Injector._Map[key] = target;
}
static resolve(key) {
return Injector._Map[key];
}
static map() {
return Injector._Map;
}
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseService = void 0;
const common_1 = require("@lettuce/common");
class BaseService extends common_1.Base {
constructor() {
super();
}
}
exports.BaseService = BaseService;
<file_sep>import * as bcrypt from 'bcrypt';
export class PasswordUtil {
static compare(plain: string, encrypted: string) {
if (plain !== null && encrypted !== null) {
console.log('compare');
console.log(plain);
console.log(encrypted);
const match = bcrypt.compareSync(plain, encrypted);
console.log(match);
return match;
} else {
throw new Error('Invalid params..!!');
}
}
static hash(password) {
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(password, salt);
return hash;
}
}
<file_sep>export { IBeforeActionProps } from './IBeforeActionProps';
export { IAfterActionProps } from './IAfterActionProps';
export { BeforeAction, SkipBeforeAction, AfterAction, SkipAfterAction } from './hook.decorator';
<file_sep>export declare class Message {
static RECORD_NOT_FOUND: string;
static INVALID_OBJECT_ID: string;
static INVALID_CREDENTIALS: string;
static INVALID_TOKEN: string;
static MISSING_TOKEN: string;
static MISSING_VERSION: string;
static INVALID_USERNAME: string;
static UNAUTHORIZED: string;
static ACCOUNT_CREATED: string;
static ACCOUNT_NOT_CREATED: string;
static EXPIRED_TOKEN: string;
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = void 0;
const debug_1 = require("debug");
const BASE = 'App';
// const COLOUR = {
// LOG: '#1abc9c',
// TRACE: '#6ab04c',
// INFO: '#0abde3',
// WARN: '#f39c12',
// ERROR: '#eb3b5a',
// };
const enabled = true; // process.env.NODE_ENV === AppEnv.PRODUCTION
const GenerateMessage = (context, level, message, source) => {
const namespace = `${context}:${level}`;
const log = debug_1.default(namespace);
// log.color = COLOUR[level]
log.enabled = enabled;
debug_1.default.enable(namespace);
if (source) {
log(source, message);
}
else {
log(message);
}
};
class Logger {
static trace(message, source, context = BASE) {
return GenerateMessage(context, 'TRACE', message, source);
}
static log(message, source, context = BASE) {
return GenerateMessage(context, 'LOG', message, source);
}
static info(message, source, context = BASE) {
return GenerateMessage(context, 'INFO', message, source);
}
static warn(message, source, context = BASE) {
return GenerateMessage(context, 'WARN', message, source);
}
static error(message, source, context = BASE) {
return GenerateMessage(context, 'ERROR', message, source);
}
static print(message, source, context = BASE) {
return GenerateMessage(context, 'INFO', message, source);
}
}
exports.Logger = Logger;
<file_sep>import debug from 'debug';
const BASE = 'App';
// const COLOUR = {
// LOG: '#1abc9c',
// TRACE: '#6ab04c',
// INFO: '#0abde3',
// WARN: '#f39c12',
// ERROR: '#eb3b5a',
// };
const enabled = true; // process.env.NODE_ENV === AppEnv.PRODUCTION
const GenerateMessage = (context, level, message, source) => {
const namespace = `${context}:${level}`;
const log = debug(namespace);
// log.color = COLOUR[level]
log.enabled = enabled;
debug.enable(namespace);
if (source) {
log(source, message);
} else {
log(message);
}
};
export class Logger {
public static trace(message, source?, context = BASE) {
return GenerateMessage(context, 'TRACE', message, source);
}
public static log(message, source?, context = BASE) {
return GenerateMessage(context, 'LOG', message, source);
}
public static info(message, source?, context = BASE) {
return GenerateMessage(context, 'INFO', message, source);
}
public static warn(message, source?, context = BASE) {
return GenerateMessage(context, 'WARN', message, source);
}
public static error(message, source?, context = BASE) {
return GenerateMessage(context, 'ERROR', message, source);
}
public static print(message, source?, context = BASE) {
return GenerateMessage(context, 'INFO', message, source);
}
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Consumer = exports.Injectable = exports.Inject = void 0;
require("reflect-metadata");
const InjectUtil_1 = require("./InjectUtil");
function Inject(props) {
return function (target, name) {
const tokens = Reflect.getMetadata('design:type', target, name) || [];
target[`${InjectUtil_1.INJECT_PREFIX}${name}`] = { source: tokens };
};
}
exports.Inject = Inject;
const Injectable = () => {
return target => {
target.prototype.injectable = true;
};
};
exports.Injectable = Injectable;
const Consumer = (args) => {
return target => {
InjectUtil_1.InjectUtil.configureInject(target);
};
};
exports.Consumer = Consumer;
<file_sep>import { Base } from '@lettuce/common';
export declare class BaseService extends Base {
constructor();
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorUtil = exports.INJECT_PREFIX = void 0;
require("reflect-metadata");
const status_1 = require("@lettuce/status");
const BaseExceptionHandler_1 = require("./BaseExceptionHandler");
const ApiError_1 = require("./ApiError");
exports.INJECT_PREFIX = '$$inject_';
class ErrorUtil {
}
exports.ErrorUtil = ErrorUtil;
ErrorUtil.loadExceptionHandler = (root) => {
const dir = root;
let list = [];
try {
const Handler = require(`${dir}/api.exception`);
list = Handler.include;
}
catch (error) {
console.log(error);
}
return list;
};
ErrorUtil.configureExceptionHandler = (root, app) => {
const handler = ErrorUtil.loadExceptionHandler(root);
app.all('*', (req, res, next) => {
res.status(404).json({
status: 'error',
message: `Can't find ${req.originalUrl} on this server!`,
});
});
app.use((err, req, res, next) => {
let result = {
message: 'Unknown Error',
status: status_1.HttpStatus.INTERNAL_SERVER_ERROR,
};
if (err instanceof ApiError_1.ApiError) {
if (handler) {
result = BaseExceptionHandler_1.BaseExceptionHandler.handle(err, handler);
}
else {
result = {
message: 'Unknown Error',
status: status_1.HttpStatus.INTERNAL_SERVER_ERROR,
};
}
}
else {
result = {
message: err.message,
status: status_1.HttpStatus.INTERNAL_SERVER_ERROR,
};
}
res.status(result.status).json({
status: 'error',
message: result.message,
stack: process.env.NODE_ENV === 'production' ? {} : err.stack,
});
});
};
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ControllerUtil = void 0;
const path = require("path");
const fs = require("fs");
const express_1 = require("express");
class ControllerUtil {
static getControllerName(filename) {
const list = filename.split('-');
let id = '';
for (let i = 0; i < list.length; i++) {
const part = list[i];
id += part.charAt(0).toUpperCase() + part.slice(1);
}
return id;
}
}
exports.ControllerUtil = ControllerUtil;
ControllerUtil.loadController = (root) => {
const list = [];
try {
const dir = root;
const files = fs.readdirSync(dir);
for (let i = 0; i < files.length; i++) {
const filename = path.basename(files[i]);
const index = filename.indexOf('Controller.');
if (index !== -1) {
const identity = `${ControllerUtil.getControllerName(filename.substring(0, index))}Controller`;
// var router = require(dir + '/' + filename).default;
const ctrl = require(`${dir}/${filename}`);
const c = new ctrl[identity]();
const rtr = express_1.Router();
if (c.routes && c.routes.length > 0) {
c.configureRouter(rtr);
list.push(c);
}
}
}
}
catch (error) {
console.log(error);
}
return list;
};
ControllerUtil.configureController = (root, app) => {
const routes = ControllerUtil.loadController(root);
routes.map(route => {
app.use(route.path, route.router);
// app.use('/', route.router);
});
};
<file_sep>export declare class PasswordUtil {
static compare(plain: string, encrypted: string): boolean;
static hash(password: any): string;
}
<file_sep>import { ApiError } from './ApiError';
export interface IRescueProp {
rescueFrom: typeof ApiError;
with: any;
}
<file_sep>import { Base } from '@lettuce/common';
import { ApiError } from './ApiError';
import { IRescueProp } from './IRescueProp';
import { IRescueResultProp } from './IRescueResultProp';
export declare class BaseExceptionHandler extends Base {
list: IRescueProp[];
static handle(error: ApiError, list: IRescueProp[]): IRescueResultProp;
}
<file_sep>import 'reflect-metadata';
export declare function Inject(props?: any): (target: any, name: string) => void;
export declare const Injectable: () => (target: any) => void;
export declare const Consumer: (args?: string) => (target: any) => void;
<file_sep>import * as path from 'path';
import * as fs from 'fs';
import { Router } from 'express';
export class ControllerUtil {
static getControllerName(filename) {
const list = filename.split('-');
let id = '';
for (let i = 0; i < list.length; i++) {
const part = list[i];
id += part.charAt(0).toUpperCase() + part.slice(1);
}
return id;
}
static loadController = (root: string) => {
const list: any[] = [];
try {
const dir = root;
const files = fs.readdirSync(dir);
for (let i = 0; i < files.length; i++) {
const filename = path.basename(files[i]);
const index = filename.indexOf('Controller.');
if (index !== -1) {
const identity = `${ControllerUtil.getControllerName(filename.substring(0, index))}Controller`;
// var router = require(dir + '/' + filename).default;
const ctrl = require(`${dir}/${filename}`);
const c = new ctrl[identity]();
const rtr = Router();
if (c.routes && c.routes.length > 0) {
c.configureRouter(rtr);
list.push(c);
}
}
}
} catch (error) {
console.log(error);
}
return list;
};
static configureController = (root: string, app: any) => {
const routes: any[] = ControllerUtil.loadController(root);
routes.map(route => {
app.use(route.path, route.router);
// app.use('/', route.router);
});
};
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Message = void 0;
class Message {
}
exports.Message = Message;
Message.RECORD_NOT_FOUND = 'Sorry, record not found.';
Message.INVALID_OBJECT_ID = 'Invalid Object ID.';
Message.INVALID_CREDENTIALS = 'Invalid credentials';
Message.INVALID_TOKEN = 'Invalid token';
Message.MISSING_TOKEN = 'Missing token';
Message.MISSING_VERSION = 'Missing version number. Specify an API version in the Accept header. Accept: application/vnd.alertizen+json; version=2;';
Message.INVALID_USERNAME = 'Invalid username. Enter a valid Email or Phone Number';
Message.UNAUTHORIZED = 'Unauthorized request';
Message.ACCOUNT_CREATED = 'Account created successfully';
Message.ACCOUNT_NOT_CREATED = 'Account could not be created';
Message.EXPIRED_TOKEN = 'Sorry, your token has expired. Please login to continue.';
<file_sep>export { MongooseUtil } from './MongooseUtil';
<file_sep>import 'reflect-metadata';
import { HttpStatus } from '@lettuce/status';
import { BaseExceptionHandler } from './BaseExceptionHandler';
import { ApiError } from './ApiError';
import { IRescueProp } from './IRescueProp';
import { IRescueResultProp } from './IRescueResultProp';
export const INJECT_PREFIX = '$$inject_';
export class ErrorUtil {
public static loadExceptionHandler = (root: string) => {
const dir = root;
let list: IRescueProp[] = [];
try {
const Handler = require(`${dir}/api.exception`);
list = Handler.include;
} catch (error) {
console.log(error);
}
return list;
};
public static configureExceptionHandler = (root: string, app?: any) => {
const handler: IRescueProp[] = ErrorUtil.loadExceptionHandler(root);
app.all('*', (req, res, next) => {
res.status(404).json({
status: 'error',
message: `Can't find ${req.originalUrl} on this server!`,
});
});
app.use((err: Error, req, res, next) => {
let result: IRescueResultProp = {
message: 'Unknown Error',
status: HttpStatus.INTERNAL_SERVER_ERROR,
};
if (err instanceof ApiError) {
if (handler) {
result = BaseExceptionHandler.handle(err, handler);
} else {
result = {
message: 'Unknown Error',
status: HttpStatus.INTERNAL_SERVER_ERROR,
};
}
} else {
result = {
message: err.message,
status: HttpStatus.INTERNAL_SERVER_ERROR,
};
}
res.status(result.status).json({
status: 'error',
message: result.message,
stack: process.env.NODE_ENV === 'production' ? {} : err.stack,
});
});
};
}
<file_sep>import * as AppRoot from 'app-root-path';
export { AppRoot };
<file_sep>export declare class ActionDecoratorUtil {
static ROUTE_PREFIX: string;
static GetClassName: (target: any) => string;
static DestructRouteDecorator(args: any): {
path: any;
middlewareList: any;
};
static DestructApiDecorator(args: any): {
path: any;
};
}
<file_sep>import { IBeforeActionProps } from './IBeforeActionProps';
import { IAfterActionProps } from './IAfterActionProps';
const ProcessBeforeAction =
(skip: boolean) =>
(param: Function | (IBeforeActionProps | Function)[], actions?: Pick<IBeforeActionProps, 'except' | 'only'>) => {
return function (target: any) {
const proto = target.prototype;
let hookList: IBeforeActionProps[] = skip
? target.prototype.beforeActionSkipList
: target.prototype.beforeActionList;
let list: IBeforeActionProps[];
let props: IBeforeActionProps;
if (Array.isArray(param)) {
list = (param as Array<any>).map(x => {
return x instanceof Function ? { hook: x } : x;
});
hookList = hookList ? hookList.concat(list) : list;
} else if (param instanceof Function) {
props = {
...actions,
hook: param,
};
hookList = hookList ? hookList.concat([props]) : [props];
} else {
throw new Error('Param must be Function or Array');
}
if (skip) {
target.prototype.beforeActionSkipList = hookList;
} else {
target.prototype.beforeActionList = hookList;
}
};
};
const ProcessAfterAction =
(skip: boolean) =>
(param: Function | (IAfterActionProps | Function)[], actions?: Pick<IAfterActionProps, 'except' | 'only'>) => {
return function (target: any) {
const proto = target.prototype;
let hookList: IAfterActionProps[] = skip
? target.prototype.afterActionSkipList
: target.prototype.afterActionList;
let list: IAfterActionProps[];
let props: IAfterActionProps;
if (Array.isArray(param)) {
list = (param as Array<any>).map(x => {
return x instanceof Function ? { hook: x } : x;
});
hookList = hookList ? hookList.concat(list) : list;
} else if (param instanceof Function) {
props = {
...actions,
hook: param,
};
hookList = hookList ? hookList.concat([props]) : [props];
} else {
throw new Error('Param must be Function or Array');
}
if (skip) {
target.prototype.afterActionSkipList = hookList;
} else {
target.prototype.afterActionList = hookList;
}
};
};
const BeforeAction = ProcessBeforeAction(false);
const SkipBeforeAction = ProcessBeforeAction(true);
const AfterAction = ProcessAfterAction(false);
const SkipAfterAction = ProcessAfterAction(true);
export { BeforeAction, SkipBeforeAction, AfterAction, SkipAfterAction };
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PasswordUtil = exports.JsonWebToken = void 0;
var JsonWebToken_1 = require("./JsonWebToken");
Object.defineProperty(exports, "JsonWebToken", { enumerable: true, get: function () { return JsonWebToken_1.JsonWebToken; } });
var PasswordUtil_1 = require("./PasswordUtil");
Object.defineProperty(exports, "PasswordUtil", { enumerable: true, get: function () { return PasswordUtil_1.PasswordUtil; } });
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Base = void 0;
const logger_1 = require("@lettuce/logger");
const inject_1 = require("@lettuce/inject");
class Base {
constructor() {
this.name = this.constructor.name;
this.log = msg => logger_1.Logger.print(msg, undefined, `${this.name}`);
this.injects = this.injects || [];
console.log(this.name);
console.log(this.injects);
this.injects.map(x => {
this[x.injectName] = inject_1.Injector.resolve(x.source.name);
});
this.injectable && inject_1.Injector.add(this, this.name);
}
}
exports.Base = Base;
<file_sep>export class Message {
public static RECORD_NOT_FOUND = 'Sorry, record not found.';
public static INVALID_OBJECT_ID = 'Invalid Object ID.';
public static INVALID_CREDENTIALS = 'Invalid credentials';
public static INVALID_TOKEN = 'Invalid token';
public static MISSING_TOKEN = 'Missing token';
public static MISSING_VERSION =
'Missing version number. Specify an API version in the Accept header. Accept: application/vnd.alertizen+json; version=2;';
public static INVALID_USERNAME = 'Invalid username. Enter a valid Email or Phone Number';
public static UNAUTHORIZED = 'Unauthorized request';
public static ACCOUNT_CREATED = 'Account created successfully';
public static ACCOUNT_NOT_CREATED = 'Account could not be created';
public static EXPIRED_TOKEN = 'Sorry, your token has expired. Please login to continue.';
}
<file_sep>import 'reflect-metadata';
export declare const INJECT_PREFIX = "$$inject_";
export declare class ServiceDecoratorUtil {
static configureInject(target: any): any[];
}
<file_sep>import * as mongoose from 'mongoose';
export class MongooseUtil {
static configureMongoose = async (url?: string, options?: any) => {
const DB_URL = url || process.env.MONGODB_URI || '';
try {
await mongoose.connect(DB_URL, options);
} catch (error) {
console.log(error.message);
}
};
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Injector = void 0;
class Injector {
static add(target, key) {
Injector._Map[key] = target;
}
static resolve(key) {
return Injector._Map[key];
}
static map() {
return Injector._Map;
}
}
exports.Injector = Injector;
Injector._Map = {};
<file_sep>export declare class Injector {
private static _Map;
static add(target: any, key: any): void;
static resolve(key: any): any;
static map(): any;
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppUtil = void 0;
const logger = require("morgan");
const helmet = require("helmet");
const cors = require("cors");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const compress = require("compression");
const methodOverride = require("method-override");
const expressWinston = require("express-winston");
global.Promise = require('q').Promise;
class AppUtil {
}
exports.AppUtil = AppUtil;
AppUtil.configureApp = (app) => {
if (process.env.NODE_ENV === 'development') {
app.use(logger('dev'));
}
// secure apps by setting various HTTP headers
app.use(helmet());
// enable CORS - Cross Origin Resource Sharing
const corsOptions = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 200,
};
// app.options('*', cors(corsOptions))
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(cookieParser());
app.use(compress());
app.use(methodOverride());
// enable detailed API logging in dev env
if (process.env.NODE_ENV === 'development') {
expressWinston.requestWhitelist.push('body');
expressWinston.responseWhitelist.push('body');
}
return app;
};
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppRoot = void 0;
const AppRoot = require("app-root-path");
exports.AppRoot = AppRoot;
<file_sep>## A Simple Modular Node.JS Framework
<file_sep>import * as express from 'express';
import * as logger from 'morgan';
import * as helmet from 'helmet';
import * as cors from 'cors';
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser';
import * as compress from 'compression';
import * as methodOverride from 'method-override';
import * as expressWinston from 'express-winston';
global.Promise = require('q').Promise;
export class AppUtil {
static configureApp = (app): express.Application => {
if (process.env.NODE_ENV === 'development') {
app.use(logger('dev'));
}
// secure apps by setting various HTTP headers
app.use(helmet());
// enable CORS - Cross Origin Resource Sharing
const corsOptions = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 200,
};
// app.options('*', cors(corsOptions))
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
}),
);
app.use(cookieParser());
app.use(compress());
app.use(methodOverride());
// enable detailed API logging in dev env
if (process.env.NODE_ENV === 'development') {
expressWinston.requestWhitelist.push('body');
expressWinston.responseWhitelist.push('body');
}
return app;
};
}
<file_sep>export declare class Logger {
static trace(message: any, source?: any, context?: string): void;
static log(message: any, source?: any, context?: string): void;
static info(message: any, source?: any, context?: string): void;
static warn(message: any, source?: any, context?: string): void;
static error(message: any, source?: any, context?: string): void;
static print(message: any, source?: any, context?: string): void;
}
<file_sep>export { IRescueProp } from './IRescueProp';
export { IRescueResultProp } from './IRescueResultProp';
export { Message } from './Message';
export { BaseExceptionHandler } from './BaseExceptionHandler';
export { ErrorUtil } from './ErrorUtil';
export { ApiError, AuthenticationError, MissingTokenError, InvalidTokenError, InvalidUsernameError, MissingVersionError, RecordNotFoundError, InvalidObjectIdError, } from './ApiError';
<file_sep>#!/bin/bash
protected_branch='master'
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
if [ $protected_branch = $current_branch ]
then
echo "[PROTECT-MASTER: tried update \"master\" - FAIL]"
exit 1
fi
echo "[PROTECT-MASTER: ok]"
exit 0<file_sep>import 'reflect-metadata';
import { IRescueProp } from './IRescueProp';
export declare const INJECT_PREFIX = "$$inject_";
export declare class ErrorUtil {
static loadExceptionHandler: (root: string) => IRescueProp[];
static configureExceptionHandler: (root: string, app?: any) => void;
}
<file_sep>import { Base } from '@lettuce/common';
export class BaseService extends Base {
constructor() {
super();
}
}
<file_sep>export declare class ControllerUtil {
static getControllerName(filename: any): string;
static loadController: (root: string) => any[];
static configureController: (root: string, app: any) => void;
}
<file_sep>export class ActionDecoratorUtil {
static ROUTE_PREFIX = '$$route_';
static GetClassName = (target: any): string => target.constructor.name;
static DestructRouteDecorator(args) {
if (args.length === 0) {
throw new Error('Missing Route path');
}
if (typeof args !== 'string' && typeof args[0] !== 'string') {
throw new Error('Route path must be string');
}
const list = args.length > 1 ? args[1] : [];
const path = typeof args !== 'string' ? args[0] : args;
return { path, middlewareList: list };
}
static DestructApiDecorator(args) {
if (args.length === 0) {
throw new Error('Missing Route path');
}
if (typeof args !== 'string' && typeof args[0] !== 'string') {
throw new Error('Route path must be string');
}
const path = typeof args !== 'string' ? args[0] : args;
return { path };
}
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SkipAfterAction = exports.AfterAction = exports.SkipBeforeAction = exports.BeforeAction = void 0;
const ProcessBeforeAction = (skip) => (param, actions) => {
return function (target) {
const proto = target.prototype;
let hookList = skip
? target.prototype.beforeActionSkipList
: target.prototype.beforeActionList;
let list;
let props;
if (Array.isArray(param)) {
list = param.map(x => {
return x instanceof Function ? { hook: x } : x;
});
hookList = hookList ? hookList.concat(list) : list;
}
else if (param instanceof Function) {
props = Object.assign(Object.assign({}, actions), { hook: param });
hookList = hookList ? hookList.concat([props]) : [props];
}
else {
throw new Error('Param must be Function or Array');
}
if (skip) {
target.prototype.beforeActionSkipList = hookList;
}
else {
target.prototype.beforeActionList = hookList;
}
};
};
const ProcessAfterAction = (skip) => (param, actions) => {
return function (target) {
const proto = target.prototype;
let hookList = skip
? target.prototype.afterActionSkipList
: target.prototype.afterActionList;
let list;
let props;
if (Array.isArray(param)) {
list = param.map(x => {
return x instanceof Function ? { hook: x } : x;
});
hookList = hookList ? hookList.concat(list) : list;
}
else if (param instanceof Function) {
props = Object.assign(Object.assign({}, actions), { hook: param });
hookList = hookList ? hookList.concat([props]) : [props];
}
else {
throw new Error('Param must be Function or Array');
}
if (skip) {
target.prototype.afterActionSkipList = hookList;
}
else {
target.prototype.afterActionList = hookList;
}
};
};
const BeforeAction = ProcessBeforeAction(false);
exports.BeforeAction = BeforeAction;
const SkipBeforeAction = ProcessBeforeAction(true);
exports.SkipBeforeAction = SkipBeforeAction;
const AfterAction = ProcessAfterAction(false);
exports.AfterAction = AfterAction;
const SkipAfterAction = ProcessAfterAction(true);
exports.SkipAfterAction = SkipAfterAction;
<file_sep>import { Base } from '@lettuce/common';
import { IBeforeActionProps, IAfterActionProps } from '@lettuce/hook';
export type Middleware = (req?, res?, next?: any) => any;
class ActionController extends Base {
public router = undefined;
public routes;
public beforeActionList;
public beforeActionSkipList;
public afterActionList;
public afterActionSkipList;
constructor() {
super();
this.routes = this.routes || [];
console.log(this.routes);
this.beforeActionList = this.beforeActionList || [];
this.beforeActionSkipList = this.beforeActionSkipList || [];
this.afterActionList = this.afterActionList || [];
this.afterActionSkipList = this.afterActionSkipList || [];
}
configureRouter(router) {
for (let i = 0; i < this.routes.length; i++) {
const route = this.routes[i];
const { method, url, actionName } = route;
const baList = this.getHooksByName(actionName, this.beforeActionList);
const baSkipList = this.getHooksByName(actionName, this.beforeActionSkipList);
const finalBAList = this.getFinalHooks(baList, baSkipList);
const aaList = this.getHooksByName(actionName, this.afterActionList);
const aaSkipList = this.getHooksByName(actionName, this.afterActionSkipList);
const finalAAList = this.getFinalHooks(aaList, aaSkipList);
const action = async (req: any, res: any, next: any) => {
try {
const context = req.context || {};
context.body = context.body || req.body;
context.params = context.params || req.params;
context.query = context.query || req.query;
const fn = this[actionName];
console.log('actionName');
console.log(actionName);
console.log(this[actionName]);
console.log(context);
const [result, status] = await fn.apply(this, [context]);
context.result = result;
context.status = status;
req.context = context;
} catch (error) {
next(error);
}
next();
};
const beforeActions = finalBAList || [];
const afterActions = finalAAList || [];
const middlewares = [beforeActions, action, afterActions];
router[method](url, ...middlewares, async (req: any, res: any, next: any) => {
try {
const { context } = req;
res.status(context.status || 200).json(context.result);
} catch (error) {
next(error);
}
});
}
this.router = router;
}
getFinalHooks(srcList, rmList) {
const list: Array<any> = srcList && srcList.filter(x => rmList.indexOf(x) === -1);
return list || [];
}
getHooksByName(name: string, actionList) {
const list: Array<any> = [];
if (actionList && actionList.length) {
actionList.map((a: IBeforeActionProps | IAfterActionProps) => {
if (!a.except && !a.only) {
list.push(a.hook);
} else if (a.only) {
if (a.only.indexOf(name) !== -1) {
list.push(a.hook);
}
} else if (a.except) {
if (a.except.indexOf(name) === -1) {
list.push(a.hook);
}
}
});
}
return list;
}
}
export { ActionController };
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PasswordUtil = void 0;
const bcrypt = require("bcrypt");
class PasswordUtil {
static compare(plain, encrypted) {
if (plain !== null && encrypted !== null) {
console.log('compare');
console.log(plain);
console.log(encrypted);
const match = bcrypt.compareSync(plain, encrypted);
console.log(match);
return match;
}
else {
throw new Error('Invalid params..!!');
}
}
static hash(password) {
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(password, salt);
return hash;
}
}
exports.PasswordUtil = PasswordUtil;
<file_sep>import { Service } from './ServiceDecorator';
import { BaseService } from './BaseService';
export { Service, BaseService };
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseService = exports.Service = void 0;
const ServiceDecorator_1 = require("./ServiceDecorator");
Object.defineProperty(exports, "Service", { enumerable: true, get: function () { return ServiceDecorator_1.Service; } });
const BaseService_1 = require("./BaseService");
Object.defineProperty(exports, "BaseService", { enumerable: true, get: function () { return BaseService_1.BaseService; } });
<file_sep>import 'reflect-metadata';
import * as path from 'path';
import * as fs from 'fs';
export const INJECT_PREFIX = '$$inject_';
export class ServiceDecoratorUtil {
// static getResourceName(filename) {
// const list = filename.split('-');
// let id = '';
// try {
// for (let i = 0; i < list.length; i++) {
// const part = list[i];
// id += part.charAt(0).toUpperCase() + part.slice(1);
// }
// } catch (error) {
// console.log(error);
// }
// return id;
// }
// static loadResource (root: string) {
// const dir = root;
// const list: any[] = [];
// try {
// const files = fs.readdirSync(dir);
// Object.keys(files).map((i) => {
// const filename = path.basename(files[i]);
// const index = filename.indexOf('.repository.');
// if (index !== -1) {
// const identity = `${ServiceDecoratorUtil.getResourceName(filename.substring(0, index))}Resource`;
// // let router = require(dir + '/' + filename).default;
// const manager = require(`${dir}/${filename}`);
// const m = new manager[identity]();
// list.push(m);
// }
// });
// } catch (error) {
// console.log(error);
// }
// return list;
// };
static configureInject(target) {
let injects: any[] = [];
const proto = target.prototype;
try {
injects = Object.getOwnPropertyNames(proto).filter(prop => prop.indexOf(INJECT_PREFIX) === 0);
injects = injects.map(prop => {
const injectName = prop.substring(INJECT_PREFIX.length);
const injectProps = {
...proto[prop],
injectName,
};
return injectProps;
});
target.prototype.injects = target.prototype.injects ? target.prototype.injects.concat(injects) : injects;
} catch (error) {
console.log(error);
}
return injects;
}
// static configureResource (root: string, app?: any) {
// ServiceDecoratorUtil.loadResource(root);
// };
}
<file_sep>export declare class HttpStatus {
static OK: number;
static CREATED: number;
static ACCEPTED: number;
static NO_CONTENT: number;
static RESET_CONTENT: number;
static BAD_REQUEST: number;
static UNAUTHORIZED: number;
static FORBIDDEN: number;
static NOT_FOUND: number;
static METHOD_NOT_ALLOWED: number;
static NOT_ACCEPTABLE: number;
static REQUEST_TIMEOUT: number;
static CONFLICT: number;
static UNPROCESSABLE_ENTITY: number;
static INTERNAL_SERVER_ERROR: number;
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseExceptionHandler = void 0;
const common_1 = require("@lettuce/common");
class BaseExceptionHandler extends common_1.Base {
constructor() {
super(...arguments);
this.list = [];
}
static handle(error, list) {
for (let i = 0; i < list.length; i++) {
const prop = list[i];
if (error instanceof prop.rescueFrom) {
return prop.with.apply(null, [error]);
}
}
return {
message: 'Unknown Error',
status: 500,
};
}
}
exports.BaseExceptionHandler = BaseExceptionHandler;
<file_sep>/// <reference types="node" />
import * as http from 'http';
export declare class ServerUtil {
static configureServer: (server: http.Server) => http.Server;
static startServer: (server: http.Server) => void;
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidObjectIdError = exports.RecordNotFoundError = exports.MissingVersionError = exports.InvalidUsernameError = exports.InvalidTokenError = exports.MissingTokenError = exports.AuthenticationError = exports.ApiError = void 0;
class ApiError extends Error {
constructor(message, status, isPublic) {
super(message);
this.message = message;
this.status = status;
this.isPublic = isPublic;
}
}
exports.ApiError = ApiError;
class AuthenticationError extends ApiError {
}
exports.AuthenticationError = AuthenticationError;
class MissingTokenError extends ApiError {
}
exports.MissingTokenError = MissingTokenError;
class InvalidTokenError extends ApiError {
}
exports.InvalidTokenError = InvalidTokenError;
class InvalidUsernameError extends ApiError {
}
exports.InvalidUsernameError = InvalidUsernameError;
class MissingVersionError extends ApiError {
}
exports.MissingVersionError = MissingVersionError;
class RecordNotFoundError extends ApiError {
}
exports.RecordNotFoundError = RecordNotFoundError;
class InvalidObjectIdError extends ApiError {
}
exports.InvalidObjectIdError = InvalidObjectIdError;
<file_sep>import { ServiceDecoratorUtil } from './ServiceDecoratorUtil';
export const Service = () => {
return target => {
target.prototype.injectable = true;
ServiceDecoratorUtil.configureInject(target);
};
};
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpStatus = void 0;
class HttpStatus {
}
exports.HttpStatus = HttpStatus;
HttpStatus.OK = 200;
HttpStatus.CREATED = 201;
HttpStatus.ACCEPTED = 202;
HttpStatus.NO_CONTENT = 204;
HttpStatus.RESET_CONTENT = 205;
HttpStatus.BAD_REQUEST = 400;
HttpStatus.UNAUTHORIZED = 401;
HttpStatus.FORBIDDEN = 403;
HttpStatus.NOT_FOUND = 404;
HttpStatus.METHOD_NOT_ALLOWED = 405;
HttpStatus.NOT_ACCEPTABLE = 406;
HttpStatus.REQUEST_TIMEOUT = 408;
HttpStatus.CONFLICT = 409;
HttpStatus.UNPROCESSABLE_ENTITY = 422;
HttpStatus.INTERNAL_SERVER_ERROR = 500;
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongooseUtil = void 0;
var MongooseUtil_1 = require("./MongooseUtil");
Object.defineProperty(exports, "MongooseUtil", { enumerable: true, get: function () { return MongooseUtil_1.MongooseUtil; } });
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServerUtil = void 0;
const logger_1 = require("@lettuce/logger");
const DefaultPort = 5555;
let PORT = process.env.PORT || DefaultPort;
function onError(error) {
PORT = process.env.PORT || DefaultPort;
if (error.syscall !== 'listen')
throw error;
const bind = typeof PORT === 'string' ? `Pipe ${PORT}` : `Port ${PORT}`;
switch (error.code) {
case 'EACCES':
logger_1.Logger.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
logger_1.Logger.error(`${bind} is already in use`);
process.exit(1);
break;
case 'SIGTERM':
logger_1.Logger.error(error.stack ? error.stack : error.toString());
process.exit(1);
break;
case 'SIGINT':
logger_1.Logger.error(error.stack ? error.stack : error.toString());
process.exit(1);
break;
default:
logger_1.Logger.log(error.stack ? error.stack : error.toString());
throw error;
}
}
function onListening() {
PORT = process.env.PORT || DefaultPort;
logger_1.Logger.info(`server started on http://127.0.0.1:${PORT}; press Ctrl-C to terminate.`);
}
class ServerUtil {
}
exports.ServerUtil = ServerUtil;
ServerUtil.configureServer = (server) => {
PORT = process.env.PORT || DefaultPort;
server.on('error', onError);
server.on('listening', onListening);
return server;
};
ServerUtil.startServer = (server) => {
PORT = process.env.PORT || DefaultPort;
server.listen(PORT);
};
<file_sep>export { IRescueProp } from './IRescueProp';
export { IRescueResultProp } from './IRescueResultProp';
export { Message } from './Message';
export { BaseExceptionHandler } from './BaseExceptionHandler';
export { ErrorUtil } from './ErrorUtil';
export {
ApiError,
AuthenticationError,
MissingTokenError,
InvalidTokenError,
InvalidUsernameError,
MissingVersionError,
RecordNotFoundError,
InvalidObjectIdError,
} from './ApiError';
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SkipAfterAction = exports.AfterAction = exports.SkipBeforeAction = exports.BeforeAction = void 0;
var hook_decorator_1 = require("./hook.decorator");
Object.defineProperty(exports, "BeforeAction", { enumerable: true, get: function () { return hook_decorator_1.BeforeAction; } });
Object.defineProperty(exports, "SkipBeforeAction", { enumerable: true, get: function () { return hook_decorator_1.SkipBeforeAction; } });
Object.defineProperty(exports, "AfterAction", { enumerable: true, get: function () { return hook_decorator_1.AfterAction; } });
Object.defineProperty(exports, "SkipAfterAction", { enumerable: true, get: function () { return hook_decorator_1.SkipAfterAction; } });
<file_sep>export declare class ApiError extends Error {
message: string;
status?: string;
isPublic?: boolean;
constructor(message: any, status?: any, isPublic?: boolean);
}
export declare class AuthenticationError extends ApiError {
}
export declare class MissingTokenError extends ApiError {
}
export declare class InvalidTokenError extends ApiError {
}
export declare class InvalidUsernameError extends ApiError {
}
export declare class MissingVersionError extends ApiError {
}
export declare class RecordNotFoundError extends ApiError {
}
export declare class InvalidObjectIdError extends ApiError {
}
<file_sep>export interface IAfterActionProps {
hook: Function;
except?: string[];
only?: string[];
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Lettuce = void 0;
var Lettuce_1 = require("./Lettuce");
Object.defineProperty(exports, "Lettuce", { enumerable: true, get: function () { return Lettuce_1.Lettuce; } });
<file_sep>export declare class MongooseUtil {
static configureMongoose: (url?: string, options?: any) => Promise<void>;
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceDecoratorUtil = exports.INJECT_PREFIX = void 0;
require("reflect-metadata");
exports.INJECT_PREFIX = '$$inject_';
class ServiceDecoratorUtil {
// static getResourceName(filename) {
// const list = filename.split('-');
// let id = '';
// try {
// for (let i = 0; i < list.length; i++) {
// const part = list[i];
// id += part.charAt(0).toUpperCase() + part.slice(1);
// }
// } catch (error) {
// console.log(error);
// }
// return id;
// }
// static loadResource (root: string) {
// const dir = root;
// const list: any[] = [];
// try {
// const files = fs.readdirSync(dir);
// Object.keys(files).map((i) => {
// const filename = path.basename(files[i]);
// const index = filename.indexOf('.repository.');
// if (index !== -1) {
// const identity = `${ServiceDecoratorUtil.getResourceName(filename.substring(0, index))}Resource`;
// // let router = require(dir + '/' + filename).default;
// const manager = require(`${dir}/${filename}`);
// const m = new manager[identity]();
// list.push(m);
// }
// });
// } catch (error) {
// console.log(error);
// }
// return list;
// };
static configureInject(target) {
let injects = [];
const proto = target.prototype;
try {
injects = Object.getOwnPropertyNames(proto).filter(prop => prop.indexOf(exports.INJECT_PREFIX) === 0);
injects = injects.map(prop => {
const injectName = prop.substring(exports.INJECT_PREFIX.length);
const injectProps = Object.assign(Object.assign({}, proto[prop]), { injectName });
return injectProps;
});
target.prototype.injects = target.prototype.injects ? target.prototype.injects.concat(injects) : injects;
}
catch (error) {
console.log(error);
}
return injects;
}
}
exports.ServiceDecoratorUtil = ServiceDecoratorUtil;
<file_sep>export { JsonWebToken } from './JsonWebToken';
export { PasswordUtil } from './PasswordUtil';
<file_sep>import 'reflect-metadata';
export declare const INJECT_PREFIX = "$$inject_";
export declare class InjectUtil {
static getResourceName(filename: any): string;
static loadResource(root: string): any[];
static configureInject(target: any): any[];
static configureResource(root: string, app?: any): void;
}
<file_sep>export class HttpStatus {
public static OK = 200;
public static CREATED = 201;
public static ACCEPTED = 202;
public static NO_CONTENT = 204;
public static RESET_CONTENT = 205;
public static BAD_REQUEST = 400;
public static UNAUTHORIZED = 401;
public static FORBIDDEN = 403;
public static NOT_FOUND = 404;
public static METHOD_NOT_ALLOWED = 405;
public static NOT_ACCEPTABLE = 406;
public static REQUEST_TIMEOUT = 408;
public static CONFLICT = 409;
public static UNPROCESSABLE_ENTITY = 422;
public static INTERNAL_SERVER_ERROR = 500;
}
<file_sep>import { Base } from '@lettuce/common';
import { ApiError } from './ApiError';
import { IRescueProp } from './IRescueProp';
import { IRescueResultProp } from './IRescueResultProp';
export class BaseExceptionHandler extends Base {
public list: IRescueProp[] = [];
static handle(error: ApiError, list: IRescueProp[]): IRescueResultProp {
for (let i = 0; i < list.length; i++) {
const prop = list[i];
if (error instanceof prop.rescueFrom) {
return prop.with.apply(null, [error]);
}
}
return {
message: 'Unknown Error',
status: 500,
};
}
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpStatus = void 0;
var HttpStatus_1 = require("./HttpStatus");
Object.defineProperty(exports, "HttpStatus", { enumerable: true, get: function () { return HttpStatus_1.HttpStatus; } });
<file_sep>import 'reflect-metadata';
import { INJECT_PREFIX, InjectUtil } from './InjectUtil';
export function Inject(props?: any) {
return function (target: any, name: string) {
const tokens = Reflect.getMetadata('design:type', target, name) || [];
target[`${INJECT_PREFIX}${name}`] = { source: tokens };
};
}
export const Injectable = () => {
return target => {
target.prototype.injectable = true;
};
};
export const Consumer = (args?: string) => {
return target => {
InjectUtil.configureInject(target);
};
};
<file_sep>import * as JWT from 'jsonwebtoken';
import { InvalidTokenError } from '@lettuce/error';
export class JsonWebToken {
static SECRET = process.env.JWT_SECRET || '1d62ada3461$a091c38c95c!0388c8a1a2';
public static encode(payload: any) {
const token = JWT.sign(payload, JsonWebToken.SECRET, { expiresIn: '300d' });
return token;
}
public static decode(token: string) {
let body: string | object = '';
try {
body = JWT.verify(token, JsonWebToken.SECRET);
} catch (error) {
throw new InvalidTokenError(error.message);
}
return body;
}
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongooseUtil = void 0;
const mongoose = require("mongoose");
class MongooseUtil {
}
exports.MongooseUtil = MongooseUtil;
MongooseUtil.configureMongoose = async (url, options) => {
const DB_URL = url || process.env.MONGODB_URI || '';
try {
await mongoose.connect(DB_URL, options);
}
catch (error) {
console.log(error.message);
}
};
<file_sep>export class ApiError extends Error {
message: string;
status?: string;
isPublic?: boolean;
constructor(message: any, status?: any, isPublic?: boolean) {
super(message);
this.message = message;
this.status = status;
this.isPublic = isPublic;
}
}
export class AuthenticationError extends ApiError {}
export class MissingTokenError extends ApiError {}
export class InvalidTokenError extends ApiError {}
export class InvalidUsernameError extends ApiError {}
export class MissingVersionError extends ApiError {}
export class RecordNotFoundError extends ApiError {}
export class InvalidObjectIdError extends ApiError {}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.All = exports.Del = exports.Delete = exports.Patch = exports.Put = exports.Post = exports.Get = exports.Options = exports.Head = exports.Route = void 0;
const ActionDecoratorUtil_1 = require("./ActionDecoratorUtil");
const inject_1 = require("@lettuce/inject");
const { ROUTE_PREFIX } = ActionDecoratorUtil_1.ActionDecoratorUtil;
const Route = (args) => {
const ctrlPath = ActionDecoratorUtil_1.ActionDecoratorUtil.DestructApiDecorator(args).path;
return target => {
const proto = target.prototype;
let routes = Object.getOwnPropertyNames(proto).filter(prop => prop.indexOf(ROUTE_PREFIX) === 0);
routes = routes.map(prop => {
const { method, path, middlewareList } = proto[prop];
// const url = `${ctrlPath}${path}`;
const url = `${path}`;
const actionName = prop.substring(ROUTE_PREFIX.length);
const routeProps = {
method: method === 'del' ? 'delete' : method,
url,
middlewareList,
actionName,
};
return routeProps;
});
target.prototype.path =
target.prototype.path && target.prototype.path !== '/' ? target.prototype.path + ctrlPath : ctrlPath;
target.prototype.routes = routes;
inject_1.InjectUtil.configureInject(target);
};
};
exports.Route = Route;
function route(method, ...args) {
if (typeof method !== 'string') {
throw new Error('The first argument must be an HTTP method');
}
const { path, middlewareList } = ActionDecoratorUtil_1.ActionDecoratorUtil.DestructRouteDecorator(args);
return function (target, name, descriptor) {
target[`${ROUTE_PREFIX}${name}`] = {
method,
path,
middlewareList,
};
};
}
const Head = route.bind(null, 'head');
exports.Head = Head;
const Options = route.bind(null, 'options');
exports.Options = Options;
const Get = route.bind(null, 'get');
exports.Get = Get;
const Post = route.bind(null, 'post');
exports.Post = Post;
const Put = route.bind(null, 'put');
exports.Put = Put;
const Patch = route.bind(null, 'patch');
exports.Patch = Patch;
const Delete = route.bind(null, 'delete');
exports.Delete = Delete;
const Del = route.bind(null, 'del');
exports.Del = Del;
const All = route.bind(null, 'all');
exports.All = All;
<file_sep>import * as express from 'express';
export declare class AppUtil {
static configureApp: (app: any) => express.Application;
}
<file_sep>export declare class Base {
log: any;
name: string;
injects: Array<any>;
injectable: boolean;
static NAME: string;
constructor();
}
<file_sep>export { AppConfig, Lettuce } from './Lettuce';
<file_sep>import * as express from 'express';
import * as http from 'http';
import { Base } from '@lettuce/common';
import { AppUtil } from './AppUtil';
import { ServerUtil } from './ServerUtil';
import { ControllerUtil } from '@lettuce/action';
import { ErrorUtil } from '@lettuce/error';
export interface AppConfig {
appRoot: string | any;
staticRoot?: string;
cors?: any;
}
export class Lettuce extends Base {
public appConfig: AppConfig;
public app: express.Application;
public server: http.Server;
constructor(config: AppConfig) {
super();
this.appConfig = config;
this.preInitialize();
}
preInitialize() {
this.app = express();
AppUtil.configureApp(this.app);
}
initialize() {
ControllerUtil.configureController(this.appConfig.appRoot + '/controller', this.app);
ErrorUtil.configureExceptionHandler(this.appConfig.appRoot + '/error', this.app);
}
setup() {
this.server = http.createServer(this.app);
ServerUtil.configureServer(this.server);
}
startup() {
this.initialize();
this.setup();
ServerUtil.startServer(this.server);
}
}
<file_sep>import { Base } from '@lettuce/common';
export declare type Middleware = (req?: any, res?: any, next?: any) => any;
declare class ActionController extends Base {
router: any;
routes: any;
beforeActionList: any;
beforeActionSkipList: any;
afterActionList: any;
afterActionSkipList: any;
constructor();
configureRouter(router: any): void;
getFinalHooks(srcList: any, rmList: any): any[];
getHooksByName(name: string, actionList: any): any[];
}
export { ActionController };
<file_sep>/// <reference types="node" />
import * as express from 'express';
import * as http from 'http';
import { Base } from '@lettuce/common';
export interface AppConfig {
appRoot: string | any;
staticRoot?: string;
cors?: any;
}
export declare class Lettuce extends Base {
appConfig: AppConfig;
app: express.Application;
server: http.Server;
constructor(config: AppConfig);
preInitialize(): void;
initialize(): void;
setup(): void;
startup(): void;
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionController = void 0;
const common_1 = require("@lettuce/common");
class ActionController extends common_1.Base {
constructor() {
super();
this.router = undefined;
this.routes = this.routes || [];
console.log(this.routes);
this.beforeActionList = this.beforeActionList || [];
this.beforeActionSkipList = this.beforeActionSkipList || [];
this.afterActionList = this.afterActionList || [];
this.afterActionSkipList = this.afterActionSkipList || [];
}
configureRouter(router) {
for (let i = 0; i < this.routes.length; i++) {
const route = this.routes[i];
const { method, url, actionName } = route;
const baList = this.getHooksByName(actionName, this.beforeActionList);
const baSkipList = this.getHooksByName(actionName, this.beforeActionSkipList);
const finalBAList = this.getFinalHooks(baList, baSkipList);
const aaList = this.getHooksByName(actionName, this.afterActionList);
const aaSkipList = this.getHooksByName(actionName, this.afterActionSkipList);
const finalAAList = this.getFinalHooks(aaList, aaSkipList);
const action = async (req, res, next) => {
try {
const context = req.context || {};
context.body = context.body || req.body;
context.params = context.params || req.params;
context.query = context.query || req.query;
const fn = this[actionName];
console.log('actionName');
console.log(actionName);
console.log(this[actionName]);
console.log(context);
const [result, status] = await fn.apply(this, [context]);
context.result = result;
context.status = status;
req.context = context;
}
catch (error) {
next(error);
}
next();
};
const beforeActions = finalBAList || [];
const afterActions = finalAAList || [];
const middlewares = [beforeActions, action, afterActions];
router[method](url, ...middlewares, async (req, res, next) => {
try {
const { context } = req;
res.status(context.status || 200).json(context.result);
}
catch (error) {
next(error);
}
});
}
this.router = router;
}
getFinalHooks(srcList, rmList) {
const list = srcList && srcList.filter(x => rmList.indexOf(x) === -1);
return list || [];
}
getHooksByName(name, actionList) {
const list = [];
if (actionList && actionList.length) {
actionList.map((a) => {
if (!a.except && !a.only) {
list.push(a.hook);
}
else if (a.only) {
if (a.only.indexOf(name) !== -1) {
list.push(a.hook);
}
}
else if (a.except) {
if (a.except.indexOf(name) === -1) {
list.push(a.hook);
}
}
});
}
return list;
}
}
exports.ActionController = ActionController;
<file_sep>export { Inject, Injectable, Consumer } from './inject.decorator';
export { Injector } from './Injector';
export { InjectUtil } from './InjectUtil';
<file_sep>export interface IRescueResultProp {
message: string;
status: number | string;
}
<file_sep>export { ActionController } from './ActionController';
export { Route, Head, Options, Get, Post, Put, Patch, Delete, Del, All } from './ActionDecorator';
export { ControllerUtil } from './ControllerUtil';
<file_sep>import * as http from 'http';
import { Logger } from '@lettuce/logger';
const DefaultPort = 5555;
let PORT: string | number = process.env.PORT || DefaultPort;
function onError(error: NodeJS.ErrnoException): void {
PORT = process.env.PORT || DefaultPort;
if (error.syscall !== 'listen') throw error;
const bind = typeof PORT === 'string' ? `Pipe ${PORT}` : `Port ${PORT}`;
switch (error.code) {
case 'EACCES':
Logger.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
Logger.error(`${bind} is already in use`);
process.exit(1);
break;
case 'SIGTERM':
Logger.error(error.stack ? error.stack : error.toString());
process.exit(1);
break;
case 'SIGINT':
Logger.error(error.stack ? error.stack : error.toString());
process.exit(1);
break;
default:
Logger.log(error.stack ? error.stack : error.toString());
throw error;
}
}
function onListening(): void {
PORT = process.env.PORT || DefaultPort;
Logger.info(`server started on http://127.0.0.1:${PORT}; press Ctrl-C to terminate.`);
}
export class ServerUtil {
static configureServer = (server: http.Server) => {
PORT = process.env.PORT || DefaultPort;
server.on('error', onError);
server.on('listening', onListening);
return server;
};
static startServer = (server: http.Server) => {
PORT = process.env.PORT || DefaultPort;
server.listen(PORT);
};
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonWebToken = void 0;
const JWT = require("jsonwebtoken");
const error_1 = require("@lettuce/error");
class JsonWebToken {
static encode(payload) {
const token = JWT.sign(payload, JsonWebToken.SECRET, { expiresIn: '300d' });
return token;
}
static decode(token) {
let body = '';
try {
body = JWT.verify(token, JsonWebToken.SECRET);
}
catch (error) {
throw new error_1.InvalidTokenError(error.message);
}
return body;
}
}
exports.JsonWebToken = JsonWebToken;
JsonWebToken.SECRET = process.env.JWT_SECRET || '1d62ada3461$a091c38c95c!<PASSWORD>c8a1a2';
|
a3e1c5049c4249ab2a6bf096ab2069a7d8c8c37b
|
[
"JavaScript",
"TypeScript",
"Markdown",
"Shell"
] | 89
|
TypeScript
|
chazeprasad/lettuce
|
94ea53248864a6ab599a1bb3fded76e522ea862d
|
58219cc1b8d0f0afda3d9fd58c57739e36a53e30
|
refs/heads/master
|
<file_sep>class UsersController < ApplicationController
before_action :logged_in_user, only: [:edit, :update]
# user GET /users/:id(.:format) users#show
def show
@user = User.find(params[:id])
@microposts = @user.microposts.order(created_at: :desc)
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
# edit_user GET /users/:id/edit(.:format) users#edit
def edit
# @user は編集対象のユーザー
# current_user はログインしているユーザー
@user = User.find(params[:id])
if (current_user != @user)
redirect_to root_path
end
end
def update
@user = User.find(params[:id])
if (current_user != @user)
redirect_to root_path
end
if (@user.update(user_profile))
redirect_to user_path(@user.id)
# OKしょり
else
flash.now[:alert] = "更新できませんでした"
render "edit"
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
def user_profile
params.require(:user).permit(:name, :email, :password,
:password_confirmation, :profile)
end
end
|
68f1cf99694ed739c91a9673018adc68774120db
|
[
"Ruby"
] | 1
|
Ruby
|
yuriehayashi095/microposts
|
a0acd98f126c8cab8a6c89b50f36fa5d73cd6ac3
|
262dabb3f3306116bb18f081ea72d31439eac959
|
refs/heads/master
|
<repo_name>CurtisMorice/real_estate<file_sep>/database.sql
CREATE TABLE listings(
id serial primary key,
cost integer,
sqft integer,
type varchar(80),
city varchar(120),
image_path varchar(120),
);<file_sep>/server/public/scripts/services/rent.services.js
ngApp.service('RentService', function($http) {
console.log('in the RentService');
let self = this;
self.allListings = ['this is because I am bringing back an array'];
//GET to display the card to see they're for rent
self.getListing = function() {
return $http({
method: 'GET',
url: '/real_estate'
}).then((response) => {
console.log(response);
self.allListings = response.data;
}).catch((error) => {
console.log(`error getting all songs:`, error);
});
};
});<file_sep>/server/public/scripts/controllers/sales.controller.js
ngApp.controller('SalesController', function(SalesService) {
console.log('in the SalesController');
let scon = this;
scon.deleteListing = function(listing) {
console.log(listing);
}
});<file_sep>/README.md
# prime-pw-week-2-assignment
This week we introduced the programming language of the Internet, JavaScript. With JavaScript we can make our websites smart by adding interactivity and logic.
## Topics Covered
* Variables and Constants
* Conditional statements
## Assignment
As always, start off by forking and cloning this repository from GitHub. Open the code up in Atom to get started.
Remember `console.log()` is your friend and you can use it in conjunction with the browser console to see the output of your code as you go.
### Files Provided
This week you'll be completing the scripts in the following files. But note, that we have different levels of difficulty.
- [ ] *aboutMe.js* (Base, Hard, Pro)
The file contains comments with prompts on what code to write. Do not erase the comments, just write the code below each commented line.
#### Modes
Above, we introduced the concept of levels of difficulty. "Mode" is how we will typically refer to each level. Below is a brief explanation of
* what to expect when attempting each mode
* if they are required or not
Mode | Description
--- | ---
Base | required
Hard | optional, stretches your understanding
Pro | optional, stretches your understanding and may require additional research
**NOTE:** All the *.js* files are already sourced into *index.html*.
**IMPORTANT:** Don't edit or worry about any files other than the *.js* files.
### Assignment Submission
Check in your repo, then turn in your work via the <a target="_blank" href="http://www.primeacademy.io/student/assignments">Prime Academy Assignment Application</a>, as usual and don't hesitate to hit up the Slack channel as needed!
<file_sep>/server/public/scripts/controllers/rent.controller.js
ngApp.controller('RentController', function(RentService) {
console.log('in the RentController');
let self = this;
self.rentalListing = function() {
RentService.getListing().then(function() {
self.allListings = RentService.allListings;
});
}
self.rentalListing();
});<file_sep>/server/modules/routers/real_estate.router.js
const express = require('express');
const router = express.Router();
const pool = require('../pool');
//router.get
router.get('/', (req, res) => {
console.log('In real_estate GET router ', res);
const queryText = `SELECT * FROM listings`;
pool.query(queryText)
.then((result) => {
res.send(result.rows);
})
.catch((error) => {
res.sendStatus(500);
});
}); // end GET
//router.post
router.post('/', (req, res) => {
console.log('In real_estate POST router ', req.body);
let newListing = req.body;
const queryText = `INSERT INTO listings ("cost", "sqft", "type", "city", "image_path")
VALUES($1, $2, $3, $4, $5);`;
pool.query(queryText, [newListing.cost, newListing.sqft, newListing.type, newListing.city, newListing.image_path])
.then((result) => {
console.log(`successful add of listing!`, req.body);
res.sendStatus(200);
})
.catch((error) => {
res.sendStatus(500);
});
}); // end POST
//router.delete
router.delete('/:id', (req, res) => {
const realEstateId = req.params.id;
console.log('In real_estate DELETE router ', req.params.id);
const queryText = 'DELETE FROM listings WHERE id=$1';
pool.query(queryText, [realEstateId])
.then((result) => {
console.log(`successful DELETE of listing`, result);
res.sendStatus(200);
})
.catch((error) => {
console.log(`Error DELETE`, error);
res.sendStatus(500);
});
}); //end DELETE
module.exports = router;<file_sep>/server/modules/pool.js
//require in pg /postgres
const pg = require('pg');
//not a function, is an element of Pool
const Pool = pg.Pool;
//name of DB
const DATABASE_NAME = 'real_estate';
//configuration
const config = {
database: DATABASE_NAME, //the name of the database to connect to
host: 'localhost',
port: 5432,
max: 10,
idleTimeoutMillis: 30000
};
// everything above is to create what to pass into the pool variable
const pool = new Pool(config); // creating new object using the config attached to the pool
pool.on('connect', (client) => {
console.log(`Connected to the DATABASE connection ${DATABASE_NAME} from ${client}`);
});
pool.on('error', (err, client) => {
console.log(`Connected to the DATABASE connection ${client} from ${err}`);
process.exit(-1); //used to exit the db
});
module.exports = pool;<file_sep>/server/public/scripts/client.js
const ngApp = angular.module('ngApp', ['ngRoute']);
ngApp.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home.html'
}).when('/rent', {
templateUrl: 'views/rent.html'
}).when('/sales', {
templateUrl: 'views/sales.html'
}).otherwise({
template: `<h1> 404 No Bueno / C'EST PERDU</h1>`
});
});<file_sep>/server/public/scripts/services/add.services.js
ngApp.service('AddService', ['$http', function($http) {
console.log('in the AddService');
let self = this;
//POST
self.postListing = function(newListing) {
return $http({
method: 'POST',
url: '/real_estate',
data: newListing
}).then((response) => {
console.log('back from POST with:', response);
}).catch((error) => {
console.log('back from POST with:', error);
});
};
}]);<file_sep>/server/server.js
//requires
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
//ports
const port = process.env.PORT || 5000;
//uses
app.use(express.static('server/public'));
app.use(bodyParser.json());
//router
const real_estateRouter = require('./modules/routers/real_estate.router');
app.use('/real_estate', real_estateRouter);
//spin UP
app.listen(port, () => {
console.log(`you awake PORT 500`);
});
|
0fadb2824351dd5a0a1cbe01d9c33fc5ecbcfe8f
|
[
"JavaScript",
"SQL",
"Markdown"
] | 10
|
SQL
|
CurtisMorice/real_estate
|
22312b95af247a31b1d840bb3d8ce5ebd9aadd2e
|
536bfdfd7b7b9bc39cb923b64f6ccda1622864ee
|
refs/heads/master
|
<repo_name>superchen14/leetcode<file_sep>/ruby/072.rb
# @param {String} word1
# @param {String} word2
# @return {Integer}
def min_distance(word1, word2)
length1 = word1.length
length2 = word2.length
cache = []
0.upto(length1).each do |num|
cache[num] = num
end
0.upto(length2).each do |num|
cache[num * (length1 + 1)] = num
end
1.upto(length2).each do |i|
1.upto(length1).each do |j|
if word1[j - 1] == word2[i - 1]
cache[i * (length1 + 1) + j] = cache[(i - 1) * (length1 + 1) + j - 1]
else
a = cache[(i - 1) * (length1 + 1) + j]
b = cache[i * (length1 + 1) + j - 1]
c = cache[(i - 1) * (length1 + 1) + j - 1]
cache[i * (length1 + 1) + j] = [a, b, c].min + 1
end
end
end
return cache[(length1 + 1) * (length2 + 1) - 1]
end<file_sep>/ruby/056.rb
# Definition for an interval.
# class Interval
# attr_accessor :start, :end
# def initialize(s=0, e=0)
# @start = s
# @end = e
# end
# end
# @param {Interval[]} intervals
# @return {Interval[]}
def merge(intervals)
intervals.sort! {|a, b| a.start <=> b.start}
result = []
intervals.each do |interval|
if result.length == 0
result.push(interval)
else
last_end = result[-1].end
if interval.start > last_end
result.push(interval)
else
result[-1].end = interval.end if interval.end >= last_end
end
end
end
result
end<file_sep>/ruby/051_1.rb
# @param {Integer} n
# @return {String[][]}
def is_valid(board, row, col)
return false if board[row].each_with_index.any? do |item, c|
c != col && item == "Q"
end
return false if board.each_with_index.any? do |line, r|
r != row && line[col] == "Q"
end
if row >= col
return false if (row - col).upto(board.length - 1).any? do |r|
c = r - row + col
r != row && board[r][c] == "Q"
end
else
return false if 0.upto(board.length - 1 - col + row).any? do |r|
c = col - row + r
r != row && board[r][c] == "Q"
end
end
if row + col < board.length
return false if 0.upto(row + col).any? do |r|
c = row + col - r
r != row && board[r][c] == "Q"
end
else
return false if (row + col - board.length + 1).upto(board.length - 1).any? do |r|
c = row + col - r
r != row && board[r][c] == "Q"
end
end
true
end
def find_solution board, row, col, results
if row == board.length
sum = 0
board.each do |line|
line.each do |item|
sum += 1 if item == "Q"
end
end
results.push(board.map{|line| line.join("")}) if sum == board.length
return
end
return find_solution(board, row + 1, 0, results) if col == board.length
if is_valid(board, row, col)
board[row][col] = "Q"
find_solution(board, row + 1, 0, results)
board[row][col] = "."
end
find_solution(board, row, col + 1, results)
end
def solve_n_queens(n)
board = []
1.upto(n).each { board.push(Array.new(n, ".")) }
results = []
find_solution(board, 0, 0, results)
results
end<file_sep>/ruby/039.rb
def find_result(candidates, i, target, results, list)
return if target < 0
if target == 0
results.push(list.dup)
return
end
i.upto(candidates.length - 1).each do |index|
list.push(candidates[index])
find_result(candidates, index, target - candidates[index], results, list)
list.pop
end
end
# @param {Integer[]} candidates
# @param {Integer} target
# @return {Integer[][]}
def combination_sum(candidates, target)
results = []
list = []
find_result(candidates, 0, target, results, list)
results
end<file_sep>/javascript/078.js
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function(nums) {
if (nums.length === 0) return [[]];
var previousSubsets = subsets(nums.slice(0, nums.length - 1));
var lastNum = nums[nums.length - 1];
var patchedPreviousSubsets = previousSubsets.map(function(subset){ return subset.concat([lastNum]); });
return previousSubsets.concat(patchedPreviousSubsets);
};<file_sep>/javascript/140.js
/**
* @param {string} s
* @param {string[]} wordDict
* @return {string[]}
*/
var wordBreak = function(s, wordDict) {
const map = {"-1": {hasSolution: true, solutions:[[]]}};
const maxWordLength = Math.max(...wordDict.map(word => word.length));
for (let i = 0; i < s.length; ++i) {
let hasSolution = false;
let solutions = [];
wordDict.forEach(word => {
if (i + 1 >= word.length && map[i - word.length].hasSolution && s.substring(i - word.length + 1, i + 1) === word) {
hasSolution = true;
solutions.push(...map[i - word.length].solutions.map(solution => solution.concat(word)));
}
});
map[i] = {hasSolution, solutions};
if (i > maxWordLength) { delete map[i - maxWordLength - 1]; }
}
return map[s.length - 1].solutions.map(solution => solution.join(" "));
};<file_sep>/javascript/115.js
/**
* @param {string} s
* @param {string} t
* @return {number}
*/
var numDistinct = function(s, t) {
const sLength = s.length;
const tLength = t.length;
if (sLength === 0) return 0;
if (tLength === 0) return 0;
const map = (new Array(sLength));
for (let i = 0; i < s.length; ++i) { map[i] = [] }
for(let i = 0; i < sLength; ++i) {
for (let j = 0; j < tLength; ++j) {
if (i < j) {
map[i][j] = 0;
continue;
}
if (i === 0) {
map[i][j] = s[i] === t[j] ? 1 : 0;
continue;
}
if (j === 0) {
map[i][j] = map[i - 1][j] + (s[i] === t[j] ? 1 : 0);
continue;
}
let sum = map[i - 1][j];
if (s[i] === t[j]) {
sum += map[i - 1][j - 1];
}
map[i][j] = sum;
}
}
return map[sLength - 1][tLength - 1];
};<file_sep>/ruby/059.rb
# @param {Integer} n
# @return {Integer[][]}
def generate_matrix(n)
matrix = []
n.times { matrix.push(Array.new(n, 0)) }
min_col = 0
max_col = n - 1
min_row = 0
max_row = n - 1
value = 1
while true do
return matrix if min_col > max_col
min_col.upto(max_col).each do |col|
matrix[min_row][col] = value
value += 1
end
min_row += 1
return matrix if min_row > max_row
min_row.upto(max_row).each do |row|
matrix[row][max_col] = value
value += 1
end
max_col -= 1
return matrix if min_col > max_col
max_col.downto(min_col).each do |col|
matrix[max_row][col] = value
value += 1
end
max_row -= 1
return matrix if min_row > max_row
max_row.downto(min_row).each do |row|
matrix[row][min_col] = value
value += 1
end
min_col += 1
end
end<file_sep>/javascript/092.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} m
* @param {number} n
* @return {ListNode}
*/
var reverseBetween = function(head, m, n) {
if (m === n) return head;
let dummy = {val: 0, next: head};
let beforeM = dummy;
while(m > 1) {
beforeM = beforeM.next;
--m;
}
let theM = beforeM.next;
let theN = dummy;
while(n > 0) {
theN = theN.next;
--n;
}
let afterN = theN.next;
theN.next = null;
while(theM) {
let temp = theM;
theM = theM.next;
temp.next = afterN;
afterN = temp;
}
beforeM.next = afterN;
return dummy.next;
};<file_sep>/javascript/061.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var rotateRight = function(head, k) {
if (k === 0) return head;
let temp = head;
let length = 0;
let list = [];
while(temp) {
list.push(temp);
temp = temp.next;
++length;
}
let lastNode = list[length - 1];
if (length === 0) return head;
while(k > length) {
k = k - length;
}
if (k === length) return head;
let left = length - k - 1;
let leftNode = list[left];
let leftNextNode = list[left + 1];
lastNode.next = head;
leftNode.next = null;
return leftNextNode;
};<file_sep>/javascript/160.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function(headA, headB) {
if (headA === null || headB === null) return null;
let lengthA = 0;
let tempA = headA;
while(tempA) { ++lengthA; tempA = tempA.next; }
let lengthB = 0;
let tempB = headB;
while(tempB) { ++lengthB; tempB = tempB.next; }
if (lengthA > lengthB) {
let delta = lengthA - lengthB;
while(delta > 0) { headA = headA.next; --delta; }
} else {
let delta = lengthB - lengthA;
while(delta > 0) { headB = headB.next; --delta; }
}
while(headA !== null && headA !== headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
};<file_sep>/javascript/101.js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function(root) {
if (root === null) return true;
_isSymmetric = (rootA, rootB) => {
if (rootA === null && rootB === null) return true;
if (rootA === null || rootB === null) return false;
if (rootA.val !== rootB.val) return false;
return _isSymmetric(rootA.left, rootB.right) && _isSymmetric(rootA.right, rootB.left);
}
return _isSymmetric(root.left, root.right);
};<file_sep>/javascript/121.js
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
const _maxProfit = start => {
if (prices.length - start <= 1) return 0;
if (prices[start] >= prices[start + 1]) return _maxProfit(start + 1);
let maxIndex = start + 1;
let maxValue = prices[start + 1];
for (let i = start + 2; i < prices.length; ++i) {
if (prices[i] > maxValue) {
maxIndex = i;
maxValue = prices[i];
}
}
let minIndex = start;
let minValue = prices[start];
for (let i = start + 1; i < maxIndex; ++i) {
if (prices[i] < minValue) {
minIndex = i;
minValue = prices[i];
}
}
return Math.max(maxValue - minValue, _maxProfit(maxIndex + 1));
}
return _maxProfit(0);
};<file_sep>/ruby/058.rb
# @param {String} s
# @return {Integer}
def length_of_last_word(s)
s.strip!
return 0 if s.length == 0
s.split(" ")[-1].length
end<file_sep>/javascript/004.js
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findMedianSortedArrays = function(nums1, nums2) {
let nums = nums1.concat(nums2);
nums.sort(function(a, b) { return a - b; });
const length = nums1.length + nums2.length;
if (length % 2 === 0) {
return (nums[length / 2 - 1] + nums[length / 2]) / 2;
} else {
return nums[(length - 1) / 2];
}
};<file_sep>/javascript/062.js
/**
* @param {number} m
* @param {number} n
* @return {number}
*/
var uniquePaths = function(m, n) {
let map = {};
for (let row = 0; row < m; ++row) {
for (let col = 0; col < n; ++col) {
let pathCount = 0;
if (row === 0 && col === 0) {
pathCount = 1;
} else {
if (row !== 0) pathCount = pathCount + map[(row - 1) * n + col];
if (col !== 0) pathCount = pathCount + map[row * n + col - 1];
}
map[row * n + col] = pathCount;
}
}
return map[m * n - 1];
};<file_sep>/problems/043.md
Given two non-negative integers num1 and num2 represented as strings, return the product of `num1` and `num2`.
**Note:**
1. The length of both `num1` and `num2` is < 110.
2. Both `num1` and `num2` contains only digits `0-9`.
3. Both `num1` and `num2` does not contain any leading zero.
4. You **must not use any built-in BigInteger library** or **convert the inputs to integer** directly.<file_sep>/javascript/044.js
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
let v1 = 0;
let v2 = 0;
// use "*" instead of "**"
while(p.indexOf("**") !== -1) {
p = p.replace("**", "*");
}
let v1Restart = -1;
let v2Restart = -1;
while(v1 < s.length) {
if (v2 < p.length && p[v2] === "*") {
v1Restart = v1 + 1;
v2Restart = v2++;
} else if (v2 < p.length && (p[v2] === "?" || s[v1] === p[v2])) {
++v1;
++v2;
} else if (v1Restart !== -1) {
v1 = v1Restart;
v2 = v2Restart;
} else {
break;
}
}
// if code comes here, v1 must === s.length
if (v1 < s.length) return false;
while(v2 < p.length && p[v2] === "*") {
++v2;
}
return v2 === p.length;
};<file_sep>/ruby/022.rb
# @param {Integer} n
# @return {String[]}
def generate_parenthesis(n)
return [] if n == 0
return ["()"] if n == 1
parent_results = generate_parenthesis(n - 1)
results = []
parent_results.each do |r|
r.each_char.with_index do |char, i|
if char == "("
if i == 0
results.push("()" + r)
results.push("(()" + r[1..-1]);
else
results.push(r[0..i-1] + "()" + r[i..-1])
results.push(r[0..i] + "()" + r[i+1..-1])
end
end
end
end
results.uniq
end<file_sep>/ruby/040.rb
def find_result(candidates, i, target, results, list)
if target == 0
results.push(list.dup)
return
end
return if target < 0
return if i == candidates.length
i.upto(candidates.length - 1).each do |index|
next if index > i && candidates[index] == candidates[index - 1]
list.push(candidates[index])
find_result(candidates, index + 1, target - candidates[index], results, list)
list.pop
end
end
# @param {Integer[]} candidates
# @param {Integer} target
# @return {Integer[][]}
def combination_sum2(candidates, target)
candidates.sort!
results = []
list = []
find_result(candidates, 0, target, results, list)
results
end<file_sep>/javascript/105.js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function(preorder, inorder) {
if (preorder.length === 0) return null;
if (preorder.length === 1) return new TreeNode(preorder[0]);
const mid = preorder[0];
const index = inorder.indexOf(mid);
const inorderLeft = inorder.slice(0, index);
const inorderRight = inorder.slice(index + 1, inorder.length);
const preorderLeft = preorder.slice(1, inorderLeft.length + 1);
const preorderRight = preorder.slice(inorderLeft.length + 1, preorder.length);
const returnValue = new TreeNode(mid);
returnValue.left = buildTree(preorderLeft, inorderLeft);
returnValue.right = buildTree(preorderRight, inorderRight);
return returnValue;
};<file_sep>/javascript/069.js
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function(x) {
if (x <= 0) return 0;
var start = 0;
var end = x;
while(true) {
var temp = parseInt((start + end) / 2);
var squareTemp = temp * temp;
if (squareTemp === x) return temp;
if (squareTemp < x && (temp + 1) * (temp + 1) > x) return temp;
if (squareTemp > x) {
end = temp;
} else {
start = temp + 1;
}
}
};<file_sep>/ruby/035.rb
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer}
def search_insert(nums, target)
return 0 if target <= nums[0]
return nums.length if target > nums[-1]
i = 1
while nums[i] < target do
i += 1
end
i
end<file_sep>/ruby/023.rb
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode[]} lists
# @return {ListNode}
def merge_k_lists(lists)
array = []
lists.each do |list|
while !list.nil? do
array.push(list.val)
list = list.next
end
end
array.sort!
dummy = ListNode.new(0)
head = dummy
array.each do |val|
head.next = ListNode.new(val)
head = head.next
end
dummy.next
end<file_sep>/ruby/006.rb
# @param {String} s
# @param {Integer} num_rows
# @return {String}
def convert(s, num_rows)
string_rows = Array.new(num_rows)
num_rows.times { |index| string_rows[index] = []}
return s if num_rows == 1
mod_value = 2 * num_rows - 2
s.each_char.with_index do |char, index|
mod = index % mod_value
if mod >= num_rows
mod = num_rows - (mod - num_rows + 2)
end
string_rows[mod].push char
end
return string_rows.map{|row| row.join("")}.join("")
end<file_sep>/javascript/084.js
/**
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function(heights) {
let stack = [];
let result = 0;
heights.forEach(height => {
if (stack.length === 0 || stack[stack.length - 1] <= height) {
stack.push(height);
} else {
let count = 0;
while (stack.length > 0 && stack[stack.length - 1] > height) {
++count;
const h = stack.pop();
if (h * count > result) result = h * count;
}
while (count >= 0) {
stack.push(height);
--count;
}
}
});
const length = stack.length;
for(let i = 0; i < length; ++i) {
const value = stack[i] * (length - i);
if (value > result) result = value;
}
return result;
};<file_sep>/ruby/080.rb
# @param {Integer[]} nums
# @return {Integer}
def remove_duplicates(nums)
current = 0
current_value = nums[0]
current_count = 0
0.upto(nums.length - 1) do |i|
if nums[i] == current_value
if current_count < 2
nums[current] = nums[i]
current_count += 1
current += 1
end
else
current_value = nums[i]
current_count = 1
nums[current] = current_value
current += 1
end
end
current
end<file_sep>/javascript/007.js
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
var positiveMax = (1 << 30) * 2 - 1;
var isNegative = false;
if (x < 0) {
x = -x;
isNegative = true;
}
var result = 0;
while(true) {
var remain = x % 10;
result = result * 10 + remain;
if (result > positiveMax) return 0;
if (x - remain === 0) { break; }
x = (x - remain) / 10;
}
if (isNegative) { result = -result; }
return result;
};<file_sep>/javascript/015.js
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
nums.sort((a, b) => a - b);
let result = [];
const length = nums.length;
let lastValue = nums[0] - 1;
for(var i = 0; nums[i] <= 0; ++i) {
if (nums[i] === lastValue) continue;
lastValue = nums[i];
let j = i + 1;
let k = length - 1;
const target = -nums[i];
while(i < j && j < k && k < length) {
const currentTarget = nums[j] + nums[k];
if (currentTarget === target) {
result.push([nums[i], nums[j], nums[k]]);
const currentJValue = nums[j];
while(++j < k && nums[j] === currentJValue){};
continue;
} else if (currentTarget > target) {
--k;
} else {
++j;
}
}
}
return result;
};<file_sep>/javascript/127.js
/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
var ladderLength = function(beginWord, endWord, wordList) {
var wordHash = {};
wordList.forEach(function(w){ wordHash[w] = true; });
if (!wordHash[endWord]) return 0;
const getSimilarWords = word => {
const similarWords = [];
for (let i = 0; i < word.length; ++i) {
var alphabets = "abcdefghijklmnopqrstuvwxyz";
for (let j = 0; j < 26; ++j) {
if (alphabets[j] == word[i]) continue;
const similarWord = word.substring(0, i) + alphabets[j] + word.substring(i + 1);
if (wordHash[similarWord]) similarWords.push(similarWord);
}
}
return similarWords;
}
const depthHash = {};
depthHash[beginWord] = 1;
const array = [beginWord];
while(array.length > 0) {
const currentWord = array.shift();
const similarWords = getSimilarWords(currentWord, wordHash);
for (let i = 0; i < similarWords.length; ++i) {
const similarWord = similarWords[i];
if (similarWord == endWord) return depthHash[currentWord] + 1;
depthHash[similarWord] = depthHash[currentWord] + 1;
delete wordHash[similarWord];
array.push(similarWord);
}
}
return 0;
};<file_sep>/ruby/061.rb
# Definition for singly-linked list.
class ListNode
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
# @param {ListNode} head
# @param {Integer} k
# @return {ListNode}
def rotate_right(head, k)
return nil if head.nil?
dummy_node = ListNode.new(0)
dummy_node.next = head
length = 0
temp = dummy_node.next
list_tail = temp
while !temp.nil? do
list_tail = temp
length += 1
temp = temp.next
end
k = k % length
return head if k == 0
k = length - k
k_node = dummy_node
while k > 0 do
k_node = k_node.next
k -= 1
end
list_tail.next = dummy_node.next
dummy_node.next = k_node.next
k_node.next = nil
dummy_node.next
end<file_sep>/ruby/041.rb
# @param {Integer[]} nums
# @return {Integer}
def first_missing_positive(nums)
length = nums.length
0.upto(length - 1).each do |i|
next if nums[i] > length || nums[i] <= 0
while true do
break if nums[i] > length || nums[i] <= 0
target_index = nums[i] - 1
break if target_index == i
break if nums[i] == nums[target_index]
nums[i], nums[target_index] = nums[target_index], nums[i]
end
end
result = 1
while nums[result - 1] == result do
result += 1
end
result
end<file_sep>/javascript/079.js
/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function(board, word) {
var usedBoard = [];
var iMax = board.length - 1;
var jMax = board[0].length - 1;
for(var i = 0; i <= iMax; ++i) {
usedBoard.push([]);
for(var j = 0; j <= jMax; ++j) {
usedBoard[i].push(false);
}
}
// make sure usedBoard[i][j] === false before call this method
function existWithStartPos(i, j, word) {
if (i > iMax || i < 0 || j > jMax || j < 0) return false;
if (board[i][j] !== word[0]) return false;
if (usedBoard[i][j]) return false;
if (word.length === 1) {
if (board[i][j] === word[0]) {
return true;
} else {
return false;
}
}
usedBoard[i][j] = true;
if (existWithStartPos(i + 1, j, word.substring(1))) return true;
if (existWithStartPos(i - 1, j, word.substring(1))) return true;
if (existWithStartPos(i, j + 1, word.substring(1))) return true;
if (existWithStartPos(i, j - 1, word.substring(1))) return true;
usedBoard[i][j] = false;
return false;
}
for(var i = 0; i <= iMax; ++i) {
for(var j = 0; j <= jMax; ++j) {
if(existWithStartPos(i, j, word)) return true;
}
}
return false;
};<file_sep>/ruby/034.rb
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def search_range(nums, target)
first_index = nums.index(target)
return [-1, -1] if first_index.nil?
second_index = first_index
while second_index < nums.length && nums[second_index + 1] == target do
second_index += 1
end
[first_index, second_index]
end
search_range([1, 2, 2, 3], 4)<file_sep>/javascript/033.js
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
const binarySearch = (start, end) => {
// TODO: should use truely binary search implementation
if (start === end) return -1;
if (start + 1 === end) return nums[start] === target;
if (target < nums[start]) return -1;
if (target > nums[end - 1]) return -1;
for (let i = start; i < end; ++i) {
if (nums[i] === target) return i;
}
return -1;
}
const _search = (start, end) => {
if (start === end) return -1;
if (start + 1 === end) return nums[start] === target ? start : -1;
if (nums[start] < nums[end - 1]) {
// start to end is sorted sub-array
return binarySearch(start, end);
} else {
// start to end is rotated sub-array
const mid = Number.parseInt((start + end) / 2);
if (target === nums[mid]) return mid;
const index1 = _search(start, mid);
if (index1 !== -1) return index1;
return _search(mid + 1, end);
}
}
return _search(0, nums.length);
};<file_sep>/javascript/143.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderList = function(head) {
if (head === null) return;
if (head.next === null) return;
const getLastNode = node => {
while(node.next) {
node = node.next;
}
return node;
}
const getNode = (node, nextNode) => {
while(node.next !== nextNode) {
node = node.next;
}
return node;
}
let current = head;
let next = current.next;
let lastNode = getLastNode(next);
while(lastNode !== next && lastNode !== current && current) {
current.next = lastNode;
lastNode.next = next;
lastNode = getNode(next, lastNode);
lastNode.next = null;
current = next;
next = current.next;
}
};<file_sep>/javascript/108.js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function(nums) {
if (nums.length === 0) return null;
if (nums.length === 1) return new TreeNode(nums[0]);
const midIndex = Number.parseInt(nums.length / 2);
const returnValue = new TreeNode(nums[midIndex]);
returnValue.left = sortedArrayToBST(nums.slice(0, midIndex));
returnValue.right = sortedArrayToBST(nums.slice(midIndex + 1, nums.length));
return returnValue;
};<file_sep>/javascript/086.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} x
* @return {ListNode}
*/
var partition = function(head, x) {
let partition1Head = null;
let partition1 = null;
let partition2Head = null;
let partition2 = null;
let current = head;
while(current) {
if (current.val < x) {
if (partition1 === null) {
partition1 = current;
partition1Head = current;
} else {
partition1.next = current;
partition1 = current;
}
} else {
if (partition2 === null) {
partition2 = current;
partition2Head = current;
} else {
partition2.next = current;
partition2 = current;
}
}
current = current.next;
}
if (partition1 !== null) { partition1.next = partition2Head; }
if (partition2 !== null) { partition2.next = null; }
if (partition1Head !== null) return partition1Head;
return partition2Head;
};<file_sep>/javascript/068.js
/**
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
var fullJustify = function(words, maxWidth) {
let results = [];
let itemCount = 0;
let currentlength = 0;
let currentWords = [];
words.forEach(word => {
if (currentlength + itemCount * 1 + word.length <= maxWidth) {
currentWords.push(word);
currentlength += word.length;
itemCount += 1;
} else {
results.push(currentWords);
currentWords = [word];
itemCount = 1;
currentlength = word.length;
}
});
if (currentWords.length > 0) {
results.push(currentWords);
}
const getLineStr = (wordsInLine, isLastLine) => {
if (wordsInLine.length === 1) {
let word = wordsInLine[0];
spaceCount = maxWidth - word.length;
while(spaceCount > 0) {
word = word + " ";
--spaceCount;
}
return word;
} else if (isLastLine) {
let word = wordsInLine.join(" ");
spaceCount = maxWidth - word.length;
while(spaceCount > 0) {
word = word + " ";
--spaceCount;
}
return word;
} else {
let spaceCount = maxWidth - wordsInLine.reduce((sum, w) => {return sum + w.length}, 0);
let slotCount = wordsInLine.length - 1;
let value = Number.parseInt(spaceCount / slotCount);
spaceCount -= slotCount * value;
let slots = (new Array(slotCount)).fill(value);
let i = 0;
while(spaceCount > 0) {
slots[i] += 1;
--spaceCount;
++i;
}
let result = wordsInLine[0];
for (let i = 1; i < wordsInLine.length; ++i) {
result += ((new Array(slots[i - 1])).fill(" ").join("") + wordsInLine[i]);
}
return result;
}
}
if (results.length === 1) {
return results.map(wordsInLine => getLineStr(wordsInLine, true));
} else {
let lastOne = results[results.length - 1];
results.pop();
return results.map(wordsInLine => getLineStr(wordsInLine, false)).concat(getLineStr(lastOne, true));
}
};<file_sep>/javascript/141.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if (head === null) return false;
let twoStepNode = head;
let oneStepNode = head;
while(twoStepNode) {
twoStepNode = twoStepNode.next;
if (twoStepNode === null) return false;
twoStepNode = twoStepNode.next;
if (twoStepNode === null) return false;
oneStepNode = oneStepNode.next;
if (oneStepNode === twoStepNode) return true;
}
};<file_sep>/javascript/038.js
/**
* @param {number} n
* @return {string}
*/
var countAndSay = function(n) {
if (n === 1) return "1";
strValue = countAndSay(n - 1);
let number = "";
let count = 0;
let result = ""
while(strValue.length > 0) {
if (strValue[0] === number) {
++count;
} else {
if (count > 0) result = result + count + number;
number = strValue[0];
count = 1;
}
strValue = strValue.substring(1);
}
result = result + count + number;
return result;
};<file_sep>/ruby/025.rb
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} head
# @param {Integer} k
# @return {ListNode}
def reverse_k_group(head, k)
return head if head.nil?
return head if k == 1
result = head
current = head
while true do
return head if current.nil?
temp = k
current_k = current
values = []
while temp > 0 do
values.push(current_k.val)
current_k = current_k.next
break if current_k.nil?
temp -= 1
end
return head if values.length < k
values.reverse!
temp = k
while temp > 0 do
current.val = values.shift
current = current.next
temp -= 1
end
end
end<file_sep>/ruby/045.rb
def jump_range(nums, start, last)
next_start = last + 1
next_end = last + 1
start.upto(last) do |i|
next_end = nums[i] + i if nums[i] + i > next_end
end
if next_end >= nums.length - 1
return 1
else
return jump_range(nums, next_start, next_end) + 1
end
end
# @param {Integer[]} nums
# @return {Integer}
def jump(nums)
return 0 if nums.length == 1
jump_range(nums, 0, 0)
end<file_sep>/javascript/030.js
/**
* @param {string} s
* @param {string[]} words
* @return {number[]}
*/
var findSubstring = function(s, words) {
const getMap = () => {
let map = {};
words.forEach(word => {
if (word in map) {
map[word] = map[word] + 1;
} else {
map[word] = 1;
}
});
return map;
}
if (words.length === 0) return [];
let wordLength = words[0].length;
let results = [];
for(let i = 0; i <= s.length - wordLength * words.length; i = i + 1) {
let map = getMap();
let j = i;
while(j <= s.length - wordLength) {
const subString = s.substr(j, wordLength);
if (subString in map) {
if (map[subString] === 1) {
delete map[subString];
} else {
map[subString] = map[subString] - 1;
}
j = j + wordLength;
} else {
break;
}
}
if (Object.keys(map).length === 0) results.push(i);
}
return results;
};<file_sep>/ruby/020.rb
# @param {String} s
# @return {Boolean}
def is_valid(s)
is_valid = true
list = []
s.each_char do |char|
case char
when "(", "[", "{"
list.push(char)
when ")"
if list[-1] == "("
list.pop
else
is_valid = false
break
end
when "]"
if list[-1] == "["
list.pop
else
is_valid = false
break
end
when "}"
if list[-1] == "{"
list.pop
else
is_valid = false
break
end
end
end
is_valid && list.empty?
end<file_sep>/javascript/034.js
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {
var start = 0;
var end = nums.length - 1;
if (target < nums[start] || target > nums[end]) return [-1, -1];
var targetIndex = -1;
do {
if (nums[start] === target) {
targetIndex = start;
break;
}
if (nums[end] === target) {
targetIndex = end;
break;
}
var mid = Number.parseInt((start + end) / 2);
if (nums[mid] === target) {
targetIndex = mid;
break;
} else if (nums[mid] < target) {
start = mid;
} else {
end = mid;
}
}while(start < end - 1);
if (targetIndex < 0) return [-1, -1];
start = targetIndex;
end = targetIndex;
while(start > 0 && nums[start - 1] === target) { --start; }
while(end < nums.length - 1 && nums[end + 1] === target) { ++end; }
return [start, end];
};<file_sep>/javascript/070.js
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
fibonacci = [];
for (var i = 1; i <= n; ++i) {
if (i === 1) { fibonacci.push(1); continue; }
if (i === 2) { fibonacci.push(2); continue; }
fibonacci.push(fibonacci[i - 3] + fibonacci[i - 2]);
}
return fibonacci[n - 1];
};<file_sep>/javascript/045.js
/**
* @param {number[]} nums
* @return {number}
*/
var jump = function(nums) {
if (nums.length <= 1) return 0;
const maxIndex = nums.length - 1;
let jumpTimes = 0;
let index = 0;
let maxReach = 0;
let i = 0;
while(maxReach < maxIndex) {
// check [index, maxReach] can react maxIndex
let nextMaxReach = maxReach;
for(; i <= maxReach; ++i) {
const currentReach = i + nums[i];
if (currentReach > nextMaxReach) nextMaxReach = currentReach;
}
++jumpTimes;
maxReach = nextMaxReach;
}
return jumpTimes;
};<file_sep>/javascript/071.js
/**
* @param {string} path
* @return {string}
*/
var simplifyPath = function(path) {
const subPaths = path.split("/");
const stack = [];
subPaths.forEach(subPath => {
if (subPath === "" || subPath === ".") return;
if (subPath === "..") {
if (stack.length > 0) { stack.pop(); }
return;
}
stack.push(subPath);
});
return "/" + stack.join("/");
};<file_sep>/ruby/033.rb
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer}
def search_with_index(nums, start_index, end_index, target)
if (start_index + end_index) % 2 == 0
mid_index = (start_index + end_index) / 2
else
mid_index = (start_index + end_index - 1) / 2
end
return -1 if start_index > end_index
return mid_index if nums[mid_index] == target
return search_with_index(nums, mid_index + 1, end_index, target) if mid_index == start_index
if nums[start_index] < nums[mid_index]
# first part is ascending array
if target < nums[mid_index] && target >= nums[start_index]
search_with_index(nums, start_index, mid_index, target)
start_index.upto(mid_index).each do |i|
return i if nums[i] == target
end
return -1
else
search_with_index(nums, mid_index + 1, end_index, target)
end
else
# second part is ascending array
if target >= nums[mid_index + 1] && target <= nums[end_index]
(mid_index + 1).upto(end_index).each do |i|
return i if nums[i] == target
end
return -1
else
search_with_index(nums, start_index, mid_index, target)
end
end
end
def search(nums, target)
start_index = 0
end_index = nums.length - 1
search_with_index(nums, start_index, end_index, target)
end<file_sep>/javascript/137.js
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
const map = {};
nums.forEach(num => {
if (map[num]) {
map[num] += 1;
} else {
map[num] = 1
}
});
const key = Object.keys(map).find(key => map[key] === 1);
return Number.parseInt(key);
};<file_sep>/ruby/015.rb
# @param {Integer[]} nums
# @return {Integer[][]}
def three_sum(nums)
nums.sort!
results = []
i = 0
while i < nums.length do
j = i + 1
k = nums.length - 1
break if j >= k
target = -nums[i]
break if target < 0
while j < k do
current_target = nums[j] + nums[k]
if current_target == target
results.push([nums[i], nums[j], nums[k]])
while nums[j + 1] == nums[j] && j < k do
j += 1
end
j += 1
elsif current_target > target
k -= 1
else
j += 1
end
end
while nums[i + 1] == nums[i] && i < nums.length do
i += 1
end
i += 1
end
results
end<file_sep>/javascript/012.js
/**
* @param {number} num
* @return {string}
*/
var intToRoman = function(num) {
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const symbols = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
let roman = "";
for(var i = 0; num > 0; ++i) {
let times = Number.parseInt(num / values[i]);
num = num - times * values[i];
while(times > 0) {
roman += symbols[i];
--times;
}
}
return roman;
};<file_sep>/ruby/018.rb
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[][]}
def four_sum(nums, target)
return [] if nums.length < 4
nums.sort!
results = []
0.upto(nums.length - 4).each do |i|
(i + 1).upto(nums.length - 3) do |j|
k = j + 1
l = nums.length - 1
while(k < l) do
current_sum = nums[i] + nums[j] + nums[k] + nums[l]
if current_sum == target
results.push([nums[i], nums[j], nums[k], nums[l]])
current_k_value = nums[k]
while nums[k + 1] == current_k_value && k < l do
k += 1
end
k += 1
elsif current_sum > target
l -= 1
else
k += 1
end
end
end
end
results.uniq
end<file_sep>/ruby/042.rb
# @param {Integer[]} height
# @return {Integer}
def trap(height)
return 0 if height.length == 0
max_height = 0
max_index = -1
height.each_with_index do |h, i|
if h > max_height
max_height = h
max_index = i
end
end
volume = 0
current_max = 0
0.upto(max_index).each do |i|
if height[i] > current_max
current_max = height[i]
else
volume += (current_max - height[i])
end
end
current_max = 0
(height.length - 1).downto(max_index).each do |i|
if height[i] > current_max
current_max = height[i]
else
volume += (current_max - height[i])
end
end
volume
end<file_sep>/ruby/050.rb
# @param {Float} x
# @param {Integer} n
# @return {Float}
def my_pow(x, n)
return 1 if n == 0
return 1 / my_pow(x, -n) if n < 0
if n % 2 == 0
value = my_pow(x, n / 2)
value * value
else
value = my_pow(x, (n - 1) / 2)
x * value * value
end
end<file_sep>/javascript/017.js
/**
* @param {string} digits
* @return {string[]}
*/
var mapping = {
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"]
};
var letterCombinations = function(digits) {
if (digits.length === 0) return [];
if (digits.length === 1) return mapping[digits[0]];
const results = [];
const partialResults = letterCombinations(digits.substring(1));
mapping[digits[0]].forEach(function(digit) {
partialResults.forEach(function(partialResult) {
results.push(digit + partialResult);
});
});
return results;
};<file_sep>/ruby/055.rb
# @param {Integer[]} nums
# @return {Boolean}
def can_jump(nums)
target = nums.length - 1
range_start = 0
range_end = 0
while true do
return true if range_end >= target
next_end = range_end
range_start.upto(range_end).each do |i|
current_target = i + nums[i]
next_end = current_target if current_target > next_end
end
return false if next_end == range_end
range_start = range_end + 1
range_end = next_end
end
end<file_sep>/ruby/012.rb
# @param {Integer} num
# @return {String}
def int_to_roman(num)
keys = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
result = ""
while num > 0 do
if values[0] > num
values.shift
keys.shift
else
result += keys[0]
num -= values[0]
end
end
result
end<file_sep>/javascript/011.js
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(heights) {
let i = 0;
let j = heights.length - 1;
const getVolume = (i, j) => {
const height = heights[i] < heights[j] ? heights[i] : heights[j];
return height * (j - i);
}
let maxVolume = getVolume(i, j);
while(true) {
const iHeight = heights[i];
const jHeight = heights[j];
if (iHeight < jHeight) {
while(iHeight > heights[++i]) {}
} else {
while(jHeight > heights[--j]) {}
}
if (i >= j) break;
const volume = getVolume(i, j);
if (volume > maxVolume) maxVolume = volume;
}
return maxVolume;
};<file_sep>/ruby/044.rb
# Time Limit Exceeded, correct solution see 044.js
# @param {String} s
# @param {String} p
# @return {Boolean}
def is_match(s, p)
return true if p.length == 0 && s.length == 0
return false if p.length == 0
if s.length == 0
if p[0] == "*"
return is_match("", p[1..p.length-1])
else
return false
end
end
p.sub!('**', '*')
if p[0] == "*"
return true if p.length == 1
next_p = p[1..p.length-1]
return is_match("", next_p) if s == ""
return 0.upto(s.length).any? {|i| is_match(s[i..s.length-1], next_p)}
elsif p[0] == "?"
return is_match(s[1..s.length-1], p[1..p.length-1])
else
return false if s[0] != p[0]
return is_match(s[1..s.length-1], p[1..p.length-1])
end
end<file_sep>/ruby/036.rb
# @param {Character[][]} board
# @return {Boolean}
def is_valid_sudoku(board)
size = 9
0.upto(size - 1).each do |row_num|
row = board[row_num].dup.select{|c| c != "."}
return false if row.length != row.uniq.length
end
0.upto(size - 1).each do |col_num|
col = board.map{|row| row[col_num]}.select{|c| c != "."}
return false if col.length != col.uniq.length
end
0.upto(2).each do |i|
0.upto(2).each do |j|
row_start = i * 3
col_start = j * 3
char_group = []
row_start.upto(row_start + 2) do |row_num|
char_group += board[row_num][col_start..col_start+2]
end
char_group.select!{|c| c != "."}
return false if char_group.length != char_group.uniq.length
end
end
true
end<file_sep>/javascript/008.js
var myAtoi = function(str) {
str = str.trim();
var pattern = /^(\-|\+)?[0-9]+/;
var matchResults = pattern.exec(str);
if (!matchResults) { return 0; }
var num = Number(matchResults[0]);
var intMax = 2147483647;
var intMin = -2147483648;
if (num > intMax) { return intMax; }
if (num < intMin) { return intMin; }
return num;
};<file_sep>/javascript/023.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
const mergedArray = [];
for (let i = 0; i < lists.length; ++i) {
let list = lists[i];
while(list) {
mergedArray.push(list.val);
list = list.next;
}
}
mergedArray.sort((a, b) => a - b);
let mergedList = null;
let current = null;
mergedArray.forEach(function(value){
if (mergedList === null) {
mergedList = new ListNode(value);
current = mergedList;
} else {
var newNode = new ListNode(value);
current.next = newNode;
current = newNode;
}
})
return mergedList;
};<file_sep>/ruby/073.rb
# @param {Integer[][]} matrix
# @return {Void} Do not return anything, modify matrix in-place instead.
def set_zeroes(matrix)
is_top_row_zero = matrix[0].any? {|num| num == 0}
is_left_col_zero = 0.upto(matrix.length - 1).any? {|i| matrix[i][0] == 0}
1.upto(matrix.length - 1).each do |row|
matrix[row][0] = 0 if matrix[row].any? {|num| num == 0}
end
1.upto(matrix[0].length - 1).each do |col|
matrix[0][col] = 0 if 0.upto(matrix.length - 1).any? {|row| matrix[row][col] == 0}
end
1.upto(matrix.length - 1).each do |row|
if matrix[row][0] == 0
0.upto(matrix[row].length - 1) do |col|
matrix[row][col] = 0
end
end
end
1.upto(matrix[0].length - 1).each do |col|
1.upto(matrix.length - 1).each {|row| matrix[row][col] = 0} if matrix[0][col] == 0
end
0.upto(matrix[0].length - 1).each {|col| matrix[0][col] = 0} if is_top_row_zero
0.upto(matrix.length - 1).each {|row| matrix[row][0] = 0} if is_left_col_zero
end<file_sep>/javascript/074.js
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function(matrix, target) {
const rowCount = matrix.length;
if (rowCount === 0) return false;
const colCount = matrix[0].length;
if (colCount === 0) return false;
if (matrix[0][0] > target) return false;
let row = 0;
while(true) {
if (matrix[row][0] === target) { return true; }
if (row === rowCount - 1) break;
if (matrix[row + 1][0] <= target) {
++row;
} else {
break;
}
}
for (let col = 0; col < colCount; ++col) {
if (matrix[row][col] === target) return true;
if (matrix[row][col] > target) return false;
}
return false;
};<file_sep>/ruby/010.rb
# @param {String} s
# @param {String} p
# @return {Boolean}
def is_match_imp(s, p, i, j)
return i == s.length if j == p.length
if p.length == j + 1 || p[j + 1] != "*"
return false if s.length == i
return false if s[i] != p[j] && p[j] != "."
return is_match_imp(s, p, i + 1, j + 1)
end
# if code comes here p[j + 1] === "*"
while i < s.length && (s[i] == p[j] || p[j] == ".") do
return true if is_match_imp(s, p, i, j + 2)
i += 1
end
is_match_imp(s, p, i, j + 2)
end
def is_match(s, p)
is_match_imp(s, p, 0, 0)
end<file_sep>/javascript/096.js
/**
* @param {number} n
* @return {number}
*/
var numTrees = function(n) {
let cache = {0: 1, 1: 1};
const getNum = n => {
if (n in cache) return cache[n];
if (n === 1 || n === 0) return 1;
if (n < 0) return 0;
let temp = 0;
let result = 0;
while(temp < n) {
result += getNum(temp) * getNum(n - temp - 1);
++temp;
}
cache[n] = result;
return result;
}
return getNum(n);
};<file_sep>/ruby/066.rb
# @param {Integer[]} digits
# @return {Integer[]}
def plus_one(digits)
left = 1
current = digits.length - 1
while current >= 0 do
digits[current] += left
if digits[current] > 9
digits[current] -= 10
left = 1
else
left = 0
break
end
current -= 1
end
if left == 1
digits.unshift(1)
end
digits
end<file_sep>/ruby/064.rb
# @param {Integer[][]} grid
# @return {Integer}
def min_path_sum(grid)
row_count = grid.length
col_count = grid[0].length
0.upto(row_count - 1).each do |row|
0.upto(col_count - 1).each do |col|
next if row == 0 && col == 0
if row == 0
grid[row][col] += grid[row][col - 1]
next
end
if col == 0
grid[row][col] += grid[row - 1][col]
next
end
up = grid[row - 1][col]
left = grid[row][col - 1]
grid[row][col] += (left < up ? left : up)
end
end
grid[row_count - 1][col_count - 1]
end<file_sep>/ruby/043.rb
# @param {String} num1
# @param {String} num2
# @return {String}
def multiply(num1, num2)
return "0" if num2 == "0"
return "0" if num1 == "0"
num1 = num1.split("").map(&:to_i).reverse
num2 = num2.split("").map(&:to_i)
results = []
num2.each do |b|
sub_result = []
left = 0
num1.each do |a|
value = a * b + left
sub_result.push(value % 10)
left = (value - value % 10) / 10
end
sub_result.push(left) if left > 0
results = results.map{|sb| sb.push(0)}.push(sub_result.reverse)
end
results = results.map{|r| r.reverse}
length = results[0].length
result = []
left = 0
0.upto(length - 1).each do |i|
sum = results.map{|r| i < r.length ? r[i] : 0}.reduce(:+) + left
result.push(sum % 10)
left = (sum - sum % 10) / 10
end
result.push(left) if left > 0
result.reverse.join("")
end<file_sep>/ruby/019.rb
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} head
# @param {Integer} n
# @return {ListNode}
def remove_nth_from_end(head, n)
fake_node = ListNode.new(0)
fake_node.next = head
current_node = fake_node
n_node = fake_node
(n + 1).times.each do
n_node = n_node.next
end
while !n_node.nil? do
current_node = current_node.next
n_node = n_node.next
end
current_node.next = current_node.next.next
fake_node.next
end<file_sep>/javascript/089.js
/**
* @param {number} n
* @return {number[]}
*/
var grayCode = function(n) {
if (n === 0) return [0];
if (n === 1) return [0, 1];
let n_2 = 1;
let temp = n;
while(temp > 1) {
n_2 *= 2;
--temp;
}
var subResults = grayCode(n - 1);
var results = subResults.slice();
return results.concat(subResults.reverse().map(r => r + n_2));
};<file_sep>/ruby/005.rb
# @param {String} s
# @return {String}
def longest_palindrome(s)
s = " " + s.split("").join(" ") + " "
length = s.length
max_length = 1
max_string = ""
max_left = 0
max_right = 0
s.each_char.with_index do |char, index|
left = index
right = index
while left >= 0 && right < length do
if s[left] == s[right]
if right - left + 1 > max_length
max_left = left
max_right = right
max_length = right - left + 1
end
left -= 1
right += 1
else
break
end
end
end
max_string = s[max_left..max_right]
max_string.split(" ").join("")
end<file_sep>/ruby/077.rb
# @param {Integer} n
# @param {Integer} k
# @return {Integer[][]}
def combine(n, k)
map = []
0.upto(k) do |row|
map[row] = Array.new(n + 1, [])
end
1.upto(n).each do |col|
1.upto(k).each do |row|
break if row > col
if row == 1 && col == 1
map[1][1] = [[1]]
next
end
map[row][col] = map[row][col - 1] + (map[row - 1][col - 1].length == 0 ? [[col]] : map[row - 1][col - 1].map{|a| a.dup.push(col)})
end
end
p map[k][n]
end<file_sep>/ruby/014.rb
# @param {String[]} strs
# @return {String}
def longest_common_prefix(strs)
result = ""
return result if strs.length == 0
return strs[0] if strs.length == 1
strs[0].each_char.with_index do |char, index|
if strs.all? {|str| str[index] == char}
result += char
else
break
end
end
result
end<file_sep>/ruby/004.rb
# @param {Integer[]} nums1
# @param {Integer[]} nums2
# @return {Float}
def find_median_sorted_arrays(nums1, nums2)
nums = nums1 + nums2
nums.sort!
if nums.length % 2 == 0
mid1 = nums[nums.length / 2]
mid2 = nums[nums.length / 2 - 1]
(mid1 + mid2) / 2.0
else
nums[(nums.length - 1) / 2]
end
end<file_sep>/javascript/031.js
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
const swap = (a, b) => {
const temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
const getMinIndex = start => {
let minIndex = start;
let minValue = nums[minIndex];
for (let i = start + 1; i < nums.length; ++i) {
if (nums[i] < minValue) minIndex = i;
}
return minIndex;
}
let i = nums.length - 1;
while(i >= 0) {
if (i == 0) i = -1;
--i;
if (nums[i] < nums[i + 1]) break;
}
// make i + 1 to end ascend
for (let j = i + 1; j < nums.length - 1; ++j) {
const minIndex = getMinIndex(j);
if (minIndex !== j) swap(j, minIndex);
}
// find first index which value larger than nums[i] then swap
for (let j = i + 1; j < nums.length; ++j) {
if (nums[j] > nums[i]) {
swap(i, j);
break;
}
}
};<file_sep>/problems/039.md
Given a `set` of candidate numbers (`C`) (`without duplicates`) and a target number (`T`), find all unique combinations in `C` where the candidate numbers sums to `T`.
The `same` repeated number may be chosen from `C` unlimited number of times.
`Note:`
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set `[2, 3, 6, 7]` and target `7`,
A solution set is:
```
[
[7],
[2, 2, 3]
]
```<file_sep>/javascript/136.js
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
const map = {};
nums.forEach(num => {
if (num in map) {
delete map[num];
} else {
map[num] = true;
}
});
return Number.parseInt(Object.keys(map)[0]);
};<file_sep>/ruby/076.rb
# @param {String} s
# @param {String} t
# @return {String}
def min_window(s, t)
hash = {}
t.each_char do |char|
hash.has_key?(char) ? hash[char] += 1 : hash[char] = 1
end
temp_hash = hash.dup
# find first solution
current_hash = {}
a = 0
b = 0
while temp_hash.keys.count > 0 && b < s.length do
if temp_hash.has_key?(s[b])
if temp_hash[s[b]] == 1
temp_hash.delete(s[b])
else
temp_hash[s[b]] -= 1
end
end
if hash.has_key?(s[b])
if current_hash.has_key?(s[b])
current_hash[s[b]] += 1
else
current_hash[s[b]] = 1
end
end
b += 1
end
return "" if temp_hash.keys.count > 0
min_window = s[a...b]
min_length = b - a
while b < s.length do
while !hash.has_key?(s[a]) || current_hash[s[a]] > hash[s[a]] do
if hash.has_key?(s[a]) && current_hash[s[a]] > hash[s[a]]
current_hash[s[a]] -= 1
end
a += 1
end
if b - a < min_length
min_length = b - a
min_window = s[a...b]
end
return min_window if b == s.length
target_char = s[a]
a += 1
while b < s.length && s[b] != target_char do
if hash.has_key?(s[b])
current_hash[s[b]] += 1
end
b += 1
end
return min_window if b == s.length
b += 1
end
while !hash.has_key?(s[a]) || current_hash[s[a]] > hash[s[a]] do
if hash.has_key?(s[a]) && current_hash[s[a]] > hash[s[a]]
current_hash[s[a]] -= 1
end
a += 1
end
if b - a < min_length
min_length = b - a
min_window = s[a...b]
end
min_window
end<file_sep>/javascript/066.js
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
let left = 0;
for(let i = digits.length - 1; i >= 0; --i) {
if (i === digits.length - 1) {
digits[i] += (1 + left);
} else {
digits[i] += left;
}
if (digits[i] > 9) {
left = 1;
digits[i] -= 10;
} else {
left = 0;
break;
}
}
if (left > 0) {
return [left].concat(digits);
} else {
return digits;
}
};<file_sep>/problems/007.md
Reverse digits of an integer.
**Example1:** x = 123, return 321
**Example2:** x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function **should return 0 when the reversed integer overflows.**<file_sep>/ruby/088.rb
# @param {Integer[]} nums1
# @param {Integer} m
# @param {Integer[]} nums2
# @param {Integer} n
# @return {Void} Do not return anything, modify nums1 in-place instead.
def merge(nums1, m, nums2, n)
last = m + n - 1
m -= 1
n -= 1
while m >= 0 && n >= 0 do
if nums1[m] > nums2[n]
nums1[last] = nums1[m]
m -= 1
else
nums1[last] = nums2[n]
n -= 1
end
last -= 1
end
n.downto(0) do |i|
nums1[last] = nums2[i]
last -= 1
end
end<file_sep>/javascript/138.js
/**
* Definition for singly-linked list with a random pointer.
* function RandomListNode(label) {
* this.label = label;
* this.next = this.random = null;
* }
*/
/**
* @param {RandomListNode} head
* @return {RandomListNode}
*/
var copyRandomList = function(head) {
let temp = head;
let i = 0;
while(temp) {
temp.index = i;
i += 1;
temp = temp.next;
}
list = [];
temp = head;
while(temp) {
list.push(new RandomListNode(temp.label));
temp = temp.next;
}
i = 0;
while(i < list.length - 1) {
list[i].next = list[i + 1];
i += 1;
}
temp = head;
i = 0;
while(temp) {
if (temp.random !== null) {
list[i].random = list[temp.random.index];
}
temp = temp.next;
i += 1;
}
return list.length === 0 ? null : list[0];
};<file_sep>/javascript/073.js
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
var rowNum = matrix.length;
if (!rowNum) return matrix;
var colNum = matrix[0].length;
if (!colNum) return matrix;
var isFirstRowContainsZero = matrix[0].indexOf(0) !== -1;
var isFirstColContainsZero = false;
for (var row = 0; row < rowNum; ++row) {
if (!matrix[row][0]) {
isFirstColContainsZero = true;
break;
}
}
for (var row = 1; row < rowNum; ++row) {
for (var col = 1; col < colNum; ++col) {
if (!matrix[row][col]) {
matrix[row][0] = 0;
matrix[0][col] = 0;
}
}
}
for (var row = 1; row < rowNum; ++row) {
if (matrix[row][0]) continue;
for (var col = 0; col < colNum; ++col) {
matrix[row][col] = 0;
}
}
for (var col = 1; col < colNum; ++col) {
if (matrix[0][col]) continue;
for (var row = 0; row < rowNum; ++row) {
matrix[row][col] = 0;
}
}
if (isFirstRowContainsZero) {
for (var col = 0; col < colNum; ++col) {
matrix[0][col] = 0;
}
};
if (isFirstColContainsZero) {
for (var row = 0; row < rowNum; ++row) {
matrix[row][0] = 0;
}
}
};<file_sep>/ruby/067.rb
# @param {String} a
# @param {String} b
# @return {String}
def add_binary(a, b)
current_a = a.length - 1
current_b = b.length - 1
result = ""
left = 0
while current_a >= 0 || current_b >= 0 do
a_value = current_a >= 0 ? a[current_a].to_i : 0
b_value = current_b >= 0 ? b[current_b].to_i : 0
sum = a_value + b_value + left
if sum <= 1
result = sum.to_s + result
left = 0
else
result = (sum - 2).to_s + result
left = 1
end
current_a -= 1 if current_a >= 0
current_b -= 1 if current_b >= 0
end
result = left.to_s + result if left > 0
result
end<file_sep>/problems/125.md
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
`"A man, a plan, a canal: Panama"` is a palindrome.
`"race a car"` is not a palindrome.<file_sep>/javascript/025.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var reverseKGroup = function(head, k) {
if (k === 1) return head;
_reverseKGroup = (head, k) => {
let temp = k;
let values = [];
let tempNode = head;
while(temp > 0 && tempNode != null) {
values.unshift(tempNode.val);
tempNode = tempNode.next;
--temp;
}
if (values.length !== k) return;
tempNode = head;
values.forEach(value => {
tempNode.val = value;
tempNode = tempNode.next;
});
_reverseKGroup(tempNode, k);
}
_reverseKGroup(head, k);
return head;
};<file_sep>/javascript/067.js
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let indexA = a.length - 1;
let indexB = b.length - 1;
let result = "";
let left = 0;
while(indexA >= 0 || indexB >= 0) {
let aValue = 0;
let bValue = 0;
if (indexA >= 0) aValue = parseInt(a[indexA]);
if (indexB >= 0) bValue = parseInt(b[indexB]);
let newValue = aValue + bValue + left;
if (newValue >= 2) {
left = 1;
newValue = newValue - 2;
} else {
left = 0;
}
result = newValue + result;
if (indexA >= 0) --indexA;
if (indexB >= 0) --indexB;
}
if (left > 0) result = left + result;
return result;
};<file_sep>/javascript/043.js
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var multiply = function(num1, num2) {
// "123" * "4" => [4, 9, 2]
// "44" * "3" => [1, 3, 2]
const mul = (a, b) => {
if (b === "0") return [0];
let result = [];
let left = 0;
for(let i = a.length - 1; i >= 0; --i) {
let temp = a[i] * b + left;
temp > 9 ? left = Number.parseInt(temp / 10) : left = 0;
if (temp > 9) temp = temp - left * 10;
result.unshift(temp);
}
if (left > 0) result.unshift(left);
return result;
}
const plus = (a, b) => {
const maxLength = Math.max(a.length, b.length);
a = a.reverse();
b = b.reverse();
let result = [];
let left = 0;
for (let i = 0; i < maxLength; ++i) {
let temp = 0;
if (i < a.length && i < b.length) {
temp = a[i] + b[i];
} else if (i >= a.length) {
temp = b[i];
} else {
temp = a[i];
}
temp = temp + left;
temp > 9 ? left = 1 : left = 0;
if (temp > 9) temp = temp - 10;
result.unshift(temp);
}
if (left > 0) result.unshift(left);
return result;
}
if (num1 == "0" || num2 == "0") return "0";
let result = [];
for(i = 0; i < num2.length; ++i) {
let multiValue = mul(num1, num2[i]);
result.push(0);
result = plus(result, multiValue);
}
return result.join("");
};<file_sep>/javascript/085.js
/**
* @param {character[][]} matrix
* @return {number}
*/
var largestRectangleArea = function(heights) {
let stack = [];
let result = 0;
heights.forEach(height => {
if (stack.length === 0 || stack[stack.length - 1] <= height) {
stack.push(height);
} else {
let count = 0;
while (stack.length > 0 && stack[stack.length - 1] > height) {
++count;
const h = stack.pop();
if (h * count > result) result = h * count;
}
while (count >= 0) {
stack.push(height);
--count;
}
}
});
const length = stack.length;
for(let i = 0; i < length; ++i) {
const value = stack[i] * (length - i);
if (value > result) result = value;
}
return result;
};
var maximalRectangle = function(matrix) {
const rowCount = matrix.length;
if (rowCount === 0) return 0;
const colCount = matrix[0].length;
if (colCount === 0) return 0;
getHeight = (row, col) => {
let height = 0;
while(row >= 0) {
if (matrix[row][col] === "1") {
++height;
--row;
} else {
break;
}
}
return height;
}
let maxValue = 0;
for(let row = 0; row < rowCount; ++row) {
let heights = [];
for(let col = 0; col < colCount; ++col) {
heights.push(getHeight(row, col));
}
const largestArea = largestRectangleArea(heights);
if (largestArea > maxValue) maxValue = largestArea;
}
return maxValue;
};<file_sep>/ruby/030.rb
# @param {String} s
# @param {String[]} words
# @return {Integer[]}
def get_hash(words)
hash = {}
words.each do |word|
if hash[word].nil?
hash[word] = 1
else
hash[word] += 1
end
end
hash
end
def find_substring(s, words)
return [] if words.length === 0
word_length = words[0].length
result = []
0.upto(s.length - words.length * word_length).each do |i|
hash = get_hash(words)
j = i
while j <= s.length - word_length do
word = s[j..j+word_length-1]
break if hash[word].nil?
if hash[word] == 1
hash.delete(word)
else
hash[word] -= 1
end
j += word_length
end
result.push(i) if hash.keys.length == 0
end
result
end<file_sep>/ruby/013.rb
# @param {String} s
# @return {Integer}
def roman_to_int(s)
hash = {
"M" => 1000,
"CM" => 900,
"D" => 500,
"CD" => 400,
"C" => 100,
"XC" => 90,
"L" => 50,
"XL" => 40,
"X" => 10,
"IX" => 9,
"V" => 5,
"IV" => 4,
"I" => 1
}
result = 0
while s.length > 0 do
if s.length >= 2 && !hash[s[0..1]].nil?
result += hash[s[0..1]]
s = s[2..-1]
else
result += hash[s[0]]
s = s[1..-1]
end
end
result
end<file_sep>/ruby/082.rb
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} head
# @return {ListNode}
def delete_duplicates(head)
return if head.nil?
result = nil
result_current = nil
current_value = head.val
current_count = 0
current = head
while !current.nil? do
if current.val == current_value
current_count += 1
else
if current_count == 1
if result.nil?
result = ListNode.new(current_value)
result_current = result
else
result_current.next = ListNode.new(current_value)
result_current = result_current.next
end
end
current_value = current.val
current_count = 1
end
current = current.next
end
if current_count == 1
if result.nil?
result = ListNode.new(current_value)
result_current = result
else
result_current.next = ListNode.new(current_value)
result_current = result_current.next
end
end
result
end<file_sep>/ruby/079.rb
def exist_with_start_pos(word, board, used_board, row, col, row_count, col_count)
return false if row < 0 || row == row_count
return false if col < 0 || col == col_count
return board[row][col] == word[0] && !used_board[row][col] if word.length == 1
return false if used_board[row][col]
return false if board[row][col] != word[0]
result = true
used_board[row][col] = true
return true if exist_with_start_pos(word[1..-1], board, used_board, row + 1, col , row_count, col_count)
return true if exist_with_start_pos(word[1..-1], board, used_board, row - 1, col , row_count, col_count)
return true if exist_with_start_pos(word[1..-1], board, used_board, row , col - 1, row_count, col_count)
return true if exist_with_start_pos(word[1..-1], board, used_board, row , col + 1, row_count, col_count)
used_board[row][col] = false
return false
end
# @param {Character[][]} board
# @param {String} word
# @return {Boolean}
def exist(board, word)
row_count = board.length
col_count = board[0].length
used_board = []
1.upto(row_count) do
used_board.push(Array.new(col_count, false))
end
0.upto(row_count - 1) do |row|
0.upto(col_count - 1) do |col|
return true if exist_with_start_pos(word, board, used_board, row, col, row_count, col_count)
end
end
return false
end<file_sep>/javascript/002.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let nodeOnl1 = l1;
let nodeOnl2 = l2;
let resultList = null;
let resultListTail = null;
let overflow = 0;
while(nodeOnl1 || nodeOnl2) {
let val1 = nodeOnl1 ? nodeOnl1.val : 0;
let val2 = nodeOnl2 ? nodeOnl2.val : 0;
let sum = val1 + val2 + overflow;
overflow = sum >= 10 ? 1 : 0;
const remain = sum % 10;
let newNode = new ListNode(remain);
if (resultList === null) {
resultList = newNode;
resultListTail = newNode;
} else {
resultListTail.next = newNode;
resultListTail = newNode;
}
nodeOnl1 && (nodeOnl1 = nodeOnl1.next);
nodeOnl2 && (nodeOnl2 = nodeOnl2.next);
}
if (overflow === 1) { resultListTail.next = new ListNode(1); }
return resultList;
};<file_sep>/javascript/139.js
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function(s, wordDict) {
const map = {"-1": true};
for (let i = 0; i < s.length; ++i) {
let hasSolution = false;
wordDict.forEach(word => {
if (i + 1 >= word.length) {
if (s.substring(i - word.length + 1, i + 1) === word && map[i - word.length]) hasSolution = true;
}
});
map[i] = hasSolution;
}
return map[s.length - 1];
};<file_sep>/javascript/057.js
/**
* Definition for an interval.
* function Interval(start, end) {
* this.start = start;
* this.end = end;
* }
*/
/**
* @param {Interval[]} intervals
* @param {Interval} newInterval
* @return {Interval[]}
*/
var insert = function(intervals, newInterval) {
if (intervals.length === 0) return [newInterval];
if (intervals[0].start > newInterval.end) return [newInterval].concat(intervals);
if (intervals[intervals.length - 1].end < newInterval.start) return intervals.concat([newInterval]);
var mergedIntervals = [];
var start = newInterval.start;
var needToSetStart = true;
var end = newInterval.end;
for (var index = 0; index < intervals.length; ++index) {
var interval = intervals[index];
if (interval.end < newInterval.start) {
mergedIntervals.push(interval);
} else if (interval.start > newInterval.end) {
mergedIntervals.push(new Interval(start, end));
return mergedIntervals.concat(intervals.slice(index));
}
else {
if (needToSetStart) {
start = (interval.start < newInterval.start ? interval.start : newInterval.start);
needToSetStart = false;
}
end = interval.end > newInterval.end ? interval.end : newInterval.end;
}
}
mergedIntervals.push(new Interval(start, end));
return mergedIntervals;
};<file_sep>/javascript/088.js
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function(nums1, m, nums2, n) {
var index = m + n - 1;
var current1 = m - 1;
var current2 = n - 1;
while(current1 >= 0 && current2 >= 0) {
var value1 = nums1[current1];
var value2 = nums2[current2];
if (value1 < value2) {
nums1[index] = value2;
--index;
--current2;
} else {
nums1[index] = value1;
--index;
--current1;
}
}
while(current2 >= 0) {
nums1[index] = nums2[current2];
--index;
--current2;
}
};<file_sep>/javascript/120.js
/**
* @param {number[][]} triangle
* @return {number}
*/
var minimumTotal = function(triangle) {
let lastRow = [];
triangle.forEach(row => {
if (row.length === 1) {
lastRow = row;
} else {
let currentRow = [];
for (let i = 0; i < row.length; ++i) {
if (i === 0) {
currentRow[i] = row[i] + lastRow[i];
} else if (i === row.length - 1) {
currentRow[i] = row[i] + lastRow[i - 1];
} else {
currentRow[i] = row[i] + Math.min(lastRow[i - 1], lastRow[i]);
}
}
lastRow = currentRow;
}
});
return Math.min(...lastRow);
};<file_sep>/javascript/020.js
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
if (s === "") return true;
const isLeft = c => c === '[' || c === '{' || c === '(';
const map = {"[": "]", "{": "}", "(":")"};
const isMatch = (c1, c2) => map[c1] === c2;
const stack = [];
for (let i = 0; i < s.length; ++i) {
const c = s[i];
if (isLeft(c)) {
stack.push(c);
} else {
if (stack.length === 0) return false;
const last = stack.pop();
if (!isMatch(last, c)) return false;
}
}
return stack.length === 0;
};<file_sep>/ruby/049.rb
# @param {String[]} strs
# @return {String[][]}
def group_anagrams(strs)
strs.group_by {|str| str.split("").sort!}.values
end<file_sep>/javascript/056.js
/**
* Definition for an interval.
* function Interval(start, end) {
* this.start = start;
* this.end = end;
* }
*/
/**
* @param {Interval[]} intervals
* @return {Interval[]}
*/
var merge = function(intervals) {
intervals.sort(function(a, b) { return a.start - b.start; });
var mergedIntervals = [];
intervals.forEach(function(interval) {
if (mergedIntervals.length === 0) {
mergedIntervals.push(interval);
} else {
var lastInterval = mergedIntervals[mergedIntervals.length - 1];
if (interval.start > lastInterval.end) {
mergedIntervals.push(interval);
} else if (interval.end > lastInterval.end) {
lastInterval.end = interval.end;
}
}
});
return mergedIntervals;
};<file_sep>/ruby/054.rb
# @param {Integer[][]} matrix
# @return {Integer[]}
def spiral_order(matrix)
return [] if matrix.length == 0
return [] if matrix[0].length == 0
min_col = 0
max_col = matrix[0].length - 1
min_row = 0
max_row = matrix.length - 1
result = []
while true do
return result if min_col > max_col
min_col.upto(max_col).each do |col|
result.push(matrix[min_row][col])
end
min_row += 1
return result if min_row > max_row
min_row.upto(max_row).each do |row|
result.push(matrix[row][max_col])
end
max_col -= 1
return result if min_col > max_col
max_col.downto(min_col).each do |col|
result.push(matrix[max_row][col])
end
max_row -= 1
return result if min_row > max_row
max_row.downto(min_row).each do |row|
result.push(matrix[row][min_col])
end
min_col += 1
end
result
end<file_sep>/javascript/047.js
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permuteUnique = function(nums) {
if (nums.length == 1) return [nums];
nums = nums.sort((a, b) => a - b);
let usedNums = [];
let results = [];
const swap = (i, j) => {
const temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
for(var i = 0; i < nums.length; ++i) {
if (usedNums.indexOf(nums[i]) !== -1) continue;
usedNums.push(nums[i]);
swap(0, i);
var subResults = permuteUnique(nums.slice(1));
for (let j = 0; j < subResults.length; ++j) {
results.push([nums[0]].concat(subResults[j]));
}
swap(0, i);
}
return results;
};<file_sep>/problems/097.md
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = `"aabcc"`,
s2 = `"dbbca"`,
When s3 = `"aadbbcbcac"`, return true.
When s3 = `"aadbbbaccc"`, return false.<file_sep>/ruby/052.rb
def is_valid(board, row, col)
return false if board[row].each_with_index.any? do |item, c|
c != col && item
end
return false if board.each_with_index.any? do |line, r|
r != row && line[col]
end
if row >= col
return false if (row - col).upto(board.length - 1).any? do |r|
c = r - row + col
r != row && board[r][c]
end
else
return false if 0.upto(board.length - 1 - col + row).any? do |r|
c = col - row + r
r != row && board[r][c]
end
end
if row + col < board.length
return false if 0.upto(row + col).any? do |r|
c = row + col - r
r != row && board[r][c]
end
else
return false if (row + col - board.length + 1).upto(board.length - 1).any? do |r|
c = row + col - r
r != row && board[r][c]
end
end
true
end
def find_solution board, row, results
if row == board.length
sum = 0
board.each do |line|
line.each do |item|
sum += 1 if item
end
end
results.push(board.map{|line| line.map {|item| item ? "Q" : "."}.join("")}) if sum == board.length
return
end
0.upto(board.length - 1).each do |col|
next unless is_valid(board, row, col)
board[row][col] = true
find_solution(board, row + 1, results)
board[row][col] = false
end
end
# @param {Integer} n
# @return {Integer}
def total_n_queens(n)
board = []
1.upto(n).each { board.push(Array.new(n, false)) }
results = []
find_solution(board, 0, results)
results.length
end<file_sep>/ruby/031.rb
# @param {Integer[]} nums
# @return {Void} Do not return anything, modify nums in-place instead.
def next_permutation(nums)
last_asc_index = -1
0.upto(nums.length - 2) do |i|
last_asc_index = i if nums[i] < nums[i + 1]
end
if last_asc_index == -1
nums.reverse!
else
sub_array = nums[last_asc_index + 1..-1]
min_in_sub = sub_array.select{|n| n > nums[last_asc_index]}.min
sub_array.push(nums[last_asc_index])
sub_array.delete_at(sub_array.index(min_in_sub))
sub_array.sort!
p sub_array
nums[last_asc_index] = min_in_sub
temp = last_asc_index + 1
sub_array.each do |n|
nums[temp] = n
temp += 1
end
end
end<file_sep>/ruby/037.rb
# @param {Character[][]} board
# @return {Void} Do not return anything, modify board in-place instead.
def is_valid(board, i, j)
value = board[i][j]
is_row_invalid = board[i].each_with_index.any? {|char, index| index != j && char == value}
return false if is_row_invalid
is_col_invalid = board.map{|row| row[j]}.each_with_index.any? {|char, index| index != i && char == value}
return false if is_col_invalid
group_row = (i / 3).to_i
group_col = (j / 3).to_i
group = []
is_group_invalid = false
(3 * group_row).upto(3 * group_row + 2) do |row|
(3 * group_col).upto(3 * group_col + 2) do |col|
is_group_invalid = true if row != i && col != j && board[row][col] == value
end
end
!is_group_invalid
end
def solve_sudoku_helper(board, i, j)
return board[8][8] != "." if i == 9
return solve_sudoku_helper(board, i + 1, 0) if j == 9
return solve_sudoku_helper(board, i, j + 1) if (board[i][j] != ".")
has_solution = false
1.upto(9).each do |value|
board[i][j] = value.to_s
if is_valid(board, i, j) && solve_sudoku_helper(board, i, j + 1)
has_solution = true
break
else
board[i][j] = "."
end
end
has_solution
end
def solve_sudoku(board)
solve_sudoku_helper(board, 0, 0)
end<file_sep>/ruby/063.rb
# @param {Integer[][]} obstacle_grid
# @return {Integer}
def unique_paths_with_obstacles(obstacle_grid)
row_count = obstacle_grid.length
col_count = obstacle_grid[0].length
values = Array.new(row_count * col_count, 0)
0.upto(row_count - 1).each do |row|
0.upto(col_count - 1).each do |col|
next if obstacle_grid[row][col] == 1
if row == 0 && col == 0
values[0] = 1
next
end
if row == 0
values[col] = values[col - 1]
next
end
if col == 0
values[row * col_count] = values[(row - 1) * col_count]
next
end
values[row * col_count + col] = values[row * col_count + col - 1] + values[(row - 1) * col_count + col]
end
end
values[-1]
end<file_sep>/javascript/064.js
/**
* @param {number[][]} grid
* @return {number}
*/
var minPathSum = function(grid) {
const rowCount = grid.length;
if (rowCount === 0) return 0;
const colCount = grid[0].length;
if (colCount === 0) return 0;
for (let row = 0; row < rowCount; ++row) {
for (let col = 0; col < colCount; ++col) {
let currentSum = 0;
if (row === 0 && col === 0) continue;
if (row === 0) grid[row][col] = grid[row][col - 1] + grid[row][col];
if (col === 0) grid[row][col] = grid[row - 1][col] + grid[row][col];
if (row !== 0 && col !== 0) grid[row][col] = grid[row][col] + Math.min(grid[row - 1][col], grid[row][col - 1]);
}
}
return grid[rowCount - 1][colCount - 1];
};<file_sep>/javascript/082.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
let result = null;
let resultTail = null;
while(head) {
const currentValue = head.val;
if (head.next && head.next.val === currentValue) {
while(head && head.val === currentValue) {
head = head.next;
}
} else {
if (resultTail === null) {
result = head;
resultTail = head;
} else {
resultTail.next = head;
resultTail = head;
}
head = head.next;
}
}
resultTail && (resultTail.next = null);
return result;
};;<file_sep>/ruby/078.rb
# @param {Integer[]} nums
# @return {Integer[][]}
def subsets(nums)
return [[], [nums[0]]] if nums.length == 1
num = nums[-1]
parent_result = subsets(nums[0...-1])
parent_result + parent_result.map { |r| r.dup.push(num) }
end<file_sep>/javascript/018.js
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
nums.sort(function(a, b) { return a - b; });
let result = [];
const length = nums.length;
let lastFirstValue = nums[0] - 1;
for(var i = 0; i < length - 3; ++i) {
if (nums[i] === lastFirstValue) continue;
lastFirstValue = nums[i];
let lastSecondValue = nums[i + 1] - 1;
for (var j = i + 1; j < length - 2; ++j) {
if (nums[j] === lastSecondValue) continue;
lastSecondValue = nums[j];
const leftTarget = target - nums[i] - nums[j];
let k = j + 1;
let l = length - 1;
while(j < k && k < l && l < length) {
let currentTarget = nums[k] + nums[l];
if (currentTarget === leftTarget) {
result.push([nums[i], nums[j], nums[k], nums[l]]);
const currentKValue = nums[k];
while(++k < l && nums[k] === currentKValue){};
} else if (currentTarget < leftTarget) {
++k;
} else {
--l;
}
}
}
}
return result;
};<file_sep>/javascript/051.js
/**
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function(n) {
const n2 = n * n;
const board = (new Array(n2)).fill(false);
const isPosValid = (row, col) => {
// check all rows with col
for (let i = 0; i < n; ++i) {
if (board[i * n + col] && i !== row) return false;
}
// check all cols with row
for (let i = 0; i < n; ++i) {
if (board[row * n + i] && i !== col) return false;
}
// check 45 direction
var row1 = row >= col ? row - col : 0;
var col1 = row >= col ? 0 : col - row;
while(row1 < n && col1 < n) {
if (row1 !== row && board[row1 * n + col1]) return false;
++row1;
++col1;
}
// check 135 direction
var row2 = row + col >= n - 1 ? row + col - n + 1 : 0;
var col2 = row + col >= n - 1 ? n - 1 : row + col;
while(row2 < n && col2 >= 0) {
if (row2 !== row && board[row2 * n + col2]) return false;
++row2;
--col2;
}
return true;
};
let solutions = [];
findSolutions = row => {
for(let col = 0; col < n; ++col) {
if (!isPosValid(row, col)) continue;
board[row * n + col] = true;
if (row < n - 1) {
findSolutions(row + 1);
} else {
solutions.push(Array.from(board));
}
board[row * n + col] = false;
}
}
findSolutions(0);
toResult = solutions => {
let strArrayArray = [];
solutions.forEach(solution => {
let strArray = [];
for(let i = 0; i < n; ++i) {
let str = "";
for (let j = 0; j < n; ++j) {
str += (solution.shift() ? "Q" : ".");
}
strArray.push(str);
}
strArrayArray.push(strArray);
});
return strArrayArray;
}
return toResult(solutions);
};<file_sep>/ruby/007.rb
# @param {Integer} x
# @return {Integer}
def reverse(x)
return 0 if x == 0
positive_max = (1 << 30) * 2 - 1;
is_negative = x < 0
x = -x if is_negative
result = 0
while x > 0 do
left = x % 10
result = result * 10 + left
return 0 if result > positive_max
x = (x - left) / 10
end
is_negative ? -result : result
end
p reverse(1534236469)<file_sep>/ruby/011.rb
# @param {Integer[]} height
# @return {Integer}
def get_volumn(height, i, j)
length = j - i
if height[i] < height[j]
length * height[i]
else
length * height[j]
end
end
def max_area(height)
i = 0
j = height.length - 1
max_volumn = get_volumn(height, i, j)
while i < j do
if height[i] < height[j]
i_height = height[i]
i += 1 while height[i] <= i_height && i < j
else
j_height = height[j]
j -= 1 while height[j] <= j_height && i < j
end
break if i >= j
new_volumn = get_volumn(height, i, j)
max_volumn = new_volumn if new_volumn > max_volumn
end
max_volumn
end<file_sep>/javascript/109.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {ListNode} head
* @return {TreeNode}
*/
var sortedListToBST = function(head) {
const sortedArrayToBST = function(nums) {
if (nums.length === 0) return null;
if (nums.length === 1) return new TreeNode(nums[0]);
const midIndex = Number.parseInt(nums.length / 2);
const returnValue = new TreeNode(nums[midIndex]);
returnValue.left = sortedArrayToBST(nums.slice(0, midIndex));
returnValue.right = sortedArrayToBST(nums.slice(midIndex + 1, nums.length));
return returnValue;
};
const nums = [];
while(head) {
nums.push(head.val);
head = head.next;
}
return sortedArrayToBST(nums);
};
<file_sep>/ruby/008.rb
# @param {String} str
# @return {Integer}
def my_atoi(str)
str.strip!
is_positive = true
if str[0] == "-" || str[0] == "+"
if str[0] == "-"
is_positive = !is_positive
end
str = str[1..-1]
end
int_max = 2147483647;
int_min = -2147483648;
result = 0
hash = {"0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9}
str.each_char do |char|
break if hash[char].nil?
value = hash[char]
result = result * 10 + value
return (is_positive ? int_max : int_min) if result > int_max
end
is_positive ? result : -result
end<file_sep>/ruby/038.rb
# @param {Integer} n
# @return {String}
def count_and_say(n)
return "1" if n == 1
parent_result = count_and_say(n - 1)
parent_length = parent_result.length
result = ""
current = 0
while current < parent_length do
value = parent_result[current]
count = 1
while current < parent_length - 1 && parent_result[current + 1] == value do
count += 1
current += 1
end
result += (count.to_s + value)
current += 1
end
result
end<file_sep>/javascript/005.js
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
var maxLength = 0;
var maxStr = "";
var strLength = s.length;
for (var index = 0; index < 2 * strLength - 1; ++index) {
var isIndexEven = index % 2 === 0;
var left = isIndexEven ? index / 2 : (index - 1)/2;
var right = isIndexEven ? left : left + 1;
var length = isIndexEven ? -1 : 0;
var currentStr = index % 2 ? "" : s[index];
while(left >= 0 && right < strLength) {
if (s[left] === s[right]) {
currentStr = s.substring(left, right + 1);
length = length + 2;
} else {
break;
}
--left;
++right;
}
if (length > maxLength) {
maxStr = currentStr;
maxLength = length;
}
}
return maxStr;
};<file_sep>/javascript/053.js
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
const length = nums.length;
let sum = nums[length - 1];
let maxSum = nums[length - 1];
let i = length - 2;
while(i >= 0) {
sum = Math.max(nums[i], nums[i] + sum);
maxSum = Math.max(sum, maxSum);
--i;
}
return maxSum;
};<file_sep>/ruby/027.rb
# @param {Integer[]} nums
# @param {Integer} val
# @return {Integer}
def remove_element(nums, val)
insert_index = 0
0.upto(nums.length - 1).each do |i|
if nums[i] != val
nums[insert_index] = nums[i]
insert_index += 1
end
end
insert_index
end<file_sep>/ruby/084.rb
# @param {Integer[]} heights
# @return {Integer}
def largest_rectangle_area(heights)
result = 0
past_heights = []
heights.each do |height|
if past_heights.length == 0 || past_heights[-1] <= height
past_heights.push(height)
else
count = 0
while past_heights.length > 0 && past_heights[-1] > height do
count += 1
h = past_heights.pop
result = h * count if h * count > result
end
(count + 1).times do
past_heights.push(height)
end
end
end
0.upto(past_heights.length - 1) do |i|
value = past_heights[i] * (past_heights.length - i)
result = value if value > result
end
result
end<file_sep>/javascript/036.js
/**
* @param {character[][]} board
* @return {boolean}
*/
var isValidSudoku = function(board) {
var rowNum = 9;
var colNum = 9;
for(var i = 0; i < rowNum; ++i) {
var row = board[i];
var hash = {};
for (var j = 0; j < colNum; ++j) {
if (row[j] === ".") continue;
if (hash[row[j]]) return false;
hash[row[j]] = true;
}
}
for (var i = 0; i < colNum; ++i) {
var hash = {};
for (var j = 0; j < rowNum; ++j) {
if (board[j][i] === ".") continue;
if (hash[board[j][i]]) return false;
hash[board[j][i]] = true;
}
}
for (var i = 0; i < 3; ++i) {
for (var j = 0; j < 3; ++j) {
var hash = {};
for (var k = 0; k < 3; ++k) {
for (var l = 0; l < 3; ++l) {
if (board[i * 3 + k][j * 3 + l] === ".") continue;
if (hash[board[i * 3 + k][j * 3 + l]]) return false;
hash[board[i * 3 + k][j * 3 + l]] = true;
}
}
}
}
return true;
};<file_sep>/javascript/006.js
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function(s, numRows) {
if (numRows === 1) { return s; }
const total = 2 * numRows - 2;
function getRow(index) {
const remain = index % total;
return remain < numRows ? remain : total - remain;
}
let rowStrings = {};
for (let index = 0; index < s.length; ++index) {
const row = getRow(index);
rowStrings[row] = (rowStrings[row] || "") + s[index];
}
let returnValue = "";
for (let index = 0; index < numRows; ++index) {
returnValue += (rowStrings[index] || "");
}
return returnValue;
};<file_sep>/javascript/087.js
/**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var isScramble = function(s1, s2) {
if (s1.length !== s2.length) return false;
let s1Map = {};
for(let i = 0; i < s1.length; ++i) {
const c = s1[i];
c in s1Map ? s1Map[c] += 1 : s1Map[c] = 0;
}
let s2Map = {};
for(let i = 0; i < s2.length; ++i) {
const c = s2[i];
c in s2Map ? s2Map[c] += 1 : s2Map[c] = 0;
}
for(key in s1Map) {
if (s1Map[key] !== s2Map[key]) return false;
}
if (s1.length === 1) return s1 === s2;
for(let i = 1; i < s1.length; ++i) {
const s1Part1 = s1.substr(0, i);
const s1Part2 = s1.substr(i);
const s2Part11 = s2.substr(0, i);
const s2Part21 = s2.substr(i);
const s2Part12 = s2.substr(0, s2.length - i);
const s2Part22 = s2.substr(s2.length - i);
if (isScramble(s1Part1, s2Part11) && isScramble(s1Part2, s2Part21)) { return true; }
if (isScramble(s1Part1, s2Part22) && isScramble(s1Part2, s2Part12)) { return true; }
}
return false;
};<file_sep>/javascript/106.js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} inorder
* @param {number[]} postorder
* @return {TreeNode}
*/
var buildTree = function(inorder, postorder) {
if (inorder.length === 0) return null;
if (inorder.length === 1) return new TreeNode(inorder[0]);
const mid = postorder[postorder.length - 1];
const index = inorder.indexOf(mid);
const inorderLeft = inorder.slice(0, index);
const inorderRight = inorder.slice(index + 1, inorder.length);
const postorderLeft = postorder.slice(0, inorderLeft.length);
const postorderRight = postorder.slice(inorderLeft.length, postorder.length - 1);
const returnValue = new TreeNode(mid);
returnValue.left = buildTree(inorderLeft, postorderLeft);
returnValue.right = buildTree(inorderRight, postorderRight);
return returnValue;
};<file_sep>/ruby/070.rb
# @param {Integer} n
# @return {Integer}
def climb_stairs(n)
values = []
1.upto(n).each do |n|
values.push(1) if n == 1
values.push(2) if n == 2
values.push(values[-1] + values[-2]) if n > 2
end
values[-1]
end<file_sep>/ruby/071.rb
# @param {String} path
# @return {String}
def simplify_path(path)
path = path[1..-1] if path[0] == "/"
path = path[0..-2] if path[-1] == "/"
stack = []
path.split("/").each do |str|
next if str == "." || str == ""
if str == ".."
stack.pop
else
stack.push(str)
end
end
"/" + stack.join("/")
end<file_sep>/ruby/046.rb
# @param {Integer[]} nums
# @return {Integer[][]}
def permute(nums)
return [] if nums.length == 0
return [[nums[0]]] if nums.length == 1
result = []
value = nums.pop
parent_result = permute(nums)
parent_result.map do |item|
0.upto(item.length).map do |i|
item.dup.insert(i, value)
end
end.reduce([], :+)
end<file_sep>/javascript/022.js
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
const generateParenthesisSet = function(n) {
if (n === 1) return {"()": true};
const set = generateParenthesisSet(n - 1);
const newSet = {};
for (var str in set) {
for (var i = 0; i < str.length; ++i) {
if (str[i] === "(") {
newSet[str.substring(0, i + 1) + "()" + str.substring(i + 1)] = true;
newSet[str.substring(0, i) + "()" + str.substring(i)] = true;
}
}
}
return newSet;
}
return Object.keys(generateParenthesisSet(n));
};<file_sep>/ruby/062.rb
# @param {Integer} m
# @param {Integer} n
# @return {Integer}
def unique_paths(m, n)
values = Array.new(m * n, 0)
0.upto(n - 1).each do |row|
0.upto(m - 1).each do |col|
if row == 0 || col == 0
values[row * m + col] = 1
else
values[row * m + col] = values[(row - 1) * m + col] + values[row * m + col - 1]
end
end
end
values[-1];
end<file_sep>/problems/037.md
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character `'.'`.
You may assume that there will be only one unique solution.

A sudoku puzzle...

...and its solution numbers marked in red.<file_sep>/ruby/048.rb
# @param {Integer[][]} matrix
# @return {Void} Do not return anything, modify matrix in-place instead.
def rotate(matrix)
return if matrix.length == 0
size = matrix.length
0.upto(size - 1).each do |i|
(i + 1).upto(size - 1) do |j|
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
end
end
mid = size % 2 == 0 ? size / 2 - 1 : (size - 1) / 2
0.upto(size - 1).each do |i|
0.upto(mid).each do |j|
matrix[i][j], matrix[i][size-1-j] = matrix[i][size-1-j], matrix[i][j]
end
end
end<file_sep>/javascript/072.js
/**
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var minDistance = function(word1, word2) {
const length1 = word1.length;
const length2 = word2.length;
const map = {};
for (let i = 0; i <= length1; ++i) {
map[(length2 + 1) * i] = i;
}
for (let j = 0; j <= length2; ++j) {
map[j] = j;
}
for (let i = 1; i <= length1; ++i) {
for (let j = 1; j <= length2; ++j) {
if (word1[i - 1] === word2[j - 1]) {
map[i * (length2 + 1) + j] = map[(i - 1) * (length2 + 1) + j - 1];
} else {
const a = map[(i - 1) * (length2 + 1) + j - 1];
const b = map[(i - 1) * (length2 + 1) + j];
const c = map[i * (length2 + 1) + j - 1];
map[i * (length2 + 1) + j] = Math.min(a, b, c) + 1;
}
}
}
return map[(length1 + 1) * (length2 + 1) - 1];
};<file_sep>/ruby/053.rb
# @param {Integer[]} nums
# @return {Integer}
def max_sub_array(nums)
return 0 if nums.length == 0
max_sum = nums[0]
current_sum = 0
nums.each do |num|
current_sum = 0 if current_sum < 0
current_sum += num
max_sum = current_sum if current_sum > max_sum
end
max_sum
end<file_sep>/ruby/060.rb
def factorial(n)
return 1 if n == 0
result = 1
1.upto(n) {|i| result *= i}
result
end
# @param {Integer} n
# @param {Integer} k
# @return {String}
def get_permutation(n, k)
k -= 1
list = []
1.upto(n).each do |i|
list.push(i)
end
result = ""
value = n - 1
while value >= 0 do
factorial_value = factorial(value)
index = (k - k % factorial_value) / factorial_value
k -= index * factorial_value
result += list.slice!(index).to_s
value -= 1
end
result
end<file_sep>/ruby/002.rb
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def add_two_numbers(l1, l2)
result = nil
result_tail = nil
node_on_l1 = l1
node_on_l2 = l2
overflow = 0
while !node_on_l1.nil? || !node_on_l2.nil? do
sum = 0
if node_on_l1.nil?
sum = node_on_l2.val
elsif node_on_l2.nil?
sum = node_on_l1.val
else
sum = node_on_l1.val + node_on_l2.val
end
sum += overflow
if sum >= 10
overflow = 1
sum -= 10
else
overflow = 0
end
if result.nil?
result = ListNode.new(sum)
result_tail = result
else
result_tail.next = ListNode.new(sum)
result_tail = result_tail.next
end
node_on_l1 = node_on_l1.next unless node_on_l1.nil?
node_on_l2 = node_on_l2.next unless node_on_l2.nil?
end
if overflow == 1
result_tail.next = ListNode.new(overflow)
end
result
end<file_sep>/ruby/009.rb
# @param {Integer} x
# @return {Boolean}
def is_palindrome(x)
return false if x < 0
return true if x == 0
x.to_s.reverse == x.to_s
end<file_sep>/javascript/118.js
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
const results = [];
for(let i = 1; i <= numRows; ++i) {
if (i === 1) { results.push([1]); continue; }
const lastRow = results[results.length - 1];
const currentRow = [];
for (let j = 0; j < i; ++j) {
if (j === 0 || j === i - 1) {
currentRow.push(1);
} else {
currentRow.push(lastRow[j - 1] + lastRow[j]);
}
}
results.push(currentRow);
}
return results;
};<file_sep>/ruby/085.rb
def largest_rectangle_area(heights)
result = 0
past_heights = []
heights.each do |height|
if past_heights.length == 0 || past_heights[-1] <= height
past_heights.push(height)
else
count = 0
while past_heights.length > 0 && past_heights[-1] > height do
count += 1
h = past_heights.pop
result = h * count if h * count > result
end
(count + 1).times do
past_heights.push(height)
end
end
end
0.upto(past_heights.length - 1) do |i|
value = past_heights[i] * (past_heights.length - i)
result = value if value > result
end
result
end
# @param {Character[][]} matrix
# @return {Integer}
def maximal_rectangle(matrix)
return 0 if matrix.length == 0
return 0 if matrix[0].length == 0
result = 0
col_count = matrix[0].length
1.upto(matrix.length) do |row_count|
heights = []
0.upto(col_count) do |col|
values = []
0.upto(row_count - 1) do |row|
values.push(matrix[row][col])
end
height = 0
while values.length > 0 && values[-1] == "1"
height += 1
values.pop
end
heights.push(height)
end
sub_result = largest_rectangle_area(heights)
result = sub_result if sub_result > result
end
result
end<file_sep>/problems/060.md
The set `[1,2,3,…,n]` contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
1. `"123"`
2. `"132"`
3. `"213"`
4. `"231"`
5. `"312"`
6. `"321"`
Given n and k, return the kth permutation sequence.
**Note:** Given n will be between 1 and 9 inclusive.<file_sep>/javascript/039.js
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
let results = [];
let result = [];
findResults = function(startIndex, target) {
if (target === 0) {
results.push(result.slice(0));
return;
}
if (startIndex === candidates.length) return;
if (target < 0) return;
for (var i = startIndex; i < candidates.length; ++i) {
result.push(candidates[i]);
findResults(i, target - candidates[i]);
result.pop();
}
};
findResults(0, target);
return results;
};<file_sep>/ruby/032.rb
# @param {String} s
# @return {Integer}
def longest_valid_parentheses(s)
stack = [-1]
max_length = 0
0.upto(s.length - 1).each do |i|
if s[i] == "("
stack.push(i)
else
if stack[-1] >= 0 && s[stack[-1]] == "("
stack.pop
current_length = i - stack[-1]
max_length = current_length if current_length > max_length
else
stack.push(i)
end
end
end
max_length
end<file_sep>/javascript/024.js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
let current = head;
while(true) {
const first = current;
if (first === null) return head;
const second = current.next;
if (second === null) return head;
const temp = first.val;
first.val = second.val;
second.val = temp;
current = current.next.next;
}
return head;
};<file_sep>/ruby/001.rb
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
hash = {}
result = nil
nums.each_with_index do |num, index|
if hash[num].nil?
hash[target - num] = index
else
result = [hash[num], index]
end
end
result
end<file_sep>/ruby/003.rb
# @param {String} s
# @return {Integer}
def length_of_longest_substring(s)
start_index = 0
end_index = 0
length = s.length
hash = {}
max_length = 0
current_str = ""
while end_index < length do
char = s[end_index]
if hash[char].nil?
hash[char] = 1
current_length = end_index - start_index + 1
if current_length > max_length
max_length = current_length
end
end_index += 1
else
start_char = s[start_index]
hash[start_char] = nil
start_index += 1
end
end
max_length
end<file_sep>/javascript/026.js
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
if (nums.length === 0) return 0;
let current = 0;
let index = 0;
let lastValue = nums[0] - 1;
while(index < nums.length) {
if (nums[index] !== lastValue) {
nums[current] = nums[index];
lastValue = nums[current];
++current;
++index;
} else {
++index;
}
}
return current;
};<file_sep>/README.md
# LeetCode Website
https://leetcode.com/problemset/algorithms/
# LeetCode Solution List
| # | Problem | Solution | Note |
| --- | -------------------------------------------------------------------------------- | ----------------------------------------------- | ---- |
| 1 | [Two Sum ](./problems/001.md) | [js](./javascript/001.js) [ruby](./ruby/001.rb) | |
| 2 | [Add Two Numbers ](./problems/002.md) | [js](./javascript/002.js) [ruby](./ruby/002.rb) | |
| 3 | [Longest Substring Without Repeating Characters ](./problems/003.md) | [js](./javascript/003.js) [ruby](./ruby/003.rb) | |
| 4 | [Median of Two Sorted Arrays ](./problems/004.md) | [js](./javascript/004.js) [ruby](./ruby/004.rb) | |
| 5 | [Longest Palindromic Substring ](./problems/005.md) | [js](./javascript/005.js) [ruby](./ruby/005.rb) | 👍 [O(N) solution](http://articles.leetcode.com/longest-palindromic-substring-part-ii/) |
| 6 | [ZigZag Conversion ](./problems/006.md) | [js](./javascript/006.js) [ruby](./ruby/006.rb) | |
| 7 | [Reverse Integer ](./problems/007.md) | [js](./javascript/007.js) [ruby](./ruby/007.rb) | |
| 8 | [String to Integer ](./problems/008.md) | [js](./javascript/008.js) [ruby](./ruby/008.rb) | |
| 9 | [Palindrome Number ](./problems/009.md) | [js](./javascript/009.js) [ruby](./ruby/009.rb) | |
| 10 | [Regular Expression Matching ](./problems/010.md) | [js](./javascript/010.js) [ruby](./ruby/010.rb) | |
| 11 | [Container With Most Water ](./problems/011.md) | [js](./javascript/011.js) [ruby](./ruby/011.rb) | |
| 12 | [Integer to Roman ](./problems/012.md) | [js](./javascript/012.js) [ruby](./ruby/012.rb) | |
| 13 | [Roman to Integer ](./problems/013.md) | [js](./javascript/013.js) [ruby](./ruby/013.rb) | |
| 14 | [Longest Common Prefix ](./problems/014.md) | [js](./javascript/014.js) [ruby](./ruby/014.rb) | |
| 15 | [3Sum ](./problems/015.md) | [js](./javascript/015.js) [ruby](./ruby/015.rb) | |
| 16 | [3Sum Closest ](./problems/016.md) | [js](./javascript/016.js) [ruby](./ruby/016.rb) | |
| 17 | [Letter Combinations of a Phone Number ](./problems/017.md) | [js](./javascript/017.js) [ruby](./ruby/017.rb) | |
| 18 | [4Sum ](./problems/018.md) | [js](./javascript/018.js) [ruby](./ruby/018.rb) | |
| 19 | [Remove Nth Node From End of List ](./problems/019.md) | [js](./javascript/019.js) [ruby](./ruby/019.rb) | |
| 20 | [Valid Parentheses ](./problems/020.md) | [js](./javascript/020.js) [ruby](./ruby/020.rb) | |
| 21 | [Merge Two Sorted Lists ](./problems/021.md) | [js](./javascript/021.js) [ruby](./ruby/021.rb) | |
| 22 | [Generate Parentheses ](./problems/022.md) | [js](./javascript/022.js) [ruby](./ruby/022.rb) | 👍 |
| 23 | [Merge K Sorted Lists ](./problems/023.md) | [js](./javascript/023.js) [ruby](./ruby/023.rb) | |
| 24 | [Swap Nodes in Pairs ](./problems/024.md) | [js](./javascript/024.js) [ruby](./ruby/024.rb) | |
| 25 | [Reverse Nodes in k-Group ](./problems/025.md) | [js](./javascript/025.js) [ruby](./ruby/025.rb) | |
| 26 | [Remove Duplicated from Sorted Array ](./problems/026.md) | [js](./javascript/026.js) [ruby](./ruby/026.rb) | |
| 27 | [Remove Element ](./problems/027.md) | [js](./javascript/027.js) [ruby](./ruby/027.rb) | |
| 28 | [Implement strStr() ](./problems/028.md) | [js](./javascript/028.js) [ruby](./ruby/028.rb) | 最优算法搜索KMP算法 |
| 30 | [Substring with Concatenation of All Words ](./problems/030.md) | [js](./javascript/030.js) [ruby](./ruby/003.rb) | |
| 31 | [Next permutation ](./problems/031.md) | [js](./javascript/031.js) [ruby](./ruby/031.rb) | 👍 |
| 32 | [Longest Valid Parentheses ](./problems/032.md) | [js](./javascript/032.js) [ruby](./ruby/032.rb) | 👍 |
| 33 | [Search in Rotated Sorted Array ](./problems/033.md) | [js](./javascript/033.js) [ruby](./ruby/033.rb) | |
| 34 | [Search for a Range ](./problems/034.md) | [js](./javascript/034.js) [ruby](./ruby/034.rb) | |
| 35 | [Search Insert Position ](./problems/035.md) | [js](./javascript/035.js) [ruby](./ruby/035.rb) | |
| 36 | [Valid Sudoku ](./problems/036.md) | [js](./javascript/036.js) [ruby](./ruby/036.rb) | |
| 37 | [Sudoku Solver ](./problems/037.md) | [js](./javascript/037.js) [ruby](./ruby/037.rb) | |
| 38 | [Count and Say ](./problems/038.md) | [js](./javascript/038.js) [ruby](./ruby/038.rb) | |
| 39 | [Combination Sum ](./problems/039.md) | [js](./javascript/039.js) [ruby](./ruby/039.rb) | |
| 40 | [Combination Sum II ](./problems/040.md) | [js](./javascript/040.js) [ruby](./ruby/040.rb) | |
| 41 | [First Missing Positive ](./problems/041.md) | [js](./javascript/041.js) [ruby](./ruby/041.rb) | 👍 |
| 42 | [Trapping Rain Water ](./problems/042.md) | [js](./javascript/042.js) [ruby](./ruby/042.rb) | 👍 |
| 43 | [Multiply Strings ](./problems/043.md) | [js](./javascript/043.js) [ruby](./ruby/043.rb) | |
| 44 | [Wildcard Matching ](./problems/044.md) | [js](./javascript/044.js) [ruby](./ruby/044.rb) | 👍 |
| 45 | [Jump Game II ](./problems/045.md) | [js](./javascript/045.js) [ruby](./ruby/045.rb) | 👍 |
| 46 | [Permutations ](./problems/046.md) | [js](./javascript/046.js) [ruby](./ruby/046.rb) | |
| 47 | [Permutations II ](./problems/047.md) | [js](./javascript/047.js) [ruby](./ruby/047.rb) | |
| 48 | [Rotate Image ](./problems/048.md) | [js](./javascript/048.js) [ruby](./ruby/048.rb) | |
| 49 | [Group Anagrams ](./problems/049.md) | [js](./javascript/049.js) [ruby](./ruby/049.rb) | |
| 50 | [Pow(x, n) ](./problems/050.md) | [js](./javascript/050.js) [ruby](./ruby/050.rb) | |
| 51 | [N-Queens ](./problems/051.md) | [js](./javascript/051.js) [ruby 1](./ruby/051_1.rb) [ruby 2](./ruby/051_2.rb) | |
| 52 | [N-Queens-II ](./problems/052.md) | [js](./javascript/052.js) [ruby](./ruby/052.rb) | |
| 53 | [Maximum Subarray ](./problems/053.md) | [js](./javascript/053.js) [ruby](./ruby/053.rb) | |
| 54 | [Spiral Matrix ](./problems/054.md) | [js](./javascript/054.js) [ruby](./ruby/054.rb) | |
| 55 | [Jump Game ](./problems/055.md) | [js](./javascript/055.js) [ruby](./ruby/055.rb) | |
| 56 | [Merge Intervals ](./problems/056.md) | [js](./javascript/056.js) [ruby](./ruby/056.rb) | |
| 57 | [Insert Interval ](./problems/057.md) | [js](./javascript/057.js) [ruby](./ruby/057.rb) | |
| 58 | [Length of Last Word ](./problems/058.md) | [js](./javascript/058.js) [ruby](./ruby/058.rb) | |
| 59 | [Spiral Matrix II ](./problems/059.md) | [js](./javascript/059.js) [ruby](./ruby/059.rb) | |
| 60 | [permutation Sequence ](./problems/060.md) | [js](./javascript/060.js) [ruby](./ruby/060.rb) | |
| 61 | [Rotate List ](./problems/061.md) | [js](./javascript/061.js) [ruby](./ruby/061.rb) | |
| 62 | [Unique Paths ](./problems/062.md) | [js](./javascript/062.js) [ruby](./ruby/062.rb) | |
| 63 | [Unique Paths II ](./problems/063.md) | [js](./javascript/063.js) [ruby](./ruby/063.rb) | |
| 64 | [Minimum Path Sum ](./problems/064.md) | [js](./javascript/064.js) [ruby](./ruby/064.rb) | |
| 66 | [Plus One ](./problems/066.md) | [js](./javascript/066.js) [ruby](./ruby/066.rb) | |
| 67 | [Add Binary ](./problems/067.md) | [js](./javascript/067.js) [ruby](./ruby/067.rb) | |
| 68 | [Text Justification ](./problems/068.md) | [js](./javascript/068.js) | |
| 69 | [Sqrt(x) ](./problems/069.md) | [js](./javascript/069.js) | |
| 70 | [Climbing Stairs ](./problems/070.md) | [js](./javascript/070.js) [ruby](./ruby/070.rb) | |
| 71 | [Simplify Path ](./problems/071.md) | [js](./javascript/071.js) [ruby](./ruby/071.rb) | |
| 72 | [Edit Distance ](./problems/072.md) | [js](./javascript/072.js) [ruby](./ruby/072.rb) | |
| 73 | [Set Matrix Zeroes ](./problems/073.md) | [js](./javascript/073.js) [ruby](./ruby/073.rb) | |
| 74 | [Search a 2D Matrix ](./problems/074.md) | [js](./javascript/074.js) | |
| 75 | [Sort Colors ](./problems/075.md) | [js](./javascript/075.js) [ruby](./ruby/075.rb) | |
| 76 | [Minimum Window Substring ](./problems/076.md) | [js](./javascript/076.js) [ruby](./ruby/076.rb) | |
| 77 | [Combinations ](./problems/077.md) | [js](./javascript/077.js) [ruby](./ruby/077.rb) | |
| 78 | [Subsets ](./problems/078.md) | [js](./javascript/078.js) [ruby](./ruby/078.rb) | |
| 79 | [Word Search ](./problems/079.md) | [js](./javascript/079.js) [ruby](./ruby/079.rb) | |
| 80 | [Remove Duplicates for Sorted Array ](./problems/080.md) | [js](./javascript/080.js) [ruby](./ruby/080.rb) | |
| 81 | [Search in Rotated Sorted Array II ](./problems/081.md) | [js](./javascript/081.js) | |
| 82 | [Remove Duplicates from Sorted List II ](./problems/082.md) | [js](./javascript/082.js) [ruby](./ruby/082.rb) | |
| 83 | [Remove Duplicates from Sorted List ](./problems/083.md) | [js](./javascript/083.js) [ruby](./ruby/083.rb) | |
| 84 | [Largest Rectangle in Histogram ](./problems/084.md) | [js](./javascript/084.js) [ruby](./ruby/084.rb) | |
| 85 | [Maximal Rectangle ](./problems/085.md) | [js](./javascript/085.js) [ruby](./ruby/085.rb) | |
| 86 | [Partition List ](./problems/086.md) | [js](./javascript/086.js) [ruby](./ruby/086.rb) | |
| 87 | [Scramble String ](./problems/087.md) | [js](./javascript/087.js) [ruby](./ruby/087.rb) | |
| 88 | [Merge Sorted Array ](./problems/088.md) | [js](./javascript/088.js) [ruby](./ruby/088.rb) | |
| 89 | [Gray Code ](./problems/089.md) | [js](./javascript/089.js) | |
| 90 | [Subsets II ](./problems/090.md) | [js](./javascript/090.js) | |
| 91 | [Decode Ways ](./problems/091.md) | [js](./javascript/091.js) | |
| 92 | [Reverse Linked List II ](./problems/092.md) | [js](./javascript/092.js) | |
| 93 | [Restore IP Addresses ](./problems/093.md) | [js](./javascript/093.js) | |
| 94 | [Binary Tree Inorder Traversal ](./problems/094.md) | [js](./javascript/094.js) | |
| 95 | [Unique Binary Search Trees II ](./problems/095.md) | [js](./javascript/095.js) | |
| 96 | [Unique Binary Search Trees ](./problems/096.md) | [js](./javascript/096.js) | |
| 97 | [Interleaving String ](./problems/097.md) | [js](./javascript/097.js) | |
| 98 | [Validate Binary Search Tree ](./problems/098.md) | [js](./javascript/098.js) | |
| 99 | [Recover Binary Search Tree ](./problems/099.md) | [js](./javascript/099.js) | |
| 100 | [Same Tree ](./problems/100.md) | [js](./javascript/100.js) | |
| 101 | [Symmetric Tree ](./problems/101.md) | [js](./javascript/101.js) | |
| 102 | [Binary Tree Level Order Traversal ](./problems/102.md) | [js](./javascript/102.js) | |
| 103 | [Binary Tree ZigZag Level Order Traversal ](./problems/103.md) | [js](./javascript/103.js) | |
| 104 | [Maximum Depth of Binary Tree ](./problems/104.md) | [js](./javascript/104.js) | |
| 105 | [Construct Binary Tree from Preorder and Inorder Traversal ](./problems/105.md) | [js](./javascript/105.js) | |
| 106 | [Construct Binary Tree from Inorder and Postorder Traversal ](./problems/106.md) | [js](./javascript/106.js) | |
| 107 | [Binary Tree Level Order Traversal II ](./problems/107.md) | [js](./javascript/107.js) | |
| 108 | [Convert Sorted Array to Binary Search Tree ](./problems/108.md) | [js](./javascript/108.js) | |
| 109 | [Convert Sorted List to Binary Search Tree ](./problems/109.md) | [js](./javascript/109.js) | |
| 110 | [Balanced Binary Tree ](./problems/110.md) | [js](./javascript/110.js) | |
| 111 | [Minimum Depth of Binary Tree ](./problems/111.md) | [js](./javascript/111.js) | |
| 112 | [Path Sum ](./problems/112.md) | [js](./javascript/112.js) | |
| 113 | [Path Sum II ](./problems/113.md) | [js](./javascript/113.js) | |
| 114 | [Flatten Binary Tree to Linked List ](./problems/114.md) | [js](./javascript/114.js) | |
| 115 | [Distinct Subsequences ](./problems/115.md) | [js](./javascript/115.js) | |
| 116 | [Populating Next Right Pointers in Each Node ](./problems/116.md) | [js](./javascript/116.js) | |
| 117 | [Populating Next Right Pointers in Each Node II ](./problems/116.md) | [js](./javascript/116.js) | |
| 118 | [Pascal's Triangle ](./problems/118.md) | [js](./javascript/118.js) | |
| 119 | [Pascal's Triangle II ](./problems/119.md) | [js](./javascript/119.js) | |
| 120 | [Triangle ](./problems/120.md) | [js](./javascript/120.js) | |
| 121 | [Best Time to Buy and Sell Stock ](./problems/121.md) | [js](./javascript/121.js) | |
| 122 | [Best Time to Buy and Sell Stock II ](./problems/122.md) | [js](./javascript/122.js) | |
| 123 | [Best Time to Buy and Sell Stock III ](./problems/123.md) | [js](./javascript/123.js) | |
| 124 | [Binary Tree Maximum Path Sum ](./problems/124.md) | [js](./javascript/124.js) | |
| 125 | [Valid Palindrome ](./problems/125.md) | [js](./javascript/125.js) | |
| 127 | [Word Ladder ](./problems/127.md) | [js](./javascript/127.js) | |
| 129 | [Sum Root to Leaf Numbers ](./problems/129.md) | [js](./javascript/129.js) | |
| 130 | [Surrounded Regions ](./problems/130.md) | [js](./javascript/130.js) | |
| 131 | [Palindrome partitioning ](./problems/131.md) | [js](./javascript/131.js) | |
| 136 | [Single Number ](./problems/136.md) | [js](./javascript/136.js) | |
| 137 | [Single Number II ](./problems/137.md) | [js](./javascript/137.js) | |
| 138 | [Copy List with Random Pointer ](./problems/138.md) | [js](./javascript/138.js) | |
| 139 | [Word Break ](./problems/139.md) | [js](./javascript/139.js) | |
| 140 | [Word Break II ](./problems/140.md) | [js](./javascript/140.js) | |
| 141 | [Linked List Cycle ](./problems/141.md) | [js](./javascript/141.js) | |
| 142 | [Linked List Cycle II ](./problems/142.md) | [js](./javascript/142.js) | |
| 143 | [Reorder List ](./problems/143.md) | [js](./javascript/143.js) | |
| 144 | [Binary Tree Preorder Traversal ](./problems/144.md) | [js](./javascript/144.js) | |
| 145 | [Binary Tree Postorder Traversal ](./problems/145.md) | [js](./javascript/145.js) | |
| 146 | [LRU Cache ](./problems/146.md) | [js](./javascript/146.js) | |
| 147 | [Insertion Sort List ](./problems/147.md) | [js](./javascript/147.js) | |
| 150 | [Evaluate Reverse Polish Notation ](./problems/150.md) | [js](./javascript/150.js) | |
| 160 | [Intersection of Two Linked Lists ](./problems/160.md) | [js](./javascript/160.js) | |<file_sep>/ruby/087.rb
# @param {String} s1
# @param {String} s2
# @return {Boolean}
def is_scramble(s1, s2)
return false if s1.length != s2.length
return s1 == s2 if s1.length == 1
all_match = true
s1_array = s1.split("").sort!
s2_array = s2.split("").sort!
s1_array.each_with_index do |char, index|
if char != s2_array[index]
all_match = false
break
end
end
return false if !all_match
any_match = false
1.upto(s1.length - 1).each do |end_pos|
s1_part1 = s1[0...end_pos]
s1_part2 = s1[end_pos..s1.length]
s2_part1 = s2[0...end_pos]
s2_part2 = s2[end_pos..s2.length]
if is_scramble(s1_part1, s2_part1) && is_scramble(s1_part2, s2_part2)
any_match = true
break
end
end_pos = s1.length - end_pos
s2_part1 = s2[0...end_pos]
s2_part2 = s2[end_pos...s2.length]
if is_scramble(s1_part1, s2_part2) && is_scramble(s1_part2, s2_part1)
any_match = true
break
end
end
return any_match
end<file_sep>/ruby/024.rb
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} head
# @return {ListNode}
def swap_pairs(head)
return head if head.nil?
first = head.next
return head if first.nil?
second = swap_pairs(first.next)
first.next = head
head.next = second
first
end
|
67da1a58381e49f7963ba60d5cb4f527b996bdd6
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 153
|
Ruby
|
superchen14/leetcode
|
ed86ed9f9e15d509134cce90e3726e9d7e6c3440
|
ba151ac5479d597b097e9f9d91adefaf7c4718a8
|
refs/heads/master
|
<file_sep>package com.liuyan.beans;
import com.liuyan.core.FactoryBean;
/**
* @author liuyan
* @date 2018/10/16 15:46
*/
public class BeanDefinition extends FactoryBean{
private String beanClassName;
private boolean lazyInit = false;
private String factoryBeanname;
private boolean isSimple =true;
public String getBeanClassName() {
return beanClassName;
}
public void setBeanClassName(String beanClassName) {
this.beanClassName = beanClassName;
}
public boolean isLazyInit() {
return lazyInit;
}
public void setLazyInit(boolean lazyInit) {
this.lazyInit = lazyInit;
}
public String getFactoryBeanname() {
return factoryBeanname;
}
public void setFactoryBeanname(String factoryBeanname) {
this.factoryBeanname = factoryBeanname;
}
public boolean isSimple() {
return isSimple;
}
public void setSimple(boolean simple) {
isSimple = simple;
}
}
<file_sep>package com.liuyan.core;
/**
* @author zhaoxiuhuan
* @date 2018/10/25 16:44
*/
public class FactoryBean {
}
<file_sep>package com.liuyan.demo.mvc.action;
import com.liuyan.annotation.Autowired;
import com.liuyan.annotation.LyController;
import com.liuyan.annotation.LyRequestMapping;
import com.liuyan.annotation.RequestParam;
import com.liuyan.beans.LyModelAndView;
import com.liuyan.demo.service.IDemoService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@LyController
@LyRequestMapping("/demo")
public class DemoAction {
@Autowired
private IDemoService demoService;
@LyRequestMapping("/query.json")
public LyModelAndView query(HttpServletRequest req, HttpServletResponse resp,
@RequestParam("name") String name){
String result = demoService.get(name);
System.out.println(result);
try {
resp.getWriter().write(result);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@LyRequestMapping("/edit.json")
public LyModelAndView edit(HttpServletRequest req,HttpServletResponse resp,Integer id){
return null;
}
}
<file_sep>package com.liuyan.beans;
import com.liuyan.core.FactoryBean;
/**
* @author zhaoxiuhuan
* @date 2018/10/16 15:46
*/
public class BeanWrapper extends FactoryBean {
//还会用到观察者模式
//支持时间响应会有一个监听
private BeanPostProcessor beanPostProcessor;
private Object wrapperInstance;
private Object originalInstance;
public BeanWrapper(Object instance) {
this.wrapperInstance = instance;
this.originalInstance=instance;
}
public Object getWrappedInstance(){
return this.wrapperInstance;
}
//返回代理以后的class
public Class<?> getWrapperClass(){
return this.wrapperInstance.getClass();
}
}
|
037140924988f3bf888c1452d9e2d28ccae19e2d
|
[
"Java"
] | 4
|
Java
|
atguiguliuyan/myspring
|
6d9c809267fc10289320355ccdf6a3f847ca3a7f
|
76d48b22de06bcbc23e5b3f0beed31403882eecb
|
refs/heads/master
|
<file_sep>"# hiking-buddy"
<file_sep>package com.menthoven.arduinoandroid;
import android.app.NotificationManager;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by da Ent on 28/11/2015.
*/
public class ChatAdapter extends ArrayAdapter<ChatMessage> {
public double convertedWeight;
public String initWeight = "1";
public String finalWeight = "1";
public double convertedTemp;
public String initTemp = "1";
public String finalTemp = "1";
public double convertedHumid;
public String initHumid = "1";
public String finalHumid = "1";
public double distance;
public double [] weightArray = new double [10];
int w = 0;
public double [] distaneArray = new double [10];
int d = 0;
public double [] tempArray = new double [10];
int t = 0;
public double [] humidArray = new double [10];
int h = 0;
public double averageWeight;
public double averageDistance;
public double averageTemp;
public double averageHumid;
public double averageWeightFinal;
public double averageDistanceFinal;
public double averageTempFinal;
public double averageHumidFinal;
// View lookup cache
static class ViewHolder {
@Bind(R.id.time_text_view) TextView time;
@Bind(R.id.device_text_view) TextView device;
@Bind(R.id.message_text_view) TextView message;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
public ChatAdapter(Context context) {
super(context, 0);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
ChatMessage chatMessage = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_message, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
/* if (BluetoothActivity.showTimeIsChecked) {
viewHolder.time.setText(chatMessage.getTime());
} else {
viewHolder.time.setText("");
}
*/
// PARSE AND CONVERT WEIGHT
try{
if (chatMessage.getMessage().charAt(0) == '-'){
convertedWeight = 0;
if(w < 10){
weightArray[w] = convertedWeight;
w++;
}
else{
w = 0;
for (int i = 0; i < 10; i++){
averageWeight = averageWeight + weightArray[i];
}
averageWeightFinal = averageWeight/10;
averageWeight = 0;
weightArray = new double [10];
}
}
else{
initWeight = chatMessage.getMessage().split("W")[0];
initWeight = initWeight.replaceAll("\\D+","");
convertedWeight = Double.parseDouble(initWeight);
convertedWeight = convertedWeight /200;
if(w < 10){
weightArray[w] = convertedWeight;
w++;
}
else{
w = 0;
for (int i = 0; i < 10; i++){
averageWeight = averageWeight + weightArray[i];
}
averageWeightFinal = averageWeight/10;
averageWeight = 0;
weightArray = new double [10];
}
}
finalWeight = Double.toString(convertedWeight);
viewHolder.time.setText(finalWeight);
// PARSE AND CONVERT TEMPERATURE
initTemp = chatMessage.getMessage();
initTemp = initTemp.substring(initTemp.indexOf("W") + 1);
initTemp = initTemp.substring(0, initTemp.indexOf("T"));
initTemp = initTemp.replaceAll("\\D+","");
convertedTemp = Double.parseDouble(initTemp);
convertedTemp = convertedTemp/100;
if(t < 10){
tempArray[t] = convertedTemp;
t++;
}
else{
t = 0;
for (int i = 0; i < 10; i++){
averageTemp = averageTemp + tempArray[i];
}
averageTempFinal = averageTemp/10;
averageTemp = 0;
tempArray = new double [10];
}
finalTemp = Double.toString(convertedTemp);
viewHolder.device.setText(finalTemp);
// PARSE AND CONVERT HUMIDITY
initHumid = chatMessage.getMessage();
initHumid = initHumid.substring(initHumid.indexOf("T") + 1);
initHumid = initHumid.substring(0, initHumid.indexOf("H"));
initHumid = initHumid.replaceAll("\\D+","");
convertedHumid = Double.parseDouble(initHumid);
convertedHumid = convertedHumid/100;
if(h < 10){
humidArray[h] = convertedHumid;
h++;
}
else{
h = 0;
for (int i = 0; i < 10; i++){
averageHumid = averageHumid + humidArray[i];
}
averageHumidFinal = averageHumid/10;
averageHumid = 0;
humidArray = new double [10];
}
finalHumid = Double.toString(convertedHumid);
//viewHolder.message.setText(finalHumid);
}
catch (StringIndexOutOfBoundsException | NumberFormatException e){
}
//calculate the remaining distance
distance = distanceCalc(averageWeightFinal, averageTempFinal, averageHumidFinal);
viewHolder.message.setText(Double.toString(distance));
// Return the completed to render on screen
return convertView;
}
public double distanceCalc(double weight, double temp, double humid){
double tempFactor = -(1/130)*temp + 2;
double tempHumid = -(1/130)*humid + 2;
double distance = ((tempFactor + tempHumid)/2)*weight;
distance = distance/100;
return distance;
}
public double getConvertedWeight(){
return convertedWeight;
}
public double getDistance(){
return distance;
}
public double getConvertedTemp(){
return convertedTemp;
}
public double getConvertedHumid(){
return convertedHumid;
}
public double getAverageWeightFinal(){
return averageWeightFinal;
}
public double getAverageDistanceFinal(){
return averageDistanceFinal;
}
public double getAverageTempFinal(){
return averageTempFinal;
}
public double getAverageHumidFinal(){
return averageHumidFinal;
}
}<file_sep>package com.menthoven.arduinoandroid;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import butterknife.Bind;
public class ImageChangingActivity extends Activity {
/*
private Integer images[] = {R.drawable.waterdrop, R.drawable.waterdrop75, R.drawable.waterdrop50};
private int currImage = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(Constants.TAG, "AAAAAAAAAAAAAAAA");
super.onCreate(savedInstanceState);
setContentView(R.layout.item_message);
setInitialImage();
setImageRotateListener();
}
public void setImageRotateListener() {
Log.d(Constants.TAG, "AAAAAAAAAA");
final Button rotatebutton = (Button) findViewById(R.id.btnRotateImage);
rotatebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
currImage++;
if (currImage == 3) {
currImage = 0;
}
setCurrentImage();
}
});
}
public void setInitialImage() {
Log.d(Constants.TAG, "AAAAAAAAAAAAAAA");
setCurrentImage();
}
public void setCurrentImage() {
Log.d(Constants.TAG, "AAAAAAAAAAAAAAr");
final ImageView imageView = (ImageView) findViewById(R.id.imageDisplay);
imageView.setImageResource(images[currImage]);
}*/
}
|
efd9db3044cd1ed86aeb4ab1541f7eaf5ebbd56f
|
[
"Markdown",
"Java"
] | 3
|
Markdown
|
mirmulk/hiking-buddy
|
620d4393327199b39ea569493b26ba01601f45e5
|
9ba56d8c117f14f32fe7551659e5259f02ef1721
|
refs/heads/master
|
<repo_name>carlba/flast<file_sep>/README.md
# flast
A simple flask application
<file_sep>/setup.py
from distutils.core import setup
setup(
name='flast',
version='0.1',
packages=[''],
url='',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='A simple flask application'
)
|
570e349c06f6063d014644be53ded4ddda6572b8
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
carlba/flast
|
5fe598b459f53ef811f7a6c80c86557aa151a1f7
|
3f84866fe9b11d1a31c856eaf59b0dd3f181ce84
|
refs/heads/master
|
<repo_name>zuowenzhan/LiveRookie<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/MainActivity.java
package com.projectdemo.zwz.liverookie;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import com.projectdemo.zwz.liverookie.base.BaseActivity;
import com.projectdemo.zwz.liverookie.fragment.LiveMainFragment;
import com.projectdemo.zwz.liverookie.fragment.UserInfoFragment;
public class MainActivity extends BaseActivity {
private FragmentTabHost mTabHost;
private final Class mTabFangment[] = {LiveMainFragment.class, Fragment.class, UserInfoFragment.class};
private int mTabIcons[] = {R.drawable.tab_live_selector, R.drawable.tab_room_selector, R.drawable.tab_me_selector};
private String mTabNames[] = {"video", "publish", "user"};
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void initView() {
mTabHost = obtainView(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.contentPanel);
}
@Override
protected void initData() {
int fragmentCount = mTabFangment.length;
TabHost.TabSpec tabSpec;
for (int i = 0; i < fragmentCount; i++) {
tabSpec = mTabHost.newTabSpec(mTabNames[i]).setIndicator(getTabItemView(i));
mTabHost.addTab(tabSpec, mTabFangment[i], null);
}
}
private View getTabItemView(int index) {
View view;
if (index % 2 == 0) {
view = LayoutInflater.from(this).inflate(R.layout.tab_button1, null);
} else {
view = LayoutInflater.from(this).inflate(R.layout.tab_button, null);
}
ImageView icon = (ImageView) view.findViewById(R.id.tab_icon);
icon.setImageResource(mTabIcons[index]);
return view;
}
@Override
protected void setListener() {
}
public static void invoke(Context context) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/adapter/ChatMsgListAdapter.java
package com.projectdemo.zwz.liverookie.adapter;
import android.content.Context;
import android.widget.TextView;
import com.projectdemo.zwz.liverookie.R;
import com.projectdemo.zwz.liverookie.base.BaseAdapter;
import com.projectdemo.zwz.liverookie.model.ChatMsg;
import java.util.List;
/**
* @Description: 消息列表的Adapter
* @author: Andruby
* @date: 2016年7月9日
*/
public class ChatMsgListAdapter extends BaseAdapter<ChatMsg> {
public ChatMsgListAdapter(Context context, List<ChatMsg> dataList) {
super(context, dataList);
}
@Override
protected int getViewLayoutId() {
return R.layout.listview_msg_item;
}
@Override
protected void initData(ViewHolder viewHolder, ChatMsg data, int position) {
TextView tvMsg = viewHolder.getView(R.id.tv_msg);
//谁发给谁的消息是
tvMsg.setText(String.format("%s发给%的消息是%s",data.sendName,data.receiveName,data.msg));
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/util/BitmapUtils.java
package com.projectdemo.zwz.liverookie.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.view.View;
/**
* @description: Bitmap工具
* 高斯模糊
*
* @author: Andruby
* @time: 2016/12/17 10:23
*/
public class BitmapUtils {
public static Bitmap blurBitmap(Context context, Bitmap bitmap) {
Bitmap copy = bitmap.copy(bitmap.getConfig(), true);
Bitmap outBitmap = Bitmap.createBitmap(copy.getWidth(), copy.getHeight(), Bitmap.Config.ARGB_8888);
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation allIn = Allocation.createFromBitmap(rs, copy);
Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
blurScript.setRadius(25.f);
blurScript.setInput(allIn);
blurScript.forEach(allOut);
allOut.copyTo(outBitmap);
copy.recycle();
rs.destroy();
return outBitmap;
}
public static Bitmap blurBitmap(Context context, Bitmap bitmap , float radius) {
if(bitmap == null){
return null;
}
Bitmap copy = bitmap.copy(bitmap.getConfig(), true);
Bitmap outBitmap = Bitmap.createBitmap(copy.getWidth(), copy.getHeight(), Bitmap.Config.ARGB_8888);
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation allIn = Allocation.createFromBitmap(rs, copy);
Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
blurScript.setRadius(radius);
blurScript.setInput(allIn);
blurScript.forEach(allOut);
allOut.copyTo(outBitmap);
copy.recycle();
rs.destroy();
return outBitmap;
}
/**
* 获取一个 View 的缓存视图
*
* @param view
* @return
*/
public static Bitmap getCacheBitmapFromView(View view) {
final boolean drawingCacheEnabled = true;
view.setDrawingCacheEnabled(drawingCacheEnabled);
view.buildDrawingCache(drawingCacheEnabled);
final Bitmap drawingCache = view.getDrawingCache();
Bitmap bitmap;
if (drawingCache != null) {
bitmap = Bitmap.createBitmap(drawingCache);
view.setDrawingCacheEnabled(false);
} else {
bitmap = null;
}
return bitmap;
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/presenter/LoginPresenter.java
package com.projectdemo.zwz.liverookie.presenter;
import android.text.TextUtils;
import android.util.Log;
import com.projectdemo.zwz.liverookie.http.AsyncHttp;
import com.projectdemo.zwz.liverookie.http.data.UserInfo;
import com.projectdemo.zwz.liverookie.http.request.LoginRequest;
import com.projectdemo.zwz.liverookie.http.request.PhoneLoginRequest;
import com.projectdemo.zwz.liverookie.http.request.RequestComm;
import com.projectdemo.zwz.liverookie.http.request.VerifyCodeRequest;
import com.projectdemo.zwz.liverookie.http.response.Response;
import com.projectdemo.zwz.liverookie.logic.IMLogin;
import com.projectdemo.zwz.liverookie.logic.IUserInfoMgrListener;
import com.projectdemo.zwz.liverookie.logic.UserInfoMgr;
import com.projectdemo.zwz.liverookie.util.AsimpleCache.ACache;
import com.projectdemo.zwz.liverookie.util.AsimpleCache.CacheConstants;
import com.projectdemo.zwz.liverookie.util.Constants;
import com.projectdemo.zwz.liverookie.util.OtherUtils;
/**
* Created by ylzx on 2017/6/23.
*登录逻辑处理
*
*/
public class LoginPresenter extends ILoginPresenter implements IMLogin.IMLoginListener {
private ILoginView mLoginView;
private IMLogin mIMLogin = IMLogin.getInstance();
public LoginPresenter(ILoginView iLoginView) {
super(iLoginView);
mLoginView=iLoginView;
}
/**
* 验证手机号登录
* @param phone
* @param verifyCode
* @return
*/
@Override
public boolean checkPhoneLogin(String phone, String verifyCode) {
if (OtherUtils.isPhoneNumValid(phone)) {
if (OtherUtils.isVerifyCodeValid(verifyCode)) {
if (OtherUtils.isNetworkAvailable(mLoginView.getContext())) {
return true;
} else {
mLoginView.showMsg("当前无网络连接");
}
} else {
mLoginView.phoneError("验证码错误");
}
} else {
mLoginView.phoneError("手机格式错误");
}
mLoginView.dismissLoading();
return false;
}
@Override
public boolean checkUserNameLogin(String userName, String password) {
if (OtherUtils.isUsernameVaild(userName)) {
if (OtherUtils.isPasswordValid(password)) {
if (OtherUtils.isNetworkAvailable(mLoginView.getContext())) {
return true;
} else {
mLoginView.showMsg("当前无网络连接");
}
} else {
mLoginView.passwordError("密码过短");
}
} else {
mLoginView.usernameError("用户名不符合规范");
}
mLoginView.dismissLoading();
return false;
}
@Override
public void phoneLogin(final String phone, String verifyCode) {
if (checkPhoneLogin(phone, verifyCode)) {
PhoneLoginRequest req = new PhoneLoginRequest(1200, phone, verifyCode);
AsyncHttp.instance().postJson(req, new AsyncHttp.IHttpListener() {
@Override
public void onStart(int requestId) {
mLoginView.showLoading();
}
@Override
public void onSuccess(int requestId, Response response) {
if (response.status == RequestComm.SUCCESS) {
ACache.get(mLoginView.getContext()).put(CacheConstants.LOGIN_USERNAME, phone);
mLoginView.loginSuccess();
} else {
mLoginView.loginFailed(response.status, response.msg);
}
mLoginView.dismissLoading();
}
@Override
public void onFailure(int requestId, int httpStatus, Throwable error) {
mLoginView.verifyCodeFailed("网络异常");
mLoginView.dismissLoading();
}
});
}
}
@Override
public void usernameLogin(final String userName, final String password) {
if (checkUserNameLogin(userName, password)) {
LoginRequest req = new LoginRequest(RequestComm.register, userName, password);
AsyncHttp.instance().postJson(req, new AsyncHttp.IHttpListener() {
@Override
public void onStart(int requestId) {
mLoginView.showLoading();
}
@Override
public void onSuccess(int requestId, Response response) {
if (response.status == RequestComm.SUCCESS) {
UserInfo info = (UserInfo) response.data;
if (!TextUtils.isEmpty(info.sdkAppId) && !TextUtils.isEmpty(info.sdkAccountType)) {
try {
Constants.IMSDK_APPID = Integer.parseInt(info.sdkAppId);
Constants.IMSDK_ACCOUNT_TYPE = Integer.parseInt(info.sdkAccountType);
} catch (Exception e) {
e.printStackTrace();
}
}
UserInfo.saveCache(mLoginView.getContext(), info);
UserInfoMgr.getInstance().setUserInfo(info);
mIMLogin.imLogin(info.userId, info.sigId);
mIMLogin.setIMLoginListener(LoginPresenter.this);
ACache.get(mLoginView.getContext()).put(CacheConstants.LOGIN_USERNAME, userName);
ACache.get(mLoginView.getContext()).put(CacheConstants.LOGIN_PASSWORD, <PASSWORD>);
ACache.get(mLoginView.getContext()).put("user_id", info.userId);
} else {
mLoginView.loginFailed(response.status, response.msg);
mLoginView.dismissLoading();
}
}
@Override
public void onFailure(int requestId, int httpStatus, Throwable error) {
mLoginView.loginFailed(httpStatus, error.getMessage());
mLoginView.dismissLoading();
}
});
}
}
@Override
public void sendVerifyCode(String phoneNum) {
if (OtherUtils.isPhoneNumValid(phoneNum)) {
if (OtherUtils.isNetworkAvailable(mLoginView.getContext())) {
VerifyCodeRequest req = new VerifyCodeRequest(1000, phoneNum);
AsyncHttp.instance().postJson(req, new AsyncHttp.IHttpListener() {
@Override
public void onStart(int requestId) {
mLoginView.showLoading();
}
@Override
public void onSuccess(int requestId, Response response) {
if (response.status == RequestComm.SUCCESS) {
UserInfo userInfo = (UserInfo) response.data;
if (null != mLoginView) {
mLoginView.verifyCodeSuccess(60, 60);
}
} else {
mLoginView.verifyCodeFailed("获取台验证码失败");
}
mLoginView.dismissLoading();
}
@Override
public void onFailure(int requestId, int httpStatus, Throwable error) {
if (null != mLoginView) {
mLoginView.verifyCodeFailed("获取台验证码失败");
}
mLoginView.dismissLoading();
}
});
} else {
mLoginView.showMsg("当前无网络连接");
}
} else {
mLoginView.phoneError("手机号码不符合规范");
}
}
@Override
public void start() {
}
@Override
public void finish() {
}
public void setIMLoginListener() {
mIMLogin.setIMLoginListener(this);
}
public void removeIMLoginListener() {
mIMLogin.removeIMLoginListener();
}
@Override
public void onSuccess() {
UserInfoMgr.getInstance().setUserId(mIMLogin.getLastUserInfo().identifier, new IUserInfoMgrListener() {
@Override
public void OnQueryUserInfo(int error, String errorMsg) {
// TODO: 16/8/10
}
@Override
public void OnSetUserInfo(int error, String errorMsg) {
if (0 != error) {
mLoginView.showMsg("设置 User ID 失败");
}
}
});
mLoginView.showMsg("登陆成功");
mIMLogin.removeIMLoginListener();
mLoginView.dismissLoading();
mLoginView.loginSuccess();
}
@Override
public void onFailure(int code, String msg) {
Log.d("log", "IM Login Error errCode:" + code + " msg:" + msg);
//被踢下线后弹窗显示被踢
if (6208 == code) {
OtherUtils.showKickOutDialog(mLoginView.getContext());
}
mLoginView.showMsg("登录失败");
mLoginView.dismissLoading();
mLoginView.loginFailed(code, msg);
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/http/request/LiveLikeRequest.java
package com.projectdemo.zwz.liverookie.http.request;
import com.google.gson.reflect.TypeToken;
import com.projectdemo.zwz.liverookie.http.response.Response;
import java.lang.reflect.Type;
/**
* @description: 直播喜欢请求
*
* @author: Andruby
* @time: 2016/11/2 18:07
*/
public class LiveLikeRequest extends IRequest {
public LiveLikeRequest(int requestId, String userId, String liveId) {
mRequestId = requestId;
mParams.put("action","liveLike");
mParams.put("userId",userId);
mParams.put("liveId",liveId);
}
@Override
public String getUrl() {
return getHost() + "Live";
}
@Override
public Type getParserType() {
return new TypeToken<Response>() {}.getType();
}
}<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/http/request/FetchGroupMemberListReuest.java
package com.projectdemo.zwz.liverookie.http.request;
import com.google.gson.reflect.TypeToken;
import com.projectdemo.zwz.liverookie.http.data.UserInfo;
import com.projectdemo.zwz.liverookie.http.response.GroupMemberList;
import com.projectdemo.zwz.liverookie.http.response.Response;
import java.lang.reflect.Type;
/**
* @description: 观众列表请求
*
* @author: Andruby
* @time: 2016/11/2 18:07
*/
public class FetchGroupMemberListReuest extends IRequest {
public FetchGroupMemberListReuest(int requestId, String userId, String groupId, String liveId,
String hostId, int pageIndex, int pageSize) {
mRequestId = requestId;
mParams.put("action", "groupMember");
mParams.put("userId", userId);
mParams.put("groupId", groupId);
mParams.put("liveId", liveId);
mParams.put("hostId", hostId);
mParams.put("pageIndex", pageIndex);
mParams.put("pageSize", pageSize);
}
@Override
public String getUrl() {
return getHost() + "Live";
}
@Override
public Type getParserType() {
return new TypeToken<Response<GroupMemberList<UserInfo>>>() {
}.getType();
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/fragment/UserInfoFragment.java
package com.projectdemo.zwz.liverookie.fragment;
import android.view.View;
import com.projectdemo.zwz.liverookie.R;
import com.projectdemo.zwz.liverookie.base.BaseFragment;
/**
* Created by ylzx on 2017/6/26.
*/
public class UserInfoFragment extends BaseFragment {
@Override
protected void initData() {
}
@Override
protected void setListener(View view) {
}
@Override
protected int getLayoutId() {
return R.layout.fragment_user_info;
}
@Override
protected void initView(View rootView) {
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/activity/SplashActivity.java
package com.projectdemo.zwz.liverookie.activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.WindowManager;
import com.projectdemo.zwz.liverookie.base.BaseActivity;
import java.lang.ref.WeakReference;
/**
*欢迎页面
*/
public class SplashActivity extends BaseActivity {
private static final String TAG = SplashActivity.class.getSimpleName();
private static final int START_LOGIN = 2873;
private final MyHandler mHandler = new MyHandler(this);
@Override
protected int getLayoutId() {
return 0;
}
@Override
protected void initView() {
}
@Override
protected void initData() {
if (!isTaskRoot()
&& getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
&& getIntent().getAction() != null
&& getIntent().getAction().equals(Intent.ACTION_MAIN)) {
finish();
return;
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Message msg = Message.obtain();
msg.arg1 = START_LOGIN;
mHandler.sendMessageDelayed(msg, 1000);
}
@Override
protected void setListener() {
}
@Override
public void onBackPressed() {
}
private void jumpToLoginActivity() {
LoginActivity.invoke(this);
finish();
}
private static class MyHandler extends Handler {
private final WeakReference<SplashActivity> mActivity;
public MyHandler(SplashActivity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
SplashActivity activity = mActivity.get();
if (activity != null) {
activity.jumpToLoginActivity();
}
}
}
}<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/base/BaseFragment.java
package com.projectdemo.zwz.liverookie.base;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public abstract class BaseFragment extends Fragment {
protected BaseActivity mContext;
protected Handler mHandler = new Handler();
protected View rootView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = (BaseActivity) getActivity();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (getLayoutId() != 0) {
rootView = inflater.inflate(getLayoutId(), container, false);
} else {
try {
throw new Exception("layout is empty");
} catch (Exception e) {
e.printStackTrace();
}
}
initView(rootView);
initData();
setListener(rootView);
return rootView;
}
/**
* 返回当前界面布局文件
*/
protected abstract int getLayoutId();
/**
* 此方法描述的是: 初始化所有view
*/
protected abstract void initView(View view);
/**
* 此方法描述的是: 初始化所有数据的方法
*/
protected abstract void initData();
/**
* 此方法描述的是: 设置所有事件监听
*/
protected abstract void setListener(View view);
/**
* 显示toast
*
* @param resId
*/
public void showToast(final int resId) {
showToast(getString(resId));
}
public <T extends View> T obtainView(int resId) {
return (T) rootView.findViewById(resId);
}
/**
* 显示toast
*
* @param resStr
* @return Toast对象,便于控制toast的显示与关闭
*/
public Toast showToast(final String resStr) {
if (TextUtils.isEmpty(resStr)) {
return null;
}
Toast toast = null;
mHandler.post(new Runnable() {
@Override
public void run() {
Toast toast = Toast.makeText(mContext, resStr,
Toast.LENGTH_SHORT);
toast.show();
}
});
return toast;
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/http/response/NullObject.java
package com.projectdemo.zwz.liverookie.http.response;
import com.projectdemo.zwz.liverookie.http.IDontObfuscate;
public class NullObject extends IDontObfuscate {
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/model/LiveInfo.java
package com.projectdemo.zwz.liverookie.model;
/**
* 直播信息
* Created by ylzx on 2017/6/27.
*/
public class LiveInfo {
public String userId;
public String groupId;
public String liveId;
public int createTime;
public int type;
public int viewCount;
public int likeCount;
public String title;
public String playUrl;
public String fileId;
public String liveCover;
//TCLiveUserInfo
public TCLiveUserInfo userInfo;
public class TCLiveUserInfo {
public String userId;
public String nickname;
public String headPic;
public String frontcover;
public String location;
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/presenter/RegisterPresenter.java
package com.projectdemo.zwz.liverookie.presenter;
import com.projectdemo.zwz.liverookie.http.AsyncHttp;
import com.projectdemo.zwz.liverookie.http.data.UserInfo;
import com.projectdemo.zwz.liverookie.http.request.PhoneRegisterRequest;
import com.projectdemo.zwz.liverookie.http.request.RegisterRequest;
import com.projectdemo.zwz.liverookie.http.request.RequestComm;
import com.projectdemo.zwz.liverookie.http.request.VerifyCodeRequest;
import com.projectdemo.zwz.liverookie.http.response.Response;
import com.projectdemo.zwz.liverookie.util.OtherUtils;
/**
*
* 注册信息管理
* Created by ylzx on 2017/6/26.
*/
public class RegisterPresenter extends IRegisterPresenter {
public static final String TAG = RegisterPresenter.class.getSimpleName();
private IRegisterView mIRegisterView;
public RegisterPresenter(IRegisterView iRegisterView) {
super(iRegisterView);
mIRegisterView = iRegisterView;
}
@Override
public void sendVerifyCode(String phoneNum) {
if (OtherUtils.isPhoneNumValid(phoneNum)) {
if (OtherUtils.isNetworkAvailable(mIRegisterView.getContext())) {
VerifyCodeRequest req = new VerifyCodeRequest(1000, phoneNum);
AsyncHttp.instance().postJson(req, new AsyncHttp.IHttpListener() {
@Override
public void onStart(int requestId) {
mIRegisterView.showLoading();
}
@Override
public void onSuccess(int requestId, Response response) {
if (response.status == RequestComm.SUCCESS) {
UserInfo userInfo = (UserInfo) response.data;
if (null != mIRegisterView) {
mIRegisterView.verifyCodeSuccess(60, 60);
}
} else {
mIRegisterView.verifyCodeFailed("获取台验证码失败");
}
mIRegisterView.dismissLoading();
}
@Override
public void onFailure(int requestId, int httpStatus, Throwable error) {
if (null != mIRegisterView) {
mIRegisterView.verifyCodeFailed("获取台验证码失败");
}
mIRegisterView.dismissLoading();
}
});
} else {
mIRegisterView.showMsg("当前无网络连接");
}
} else {
mIRegisterView.showRegistError("手机号码不符合规范");
}
}
@Override
protected boolean checkNormalRegister(String username, String password, String passwordVerify) {
if (OtherUtils.isUsernameVaild(username)) {
if (OtherUtils.isPasswordValid(password)) {
if (password.equals(passwordVerify)) {
if (OtherUtils.isNetworkAvailable(mIRegisterView.getContext())) {
return true;
} else {
mIRegisterView.showMsg("当前无网络连接");
}
} else {
mIRegisterView.showPasswordError("两次输入密码不一致");
}
} else {
mIRegisterView.showPasswordError("密码长度应为6-16位");
}
} else {
mIRegisterView.showRegistError("用户名不符合规范");
}
return false;
}
@Override
protected boolean checkPhoneRegister(String phoneNum, String verifyCode) {
if (OtherUtils.isPhoneNumValid(phoneNum)) {
if (OtherUtils.isVerifyCodeValid(verifyCode)) {
if (OtherUtils.isNetworkAvailable(mIRegisterView.getContext())) {
return true;
} else {
mIRegisterView.showMsg("当前无网络连接");
}
} else {
mIRegisterView.showPasswordError("验证码格式错误");
}
} else {
mIRegisterView.showPhoneError("手机号码不符合规范");
}
return false;
}
@Override
public void normalRegister(final String username, String password, String passwordVerify) {
if (checkNormalRegister(username, password, passwordVerify)) {
RegisterRequest req = new RegisterRequest(RequestComm.register, username, password);
AsyncHttp.instance().postJson(req, new AsyncHttp.IHttpListener() {
@Override
public void onStart(int requestId) {
mIRegisterView.showLoading();
}
@Override
public void onSuccess(int requestId, Response response) {
if (response.status == RequestComm.SUCCESS) {
UserInfo userInfo = (UserInfo) response.data;
if (null != mIRegisterView) {
mIRegisterView.onSuccess(username);
}
} else {
mIRegisterView.onFailure(response.status, response.msg);
}
mIRegisterView.dismissLoading();
}
@Override
public void onFailure(int requestId, int httpStatus, Throwable error) {
if (null != mIRegisterView) {
mIRegisterView.onFailure(httpStatus, error.getMessage());
}
mIRegisterView.dismissLoading();
}
});
}
}
@Override
public void phoneRegister(String username, String verifyCode) {
if (checkPhoneRegister(username, verifyCode)) {
PhoneRegisterRequest req = new PhoneRegisterRequest(RequestComm.register, username, verifyCode);
AsyncHttp.instance().postJson(req, new AsyncHttp.IHttpListener() {
@Override
public void onStart(int requestId) {
mIRegisterView.showLoading();
}
@Override
public void onSuccess(int requestId, Response response) {
if (response.status == RequestComm.SUCCESS) {
if (null != mIRegisterView) {
mIRegisterView.onSuccess(null);
}
} else {
mIRegisterView.verifyCodeError("验证码不正确");
}
mIRegisterView.dismissLoading();
}
@Override
public void onFailure(int requestId, int httpStatus, Throwable error) {
if (null != mIRegisterView) {
mIRegisterView.onFailure(httpStatus, "网络异常");
}
mIRegisterView.dismissLoading();
}
});
}
}
@Override
public void start() {
}
@Override
public void finish() {
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/http/request/PhoneRegisterRequest.java
package com.projectdemo.zwz.liverookie.http.request;
import com.google.gson.reflect.TypeToken;
import com.projectdemo.zwz.liverookie.http.response.Response;
import java.lang.reflect.Type;
/**
* Created by ylzx on 2017/6/26.
*/
public class PhoneRegisterRequest extends IRequest {
public PhoneRegisterRequest(int requestId, String mobile, String verifyCode) {
mRequestId = requestId;
mParams.put("action", "phoneRegister");
mParams.put("mobile", mobile);
mParams.put("verifyCode", verifyCode);
}
@Override
public String getUrl() {
return getHost() + "User";
}
@Override
public Type getParserType() {
return new TypeToken<Response>() {
}.getType();
}
}<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/activity/LoginActivity.java
package com.projectdemo.zwz.liverookie.activity;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.projectdemo.zwz.liverookie.MainActivity;
import com.projectdemo.zwz.liverookie.R;
import com.projectdemo.zwz.liverookie.base.BaseActivity;
import com.projectdemo.zwz.liverookie.presenter.ILoginPresenter;
import com.projectdemo.zwz.liverookie.presenter.LoginPresenter;
import com.projectdemo.zwz.liverookie.util.AsimpleCache.ACache;
import com.projectdemo.zwz.liverookie.util.AsimpleCache.CacheConstants;
import com.projectdemo.zwz.liverookie.util.OtherUtils;
import java.lang.ref.WeakReference;
public class LoginActivity extends BaseActivity implements ILoginPresenter.ILoginView, View.OnClickListener {
//共用控件
private ProgressBar progressBar;
private EditText etPassword;
private EditText etLogin;
private Button btnLogin;
private Button btnPhoneLogin;
private TextInputLayout tilLogin, tilPassword;
private Button btnRegister;
//手机验证登陆控件
private TextView tvVerifyCode;
private boolean isPhoneLogin = false;
private LoginPresenter mLoginPresenter;
@Override
protected void initView() {
mLoginPresenter = new LoginPresenter(this);
etLogin = obtainView(R.id.et_login_username);
etPassword = obtainView(R.id.et_password);
btnRegister = obtainView(R.id.btn_register);
btnPhoneLogin = obtainView(R.id.btn_phone_login);
btnLogin = obtainView(R.id.btn_login);
progressBar = obtainView(R.id.progressbar);
tilLogin = obtainView(R.id.tl_login_name);
tilPassword = obtainView(R.id.til_password);
tvVerifyCode = obtainView(R.id.btn_verify_code);
userNameLoginViewInit();
}
@Override
protected void initData() {
//获取存储
etLogin.setText(ACache.get(this).getAsString(CacheConstants.LOGIN_USERNAME));
etPassword.setText(ACache.get(this).getAsString(CacheConstants.LOGIN_PASSWORD));
}
@Override
protected void setListener() {
}
@Override
protected void onResume() {
super.onResume();
//设置登录回调,resume设置回调避免被registerActivity冲掉
mLoginPresenter.setIMLoginListener();
}
@Override
protected void onPause() {
super.onPause();
//删除登录回调
mLoginPresenter.removeIMLoginListener();
}
public static void invoke(Context context) {
Intent intent = new Intent(context, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
}
public void showLoginError(String errorString) {
etLogin.setError(errorString);
showOnLoading(false);
}
public void showPasswordError(String errorString) {
etPassword.setError(errorString);
showOnLoading(false);
}
@Override
public void loginSuccess() {
//登录成功
dismissLoading();
MainActivity.invoke(this);
finish();
}
@Override
public void loginFailed(int status, String msg) {
dismissLoading();
showMsg("登陆失败:" + msg);
}
@Override
public void usernameError(String errorMsg) {
etLogin.setError(errorMsg);
}
@Override
public void phoneError(String errorMsg) {
etLogin.setError(errorMsg);
}
@Override
public void passwordError(String errorMsg) {
etPassword.setError(errorMsg);
}
@Override
public void verifyCodeError(String errorMsg) {
showMsg("验证码错误");
}
@Override
public void verifyCodeFailed(String errorMsg) {
showMsg("获取验证码失败");
}
@Override
public void verifyCodeSuccess(int reaskDuration, int expireDuration) {
showMsg("注册短信下发,验证码" + expireDuration / 60 + "分钟内有效");
OtherUtils.startTimer(new WeakReference<>(tvVerifyCode), "验证码", reaskDuration, 1);
}
@Override
public void showLoading() {
showOnLoading(true);
}
@Override
public void dismissLoading() {
showOnLoading(false);
}
@Override
public void showMsg(String msg) {
showToast(msg);
}
@Override
public void showMsg(int msg) {
showToast(msg);
}
@Override
public Context getContext() {
return this;
}
@Override
protected int getLayoutId() {
return R.layout.activity_login;
}
/**
* 手机验证码登录
*/
private void phoneLoginViewinit() {
isPhoneLogin = true;
tvVerifyCode.setVisibility(View.VISIBLE);
AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(250);
tvVerifyCode.setAnimation(alphaAnimation);
//设定点击优先级于最前(避免被EditText遮挡的情况)
tvVerifyCode.bringToFront();
etLogin.setInputType(EditorInfo.TYPE_CLASS_PHONE);
btnPhoneLogin.setText(getString(R.string.activity_login_normal_login));
tilLogin.setHint(getString(R.string.activity_login_phone_num));
tilPassword.setHint(getString(R.string.activity_login_verify_code_edit));
tvVerifyCode.setOnClickListener( this);
btnPhoneLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//转换为用户名登录界面
userNameLoginViewInit();
}
});
btnLogin.setOnClickListener(this);
}
/**
* 用户名密码登录界面init
*/
public void userNameLoginViewInit() {
isPhoneLogin = false;
tvVerifyCode.setVisibility(View.GONE);
AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
alphaAnimation.setDuration(250);
tvVerifyCode.setAnimation(alphaAnimation);
etLogin.setInputType(EditorInfo.TYPE_CLASS_TEXT);
etLogin.setText("");
etPassword.setText("");
btnPhoneLogin.setText(getString(R.string.activity_login_phone_login));
tilLogin.setHint(getString(R.string.activity_login_username));
tilPassword.setHint(getString(R.string.activity_login_password));
btnRegister.setOnClickListener(this);
btnPhoneLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//转换为手机登录界面
phoneLoginViewinit();
}
});
btnLogin.setOnClickListener(this);
}
/**
* trigger loading模式
*
* @param active
*/
public void showOnLoading(boolean active) {
if (active) {
progressBar.setVisibility(View.VISIBLE);
btnLogin.setVisibility(View.INVISIBLE);
etLogin.setEnabled(false);
etPassword.setEnabled(false);
btnPhoneLogin.setClickable(false);
btnPhoneLogin.setTextColor(getResources().getColor(R.color.colorLightTransparentGray));
btnRegister.setClickable(false);
} else {
progressBar.setVisibility(View.GONE);
btnLogin.setVisibility(View.VISIBLE);
etLogin.setEnabled(true);
etPassword.setEnabled(true);
btnPhoneLogin.setClickable(true);
btnPhoneLogin.setTextColor(getResources().getColor(R.color.colorTransparentGray));
btnRegister.setClickable(true);
btnRegister.setTextColor(getResources().getColor(R.color.colorTransparentGray));
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
if (isPhoneLogin) {
//手机登录逻辑
mLoginPresenter.phoneLogin(etLogin.getText().toString(), etPassword.getText().toString());
} else {
//调用normal登录逻辑
mLoginPresenter.usernameLogin(etLogin.getText().toString(), etPassword.getText().toString());
}
break;
case R.id.btn_verify_code:
mLoginPresenter.sendVerifyCode(etLogin.getText().toString());
break;
case R.id.btn_register:
RegisterActivity.invoke(this);
break;
}
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/ui/customviews/OnProcessFragment.java
package com.projectdemo.zwz.liverookie.ui.customviews;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import com.projectdemo.zwz.liverookie.R;
/**
* @description:
* @author: Andruby
* @time: 2016/12/17 10:23
*/
public class OnProcessFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = new Dialog(getActivity(), R.style.loading_dialog);
dialog.setContentView(R.layout.fragment_loading);
dialog.setCancelable(false);
return dialog;
}
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/util/AsimpleCache/CacheConstants.java
package com.projectdemo.zwz.liverookie.util.AsimpleCache;
/**
* @description: 存储的字段
* @author: Andruby
* @time: 2016/12/21 09:51
*/
public class CacheConstants {
public static final String LOGIN_USERNAME ="login_username";
public static final String LOGIN_PASSWORD ="<PASSWORD>";
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/presenter/LiveListPresenter.java
package com.projectdemo.zwz.liverookie.presenter;
import com.projectdemo.zwz.liverookie.http.AsyncHttp;
import com.projectdemo.zwz.liverookie.http.request.LiveListRequest;
import com.projectdemo.zwz.liverookie.http.request.RequestComm;
import com.projectdemo.zwz.liverookie.http.response.ResList;
import com.projectdemo.zwz.liverookie.http.response.Response;
import com.projectdemo.zwz.liverookie.model.LiveInfo;
import com.projectdemo.zwz.liverookie.util.AsimpleCache.ACache;
import com.projectdemo.zwz.liverookie.util.Constants;
import com.projectdemo.zwz.liverookie.util.LogDebugUtil;
import java.util.ArrayList;
/**
* 直播列表管理
* Created by ylzx on 2017/6/27.
*/
public class LiveListPresenter extends ILiveListPresenter {
private static final String TAG = LiveListPresenter.class.getSimpleName();
private boolean mHasMore;
private boolean isLoading;
private ArrayList<LiveInfo> mLiveInfoList = new ArrayList<>();
private ILiveListView mLiveListView;
public LiveListPresenter(ILiveListView liveListView) {
super(liveListView);
mLiveListView=liveListView;
}
/**
* 获取缓存列表
* @return
*/
@Override
public ArrayList<LiveInfo> getLiveListFormCache() {
return mLiveInfoList;
}
@Override
public boolean reloadLiveList() {
LogDebugUtil.e(TAG, "fetchLiveList start");
mLiveInfoList.clear();
fetchLiveList(RequestComm.live_list, ACache.get(mBaseView.getContext()).getAsString("user_id"), 1, Constants.PAGESIZE);
return true;
}
/**
* 分页加载数据
* @return
*/
@Override
public boolean loadDataMore() {
if (mHasMore) {
int pageIndex = mLiveInfoList.size() / Constants.PAGESIZE + 1;
fetchLiveList(RequestComm.live_list_more, ACache.get(mBaseView.getContext()).getAsString("user_id"), pageIndex, Constants.PAGESIZE);
}
return true;
}
public boolean isLoading() {
return isLoading;
}
public boolean isHasMore() {
return mHasMore;
}
@Override
public void start() {
}
@Override
public void finish() {
}
/**
* 获取直播列表
*
* @param type 1:拉取在线直播列表 2:拉取7天内录播列表 3:拉取在线直播和7天内录播列表,直播列表在前,录播列表在后
* @param pageIndex 页数
* @param pageSize 每页个数
*/
public void fetchLiveList(final int type, final String userId, final int pageIndex, final int pageSize) {
LiveListRequest request = new LiveListRequest(type, userId, pageIndex, pageSize);
AsyncHttp.instance().postJson(request, new AsyncHttp.IHttpListener() {
@Override
public void onStart(int requestId) {
isLoading = true;
}
@Override
public void onSuccess(int requestId, Response response) {
LogDebugUtil.e(TAG, "onSuccess");
if (response.status == RequestComm.SUCCESS) {
ResList<LiveInfo> resList = (ResList<LiveInfo>) response.data;
if (resList != null) {
ArrayList<LiveInfo> result = (ArrayList<LiveInfo>) resList.items;
if (result != null && !result.isEmpty()) {
mLiveInfoList.addAll(result);
mHasMore = (mLiveInfoList.size() >= pageIndex * Constants.PAGESIZE);
if (mLiveListView != null) {
mLiveListView.onLiveList(0, mLiveInfoList, pageIndex == 1);
}
} else {
mHasMore = false;
if (mLiveListView != null) {
mLiveListView.onLiveList(0, mLiveInfoList, pageIndex == 1);
}
}
} else {
if (mLiveListView != null) {
mLiveListView.onLiveList(1, null, true);
}
}
} else {
if (mLiveListView != null) {
mLiveListView.onLiveList(1, null, true);
}
}
isLoading = false;
}
@Override
public void onFailure(int requestId, int httpStatus, Throwable error) {
LogDebugUtil.e(TAG, "onFailure");
if (mLiveListView != null) {
mLiveListView.onLiveList(1, null, false);
}
isLoading = false;
}
});
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'android-apt'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.projectdemo.zwz.liverookie"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
//推荐使用最高的API Level
renderscriptTargetApi 15
//指定在运行的设备不是target version的时候,生成的字节码需要回滚到兼容的版本
renderscriptSupportModeEnabled true
}
buildTypes {
release {
minifyEnabled true
//shrinkResources为true在打包时会删除没有用到的资源
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.zhy:okhttputils:2.6.2'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.zhy:autolayout:1.4.5'
compile 'com.google.code.gson:gson:2.3.1'
//腾讯云直播
compile files('src/main/jniLibs/bugly_crash_release.jar')
compile files('src/main/jniLibs/imsdk.jar')
compile files('src/main/jniLibs/mobilepb.jar')
compile files('src/main/jniLibs/nineoldandroids-2.4.0.jar')
compile files('src/main/jniLibs/qalsdk.jar')
compile files('src/main/jniLibs/soload.jar')
compile files('src/main/jniLibs/tls_sdk.jar')
compile files('src/main/jniLibs/txrtmpsdk.jar')
compile files('src/main/jniLibs/upload_1.1.4.1.jar')
compile files('src/main/jniLibs/wup-1.0.0-SNAPSHOT.jar')
//butterknife
compile 'com.jakewharton:butterknife:8.1.0'
apt 'com.jakewharton:butterknife-compiler:8.1.0'
//android上开源弹幕解析绘制引擎项目
compile 'com.github.ctiao:dfm:0.4.4'
}
<file_sep>/app/src/main/java/com/projectdemo/zwz/liverookie/ui/customviews/BeautyDialogFragment.java
package com.projectdemo.zwz.liverookie.ui.customviews;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;
import com.projectdemo.zwz.liverookie.R;
/**
* @description: 美颜 Dialog
* @author: Andruby
* @time: 2016/12/17 10:23
*/
public class BeautyDialogFragment extends DialogFragment {
private static final String TAG = BeautyDialogFragment.class.getSimpleName();
private SeekBarCallback mSeekBarCallback;
private SeekBar mBeautySeekbar;
private TextView mTVBeauty;
private TextView mTVWhitening;
public static final int STATE_BEAUTY = 0, STATE_WHITE = 1;
private int mBeautyProgress = 100; //默认初始值为100
private int mWhiteningProgress = 0;
private int mState;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity(), R.style.BottomDialog);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.fragment_beauty_area);
dialog.setCanceledOnTouchOutside(true); // 外部点击取消
Log.d(TAG, "create fragment");
mBeautySeekbar = (SeekBar) dialog.findViewById(R.id.beauty_seekbar);
mBeautySeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mSeekBarCallback.onProgressChanged(progress, mState);
if (mState == STATE_BEAUTY)
mBeautyProgress = progress;
else
mWhiteningProgress = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mBeautySeekbar.setProgress(mBeautyProgress);
mTVBeauty = (TextView) dialog.findViewById(R.id.tv_face_beauty);
mTVWhitening = (TextView) dialog.findViewById(R.id.tv_face_whitening);
mTVBeauty.setSelected(true);
mTVWhitening.setSelected(false);
mState = STATE_BEAUTY;
mTVBeauty.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTVBeauty.setSelected(true);
mTVWhitening.setSelected(false);
//seek bar init
mState = STATE_BEAUTY;
mBeautySeekbar.setProgress(mBeautyProgress);
}
});
mTVWhitening.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTVBeauty.setSelected(false);
mTVWhitening.setSelected(true);
//seek bar init
mState = STATE_WHITE;
mBeautySeekbar.setProgress(mWhiteningProgress);
}
});
// 设置宽度为屏宽, 靠近屏幕底部。
Window window = dialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.gravity = Gravity.BOTTOM; // 紧贴底部
lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
window.setAttributes(lp);
//initView();
return dialog;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mSeekBarCallback = (SeekBarCallback) activity;
}
public interface SeekBarCallback {
void onProgressChanged(int progress, int state);
}
}
|
9104f807a2cc8ecfb85562bc3dd1c20e8bf1fa99
|
[
"Java",
"Gradle"
] | 19
|
Java
|
zuowenzhan/LiveRookie
|
16fa607d613aff6694cdbfab1050cb415c313985
|
076069e4069c0e51973e27a03da5a046ba749895
|
refs/heads/master
|
<file_sep>n = int(input())
for _ in range(0,n):
x,y = map(int, input().split())
area = (x * y) / 2
print("%d cm2"% area)
|
84fe854a90eec62ddd9b367162acf56b437fe2bf
|
[
"Python"
] | 1
|
Python
|
MatheusFBBueno/poo-prova1
|
6e208b1b4cbb773d4f748990a6b2639c139f9213
|
d50e48284a016c36307b2f77bd6d8d7eda75a52c
|
refs/heads/master
|
<repo_name>kbcsharp/typescriptLibrary<file_sep>/app/2-types.ts
/******************
* 01 - Declaration
******************/
let username: string = "instructor";
let instructorId: number = 5;
/*****************
* 02 - Basic Types
*******************/
/****************
* 03 - Union Types
****************/
|
7def90690c55f43feddd4c80f1ca5620d829639b
|
[
"TypeScript"
] | 1
|
TypeScript
|
kbcsharp/typescriptLibrary
|
d7f2dfe0ccc41781d9ef7d33f776a938e46236ed
|
4fc394c98da9d339d4ae673dde2422da736086f9
|
refs/heads/master
|
<file_sep><?php
//echo "dumping variables\n";
$candidates = get_defined_vars();
$outfile = fopen("/tmp/dump.txt", "w") or die("file open failure");
fwrite($outfile, "---- start ----\n");
fwrite($outfile, "---- json ----\n");
$rawJson = file_get_contents('php://input');
#$rawJson = '{"pathArg":"aaa", "query1":"ccc", "query2":"bbb", "sourceIp":"test-invoke-source-ip"}';
#$rawJson = '{"pathArg":"aaa", "query1":"ccc", "query2":"bbb", "sourceIp":"test-invoke-source-ip"}';
fwrite($outfile, $rawJson."\n");
fwrite($outfile, "---- json ----\n");
$decoded = json_decode($rawJson, true);
//var_dump($decoded);
$pathArg = trim($decoded['pathArg']);
$sourceIp = trim($decoded['sourceIp']);
fwrite($outfile, "---- outvar----\n");
fwrite($outfile, "pathArg::".$pathArg."\n");
fwrite($outfile, "sourceIp::".$sourceIp."\n");
fwrite($outfile, "---- outvar----\n");
fwrite($outfile, "PHP_SELF::".$_SERVER['PHP_SELF']."\n");
$keys1 = array_keys($candidates);
foreach ($keys1 as $value1) {
// echo $value1."\n";
// var_dump($value1);
fwrite($outfile, $value1."\n");
if (is_array($candidates[$value1])) {
$temp1 = $candidates[$value1];
$keys2 = array_keys($temp1);
foreach($keys2 as $value2) {
// var_dump($value2);
if (is_array($temp1[$value2])) {
$temp2 = $temp1[$value2];
$keys3 = array_keys($temp2);
foreach($keys3 as $value3) {
// var_dump($value3);
fwrite($outfile, $value1."::".$value2."::".$value3."\n");
}
} else {
fwrite($outfile, $value1."::".$value2."::".$temp1[$value2]."\n");
}
}
}
}
fwrite($outfile, "---- stop ----\n");
fclose($outfile);
$datum = Array();
$datum['requestTime'] = time();
$datum['requestAddress'] = $sourceIp;
$datum['transactionUuid'] = '6c5790e4-80e9-4ffe-b583-d8f50caafcd3';
//header("Access-Control-Allow-Origin: *");
//header("Access-Control-Allow-Methods: *");
//header("Content-Type: application/json");
if ($pathArg == 200) {
$status = 200;
} elseif ($pathArg == 404) {
$status = 404;
} else {
$status = 200;
}
header("HTTP/1.1 ".$status." ".'extra info');
echo json_encode($datum);
<file_sep>#!/bin/bash
#
# Title:curl.sh
#
# Description:diagnostic driver
#
# Development Environment:OS X 10.9.5
#
# Author:<NAME> (<EMAIL>)
#
#curl -v http://192.168.127.12/api_gw_lab/demo1.php/6c5790e4-80e9-4ffe-b583-d8f50caafcd3
#
#curl -v https://5g21s17vke.execute-api.us-west-2.amazonaws.com/test/demo/pathArg
#curl -v https://5g21s17vke.execute-api.us-west-2.amazonaws.com/test/demo/404
#curl -v -H "Content-Type:application/json" -d '{"key":"value"}' https://5g21s17vke.execute-api.us-west-2.amazonaws.com/test/demo/pathArg
curl -v -H "Content-Type:application/json" -d '{"key":"value"}' https://5g21s17vke.execute-api.us-west-2.amazonaws.com/test/demo/404
#
<file_sep># api_gateway_lab
### AWS API Gateway Experiment
Demonstrate features of [AWS API Gateway](https://aws.amazon.com/api-gateway).
This repository contains a [swagger](http://swagger.io) file which creates an API Gateway that interacts w/a simple PHP example. As a simple passthrough example, we can focus on the different stages/transformations that API Gateway performs.
I learn by working through small examples which exercise important features but are small with minimal dependencies (easy to experiment). In particular I learned about the interplay between swagger and amazon integration, espcially w/different HTTP status codes. I also learned about loading a swagger model from the passthrough client, and how to discover the true client IP address (turns out to be delivered via JSON). Hope you also find it useful.
## Installation
* Deploy the PHP script [demo1.php] (https://github.com/guycole/api_gateway_lab/blob/master/demo1.php)
* Verify the PHP script is working by invoking from a browser or curl(1).
* [curl.sh](https://github.com/guycole/api_gateway_lab/blob/master/curl.sh) is an example
* Note that [demo1.php] (https://github.com/guycole/api_gateway_lab/blob/master/demo1.php) writes `/tmp/dump.txt` to discover runtime state.
* Create an API Gateway using [swagger.json](https://github.com/guycole/api_gateway_lab/blob/master/swagger.json)
* Update the URI for demo1.php (within swagger.json)
* Using AWS console, navigate to Amazon API Gateway/Create new API
* Select "Import from Swagger"
* Push "Select Swagger File"
* Select `swagger.json` and then 'Import'
* If successful, you should see something like this:

* Select "GET" and press "TEST", supply the path and query arguments when prompted.

* Scroll to see test results. Should end w/a 200 status
* Inspect `/tmp/dump.txt` (note that path/query arguments are converted to a JSON post)
* Deploy API Gateway
* From AWS console, press "Actions" button and select "Deploy API"
* If successful, you should see something like this:
* "Deploy API" values not critical, I picked "New Stage", "test", "test", "test" and press "Deploy"

* Test API Gateway using curl(1)
* Cut/paste the URL supplied from deployment into [curl.sh](https://github.com/guycole/api_gateway_lab/blob/master/curl.sh)
* Invoke, should return a 200 status
* Provoke a 404 status by placing 404 at the end of URL
* i.e. `curl -v https://y2pb2sdt6d.execute-api.us-west-2.amazonaws.com/test/demo/404`
|
618f00449e0151c476669c4f79bab3b709328490
|
[
"Markdown",
"PHP",
"Shell"
] | 3
|
PHP
|
guycole/api_gateway_lab
|
fb0e0bc0ddb56826662b0a19b9b905d13f2fcc7c
|
68ded9c45403bfee71aaffddc711105beda9b144
|
refs/heads/master
|
<file_sep>var $ = require('jquery');
const { bishengFormat } = require('bisheng-formatter-core');
const { removeAllBlank, getSaleConfig, insertContent } = require('../common/utils.js');
import { defaultYuqeuOption } from '../common/config.js';
var { Readability } = require('@mozilla/readability');
var TurndownService = require('turndown').default;
var turndownPluginGfm = require('turndown-plugin-gfm');
/**
* 格式化文档
*/
function formatText() {
chrome.storage.sync.get({ yuqueOption: defaultYuqeuOption }, res => {
let option = res.yuqueOption;
const config = {
mainFeature: {
/*
决定是否格式化全角 markdown 链接
before: [title](link)
after: [title](link)
*/
markdownLinksInFullWidth: true,
/*
决定是否在粗体两侧添加空格
before: 这里是**粗体**文本
after: 这里是 **粗体** 文本
*/
boldTextBlock: true,
/* 决定是否清空连续的空行 */
blankLines: true,
/*
决定是否格式化连续的标点符号: 一般是多个句号组成的省略号 (。。。。。) 以及多个感叹号或问号。
before: 这里是一段中文带着很多很多的感叹号和问号!!!!!!!!!!!??????????????
after: 这里是一段中文带着很多很多的感叹号和问号!!!???
*/
duplicatedPunctuations: option.duplicatedPunctuations,
/*
决定是否格式化全角符号/数字/英文字符
before: 这里是一段中文,带着中文符号。这里是一段ChineseText!带着Chinese Punctuations?
after: 这里是一段中文, 带着中文符号. 这里是一段 ChineseText! 带着 Chinese Punctuations?
*/
fullWidthCharsAndFollowingSpaces: option.fullWidthCharsAndFollowingSpaces,
/*
决定是否格式化半角符号/数字/英文字符
before: 这一幕被一楼 DHBM 系统监控到,30 秒内关闭了系统.
after: 这一幕被一楼 DHBM 系统监控到, 30 秒内关闭了系统.
*/
halfWidthCharsAndFollowingSpaces: option.halfWidthCharsAndFollowingSpaces,
/* 决定是否在中文和英文之间添加空格 */
addSpacesBetweenChineseCharAndAlphabeticalChar: option.addSpacesBetweenChineseCharAndAlphabeticalChar,
},
/*
如果 duplicatedPunctuations = true, 决定替换成多少个连续的符号
如果设置为 6
before: 这里是一段中文带着很多很多的感叹号和问号!!!!!!!!!!!!!!!!!!
after: 这里是一段中文带着很多很多的感叹号和问号!!!!!!
*/
ellipsisCount: 3,
/*
决定是否使用常用标点替换全角引号
true: 使用 (""'') 替换 (“”‘’)
false: 使用 (『』「」) 替换 (“”‘’)
*/
useSimpleQuotation: option.useSimpleQuotation,
};
$('ne-p ne-text').each(function() {
let content = $(this).html();
if (!/^\s*$/.test(content)) {
$(this).html(bishengFormat(content, config));
}
});
});
}
document.addEventListener('DOMContentLoaded', function() {
let currentTabUrl = window.location.href;
if (currentTabUrl.includes('yuque')) {
// 字体替换
chrome.storage.sync.get({ yuqueOption: defaultYuqeuOption }, res => {
let option = res.yuqueOption;
if (option.fonts) {
// 当前页面设置字体
$('*').css('font-family', option.fonts);
// 文章内容是异步加载的,延迟再设置一次,但是网速过慢还是有问题,待优化
setTimeout(() => {
$('*').css('font-family', option.fonts);
}, 500);
setTimeout(() => {
$('*').css('font-family', option.fonts);
}, 1000);
setTimeout(() => {
$('*').css('font-family', option.fonts);
}, 3000);
}
});
chrome.storage.sync.get({ yuqueOption: defaultYuqeuOption }, res => {
let option = res.yuqueOption;
// 删除发现上的小红点
if (getSaleConfig(option, 'closeRedDot')) {
setTimeout(() => {
$('a[href="/explore/events"] > span > sup').remove();
}, 50);
setTimeout(() => {
$('a[href="/explore/events"] > span > sup').remove();
}, 100);
setTimeout(() => {
$('a[href="/explore/events"] > span > sup').remove();
}, 500);
setTimeout(() => {
$('a[href="/explore/events"] > span > sup').remove();
}, 1000);
}
// 统计编辑面文字数
if (currentTabUrl.endsWith('edit')) {
if (getSaleConfig(option, 'wordCount')) {
setInterval(() => {
let spanCount = $('.lark-editor-save-tip').children('span').length;
let totlaCount = removeAllBlank($('div.ne-editor-box').text()).length;
let totalWordCount = getWordCount(totlaCount, 'div.ne-editor-box');
let tipText = $('.lark-editor-save-tip')
.children('span')
.first()
.text();
if (!(tipText && tipText.indexOf('(') != -1) && spanCount <= 1) {
$('.lark-editor-save-tip').append(`<span> (${option.countPrefix} ${(totalWordCount * option.countCoefficient).toFixed(1) / 1} ${option.countSuffix})</span>`);
} else {
if (tipText && tipText.indexOf('(') != -1) {
$('.lark-editor-save-tip')
.children('span')
.first()
.text(` (${option.countPrefix} ${(totalWordCount * option.countCoefficient).toFixed(1) / 1} ${option.countSuffix})`);
} else {
$('.lark-editor-save-tip')
.children('span')
.last()
.text(` (${option.countPrefix} ${(totalWordCount * option.countCoefficient).toFixed(1) / 1} ${option.countSuffix})`);
}
}
}, 500);
}
} else {
if (getSaleConfig(option, 'readEvaluate')) {
// 统计阅读时间
// 这里不能使用,setTimeout,因为通过目录点击,不会重新加载页面
setInterval(() => {
let spanCount = $('#header > div > div.header-crumb > span').children('span').length;
let wordCount = getWordCount(removeAllBlank($('#content').text()).length, '#content');
if (spanCount <= 1) {
$('#header > div > div.header-crumb > span')
.last()
.append(`<span> (需阅读 ${Math.ceil(wordCount / option.readWordCount)} 分钟)</span>`);
} else {
$('#header > div > div.header-crumb > span')
.children('span')
.last()
.text(` (需阅读 ${Math.ceil(wordCount / option.readWordCount)} 分钟)`);
}
}, 1000);
}
}
});
}
});
/**
* 级别修改
*/
function headerLevelUpdate(isDown) {
var step = 1;
var maxLevel = 6;
if (isDown) {
step = -1;
maxLevel = 1;
}
$('div.ne-editor-box :header').each(function() {
let tagName = $(this)[0].tagName;
let tagNumber = parseInt(tagName[1]);
var newTag = 'h' + tagNumber;
if ((isDown && tagNumber > maxLevel) || (!isDown && tagNumber < maxLevel)) {
newTag = 'h' + (tagNumber + step);
}
console.log(`<${newTag}>${this.innerHTML}</${newTag}>`);
$(this).replaceWith(`<${newTag}>${this.innerHTML}</${newTag}>`);
});
}
/**
* 获得单词总数
*/
function getWordCount(totalWordCount, rootSel) {
let root = $(`${rootSel}`);
// 图片描述
let imageMaskWord = removeAllBlank(root.find('.lake-image-mask').text()).length;
// 文档描述
let docCardWord = removeAllBlank(root.find('.lake-doc-card-view').text()).length;
// 按钮描述
let dropdownWord = removeAllBlank(root.find('.dropdown-container').text()).length;
// 行内卡片
let cardInlineWord = removeAllBlank(root.find('.le-card-yuque-inline').text()).length;
// 卡片选择
let cardselectWord = removeAllBlank(root.find('.lake-cardselect-list').text()).length;
// 数学公式
let mathWord = removeAllBlank(root.find('.lake-math-container').text()).length;
let mathToolWord = removeAllBlank(root.find('.lake-math-editor-toolbar').text()).length;
// 所有卡片
let cardWord = removeAllBlank(root.find('div[data-card-element="center"]').text()).length;
// 无效字符
let invalidWordCount =
Math.max(imageMaskWord, 0) +
Math.max(docCardWord, 0) +
Math.max(dropdownWord, 0) +
Math.max(cardselectWord, 0) +
Math.max(mathWord, 0) +
Math.max(mathToolWord, 0) +
Math.max(cardWord, 0) +
Math.max(cardInlineWord, 0);
const totalCount = totalWordCount - invalidWordCount;
return totalCount < 0 ? 0 : totalCount;
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
switch (request.cmd) {
case 'toc':
let headMk = '';
$('div.ne-editor-box :header').each(function() {
let tagName = $(this)[0].tagName;
let title = $(this).text();
let id = $(this).attr('id');
let head = ' '.repeat(tagName[1] - 1);
if (!/^\s*$/.test(title)) {
headMk += `<a href="${window.location.href.slice(0, -5)}#${id}">${head}${title}</a>` + '<br/>';
}
});
$('div.ne-editor-box').prepend(headMk + '<br/>');
break;
// 添加图片
case 'append_img':
$('div.ne-editor-box').append(`<img class="ne-image" src="${request.value}">`);
break;
case 'append_color_block':
insertContent(`<blockquote class="lake-alert lake-alert-${request.value}"><p><br/></p></blockquote>`);
break;
// 在光标处插入数据
case 'append_content_in_cursor':
insertContent(`${request.value}`);
break;
case 'append_color_header':
insertContent(`<p><span style="background-color: ${request.value};"> </span> </p>`);
break;
case 'prepend_img':
$('div.ne-editor-box').prepend(`<img class="ne-image" src="https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture&a=${Math.random()}">`);
break;
// 缩进
case 'prepend_blank':
$('ne-p ne-text').each(function() {
let content = $(this).text();
if (!/^\s*$/.test(content)) {
$(this).html(' ' + content.trim());
}
});
break;
// 格式化文本
case 'format_content':
formatText();
break;
// 获得书籍
case 'get_books':
let urls = '';
$('.ant-tree-list-holder-inner a').each(function() {
let aTag = $(this);
let href = aTag.attr('href');
let title = aTag.attr('title');
if (!href.startsWith('http')) {
href = `https://${window.location.host}${href}`;
}
if (title) {
urls += `[${title}](${href})` + '<br/>';
} else {
title = aTag.text();
if (title) {
urls += `[${title}](${href})` + '<br/>';
}
}
});
sendResponse(urls);
break;
// 获得 markmap 文本
case 'get_markmap':
let markdownText = $('pre').text();
sendResponse(markdownText);
break;
// 剪藏
case 'clipper':
// 正文提取
var documentClone = document.cloneNode(true);
// 排除
// 不知道原理,直接 remove 无效,好像只支持通过 getElementById 才能删除
let array = documentClone.getElementsByClassName('lake-image-mask-point');
for (let index = 0; index < array.length; index++) {
array[index].innerText = '';
}
var article = new Readability(documentClone).parse();
// html -> markdown
var turndownService = new TurndownService({ codeBlockStyle: 'fenced', preformattedCode: true });
turndownService.addRule('code', {
filter: ['code'],
replacement: function(content) {
return '```' + content + '```';
},
});
var gfm = turndownPluginGfm.gfm;
var tables = turndownPluginGfm.tables;
turndownService.use(gfm);
turndownService.use(tables);
let content = article.content;
var markdown = turndownService.turndown(content);
console.log(article.title);
console.log(markdown);
sendResponse({ content: markdown, title: article.title });
break;
case 'generator_header':
let headerArr = new Array(0, 0, 0, 0, 0, 0);
$('div.ne-editor-box :header').each(function() {
let tagName = $(this)[0].tagName;
let tagNumber = tagName[1];
let title = $(this).text();
if (title) {
let titleArr = title.split(' ');
if (titleArr.length == 2) {
title = titleArr[1];
}
}
let curIndex = tagNumber - 1;
headerArr[curIndex] = headerArr[curIndex] + 1;
for (let index = tagNumber; index < headerArr.length; index++) {
headerArr[index] = 0;
}
let header =
headerArr
.join('.')
.split('.0')
.join('')
.split('0.')
.join('') + ' ';
$(this).text(header + title);
});
break;
// 标题降级
case 'lower_header':
headerLevelUpdate(false);
break;
// 标题升级
case 'up_header':
headerLevelUpdate(true);
break;
default:
break;
}
});
<file_sep># yuque-helper 1.0 发布了

## 什么是 yuque-helper
yuque-helper 是一个开源免费的语雀 chrome 小插件. 目前功能如下:

另外还有一个在配置项里的自定义字体功能.
具体功能的细节与使用方法见下文.
## 为什么会有 yuque-helper
语雀可能是我这几年使用过的最惊艳的笔记工具了, 大概是 18 年 5 月开始入坑, 一见如故, 把自己所有笔记的工作全部迁移到了语雀. 语雀的公共空间大概已经有了 530 篇文档.

在不断使用的过程中, 也见证着语雀功能变得的更加丰富与强大. 但是每个人的使用场景不同, 语雀也无法面面俱到. 对于一些我个人觉得很有用的小功能, 在语雀的排期应该很靠后, 甚至没有排期. 很早就萌生写插件去实现我想要的功能, 但是一直没有实施.
直到,语雀经过通盘考虑删除了原来的 markdown 视图的功能。

有些东西真的是拥有的时候, 你不知道哪里好, 直到失去才感受到他的重要.
没有这个功能后, 真的给我带了很大的不便, 以前只要点击一下按钮就可以的操作, 我现在不得不先下载 markdown 文件, 再到文件夹找到他, 然后打开文件, 再复制. 操作的步骤大大的延长, 全是摩擦阻力.
直到有一天, 看到语雀团队的仙森ᵒᵏ大佬的这篇文章
发现, 只是隐藏了相关按钮, 但是功能还是在的, 只在要网页后面拼接相应参数即可.
这的确解决了燃眉之急, 但是我还是想要之前点一下就打开的快捷, 所以就有了这个插件雏形.
## 如何使用 yuque-helper
### 如何安装
目前只支持, 通过压缩包安装, 这种方式的好处是, 你不需要会科学上网. 按下面的步骤操作即可, 坏处是没办法升级, 下次有更新, 你还需手动下载, 重新安装, 不过我已经提交到 chrome 的官方插件市场审核了, 顺利的话, 本周就可以直接在官方插件市场直接安装了.
压缩包安装:
[yuque-helper-v1.0.0.zip](https://www.yuque.com/attachments/yuque/0/2020/zip/119443/1608645487731-07a5d33f-aca4-4c13-9951-c09ce7e43f00.zip?_lake_card=%7B%22uid%22%3A%221608645484786-0%22%2C%22src%22%3A%22https%3A%2F%2Fwww.yuque.com%2Fattachments%2Fyuque%2F0%2F2020%2Fzip%2F119443%2F1608645487731-07a5d33f-aca4-4c13-9951-c09ce7e43f00.zip%22%2C%22name%22%3A%22yuque-helper-v1.0.0.zip%22%2C%22size%22%3A623958%2C%22type%22%3A%22application%2Fzip%22%2C%22ext%22%3A%22zip%22%2C%22progress%22%3A%7B%22percent%22%3A99%7D%2C%22status%22%3A%22done%22%2C%22percent%22%3A0%2C%22id%22%3A%22w4C5O%22%2C%22card%22%3A%22file%22%7D)
首先下载上面的 zip 文件到你的本地, 然后放在一个不会被不小心删除的地方, 解压好.
按如下图所示菜单进件选择, 打开 扩展程序 页面

点击 加载已解压的扩展程序 按钮

选择你刚刚解压 zip 文件的目录, 点击选择即可

如果操作正常, 你会看到你的 扩展程序面板 多了一个 yuque-helper 的卡片, 说明你安装成功了.

不知道 chrome 哪版开始, 安装的插件默认不会在地址栏显示, 为了方便使用, 你可以按如下图所示, 固定本插件, 当然本步非必须操作, 看个人喜好.

### 功能介绍
#### 1. Markdown 视图
上文也说了, 快捷显示 markdown 视图是本插件的初衷, 所以他是第一个, 功能很简单, 只是在点击时, 自动跳到当前页面地址 + markdown 参数的页面, 当然, 如果你不是在语雀文章面点击此按钮, 应该会看到 404

#### 2. Html 视图
与 markdown 类似, 只是打开的 html 视图页面

#### 3. 复制 Url
这个功能, 主要是在文章时需要引用一些页面, markdown 通过语法需要这样写
```bash
[网页标题](https://www..com)
```
所以要引用一个网页的地址, 我至少要复制一次网页的标题, 再复制一次网页地址. 我觉得太麻烦, 加了一个小功能, 点击按钮后, 会自动生成当前页面的 markdown 链接引用到你的粘贴板.

#### 4. 生成 TOC
如果对于 markdown 比较熟悉的同学, 应该见过有些编辑器是支持 toc 语法的, 可以首页生成本文的大纲, 不过语雀有侧边栏大纲, 此功能聊胜于无.

#### 5. 插入 bing 图片
我写文章时, 因为有些会发到个人的公众号上, 所以喜欢在文章开始配个首图. 通常使用 bing 的随机图就够了. 此按钮功能就是在文首接入一张随机的 bing 的配图. (配图要在外网获取, 看个人网速, 可能加载缓慢)

#### 6. 首行缩进
顾名思义, 给每段开头加两个空格.

#### 7. 文本格式化
本功能还不太完善, 使用前请先学会语雀的历史版本功能, 在出现问题时, 自行恢复历史版本.
本功能主要是为了一键格式化文本, 比如在中文与英文或者数字之前自动加个空格, 使阅读体验更好, 或修复一些标点符号错误的用法等.

#### 8. 获得目录列表
此功能一般没啥用, 初衷是语雀出了个人页面, 有些同学喜欢把个人页面上列出自己的文章列表, 但是一个一个复制又太麻烦了, 此功能就是在目录页面生成当前展开的文章到你的剪切板, 减少一定的重复劳动.

#### 9. 插入表情
写这个功能的时候, 语雀还没有在表情按钮, 写完之后, 发现语雀上线这个功能, 不过, 还好表情重复的不多, 不然就白写了😂 . 而且不光支持评论框插入还支持文章.
这些表情及插件的图标均来自下文
不过写本文的时候, 好像删除了...


#### 10. 自定义字体
语雀毕竟是用来看的, 一种字体看多了, 难免审美疲劳, 加了一个自定义设置字体的功能, 当然你设置的字体必须要是你本地安装过的.
注意看演示图, 此设置需在选项页内设置, 需右击插件图标, 打开选项页面进行设置. 可以同时设置多个字体, 建议先配置一个英文的, 再配置一个中文的.


## 其它
### 开源地址
温馨提示: 如果你是抱着学习的目的去看这个项目, 这明显不是一个好主意, 我其实是一个后端开发, 本插件都是我贫瘠的散装前端知识写成的, 希望各位前端大佬一起帮忙完善它.
[kiwiflydream/yuque-helper: yuque-helper 是一个开源免费的语雀 chrome 小插件](https://github.com/kiwiflydream/yuque-helper)
### 联系我
如果使用上有问题, 可以加我的微信, 当然如果你有好的想法, 想教我做产品, 想教我写代码, 或者仅仅只是想多交一个朋友都欢迎.

<file_sep>// 表情
let mood = [
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517148299-3fa0b903-d927-4ed5-89c0-bb663bf8b178.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517148299-3fa0b903-d927-4ed5-89c0-bb663bf8b178.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517149052-1ee79588-b78a-4140-8838-fac92eb00c69.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517149052-1ee79588-b78a-4140-8838-fac92eb00c69.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517149778-75765f7a-ab62-43e6-9d52-a231f5b46500.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517149778-75765f7a-ab62-43e6-9d52-a231f5b46500.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517150546-25750d77-e49e-4ede-b42b-dc6ed3eee3fe.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517150546-25750d77-e49e-4ede-b42b-dc6ed3eee3fe.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517151334-834d0318-508b-49bd-946d-f555c2a94d33.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517151334-834d0318-508b-49bd-946d-f555c2a94d33.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517152322-34499eb2-59a3-40b1-8a76-d6554491ef15.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517152322-34499eb2-59a3-40b1-8a76-d6554491ef15.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517153132-a0092e67-7c33-4849-adc7-7e97fd20f20b.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517153132-a0092e67-7c33-4849-adc7-7e97fd20f20b.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517153912-1ec132ff-3a71-44a6-bae5-e56996399256.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517153912-1ec132ff-3a71-44a6-bae5-e56996399256.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517154773-582e2c16-9923-4c4f-b628-267fafd35065.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517154773-582e2c16-9923-4c4f-b628-267fafd35065.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517155467-eb397d0e-13ff-4292-abf9-937452ef84c9.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517155467-eb397d0e-13ff-4292-abf9-937452ef84c9.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517156286-6a6d13d4-fc9e-412b-bbf3-8ec34386cf6c.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517156286-6a6d13d4-fc9e-412b-bbf3-8ec34386cf6c.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517157093-f5aebbea-ad42-4754-890a-6dcc3e17133a.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517157093-f5aebbea-ad42-4754-890a-6dcc3e17133a.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517157847-1826f575-d6b9-42c4-895c-26a28bdb479d.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517157847-1826f575-d6b9-42c4-895c-26a28bdb479d.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517158558-c508a781-093f-44cf-a2b9-25cc6a8137d6.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517158558-c508a781-093f-44cf-a2b9-25cc6a8137d6.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517159493-be3ff8ad-72ff-4609-b80b-d3db1af748e3.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517159493-be3ff8ad-72ff-4609-b80b-d3db1af748e3.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517162056-b5961f38-ca49-4b46-b562-fd59d52bb002.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517162056-b5961f38-ca49-4b46-b562-fd59d52bb002.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517162704-5d109b91-c4e0-4b70-8cdb-ccb71d75aa07.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517162704-5d109b91-c4e0-4b70-8cdb-ccb71d75aa07.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517163548-e9b6bacb-00ef-4d55-8df4-2400033e50c7.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517163548-e9b6bacb-00ef-4d55-8df4-2400033e50c7.png',
},
{
img: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517164348-1eef832a-179f-43d9-93a5-c09d681f9373.png',
value: 'https://cdn.nlark.com/yuque/0/2020/png/1399816/1598517164348-1eef832a-179f-43d9-93a5-c09d681f9373.png',
},
];
let colorBlockItems = [
{ img: '/icons/success.svg', value: 'success' },
{ img: '/icons/tip.svg', value: 'tips' },
{ img: '/icons/danger.svg', value: 'danger' },
{ img: '/icons/info.svg', value: 'info' },
{ img: '/icons/warn.svg', value: 'warning' },
];
let colorHeaderItems = [
{ img: '/icons/success.svg', value: '#EAF8E5' },
{ img: '/icons/tip.svg', value: '#FFF3B2' },
{ img: '/icons/danger.svg', value: '#FFF1F1' },
{ img: '/icons/info.svg', value: '#E5F6FE' },
{ img: '/icons/warn.svg', value: '#FFFAE4' },
];
let popupItems = [
{
title: 'Markdown 视图',
handlerType: 'markdown',
isShow: true,
icon: 'el-icon-sugar',
},
{
title: 'Html 视图',
handlerType: 'html',
isShow: true,
icon: 'el-icon-dessert',
},
{
title: '复制 Url',
handlerType: 'copyUrl',
isShow: true,
icon: 'el-icon-food',
},
{
title: '生成 TOC',
handlerType: 'toc',
isShow: true,
icon: 'el-icon-cherry',
},
{
title: '图片搜索',
handlerType: 'queryImg',
isShow: true,
icon: 'el-icon-picture-outline',
},
{
title: '插入 Bing 图片',
handlerType: 'prepend_img',
isShow: true,
icon: 'el-icon-apple',
},
{
title: '首行缩进',
handlerType: 'prepend_blank',
isShow: true,
icon: 'el-icon-pear',
},
{
title: '文本格式化',
handlerType: 'format_content',
isShow: true,
icon: 'el-icon-watermelon',
},
{
title: '获得目录列表',
handlerType: 'get_books',
isShow: true,
icon: 'el-icon-orange',
},
{
title: '转成思维导图',
handlerType: 'markmap',
isShow: true,
icon: 'el-icon-milk-tea',
},
{
title: '生成编号',
handlerType: 'generator_header',
isShow: true,
icon: 'el-icon-chicken',
},
{
title: '网页转存',
handlerType: 'clipper',
isShow: true,
icon: 'el-icon-burger',
},
{
title: '日记',
handlerType: 'diary',
isShow: true,
icon: 'el-icon-collection',
},
{
title: '随机漫步',
handlerType: 'randomWalk',
isShow: true,
icon: 'el-icon-magic-stick',
},
{
title: '标题降级',
handlerType: 'lower_header',
isShow: true,
icon: 'el-icon-bottom',
},
{
title: '标题升级',
handlerType: 'up_header',
isShow: true,
icon: 'el-icon-top',
},
{
title: '配置',
handlerType: 'setting',
isShow: true,
icon: 'el-icon-setting',
},
{
title: '帮助 & 反馈',
handlerType: 'help',
isShow: true,
icon: 'el-icon-bangzhu',
},
];
/**
* 默认配置
*/
let defaultYuqeuOption = {
fonts: '',
countPrefix: '已经写了',
countSuffix: '个字',
readWordCount: 300,
countCoefficient: 1,
wordCount: true,
readEvaluate: true,
closeRedDot: false,
duplicatedPunctuations: true,
fullWidthCharsAndFollowingSpaces: true,
halfWidthCharsAndFollowingSpaces: true,
addSpacesBetweenChineseCharAndAlphabeticalChar: true,
useSimpleQuotation: true,
markdown: true,
html: true,
copyUrl: true,
toc: false,
prepend_img: false,
prepend_blank: true,
format_content: true,
get_books: true,
markmap: true,
generator_header: false,
clipper: true,
diary: true,
randomWalk: true,
lower_header: false,
up_header: false,
setting: true,
help: true,
colorPopup: false,
colorHeaderPopup: false,
moodPopup: false,
queryImg: false,
};
export { mood, colorBlockItems, colorHeaderItems, popupItems, defaultYuqeuOption };
<file_sep>import axios from 'axios';
axios.defaults.baseURL = 'https://www.yuque.com/api/v2';
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.defaults.headers.common['User-Agent'] = 'yuque-helper';
async function createDoc(article) {
handlerToken(article.token);
return await axios.post('/repos/' + article.repo + '/docs', {
title: article.title,
slug: article.slug,
public: 1,
body: article.content,
});
}
async function readDoc(article) {
handlerToken(article.token);
return await axios.get('/repos/' + article.repo + '/docs/' + article.slug);
}
async function getUser(token) {
handlerToken(token);
return await axios.get('/user');
}
async function findDocs(repoAndToken) {
handlerToken(repoAndToken.token);
return await axios.get(`/repos/${repoAndToken.repo}/docs`);
}
function handlerToken(token) {
axios.defaults.headers.common['X-Auth-Token'] = token;
}
export { createDoc, getUser, readDoc, findDocs };
|
a78b0c59603214e43f654c7308a80369dfdcfadc
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
iittxgt/yuque-helper
|
2638d27d977391679cb344f6d432559162e3b883
|
3aa5fac8af2a4cac047a630ee04112e35642183c
|
refs/heads/master
|
<file_sep># blog-web_app-flask
Blog Web App using Python, Flask.
<file_sep>import os
import secrets
from PIL import Image
from flask import render_template, url_for, flash, redirect, request, abort
from flaskblog import app, db, bcrypt
from flaskblog.forms import RegistrationForm, LoginForm, UpdateAccountForm, PostForm
from flaskblog.models import User, Post
from flask_login import login_user, current_user, logout_user, login_required
import pandas as pd
import urllib.request
import sqlite3
from bs4 import BeautifulSoup as bs
@app.route("/")
@app.route("/home")
def home():
posts = Post.query.all()
return render_template('home.html', posts=posts)
@app.route("/about")
def about():
return render_template('about.html', title='About')
@app.route("/register", methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = <PASSWORD>.generate_password_hash(form.password.data).decode('utf-8')
user = User(username=form.username.data, email=form.email.data, password=<PASSWORD>)
db.session.add(user)
db.session.commit()
flash('Your account has been created! You are now able to log in', 'success')
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
@app.route("/login", methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('home'))
else:
flash('Login Unsuccessful. Please check email and password', 'danger')
return render_template('login.html', title='Login', form=form)
@app.route("/logout")
def logout():
logout_user()
return redirect(url_for('home'))
def save_picture(form_picture):
random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename)
picture_fn = random_hex + f_ext
picture_path = os.path.join(app.root_path, 'static/profile_pics', picture_fn)
output_size = (125, 125)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(picture_path)
return picture_fn
@app.route("/account", methods=['GET', 'POST'])
@login_required
def account():
form = UpdateAccountForm()
if form.validate_on_submit():
if form.picture.data:
picture_file = save_picture(form.picture.data)
current_user.image_file = picture_file
current_user.username = form.username.data
current_user.email = form.email.data
db.session.commit()
flash('Your account has been updated!', 'success')
return redirect(url_for('account'))
elif request.method == 'GET':
form.username.data = current_user.username
form.email.data = current_user.email
image_file = url_for('static', filename='profile_pics/' + current_user.image_file)
return render_template('account.html', title='Account',
image_file=image_file, form=form)
@app.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, author=current_user)
db.session.add(post)
db.session.commit()
flash('Your post has been created!', 'success')
return redirect(url_for('home'))
return render_template('create_post.html', title='New Post',
form=form, legend='New Post')
@app.route("/post/<int:post_id>")
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('post.html', title=post.title, post=post)
@app.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
flash('Your post has been updated!', 'success')
return redirect(url_for('post', post_id=post.id))
elif request.method == 'GET':
form.title.data = post.title
form.content.data = post.content
return render_template('create_post.html', title='Update Post',
form=form, legend='Update Post')
@app.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
db.session.delete(post)
db.session.commit()
flash('Your post has been deleted!', 'success')
return redirect(url_for('home'))
##################################################
@app.route("/project", methods=['GET', 'POST'])
@login_required
def project():
conn = sqlite3.connect(r"E:\COLLEGE PROJECTS\collegeproject\example.db")
if request.method == 'POST':
result = request.form["URL"]
df = {'Projects':[],'Link':[],'Language':[],'Name':[]}
inputurl=result
url=inputurl+'?tab=repositories'
content = urllib.request.urlopen(url).read()
soup = bs(content,'html.parser')
for tag in soup.find_all('a',attrs={'itemprop':'name codeRepository'}):
df['Projects'].append(str(tag.text))
for link in soup.find_all('a',attrs={'itemprop':'name codeRepository'}):
df['Link'].append('https://github.com'+str(link.get('href')))
nm=soup.find('span', attrs={'class':'p-name vcard-fullname d-block overflow-hidden'})
name=nm.text
for div in soup.find_all('div', attrs={'class':'col-10 col-lg-9 d-inline-block'}):
x=div.find('span',attrs={'itemprop':'programmingLanguage'})
if x is None:
df['Language'].append('None')
df['Name'].append(name)
else:
df['Language'].append(x.text)
df['Name'].append(name)
df1=pd.DataFrame(df)
#Database
cur = conn.cursor()
df1.to_sql('Projects', conn,if_exists='append', index=False)
df2=pd.read_sql('select * from Projects', conn)
#pd.read_sql('select * from Projects', conn)
conn.commit()
conn.close()
return render_template('index.html',result=url, table = df2.to_html()) # renders template: index.html with argument result = polarity value calculated
else:
conn = sqlite3.connect(r"E:\COLLEGE PROJECTS\collegeproject\example.db")
cur = conn.cursor()
df3=pd.read_sql('select * from Projects', conn)
conn.commit()
conn.close()
return render_template('index.html', table = df3.to_html())
|
be214218181b9c1e60a580bf3884355286698783
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
manasbichoo/blog-web_app-flask
|
d0b8049f4604144831e6a209cd4ac08d9cb1bc70
|
89313f3b308a40f96a96a2208f4dd3f4ddc9b122
|
refs/heads/master
|
<file_sep>import { NgModule } from '@angular/core';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTableModule } from '@angular/material/table';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatRadioModule } from '@angular/material/radio';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatSelectModule } from '@angular/material/select';
import { MatTabsModule } from '@angular/material/tabs';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatDividerModule } from '@angular/material/divider';
import { MatListModule } from '@angular/material/list';
import { MatDialogModule } from '@angular/material/dialog';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSliderModule} from '@angular/material/slider';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatTooltipModule } from "@angular/material/tooltip";
@NgModule({
// tslint:disable-next-line:max-line-length
imports: [MatTooltipModule, MatTableModule, MatIconModule, MatButtonModule, MatToolbarModule, MatSidenavModule, MatCardModule, MatCheckboxModule, MatRadioModule, MatFormFieldModule, MatInputModule, MatDatepickerModule, MatSelectModule, MatTabsModule, MatExpansionModule, MatDividerModule, MatListModule, MatDialogModule, MatSnackBarModule, MatProgressSpinnerModule, MatSliderModule, MatProgressBarModule],
// tslint:disable-next-line:max-line-length
exports: [MatTooltipModule, MatTableModule, MatIconModule, MatButtonModule, MatToolbarModule, MatSidenavModule, MatCardModule, MatCheckboxModule, MatRadioModule, MatFormFieldModule, MatInputModule, MatDatepickerModule, MatSelectModule, MatTabsModule, MatExpansionModule, MatDividerModule, MatListModule, MatDialogModule, MatSnackBarModule, MatProgressSpinnerModule, MatSliderModule, MatProgressBarModule],
})
export class MaterialModule { }
|
c6560d3d8c73dd18b3024cfed87cb671fa654dbe
|
[
"TypeScript"
] | 1
|
TypeScript
|
betomax-16/Avon
|
3e72ab3eb05ccdec1a19ae620365aa4dd3b83073
|
69f0b3d1a08c49ac942e4b584b5b585e41553952
|
refs/heads/master
|
<file_sep>---
title: "David Ortiz Statistics"
author: "<NAME>"
date: "October 3, 2015"
output:
html_document:
theme: journal
self_contained: false
---
Below is a selection of statistics from [Baseball Reference](http://bbref.com/pi/shareit/DY17L).
```{r, echo=F,warning=F,message=F}
library(rvest)
library(dplyr)
url <- "http://www.baseball-reference.com/play-index/share.cgi?id=DY17L"
raw.html <- read_html(url)
david.ortiz <- raw.html %>%
html_nodes("table") %>%
html_table(fill=TRUE) %>%
.[[1]]
library(stringr)
david.ortiz$Year <- str_extract(david.ortiz$Year,"\\d{4}") %>% as.numeric
david.ortiz <- david.ortiz[,c('Year','Age','Tm','Lg','G','PA','AB','R','H','RBI','HR','BB','BA')] %>%
filter(!is.na(Year))
knitr::kable(david.ortiz)
```<file_sep>library(mailR)
rmarkdown::render("davidortiz.Rmd")
send.mail(from="<EMAIL>",
to="<EMAIL>",
subject="David Ortiz Statistics",
body="davidortiz.html",
html=T,
inline=T,
smtp=list(host.name = "smtp.gmail.com",
port = 465,
user.name = "feasible.analytics",
passwd = "<PASSWORD>",
ssl = T),
authenticate=T,
attach.files="mailR.R")
<file_sep>library(mailR)
send.mail(from="<EMAIL>",
to="<EMAIL>",
subject="test email from R",
body="This is a test email to attach a file for review.",
html=T,
smtp=list(host.name = "smtp.gmail.com",
port = 465,
user.name = "feasible.analytics",
passwd = "<PASSWORD>",
ssl = T),
authenticate=T,
attach.files="mailR.R")
<file_sep>library(Lahman)
library(dplyr)
data(Master)
Master %>%
filter(nameFirst=="David") %>%
select(playerID,nameFirst,nameLast) %>%
arrange(nameLast)
## ortizda01
data(Batting)
david.ortiz.ab <- Batting %>%
filter(playerID == "ortizda01") %>%
mutate(timestamp=as.POSIXct(paste(yearID,"01","01",sep="-"), origin = "1960-01-01")) %>%
select(timestamp,count=AB)
library(BreakoutDetection)
d.ortiz.ab.breakout <- breakout(david.ortiz.ab,
min.size=2,
method="multi",
degree=1,
plot=T)
d.ortiz.ab.breakout
d.ortiz.ab.breakout$plot
<file_sep>library(Lahman)
library(DT)
data(Master)
datatable(Master)
## Kind of large, lets make it a bit smaller and remove row names
datatable(head(Master,n=1000),
rownames=F,
options=list(
pageLength=20
))
## set the default sort order by weight
### Note that first column is 0
datatable(head(Master,n=1000),
options=list(
order = list(list(20, 'desc'))
))
## drag and drop columns, show/hide columns
datatable(head(Master,n=1000),
extensions = c('ColReorder','ColVis'),
options = list(
dom = 'RC<"clear">lfrtip'
))
## Let's combine into a single call and save this table
dt <- datatable(head(Master,n=1000),
rownames = F,
extensions = c('ColReorder','ColVis'),
options = list(
pageLength = 20,
order = list(list(20, 'desc')),
dom = 'RC<"clear">lfrtip',
columnDefs = list(list(visible=F, targets=c(seq(1,14),16,17,seq(21,25))))
))
saveWidget(dt,"DT example.html")
<file_sep>library("dplyr")
library("Lahman")
data(Batting)
data(Fielding)
data(Master)
Batting %>%
group_by(playerID,yearID) %>%
summarize(triples = sum(X3B),
team=paste(teamID,collapse=','),
leagues.count=n_distinct(lgID)) %>%
ungroup() %>%
arrange(desc(triples)) %>%
filter(yearID==2004) %>%
left_join(Master %>%
mutate(name=paste(Master$nameFirst, Master$nameLast, sep=' ')) %>%
select(playerID,name)) %>%
select(Name=name,Team=team,Year=yearID,Triples=triples) %>%
slice(1:5)
<file_sep>library(xts)
library(Lahman)
library(dygraphs)
library(dplyr)
library(lubridate)
#Get <NAME>'s ID
data("Master")
david.ortiz <- Master %>% filter(nameFirst=="David",nameLast=="Ortiz") %>% select(playerID) %>% as.character
#Get his hitting data
do <- Batting %>%
filter(playerID==david.ortiz) %>%
arrange(yearID)
do.xts <- xts(x=do$HR,order.by=ymd(paste(do$yearID,"11","01",sep="-")))
#Create the plot
dygraph(df.xts)
#Add in a time selector
dygraph(df.xts) %>% dyRangeSelector()
#Adjust the label
dygraph(df.xts) %>% dyRangeSelector() %>% dySeries("V1", label = "<NAME>")
#Remove verticle lines
dygraph(df.xts) %>% dyRangeSelector() %>% dySeries("V1", label = "<NAME>") %>%
dyAxis("x", drawGrid = FALSE)
#Fill in the graph
dygraph(df.xts) %>% dyRangeSelector() %>% dySeries("V1", label = "<NAME>") %>%
dyAxis("x", drawGrid = FALSE) %>%
dyOptions(fillGraph = TRUE, fillAlpha = 0.4)
#Add markers
dygraph(df.xts) %>% dyRangeSelector() %>% dySeries("V1", label = "<NAME>") %>%
dyAxis("x", drawGrid = FALSE) %>%
dyOptions(fillGraph = TRUE, fillAlpha = 0.4,drawPoints = TRUE, pointSize = 2)
#Add in Y axis label
dygraph(df.xts) %>%
dyRangeSelector() %>%
dySeries("V1", label = "<NAME>") %>%
dyAxis("x", drawGrid = FALSE) %>%
dyAxis("y", label="Homeruns") %>%
dyOptions(fillGraph = TRUE, fillAlpha = 0.4,drawPoints = TRUE, pointSize = 2)
#Add in event for traded
dygraph(df.xts) %>%
dyRangeSelector() %>%
dySeries("V1", label = "<NAME>") %>%
dyAxis("x", drawGrid = FALSE) %>%
dyAxis("y", label="Homeruns") %>%
dyOptions(fillGraph = TRUE, fillAlpha = 0.4,drawPoints = TRUE, pointSize = 2) %>%
dyEvent(date = "2003-01-22", "Signed with the Red Sox", labelLoc = "top")
#Preselect only years he played for the redsox
dygraph(df.xts) %>%
dyRangeSelector(dateWindow = c("2003-01-23", "2014-11-01")) %>%
dySeries("V1", label = "<NAME>") %>%
dyAxis("x", drawGrid = FALSE) %>%
dyAxis("y", label="Homeruns") %>%
dyOptions(fillGraph = TRUE, fillAlpha = 0.4,drawPoints = TRUE, pointSize = 2) %>%
dyEvent(date = "2003-01-22", "Signed with the Red Sox", labelLoc = "top")
#Annotate on all star game appearances
dygraph(df.xts) %>%
dyRangeSelector(dateWindow = c("2003-01-23", "2014-11-01")) %>%
dySeries("V1", label = "<NAME>") %>%
dyAxis("x", drawGrid = FALSE) %>%
dyAxis("y", label="Homeruns") %>%
dyOptions(fillGraph = TRUE, fillAlpha = 0.4,drawPoints = TRUE, pointSize = 2) %>%
dyAnnotation("2004-11-01", text="AS", tooltip="All Star Game Appearance") %>%
dyAnnotation("2005-11-01", text="AS", tooltip="All Star Game Appearance") %>%
dyAnnotation("2006-11-01", text="AS", tooltip="All Star Game Appearance") %>%
dyAnnotation("2007-11-01", text="AS", tooltip="All Star Game Appearance") %>%
dyAnnotation("2008-11-01", text="AS", tooltip="All Star Game Appearance") %>%
dyAnnotation("2010-11-01", text="AS", tooltip="All Star Game Appearance") %>%
dyAnnotation("2011-11-01", text="AS", tooltip="All Star Game Appearance") %>%
dyAnnotation("2012-11-01", text="AS", tooltip="All Star Game Appearance") %>%
dyAnnotation("2013-11-01", text="AS", tooltip="All Star Game Appearance") %>%
dyEvent(date = "2003-01-22", "Signed with the Red Sox", labelLoc = "top")
#Let's add in another player
albert.pujols <- Master %>% filter(nameFirst=="Albert",nameLast=="Pujols") %>% select(playerID) %>% as.character
ap <- Batting %>%
filter(playerID==albert.pujols) %>%
arrange(yearID)
ap.xts <- xts(x=ap$HR,order.by=ymd(paste(ap$yearID,"11","01",sep="-")))
dygraph(cbind(df.xts,ap.xts)) %>%
dyRangeSelector() %>%
dySeries("..1", label = "<NAME>") %>%
dySeries("..2", label = "<NAME>") %>%
dyAxis("x", drawGrid = FALSE) %>%
dyAxis("y", label="Homeruns") %>%
dyOptions(fillGraph = TRUE, fillAlpha = 0.4,drawPoints = TRUE, pointSize = 2) %>%
dyLegend(labelsSeparateLines = T)
<file_sep>library(breakpoint)
library(Lahman)
data(Master)
Master %>%
filter(nameFirst=="David") %>%
select(playerID,nameFirst,nameLast) %>%
arrange(nameLast)
## ortizda01
data(Batting)
Batting %>%
filter(playerID == "ortizda01") %>%
select()
library(breakpoint)
<file_sep># Package-of-the-Month
This series of R scripts and files will give examples of a few useful packages and example code using them.
Here's my plan of packages to cover:
1. dplyr
2. DT
3. BreakoutDetection
4. httr
5. mailR
6. dtw
7. dygraphs
|
cb5890bc60522b7ff3be1dd390107be16a2dc9b8
|
[
"Markdown",
"R",
"RMarkdown"
] | 9
|
RMarkdown
|
ct-analytics/Package-of-the-Month
|
207749d46dbdf4e2670b0b4d8fd551b3a20d57f0
|
1563c452077f2132dd25364f5feedf49d1fbb3e4
|
refs/heads/main
|
<file_sep>from hydra.experimental import compose, initialize
from utils import skip_run
# Initialize the config directory
initialize(config_path="configs", job_name="learning")
with skip_run('skip', 'split_image_folder') as check, check():
hparams = compose(config_name="config")
raise NotImplementedError
<file_sep>mkdocs
mkdocs-cinder
cookiecutter
pytest
<file_sep>#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='{{ cookiecutter.project_name }}',
version='0.0.0',
description='{{ cookiecutter.description }}',
author='{{ cookiecutter.author_name }}',
author_email='',
url='', # replace with your own github repo url
install_requires=['pytorch-lightning', 'hydra-core'],
packages=find_packages(),
license='{% if cookiecutter.open_source_license == 'MIT' %}MIT{% elif cookiecutter.open_source_license == 'BSD-3-Clause' %}BSD-3{% endif %}' # noqa
)
<file_sep>import sys
from contextlib import contextmanager
import torch
from tensorboard import program
class SkipWith(Exception):
pass
@contextmanager
def skip_run(flag, f):
"""To skip a block of code.
Parameters
----------
flag : str
skip or run.
Returns
-------
None
"""
@contextmanager
def check_active():
activated = ['run']
p = ColorPrint() # printing options
if flag in activated:
p.print_run('{:>12} {:>3} {:>12}'.format('Running the block',
'|', f))
yield
else:
p.print_skip('{:>12} {:>2} {:>12}'.format(
'Skipping the block', '|', f))
raise SkipWith()
try:
yield check_active
except SkipWith:
pass
class ColorPrint:
@staticmethod
def print_skip(message, end='\n'):
sys.stderr.write('\x1b[88m' + message.strip() + '\x1b[0m' + end)
@staticmethod
def print_run(message, end='\n'):
sys.stdout.write('\x1b[1;32m' + message.strip() + '\x1b[0m' + end)
@staticmethod
def print_warn(message, end='\n'):
sys.stderr.write('\x1b[1;33m' + message.strip() + '\x1b[0m' + end)
def get_num_gpus():
if torch.cuda.device_count() == 0:
return None
else:
return list(range(torch.cuda.device_count()))
def launch_tensorboard(hparams):
tb = program.TensorBoard()
tb.configure(argv=[
None, '--logdir', hparams.log_dir, '--reload_multifile', 'true',
'--reload_interval', '15'
])
tb.launch()
return None
<file_sep>from pytorch_lightning import Callback
class ExampleCallback(Callback):
def __init__(self):
pass
def on_init_start(self, trainer):
print('Starting to initialize trainer!')
def on_init_end(self, trainer):
print('Trainer is initialized now.')
def on_train_end(self, trainer, pl_module):
print('Do something when training ends.')
class UnfreezeModelCallback(Callback):
"""
Unfreeze model after a few epochs.
It currently unfreezes every possible parameter in model, probably shouldn't work that way...
"""
def __init__(self, wait_epochs=5):
self.wait_epochs = wait_epochs
def on_epoch_end(self, trainer, pl_module):
if trainer.current_epoch == self.wait_epochs:
for param in pl_module.model.model.parameters():
param.requires_grad = True
<file_sep>from torch.utils.data import Dataset
from PIL import Image
import os
class TestDataset(Dataset):
"""
Example dataset class for loading images from folder and converting them to monochromatic.
Can be used to perform inference with trained MNIST model.
'Dataset' type classes can also be used to create 'DataLoader' type classes which are used by datamodules.
"""
def __init__(self, img_dir, transform):
self.transform = transform
self.images = [
os.path.join(img_dir, fname) for fname in os.listdir(img_dir)
]
def __getitem__(self, idx):
image = Image.open(self.images[idx]).convert(
"L") # convert to black and white
# image = Image.open(self.images[idx]).convert("RGB")
if self.transform is not None:
image = self.transform(image)
return image
def __len__(self):
return len(self.images)
<file_sep>torch>=1.7.1
torchvision>=0.8.2
torchaudio>=0.7.2
pytorch-lightning>=1.1.6
# hydra-core>=1.0.5
hydra-core>=1.1.0.dev2
wandb>=0.10.15
neptune-client>=0.5.0
scikit-learn>=0.24.0
pandas>=1.2.0
hydra_colorlog>=1.0.0
# local package
-e .
# external requirements
click
Sphinx
coverage
awscli
flake8
python-dotenv>=0.5.1
{% if cookiecutter.python_interpreter != 'python3' %}
# backwards compatibility
pathlib2
{% endif %}<file_sep>## PyTorch Lightning + Hydra cookiecutter template
### A clean and simple template to kickstart your deep learning project 🚀⚡🔥<br>
- structures ML code the same so that work can easily be extended and replicated
- allows for rapid experimentation by automating pipeline with config files
- extends functionality of popular experiment loggers like Weights&Biases (mostly with dedicated callbacks)
This template tries to be as generic as possible - you should be able to easily modify behavior in [train.py](project/train.py) in case you need some unconventional configuration wiring.<br>
Click on <b>`Use this template`</b> button above to initialize new repository.<br>
### Why Lightning + Hydra?
- <b>[PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning)</b> provides great abstractions for well structured ML code and advanced features like checkpointing, gradient accumulation, distributed training, etc.<br>
- <b>[Hydra](https://github.com/facebookresearch/hydra)</b> provides convenient way to manage experiment configurations and advanced features like overriding any config parameter from command line, scheduling execution of many runs, etc.<br>
### Some Notes
***\*warning: this template currently uses development version of hydra which might be unstable (we wait until version 1.1 is released)*** <br>
*\*based on [deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template) by PyTorchLightning organization.*<br>
*\*Suggestions are always welcome!*
## Features
- Predefined folder structure
- Modularity: all abstractions are splitted into different submodules
- Automates PyTorch Lightning training pipeline with little boilerplate, so it can be easily modified (see [train.py](project/train.py))
- All advantages of Hydra
- Main config file contains default training configuration (see [config.yaml](project/configs/config.yaml))
- Storing many experiment configurations in a convenient way (see [project/configs/experiment](project/configs/experiment))
- Command line features (see [#How to run](README.md#How-to-run) for examples)
- Override any config parameter from command line
- Schedule execution of many experiments from command line
- Sweep over hyperparameters from command line
- Convenient logging of run history, ckpts, etc. (see [#Logs](README.md#Logs))
- ~~Validating correctness of config with schemas~~ (TODO)
- Optional Weights&Biases utilities for experiment tracking
- Callbacks (see [wandb_callbacks.py](project/src/callbacks/wandb_callbacks.py))
- Automatically store all code files and model checkpoints as artifacts in W&B cloud
- Generate confusion matrices and f1/precision/recall heatmaps
- ~~Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py))~~ (TODO)
- Example of inference with trained model ([inference_example.py](project/src/utils/inference_example.py))
- Built in requirements ([requirements.txt](requirements.txt))
- Built in conda environment initialization ([conda_env.yaml](conda_env.yaml))
- Built in python package setup ([setup.py](setup.py))
- Example with MNIST digits classification ([mnist_model.py](project/src/models/mnist_model.py), [mnist_datamodule.py](project/src/datamodules/mnist_datamodule.py))
<br>
## Project structure
The directory structure of new project looks like this:
```
├── project
│ ├── configs <- Hydra configuration files
│ │ ├── trainer <- Configurations of lightning trainers
│ │ ├── model <- Configurations of lightning models
│ │ ├── datamodule <- Configurations of lightning datamodules
│ │ ├── callbacks <- Configurations of lightning callbacks
│ │ ├── logger <- Configurations of lightning loggers
│ │ ├── seeds <- Configurations of seeds
│ │ ├── experiment <- Configurations of experiments
│ │ │
│ │ └── config.yaml <- Main project configuration file
│ │
│ ├── data <- Project data
│ │
│ ├── logs <- Logs generated by hydra and pytorch lightning loggers
│ │
│ ├── notebooks <- Jupyter notebooks
│ │
│ ├── src
│ │ ├── architectures <- PyTorch model architectures
│ │ ├── callbacks <- PyTorch Lightning callbacks
│ │ ├── datamodules <- PyTorch Lightning datamodules
│ │ ├── datasets <- PyTorch datasets
│ │ ├── models <- PyTorch Lightning models
│ │ ├── transforms <- Data transformations
│ │ └── utils <- Utility scripts
│ │ ├── inference_example.py <- Example of inference with trained model
│ │ └── template_utils.py <- Some extra template utilities
│ │
│ └── train.py <- Train model with chosen experiment configuration
│
├── .gitignore
├── LICENSE
├── README.md
├── conda_env.yaml <- File for installing conda environment
├── requirements.txt <- File for installing python dependencies
└── setup.py <- File for installing project as a package
```
<br>
## Workflow
1. Write your PyTorch Lightning model (see [mnist_model.py](project/src/models/mnist_model.py) for example)
2. Write your PyTorch Lightning datamodule (see [mnist_datamodule.py](project/src/datamodules/mnist_datamodule.py) for example)
3. Write your experiment config, containing paths to your model and datamodule (see [project/configs/experiment](project/configs/experiment) for examples)
4. Run training with chosen experiment config:<br>
```bash
python train.py +experiment=experiment_name.yaml
```
<br>
## Main project configuration file ([config.yaml](project/configs/config.yaml))
Main config contains default training configuration.<br>
It determines how config is composed when simply executing command: `python train.py`
```yaml
# to execute run with default training configuration simply run:
# python train.py
# specify here default training configuration
defaults:
- trainer: default_trainer.yaml
- model: mnist_model.yaml
- datamodule: mnist_datamodule.yaml
- seeds: default_seeds.yaml # set this to null if you don't want to use seeds
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
# path to original working directory (the directory that `train.py` was executed from in command line)
# hydra hijacks working directory by changing it to the current log directory,
# so it's useful to have path to original working directory as a special variable
# read more here: https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
original_work_dir: ${hydra:runtime.cwd}
# path to folder with data
data_dir: ${original_work_dir}/data/
# output paths for hydra logs
hydra:
run:
dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S}
sweep:
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
subdir: ${hydra.job.num}
```
<br>
## Experiment configuration ([project/configs/experiment](project/configs/experiment))
You can store many experiment configurations in this folder.<br>
Example experiment configuration:
```yaml
# to execute this experiment run:
# python train.py +experiment=exp_example_simple
defaults:
- override /trainer: default_trainer.yaml
- override /model: mnist_model.yaml
- override /datamodule: mnist_datamodule.yaml
- override /seeds: default_seeds.yaml
- override /callbacks: default_callbacks.yaml
- override /logger: null
# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters
seeds:
pytorch_seed: 12345
trainer:
max_epochs: 10
gradient_clip_val: 0.5
model:
lr: 0.001
lin1_size: 128
lin2_size: 256
lin3_size: 64
datamodule:
batch_size: 64
train_val_test_split: [55_000, 5_000, 10_000]
```
<br>
More advanced experiment configuration:
```yaml
# to execute this experiment run:
# python train.py +experiment=exp_example_with_paths
defaults:
- override /trainer: null
- override /model: null
- override /datamodule: null
- override /seeds: null
- override /callbacks: default_callbacks.yaml
- override /logger: null
# we override default configurations with nulls to prevent them from loading at all
# instead we define all modules and their paths directly in this config,
# so everything is stored in one place for more readibility
seeds:
pytorch_seed: 12345
trainer:
_target_: pytorch_lightning.Trainer
min_epochs: 1
max_epochs: 10
gradient_clip_val: 0.5
model:
_target_: src.models.mnist_model.LitModelMNIST
optimizer: adam
lr: 0.001
weight_decay: 0.000001
architecture: SimpleDenseNet
input_size: 784
lin1_size: 256
dropout1: 0.30
lin2_size: 256
dropout2: 0.25
lin3_size: 128
dropout3: 0.20
output_size: 10
datamodule:
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
data_dir: ${data_dir}
batch_size: 64
train_val_test_split: [55_000, 5_000, 10_000]
num_workers: 1
pin_memory: False
```
<br>
## Logs
By default, logs have the following structure:
```
├── logs
│ ├── runs # Folder for logs generated from single runs
│ │ ├── 2021-02-15 # Date of executing run
│ │ │ ├── 16-50-49 # Hour of executing run
│ │ │ │ ├── .hydra # Hydra logs
│ │ │ │ ├── wandb # Weights&Biases logs
│ │ │ │ ├── checkpoints # Training checkpoints
│ │ │ │ └── ... # Any other thing saved during training
│ │ │ ├── ...
│ │ │ └── ...
│ │ ├── ...
│ │ └── ...
│ │
│ ├── multiruns # Folder for logs generated from sweeps
│ │ ├── 2021-02-15_16-50-49 # Date and hour of executing sweep
│ │ │ ├── 0 # Job number
│ │ │ │ ├── .hydra # Hydra logs
│ │ │ │ ├── wandb # Weights&Biases logs
│ │ │ │ ├── checkpoints # Training checkpoints
│ │ │ │ └── ... # Any other thing saved during training
│ │ │ ├── 1
│ │ │ ├── 2
│ │ │ └── ...
│ │ ├── ...
│ │ └── ...
│ │
```
<br><br>
---
## To start a new project, run:
------------
cookiecutter https://github.com/HemuManju/lightning-hydra-template.git
### Install dependencies
``` bash
$ pip install cookiecutter
$ pip install requirements.txt
```
``` bash
$ conda config --add channels conda-forge
$ conda install cookiecutter
$ pip install requirements.txt
```
Next, you can train model with default configuration without logging:
```yaml
cd project_name
python train.py
```
Or you can train model with chosen logger like Weights&Biases:
```yaml
# set project and entity names in 'project/configs/logger/wandb.yaml'
wandb:
project: "your_project_name"
entity: "your_wandb_team_name"
```
```yaml
# train model with Weights&Biases
python train.py logger=wandb
```
Or you can train model with chosen experiment config:
```yaml
# experiment configurations are placed in 'project/configs/experiment' folder
python train.py +experiment=exp_example_simple
```
To execute all experiments from folder run:
```yaml
# execute all experiments from folder `project/configs/experiment`
python train.py --multirun '+experiment=glob(*)'
```
You can override any parameter from command line like this:
```yaml
python train.py trainer.max_epochs=20 model.lr=0.0005
```
To train on GPU:
```yaml
python train.py trainer.gpus=1
```
Attach some callback set to run:
```yaml
# callback sets configurations are placed in 'project/configs/callbacks' folder
python train.py callbacks=default_callbacks
```
Combaining it all:
```yaml
python train.py --multirun '+experiment=glob(*)' trainer.max_epochs=10 logger=wandb
```
To create a sweep over some hyperparameters run:
```yaml
# this will run 6 experiments one after the other,
# each with different combination of batch_size and learning rate
python train.py --multirun datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
```
<p><small>Project based on the <a target="_blank" href="https://drivendata.github.io/cookiecutter-data-science/">cookiecutter data science project template</a> and <a target="_blank" href="https://github.com/hobogalaxy/lightning-hydra-template">pytorch lightning + hydra template</a>
<file_sep>{{cookiecutter.project_name}}
==============================
{{cookiecutter.description}}
[](https://opensource.org/licenses/MIT)
Documentation: <br />
<p><small>Project based on the <a target="_blank" href="https://drivendata.github.io/cookiecutter-data-science/">cookiecutter data science project template</a> and <a target="_blank" href="https://github.com/hobogalaxy/lightning-hydra-template">pytorch lightning + hydra template</a>
|
dd1a7444723fea26047eb096555331f789d8b7e5
|
[
"Markdown",
"Python",
"Text"
] | 9
|
Python
|
HemuManju/lightning-hydra-template
|
fee0d71f25b0a26c3047b2bf4d05834df8f70157
|
ce58ec387f91335510cc132d56f7818b97758f03
|
refs/heads/main
|
<repo_name>A00079/LiveStocksUpdate<file_sep>/src/App.js
import React, { useState, useEffect } from 'react';
import LiveStocks from './components/LiveStocks';
function App() {
const [ws, setWS] = useState(new WebSocket("ws://stocks.hulqmedia.com"));
const [stockData, setStockData] = useState([]);
useEffect(() => {
ws.onopen = () => {
// on connecting, do nothing but log it to the console
console.log('connected')
}
ws.onmessage = evt => {
// listen to data sent from the websocket server
const message = JSON.parse(evt.data)
console.log('stocks...',message);
setStockData(message);
}
ws.onclose = () => {
console.log('disconnected')
// automatically try to reconnect on connection loss
}
}, [ws.onmessage]);
return (
<div className="App">
<LiveStocks data={stockData} />
</div>
);
}
export default App;
<file_sep>/src/components/LiveStocks/index.js
import React, { useEffect, useState } from 'react';
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const LiveStocks = (props) => {
let calculatedObj = [];
const [calObj, setCalObj] = useState([]);
useEffect(() => {
let beautifyObj = [];
props.data.map((el) => {
beautifyObj.push({
'ticker': el[0],
'price': el[1]
})
});
var groupBy = function (xs, key) {
return xs.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
// .sort((a, b) => parseFloat(a.price) - parseFloat(b.price))
// console.log('sort...', groupBy(beautifyObj, 'ticker'));
const unique = [...new Set(beautifyObj.map(item => item.ticker))];
// console.log('unique', unique);
unique.map((el) =>{
console.log('sort pls',groupBy(beautifyObj, 'ticker')[el].sort((a, b) => parseFloat(a.price) - parseFloat(b.price)));
});
beautifyObj.map((el) => {
debugger
props.data.map((itm) => {
if (itm[0] === el.ticker) {
if (itm[1] > el.price) {
calculatedObj.push({
'ticker': itm[0],
'price': itm[1],
'status': 'inc'
})
} else if (itm[1] < el.price) {
calculatedObj.push({
'ticker': itm[0],
'price': itm[1],
'status': 'dec'
})
} else {
calculatedObj.push({
'ticker': itm[0],
'price': itm[1],
'status': 'nor'
})
}
}
})
});
setCalObj(calculatedObj)
// console.log('calculatedObj --->', calculatedObj);
// console.log('Beautify --->', beautifyObj);
}, [props]);
const getCurrentTime = () => {
var d = new Date();
var day = days[d.getDay()];
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
min = "0" + min;
}
var ampm = "am";
if (hr > 12) {
hr -= 12;
ampm = "pm";
}
var date = d.getDate();
var month = months[d.getMonth()];
var year = d.getFullYear();
return day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year;
}
return (
<React.Fragment>
{/* <h4>{props.data}</h4> */}
<div className="antialiased font-sans">
<div className="container mx-auto px-4 sm:px-8">
<div className="py-8">
<div>
<h2 className="text-2xl text-white font-semibold leading-tight">
<div className='flex items-center'>
<div className='mr-1'>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg>
</div>
<div>
<h2 className="text-2xl text-white font-semibold leading-tight">Live <span className='text-yellow-600'> Stocks </span> Update</h2>
</div>
</div>
</h2>
</div>
<div className="-mx-4 sm:-mx-8 px-4 sm:px-8 py-4 overflow-x-auto">
<div className="inline-block min-w-full shadow rounded-sm overflow-hidden">
<table className="min-w-full leading-normal ">
<thead className='bg-white'>
<tr>
<th
className="px-5 py-3 border-b-2 border-gray-200 text-left text-xs font-bold text-gray-600 uppercase tracking-wider">
<div className='flex items-center'>
<div className='mr-1'>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" /></svg>
</div>
<div>
ticker
</div>
</div>
</th>
<th
className="px-5 py-3 border-b-2 border-gray-200 text-left text-xs font-bold text-gray-600 uppercase tracking-wider">
<div className='flex items-center'>
<div className='mr-1'>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 8h6m-5 0a3 3 0 110 6H9l3 3m-3-6h6m6 1a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
</div>
<div>
Price
</div>
</div>
</th>
<th
className="px-5 py-3 border-b-2 border-gray-200 text-left text-xs font-bold text-gray-600 uppercase tracking-wider">
<div className='flex items-center'>
<div className='mr-1'>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
</div>
<div>
Last Updated
</div>
</div>
</th>
</tr>
</thead>
<tbody>
{
calObj.map((el, index) => {
return (
<tr key={index} className={el.status == 'inc' ? 'bg-green-300' : el.status == 'dec' ? 'bg-red-300' : 'bg-gray-200 border-b-2 border-gray-300'}>
<td className="w-64 px-5 py-5 border-b border-gray-200 text-sm">
<div className="flex items-center">
<p className="text-blue-900 font-bold whitespace-no-wrap">{el.ticker.toUpperCase()}</p>
</div>
</td>
<td className={el.status == 'inc' ? 'w-64 px-5 py-5 border-b text-sm' : el.status == 'dec' ? 'w-64 px-5 py-5 border-b text-sm' : 'w-64 px-5 py-5 border-b text-sm'}>
<div className="flex items-center text-gray-900 font-semibold whitespace-no-wrap">
<div className='mr-2'>
{
el.status == 'inc' ?
<svg className="w-6 h-6 text-green-900" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" /></svg>
:
el.status == 'dec' ?
<svg className="w-6 h-6 text-red-900" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 17h8m0 0V9m0 8l-8-8-4 4-6-6" /></svg>
:
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" /></svg>
}
</div>
<div className='font-bold text-blue-600'>
{el.price}
</div>
</div>
</td>
<td className=" px-5 py-5 border-b border-gray-200 text-sm">
<p className="text-gray-900 font-semibold whitespace-no-wrap">
{getCurrentTime()}
</p>
</td>
</tr>
)
})
}
</tbody>
</table>
<div
className="px-5 py-5 bg-white border-t flex flex-col xs:flex-row items-center xs:justify-between ">
<span className="text-xs xs:text-sm text-gray-900 font-bold">
Showing {calObj.length} Entries
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</React.Fragment>
);
}
export default LiveStocks;
|
757a3367d2e174e61bc687046307741bcd4c1857
|
[
"JavaScript"
] | 2
|
JavaScript
|
A00079/LiveStocksUpdate
|
2356475df36b272dabe02286c4bf59b15429fe87
|
929667f85925571a23715522628fbdc7c0579d23
|
refs/heads/master
|
<repo_name>arkwro/KnowingGit<file_sep>/app/scripts/controllers/sportsStore.js
'use strict';
/**
* @ngdoc function
* @name sportsStoreApp.controller:sportsStoreCtrl
* @description
* # sportsStoreCtrl
* Controller of the sportsStoreApp
*/
angular.module('sportsStoreApp')
.controller('sportsStoreCtrl',function($scope){
$scope.data = {
'products':[
{'name' : 'Product #1', 'description' : 'To jest produkt nr 1',
'category':'Kategoria 1', 'price':100
},
{
'name' : 'Product #2', 'description' : 'To jest produkt nr 2',
'category':'Kategoria 1', 'price':500
}
,
{
'name' : 'Product #3', 'description' : 'To jest produkt nr 3',
'category':'Kategoria 2', 'price':50
}
,
{
'name' : 'Product #4', 'description' : 'To jest produkt nr4 ',
'category':'Kategoria 3', 'price':45
}
]
};
});<file_sep>/app/scripts/controllers/productList.js
/**
* Created by Arkadiusz on 2015-03-25.
*/
'use stritc';
angular.module('sportsStoreApp')
.constant('activeCategory','btn-primary')
.controller('productListCtrl',function($scope, activeCategory){
var selectedCategory = null;
$scope.selectCategory = function(category){
console.log(category);
selectedCategory = category;
}
$scope.filterCategory = function(product){
return selectedCategory == null ||
selectedCategory == product.category;
}
$scope.getCategoryClass = function(category){
return selectedCategory == category ? activeCategory : '';
}
})
<file_sep>/app/scripts/filters/customFilters.js
/**
* Created by Arkadiusz on 2015-03-24.
*/
angular.module("customFilters",[])
.filter('unique',function(){
return function(data, propertyName){
if(angular.isArray(data) && angular.isString(propertyName)){
var result =[];
var checked={};
for(var i=0; i<data.length; i++){
var value = data[i][propertyName];
if(angular.isUndefined(checked[value])){
checked[value] = true;
result.push(value);
}
}
return result;
}else{
return data;
}
}
});
|
842cb6d0309dfae38c618746a344dd66aab95f14
|
[
"JavaScript"
] | 3
|
JavaScript
|
arkwro/KnowingGit
|
ee6c64a0813f98c6d7a9735962c5b21ff059a1c3
|
9b120a441139302100aaf41da22e79b4f548701d
|
refs/heads/master
|
<repo_name>slavo3dev/web_crawler<file_sep>/python_versio/semple.py
def get_url_and_index(string):
start_index = string.find('a class="Nav__Link-cDklcG dYUMBg" href=')
if start_index == -1:
return None, 0 # no links
start_quote_index = string.find('"', start_index)
end_quote_index = string.find('"', start_quote_index + 1)
url = string[start_quote_index + 1:end_quote_index]
return url, end_quote_index
print(get_url_and_index(
'<a class="Nav__Link-cDklcG dYUMBg" href="https://bot.enki.com">EnkiBot</a>'))
<file_sep>/python_versio/crawler.py
from html.parser import HTMLParser
from urllib import parse
import requests
import os
def urlCrawler(HTMLParser):
def __init__(self, home_url, page_url):
super().__init__()
self.home_url = home_url
self.page_url = page_url
self.urls = set
def handle_starttag(self, tag, attrs):
if tag == 'a':
for (attribute, value) in attrs:
if attribute == 'href':
url = parse.urljoin(self.home_url, value)
self.urls.add(url)
def page_urls(self):
return self.urls
def err(self, message):
pass
# Writing data to file
def write_file(path, data):
f = open(path, 'w')
f.write(data)
f.close()
def crawler_data(url):
q = 'q.txt'
crawled = 'crawled.txt'
if not os.path.isfile(q):
write_file(q, url)
if not os.path.isfile(crawled):
write_file(crawled, '')
def add(path, data):
with open(path, 'a') as file:
file.write(data + '\n')
# converting to set beacause we need unique items
def convert_to_set(file_name):
set_list = set()
with open(file_name, 'rt') as f:
for line in f:
set_list.add(line.replace('\n', ''))
return set_list
def set_to_data(urls, file):
for url in sorted(urls):
add(file, url)
|
9e42b656e813aa0dda9173edffbb9d8227b7ad69
|
[
"Python"
] | 2
|
Python
|
slavo3dev/web_crawler
|
8c0246175da40efbb94fef47da83871f9ef1601c
|
99d9e6342f9daf88580d3b4c45f923f156e057bc
|
refs/heads/master
|
<repo_name>gordonkristan/primer<file_sep>/README.md
# Primer
Primer is a small tool I wrote for testing time dependent functionality in my Javascript applications. (And in case you were wondering, yes, it is named after [one of my favorite movies.](http://en.wikipedia.org/wiki/Primer_(film))) I wanted to be able to fake the system time, but I didn't want to have to know anything about the internals of any function, or how it got the time. There were a few other tools like this one, but none were quite as easy to use (or as small).
## How It Works
Primer overrides the internal `Date` object with a custom one that behaves nearly identically. The only difference is that it has a few extra functions to change the time if necessary.
## Enabling Primer
Primer is disabled by default. The way to enable and disable depends on your environment. When enabled, Primer should have no effect on any of your code (unless there are bugs). The only time you should see any effect from Primer is when you call the `setTime` function.
### Browser Globals
If you're not using a module system, they're located on the `Date` object.
```js
Date.enablePrimer()
Date.disablePrimer()
```
### Node.js/CommonJS
They're directly on the exports.
```js
var primer = require('primer');
...
primer.enable();
primer.disable();
```
### AMD
They're on the exports object.
```js
define(['primer'], function(primer) {
primer.enable();
primer.disable();
});
```
## Changing The Time
There are two ways to change the time. The first is by using an absolute date. For instance, you might want to set the date to January 15, 1999. In which case you would do this:
```js
Date.setTime(new Date('January 15, 1999'));
console.log(Date()); // Fri Jan 15 1999 00:00:03 GMT-0500 (EST)
```
`setTime` can take a `Date` object, a date string or a numeric timestamp. You can also change the time to a relative point from now. For instance, say we wanted to set the date 20 minutes in the past.
```js
var realNow = Date.now();
Date.setTime(-20*60*1000, true); // second parameter means relative
console.log(realNow - Date.now()); // about 20 minutes or 20*60*1000
```
**Note:** No matter how you set the date, the **clock continues to tick**. I didn't see much use in stopping the clock since your code wouldn't normally function in that type of environment.
## Resetting The Time
If you want to go back to real-world time, but don't want to disable and enable Primer, just call `Date.resetTime()`.
## Testing
I've done some fairly basic testing, but by no means is it extensive. If you find a bug, let me know. I've tested this in the latest versions of Chrome, Firefox and Safari on OSX Mavericks, as well as in PhantomJS.
<file_sep>/primer.js
(function() {
'use strict';
// Save the original date object to do our heavy lifting
var OriginalDate = Date;
// Keep track of the difference between now and the desired time
var difference = 0;
var currentTime = function() {
return OriginalDate.now() + difference;
};
// Create our custom Date object
var PrimerDate = function() {
// Why is this not better?
// http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
var a = Array.prototype.slice.call(arguments, 0);
if (a.length === 1 && !a[0]) {
a = [];
}
var ret;
switch(a.length) {
case 0:
ret = new OriginalDate(currentTime());
break;
case 1:
ret = new OriginalDate(a[0]);
break;
case 2:
ret = new OriginalDate(a[0], a[1]);
break;
case 3:
ret = new OriginalDate(a[0], a[1], a[2]);
break;
case 4:
ret = new OriginalDate(a[0], a[1], a[2], a[3]);
break;
case 5:
ret = new OriginalDate(a[0], a[1], a[2], a[3], a[4]);
break;
case 6:
ret = new OriginalDate(a[0], a[1], a[2], a[3], a[4], a[5]);
break;
case 7:
ret = new OriginalDate(a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
break;
default:
throw new Error('You\'ve passed too many arguments to the `Date` constructor.');
}
if (this instanceof OriginalDate) {
return ret;
} else {
return ret.toString();
}
};
PrimerDate.prototype = OriginalDate.prototype;
// Proxy the 3 functions on the Date function itself
PrimerDate.now = function() {
return currentTime();
};
PrimerDate.parse = OriginalDate.parse;
PrimerDate.UTC = OriginalDate.UTC;
/**
* Changes the time. If only one argument is used, the argument
* will be used as the current time (although it will continue
* to advance as usual). The single argument should be a date
* instance, a date string or a timestamp.
*
* If the second argument is true, then the first argument should
* be a timestamp, and will be used as the difference between
* the current time and the time that shows. For instance, using
* -5*60*1000 would set the time 5 minutes in the past.
*/
PrimerDate.setTime = function(time, diffOnly) {
if (diffOnly) {
if (typeof time === 'number') {
difference = time;
} else {
throw new Error('The different for `setTime` must be a number.');
}
} else {
if (time instanceof Date) {
difference = time.getTime() - OriginalDate.now();
} else if (typeof time === 'string' || typeof time === 'number') {
difference = new OriginalDate(time).getTime() - OriginalDate.now();
} else {
throw new Error('`setTime` accepts a Date instance, a string date or a timestamp.');
}
}
};
// Reset any changes made using `setTime`.
PrimerDate.resetTime = function() {
difference = 0;
};
function enablePrimer() {
Date = PrimerDate;
}
function disablePrimer() {
Date = OriginalDate;
}
if (typeof define === 'function' && define.amd) {
define('primer', [], function() {
return {
enable: enablePrimer,
disable: disablePrimer
};
});
} else if (typeof exports === 'object') {
module.exports.enable = enablePrimer;
module.exports.disable = disablePrimer;
} else {
Date.enablePrimer = enablePrimer;
PrimerDate.disablePrimer = disablePrimer;
}
})();
|
f2a420e8cdb5e37c159336a0293dffa823773fe0
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
gordonkristan/primer
|
7f59006b5bd71a707a46d45bf9c39fe09a4aac39
|
4a8f5cfcfa859101b2f9e74d417bf0673412f7b7
|
refs/heads/master
|
<file_sep>package info.wallyson.swc.planet;
import info.wallyson.swc.planet.Planet;
import info.wallyson.swc.web.dto.RegisterPlanetDto;
import java.util.List;
class PlanetObjectMother {
public static List<Planet> getPlanets() {
return List.of(
new Planet(null, "planet1", "climate", "terrain", 0),
new Planet(null, "planet2", "climate", "terrain", 0));
}
public static RegisterPlanetDto getRegisterPlanetDto() {
return new RegisterPlanetDto("Tatooine", "climate", "terrain");
}
}
<file_sep>package info.wallyson.swc.planet;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
abstract class IntegrationTestBaseClass {
@Autowired MockMvc mockMvc;
@Autowired
PlanetRepository planetRepository;
ObjectMapper mapper = new ObjectMapper();
@MockBean
PlanetAppearance planetAppearance;
@AfterEach
void cleanDatabase() {
planetRepository.deleteAll();
}
}
<file_sep>package info.wallyson.swc.planet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class GetPlanetIntegrationTest extends IntegrationTestBaseClass {
private Planet savedPlanet;
@BeforeEach
void setUp() {
savedPlanet = planetRepository.save(PlanetObjectMother.getPlanets().get(0));
}
@Test
@DisplayName("Should get a planet by it's ID")
void shouldGetPlanetById() throws Exception {
var response =
mockMvc
.perform(get("/api/planet/{id}", savedPlanet.getId()))
.andExpect(status().isOk())
.andReturn();
var responseContent = response.getResponse().getContentAsString();
var planetResponse = mapper.readValue(responseContent, Planet.class);
assertEquals(savedPlanet, planetResponse);
}
@Test
@DisplayName("Should get a planet by it's name")
void shouldGetPlanetByName() throws Exception {
var response =
mockMvc
.perform(get("/api/planet/name/{name}", savedPlanet.getName()))
.andExpect(status().isOk())
.andReturn();
var responseContent = response.getResponse().getContentAsString();
var planetResponse = mapper.readValue(responseContent, Planet.class);
assertEquals(savedPlanet, planetResponse);
}
}
<file_sep>FROM adoptopenjdk/maven-openjdk11 as builder
WORKDIR /application
COPY src ./src
COPY pom.xml ./
RUN mvn clean package -DskipTests=true
RUN java -Djarmode=layertools -jar target/swc-1.0.jar extract
FROM adoptopenjdk:11-jre-hotspot
WORKDIR /application
COPY --from=builder application/dependencies/ ./
COPY --from=builder application/snapshot-dependencies/ ./
COPY --from=builder application/spring-boot-loader/ ./
COPY --from=builder application/application/ ./
EXPOSE 8090
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]<file_sep>package info.wallyson.swc.planet;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
class SwapiPlanetResponse {
private String name;
private List<String> films;
public int getFilmsCount() {
return films.size();
}
public String getName() {
return name;
}
public List<String> getFilms() {
return films;
}
public void setName(String name) {
this.name = name;
}
public void setFilms(List<String> films) {
this.films = films;
}
}
<file_sep>package info.wallyson.swc.web.dto;
import javax.validation.constraints.NotBlank;
public class RegisterPlanetDto {
@NotBlank private String name;
@NotBlank private String climate;
@NotBlank private String terrain;
public RegisterPlanetDto(@NotBlank String name, @NotBlank String climate, @NotBlank String terrain) {
this.name = name;
this.climate = climate;
this.terrain = terrain;
}
public String getName() {
return name;
}
public String getClimate() {
return climate;
}
public String getTerrain() {
return terrain;
}
}
<file_sep>version: "3.6"
services:
api:
build: ./
image: swc-api-wallyson:1.0
container_name: swc-api-wallyson
restart: unless-stopped
environment:
- MONGO_HOST=swc-db-wallyson
ports:
- "8095:8095"
depends_on:
- db
networks:
- backend
db:
image: mongo:4.4
restart: unless-stopped
container_name: swc-db-wallyson
ports:
- "28017:28017"
- "27017:27017"
volumes:
- backend
networks:
- backend
networks:
backend:
driver: bridge
<file_sep>package info.wallyson.swc.mappers;
import info.wallyson.swc.web.dto.PageResponse;
import org.springframework.data.domain.Page;
public class PageResponseMapper {
public static <T> PageResponse<T> toPageResponse(Page<T> page) {
return new PageResponse<>(page.getContent(), page.getTotalElements());
}
}
<file_sep>package info.wallyson.swc.planet;
interface PlanetAppearance {
int getMovieAppearance(String planetName);
}
|
3af9acde08b827e44c43a478605f6de298884832
|
[
"Java",
"Dockerfile",
"YAML"
] | 9
|
Java
|
wallysoncarvalho/b2w-sw-api-challenge
|
efbfb8849c7f7ec3d1f27b166be5590d88cbab55
|
4a22fea879b13dec612d295d85a8b29110e39e34
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include <stdint.h>
#define MAX_GENES 8000
bool isValidName(char* name);
void trim(char* str);
void usage(void);
void createGeneListFromFile(FILE* file);
void calculateDistances(char* gene);
int compareDistanceTuple (const void * a, const void * b);
typedef struct {
double e1[6], e2[6], e3[6];
char name[20];
} Gene;
typedef struct {
short geneIndex;
double distance;
} DistanceTuple;
Gene **geneList;
int geneCount = 0;
int main(int argc, char** argv) {
if(argc != 2) {
usage();
return 1;
}
char* selectedGene = "DYRK1A";
char* filePath = argv[1];
FILE *file;
if(!(file = fopen(filePath, "r"))) {
//File does not exist
printf("Unable to open input file %s\n", filePath);
return 1;
}
//Allocate memory for the gene list
geneList = malloc(MAX_GENES * sizeof(Gene*));
for(int i = 0; i < MAX_GENES; i++) {
geneList[i] = malloc(MAX_GENES * sizeof(Gene));
}
//File exists so continue
createGeneListFromFile(file);
//Close input file
fclose(file);
calculateDistances(selectedGene);
printf("Done! Results have been stored in the \"output\" folder.\n");
return 0;
}
void calculateDistances(char* gene) {
Gene *curr_gene;
bool foundGene = false;
//for(int i = 0; i < geneCount; i++) {
// curr_gene = geneList[i];
// if(strcmp(curr_gene->name,gene) == 0) {
// foundGene = true;
// printf("Found gene %s, now calculating distances.\n", gene);
// break;
// }
//}
//if(!foundGene) {
// printf("Warning: unable to find specified gene. Program will exit.\n");
// exit(1);
//}
//DistanceTuple **distanceList = malloc(sizeof(DistanceTuple*) * geneCount);
//for(int i = 0; i < geneCount; i++) {
// distanceList[i] = malloc(sizeof(DistanceTuple) * geneCount);
//}
//
DistanceTuple distanceList[geneCount];
double dist1 = 0.0, dist2 = 0.0, dist3 = 0.0, avgdist = 0.0, sumdist = 0.0;
for(int i = 0; i < geneCount; i++) {
curr_gene = geneList[i];
for(int j = 0; j < geneCount; j++) {
Gene *tmp = geneList[j];
dist1 = sqrt(pow(tmp->e1[0] - curr_gene->e1[0],2) + pow(tmp->e1[1] - curr_gene->e1[1],2) +
pow(tmp->e1[2] - curr_gene->e1[2],2) + pow(tmp->e1[3] - curr_gene->e1[3],2) +
pow(tmp->e1[4] - curr_gene->e1[4],2) + pow(tmp->e1[5] - curr_gene->e1[5],2));
dist2 = sqrt(pow(tmp->e2[0] - curr_gene->e2[0],2) + pow(tmp->e2[1] - curr_gene->e2[1],2) +
pow(tmp->e2[2] - curr_gene->e2[2],2) + pow(tmp->e2[3] - curr_gene->e2[3],2) +
pow(tmp->e2[4] - curr_gene->e2[4],2) + pow(tmp->e2[5] - curr_gene->e2[5],2));
dist3 = sqrt(pow(tmp->e3[0] - curr_gene->e3[0],2) + pow(tmp->e3[1] - curr_gene->e3[1],2) +
pow(tmp->e3[2] - curr_gene->e3[2],2) + pow(tmp->e3[3] - curr_gene->e3[3],2) +
pow(tmp->e3[4] - curr_gene->e3[4],2) + pow(tmp->e3[5] - curr_gene->e3[5],2));
avgdist = (dist1 + dist2 + dist3)/3;
sumdist = dist1 + dist2 + dist3;
distanceList[j].geneIndex = j;
//distanceList[j].distance = avgdist;
distanceList[j].distance = sumdist;
}
qsort (distanceList, geneCount, sizeof(DistanceTuple), compareDistanceTuple);
char fname[40];
strcpy(fname, "output/");
strcat(fname, curr_gene->name);
strcat(fname, ".txt");
//Write results to file
FILE * outfile = fopen(fname, "w");
if(!outfile) {
printf("Warning: File could not be created. Exiting Program.\n");
exit(1);
}
for(int j = 1; j < 11; j++) {
fprintf(outfile, "%d: %s %f\n", j, geneList[distanceList[j].geneIndex]->name, distanceList[j].distance);
}
fclose(outfile);
}
}
void trim(char *str) {
char *p1 = str, *p2 = str;
do
while (*p2 == ' ' || *p2 == '/')
p2++;
while (*p1++ = *p2++);
}
int compareDistanceTuple (const void * a, const void * b) {
DistanceTuple *ia = (DistanceTuple*)a;
DistanceTuple *ib = (DistanceTuple*)b;
double diff = ia->distance - ib->distance;
if(diff < 0) {
return -1;
} else if (diff == 0.0f) {
return 0;
} else {
return 1;
}
}
void usage(void) {
printf("Please enter the path of the input file and no other command line arguments.\n");
}
bool isValidName(char* name) {
if(strcmp(name, "analyte11") == 0) {
return false;
} else if (strcmp(name, "siControl") == 0) {
return false;
} else if (strcmp(name, "Gene Symbol") == 0) {
return false;
} else if (strcmp(name, "siCONT") == 0) {
return false;
}else if (*name == 13) {
return false;
}
return true;
}
void createGeneListFromFile(FILE* file) {
char line[256];
while(fgets( line, sizeof(line), file ) != NULL)
{
char* tok;
int len = strlen(line);
if(len > 0 && line[len-1]=='\n'){
line[len-1] = '\0';
}
if(len > 2 && line[len-2]=='\r') {
line[len-2] = '\0';
}
tok = strtok(line,",");
if(tok && isValidName(tok)) {
Gene *currGene = geneList[geneCount];
strcpy(currGene->name, tok);
//Eliminate unwanted characters (spaces, slashes)
trim(currGene->name);
//Populate experiment 1 array for the gene
for(int i = 0; i < 6; i++) {
tok = strtok(NULL,",");
//When there is no data for this experiment, skip to the next experiment
if(strcmp(tok,"=") == 0) {
currGene->e1[i] = 0.0f;
} else {
currGene->e1[i] = atof(tok);
}
}
//Populate experiment 2 array for the gene
for(int i = 0; i < 6; i++) {
tok = strtok(NULL,",");
//When there is no data for this experiment, skip to the next experiment
if(strcmp(tok,"=") == 0) {
currGene->e2[i] = 0.0f;
} else {
currGene->e2[i] = atof(tok);
}
}
//Populate experiment 2 array for the gene
for(int i = 0; i < 6; i++) {
tok = strtok(NULL,",");
//When there is no data for this experiment, skip to the next experiment
if(strcmp(tok,"=") == 0) {
currGene->e3[i] = 0.0f;
} else {
currGene->e3[i] = atof(tok);
}
}
geneCount++;
}
}
}
<file_sep>INTRODUCTION
-------------
The GeneDistance program will calculate the distance between all genes and rank them in ascending order (smallest distance will be ranked number 1). The calculations are done on CUDA when a capable CUDA GPU is available. To achieve the required precision, the CUDA card must have a compute capability of 2.0 or higher. The program will output a file for each gene that matches the specified filtering criteria (more on this in the 'TO RUN' section) that contains the the top 10 results by default. The source code for the program is written in C, with the CUDA extended language as well, and is primarily intended for use on a Linux system. The inclued Makefile assumes a Linux system.
TO COMPILE
--------------------
Ensure that you have the 'nvcc' command in your PATH (this is generally taken care of by installing the NVidia CUDA Toolkit). In the folder containing the source code, simply type 'make' and the executable file will be generated.
TO RUN
---------------------
To run the program, user must supply an input file. This is done using the "-i" or "--input" command line argument. For example:
$./GeneDistance -i input.csv
The input file must be in the format and saved as a comma separated value (csv) file. By default, the program saves the output files in the directory "output". A specific output directory can be set using the "-o" or "--output" command like argument. For example:
$./GeneDistance -i input.csv -o ~/Destkop/may_20_output
COMMAND LINE OPTIONS
---------------------
Command line options for this program are as follows:
-c or --calc: Specify a calculation variant to be used. Valid options include the following:
STANDARD - dist(r1,s1) + dist(r2,s2) + dist(r3,s3)
AVERAGE_FIRST_DISTANCE - dist(avg(r1,r2,r3), s1) + dist(avg(r1,r2,r3), s2) + dist(avg(r1,r2,r3), s3)
Example: $./GeneDistance -i input.csv -c average_first_distance
-g or --gene: Generate output only for a specific gene
Example: $./GeneDistance -i input.csv -g DYRK1A
-h or --help: Display usage for all of the command line arguments and basic information about the program
Example: $./GeneDistance -h
-i or --input: Specify the input file
Example: $./GeneDistance -i input.csv
-l or --lowPPIB: Specify a low PPIB threshold. Any genes with an average PPIB less than this value will be removed from the calculations
Example: $./GeneDistance -i input.csv -l 2500
-o or --output: Specify an output directory. Default is "output"
Example: $./GeneDistance -i input.csv -o ~/Desktop/may_20_output
-p or --plates: Specify which plates will be included in the calculation. Format is: plate#,plate#,plate#, ...
Example: $./GeneDistance -i input.csv -p 1,5,6,7
This will run calculations ONLY for gene included in plates 1,5,6 or 7
-r or --results: Specify the number of results for each gene. Default is 10, minimum is 1, maximum is the total number of genes
Example: $./GeneDistance -i input.csv -r 50
-t or --highPPIB: Specify a high PPIB threshold, Any genes with an average PPIB greater than this value will be removed from the calculations
Example: $./GeneDistance -i input.csv -t 17500
All of these command line arguments can be used together to get granular filtering at many levels. For example, the following command:
$./GeneDistance -i input.csv -o ~/Desktop/test_output -l 1750 -t 21000 -p 1,5,6,8,13,16,17 -r 30 -c average_first_distance
will run calculations using the "average_first_distance" calculation variant on genes with an average PPIB between 1750 and 21000 that are also from plates 1,5,6,8,13,16 or 17. The program will save the top 30 results for each gene in the "~/Desktop/test_output" directory.
FILES INCLUDED
---------------------
genedist.cu - main source code for program
genedist.h - header file for main source code
Makefile - makefile to create executable for program
gt - "ground truth" directory containing what are assumed to be correct values for calculations. Use to check against results after modifying code to ensure correctness has not been affected.
serialfiles - directory containing original serial versions of the code
input.csv - standard input file in the correct format. All other input files must follow this format EXACTLY<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#define MAX_GENES 25000
#define NUMBER_OF_RESULTS 10
bool isValidName(char* name);
void trim(char* str);
void usage(void);
void createGeneListFromFile(FILE* file);
void calculateDistances(char* gene);
void sortAndPrint();
int compareDistanceTuple (const void * a, const void * b);
typedef struct {
double e1[6], e2[6], e3[6];
char name[20];
} Gene;
typedef struct {
unsigned int geneOne;
unsigned int geneTwo;
double distance;
} DistanceTuple;
DistanceTuple** distanceMatrix;
Gene **geneList;
int geneCount = 0;
int main(int argc, char** argv) {
if(argc != 2) {
usage();
return 1;
}
char* selectedGene = "DYRK1A";
char* filePath = argv[1];
FILE *file;
if(!(file = fopen(filePath, "r"))) {
//File does not exist
printf("Unable to open input file %s\n", filePath);
return 1;
}
//Allocate memory for the gene list
geneList = malloc(MAX_GENES * sizeof(Gene*));
for(int i = 0; i < MAX_GENES; i++) {
geneList[i] = malloc(MAX_GENES * sizeof(Gene));
}
//File exists so continue
createGeneListFromFile(file);
//Close input file
fclose(file);
printf("This is genecount: %d\n", geneCount);
//Allocate memory for the distance matrix
distanceMatrix = malloc(geneCount * sizeof(DistanceTuple*));
for(int i = geneCount - 1; i >= 0; i--) {
distanceMatrix[geneCount - i - 1] = malloc(i * sizeof(DistanceTuple));
}
calculateDistances(selectedGene);
sortAndPrint();
printf("Done! Results have been stored in the \"output\" folder.\n");
return 0;
}
void sortAndPrint() {
printf("In sort now\n");
//Need to reconstruct a templist from the distance matrix for each gene
DistanceTuple* tempDistanceList = malloc((geneCount - 1) * sizeof(DistanceTuple));
int distanceIndex;
for(int i = 0; i < geneCount; i++) {
Gene* curr_gene = geneList[i];
distanceIndex = 0;
int row, col;
row = i - 1;
col = 0;
//weird diagonal stuff
while(row >= 0 && col <= i - 1) {
tempDistanceList[distanceIndex] = distanceMatrix[row][col];
distanceIndex++;
row--;
col++;
}
//rest of the column
for(int j = 0; j < geneCount - i - 1; j++) {
tempDistanceList[distanceIndex] = distanceMatrix[i][j];
tempDistanceList[distanceIndex].geneOne = distanceMatrix[i][j].geneTwo;
distanceIndex++;
}
qsort (tempDistanceList, geneCount - 1, sizeof(DistanceTuple), compareDistanceTuple);
char fname[40];
strcpy(fname, "output/");
strcat(fname, curr_gene->name);
strcat(fname, ".txt");
//Write results to file
FILE * outfile = fopen(fname, "w");
if(!outfile) {
printf("Warning: File could not be created. Exiting Program.\n");
exit(1);
}
for(int j = 0; j < NUMBER_OF_RESULTS; j++) {
fprintf(outfile, "%d: %s %f\n", j+1, geneList[tempDistanceList[j].geneOne]->name, tempDistanceList[j].distance);
}
fclose(outfile);
}
}
void calculateDistances(char* gene) {
Gene *curr_gene;
double dist1 = 0.0, dist2 = 0.0, dist3 = 0.0, sumdist = 0.0;
for(int i = 0; i < geneCount; i++) {
curr_gene = geneList[i];
int distColIndex = 0;
for(int j = i+1; j < geneCount; j++) {
Gene *tmp = geneList[j];
dist1 = sqrt(pow(tmp->e1[0] - curr_gene->e1[0],2) + pow(tmp->e1[1] - curr_gene->e1[1],2) +
pow(tmp->e1[2] - curr_gene->e1[2],2) + pow(tmp->e1[3] - curr_gene->e1[3],2) +
pow(tmp->e1[4] - curr_gene->e1[4],2) + pow(tmp->e1[5] - curr_gene->e1[5],2));
dist2 = sqrt(pow(tmp->e2[0] - curr_gene->e2[0],2) + pow(tmp->e2[1] - curr_gene->e2[1],2) +
pow(tmp->e2[2] - curr_gene->e2[2],2) + pow(tmp->e2[3] - curr_gene->e2[3],2) +
pow(tmp->e2[4] - curr_gene->e2[4],2) + pow(tmp->e2[5] - curr_gene->e2[5],2));
dist3 = sqrt(pow(tmp->e3[0] - curr_gene->e3[0],2) + pow(tmp->e3[1] - curr_gene->e3[1],2) +
pow(tmp->e3[2] - curr_gene->e3[2],2) + pow(tmp->e3[3] - curr_gene->e3[3],2) +
pow(tmp->e3[4] - curr_gene->e3[4],2) + pow(tmp->e3[5] - curr_gene->e3[5],2));
sumdist = dist1 + dist2 + dist3;
distanceMatrix[i][distColIndex].geneOne = i;
distanceMatrix[i][distColIndex].geneTwo = j;
distanceMatrix[i][distColIndex].distance = sumdist;
distColIndex++;
}
}
}
void trim(char *str) {
char *p1 = str, *p2 = str;
do
while (*p2 == ' ' || *p2 == '/')
p2++;
while (*p1++ = *p2++);
}
int compareDistanceTuple (const void * a, const void * b) {
DistanceTuple *ia = (DistanceTuple*)a;
DistanceTuple *ib = (DistanceTuple*)b;
double diff = ia->distance - ib->distance;
if(diff < 0) {
return -1;
} else if (diff == 0.0f) {
return 0;
} else {
return 1;
}
}
void usage(void) {
printf("Please enter the path of the input file and no other command line arguments.\n");
}
bool isValidName(char* name) {
if(strcmp(name, "analyte11") == 0) {
return false;
} else if (strcmp(name, "siControl") == 0) {
return false;
} else if (strcmp(name, "Gene Symbol") == 0) {
return false;
} else if (strcmp(name, "siCONT") == 0) {
return false;
}else if (*name == 13) {
return false;
}
return true;
}
void createGeneListFromFile(FILE* file) {
char line[256];
while(fgets( line, sizeof(line), file ) != NULL)
{
char* tok;
int len = strlen(line);
if(len > 0 && line[len-1]=='\n'){
line[len-1] = '\0';
}
if(len > 2 && line[len-2]=='\r') {
line[len-2] = '\0';
}
tok = strtok(line,",");
if(tok && isValidName(tok)) {
Gene *currGene = geneList[geneCount];
strcpy(currGene->name, tok);
//Eliminate unwanted characters (spaces, slashes)
trim(currGene->name);
//Populate experiment 1 array for the gene
for(int i = 0; i < 6; i++) {
tok = strtok(NULL,",");
//When there is no data for this experiment, skip to the next experiment
if(strcmp(tok,"=") == 0) {
currGene->e1[i] = 0.0f;
} else {
currGene->e1[i] = atof(tok);
}
}
//Populate experiment 2 array for the gene
for(int i = 0; i < 6; i++) {
tok = strtok(NULL,",");
//When there is no data for this experiment, skip to the next experiment
if(strcmp(tok,"=") == 0) {
currGene->e2[i] = 0.0f;
} else {
currGene->e2[i] = atof(tok);
}
}
//Populate experiment 2 array for the gene
for(int i = 0; i < 6; i++) {
tok = strtok(NULL,",");
//When there is no data for this experiment, skip to the next experiment
if(strcmp(tok,"=") == 0) {
currGene->e3[i] = 0.0f;
} else {
currGene->e3[i] = atof(tok);
}
}
geneCount++;
}
}
}
<file_sep>all: serial matrix
serial: serialdist.c
gcc serialdist.c -lm -g -std=c99 -O3 -o serial-dist -lprofiler
matrix: serialdist-matrix.c
gcc serialdist-matrix.c -lm -g -std=c99 -O3 -o matrixdist
gperfmatrix: serialdist-matrix.c
gcc serialdist-matrix.c -lm -g -std=c99 -O3 -o matrixdist_gperf -lprofiler
clean:
rm serial-dist matrixdist
<file_sep>all: genedistance
genedistance: genedist.cu genedist.h
nvcc -use_fast_math -g -arch=sm_21 genedist.cu -O2 -o GeneDistance -lineinfo
clean:
rm GeneDistance
<file_sep>#define MAX_GENES 33000
#define REPLICATES_PER_GENE 3
#define PROBES_PER_REPLICATE 6
#define DISTANCES_PER_GENE (REPLICATES_PER_GENE * PROBES_PER_REPLICATE)
#define MAX_GENE_NAME_SIZE 50
#define MAX_FILE_PATH_SIZE 200
//Input size less than this will be run in serial mode
#define CUDA_CUTOFF 4000
typedef struct __align__(16) {
unsigned int geneOne;
unsigned int geneTwo;
double distance;
} DistanceTuple;
enum calculationVariant {
STANDARD, //dist(r1,s1) + dist(r2,s2) + dist(r3,s3)
AVERAGE_FIRST_DISTANCE //dist(avg(r1,r2,r3), s1) + dist(avg(r1,r2,r3), s2) + dist(avg(r1,r2,r3), s3)
};
void calculateSingleDistance(char* gene, double* geneList, double* distanceList);
void calculateDistanceCPU(double* geneList, DistanceTuple** distanceMatrix);
int compareDistanceTuple (const void* a, const void* b);
void createGeneListFromFile(FILE* file, double* geneList);
bool checkCudaError(cudaError_t error, char* operation);
void getCardSpecs();
bool isValidName(char* name);
void sortAndPrint(double* geneList, double* distance, DistanceTuple** distanceMatrix);
void trim(char* str);
void usage(void);
|
294bd3cbd8f76ee2a666c9089c38fa8bf312f9dd
|
[
"Markdown",
"C",
"Makefile"
] | 6
|
C
|
mcbymef/cuda-gene
|
76416d8dae96e6698f961e0bc45cd2a19649b107
|
1cc24baf4a2ad6ecbe5c1475130803afa8551984
|
refs/heads/master
|
<repo_name>Asamasach/SQL_BackUp_Bash<file_sep>/SQL_Back_Up.sh
#!/bin/bash
# author: <NAME>(<EMAIL>)
# birthdate: 28 May 2018,08:05
# modifier: -
# modified date: -
# version: 0.1
# description: this script written in order to backup mysql databases.
# exit status help
# 0 successfull
# 1 incorrect mysql backup user password
# 2 backup directory creation fail
# 3 .my.cnf file dose not exist
#create backup directory
SERVER="localhost"
BACKUP_MINOR_DIR=$(date +%Y%m%d)
BACKUP_DB_DIR="/backup/"
BACKUP_DB_NAME_PREFIX=$(date +%Y%m%d-%H%M%S)
if [ ! -d $BACKUP_DB_DIR ]; then
mkdir -p $BACKUP_DB_DIR
if [ $? -ne 0 ];then
logger "backup-db: couldn't create backup direcroty.backup operation faild"
exit 2
fi
fi
mkdir $BACKUP_DB_DIR/$BACKUP_MINOR_DIR &> /dev/null
#mysql backup user and password
MYSQL_USER="root"
MYSQL_PASSWORD=""
#read mysql password from stdin if empty
if [ -z "${MYSQL_PASSWORD}" ]; then
echo -n "Enter MySQL ${MYSQL_USER} password: "
read -s MYSQL_PASSWORD
echo
fi
#check MySQL password
echo exit | mysql --user=${MYSQL_USER} --password=${MYSQL_PASSWORD} -B 2>/dev/null
if [ $? -ne 0 ]; then
logger "backup-db: MySQL ${MYSQL_USER} password incorrect"
exit 1
fi
#get databases
MYSQL_DATABASES=$(echo 'show databases' | mysql --user=${MYSQL_USER} --password=${MYSQL_PASSWORD} -B | sed /^Database$/d)
# backup and compress each database
for database in $MYSQL_DATABASES
do
if [ "${database}" == "information_schema" ] || [ "${database}" == "performance_schema" ]; then
ADDITIONAL_MYSQLDUMP_PARAMS="--lock-tables=false "
else
ADDITIONAL_MYSQLDUMP_PARAMS="--lock-tables=false"
fi
mysqldump ${ADDITIONAL_MYSQLDUMP_PARAMS} --triggers --routines --single-transaction --user=${MYSQL_USER} --password=${<PASSWORD>} ${database} | gzip --best > "${BACKUP_DB_DIR}/${BACKUP_MINOR_DIR}/${BACKUP_DB_NAME_PREFIX}-${database}.gz" 2> /dev/null
if [ $? -eq 0 ];then
logger "${database} backup sucess."
else
logger "${database} backup faild."
fi
done
logger "mysql database backup done successfully.for more details check log file"
exit 0
|
6c6f1ccfeadc5b013c613c2ba976f639d5c2195d
|
[
"Shell"
] | 1
|
Shell
|
Asamasach/SQL_BackUp_Bash
|
b4c7aa63e96a29d79c9aa92643aa3828a2affcc9
|
ec2314da29fcdf3f25fb6f6899d5cbade95a7e7f
|
refs/heads/master
|
<repo_name>jayczech23/Nite-Owl-1.0<file_sep>/Nite-Owl/LocationVC.swift
//
// LocationVC.swift
// Nite-Owl
//
// Created by <NAME> on 6/17/16.
// Copyright © 2016 Strana LLC All rights reserved.
//
import UIKit
import MapKit
class LocationVC: UIViewController, MKMapViewDelegate {
@IBOutlet weak var map: MKMapView!
let regionRadius: CLLocationDistance = 1000
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
map.delegate = self
}
override func viewDidAppear(animated: Bool) {
locationAuthStatus()
}
func locationAuthStatus() {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
map.showsUserLocation = true
} else {
locationManager.requestWhenInUseAuthorization()
}
}
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2, regionRadius * 2)
map.setRegion(coordinateRegion, animated: true)
}
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
if let loc = userLocation.location {
centerMapOnLocation(loc)
}
}
}
|
f392fa157c3feb90b9f0285a58568bdd61f76474
|
[
"Swift"
] | 1
|
Swift
|
jayczech23/Nite-Owl-1.0
|
015eb4402f2f25f570dbcc7dc40095cb6fd48260
|
1d934cd479160f4165b253ca4377bae4dcdde4f6
|
refs/heads/master
|
<file_sep>bittorrent-nodeID
===
Javascript implementation of [BEP42 - DHT Security extension](http://www.bittorrent.org/beps/bep_0042.html) to calculate or check the nodeID of a peer.
BEP42 is implemented in projects uTorrent, libtorrent and bootstrap-dht.
## Installation and use
This is using [node-fast-crc32c](https://github.com/ashi009/node-fast-crc32c) from Xiaoyi and/or [sse4_crc32](https://github.com/Voxer/sse4_crc32) from Anand Suresh.
npm install bittorrent-nodeid
Then:
var generate_id=require('bittorent-nodeid');
generate_id('W.X.Y.Z',Random_byte) --> prefix abcdefgh --> nodeID: (first 20 bits of prefix) (random number) Random_byte
generate_id('192.168.3.11',1) --> prefix 5fbfbdb2 --> nodeID: 5fbfb e7519910c34ae7026c3e64eacc13c5159 01
generate_id('192.168.127.12',86) --> prefix 5a3ce9b0 --> nodeID: 5a3ce 91f3dc70a057e9a9fe0cc900d52b4e61e 56
generate_id('172.16.31.10',22) --> prefix a5d4344a --> a5d43 396da271c1a4d1dc7149247f021eabc34 16
## Note about the binary format
BEP42 does define the following calculation to compute the nodeID:
crc32c((ip & 0x030f3fff) | (r << 29))
Where ip is the ip address representation in network bytes order.
For ip 192.168.3.11, the calculation with a random number set to 1 will be ``crc32c((0x7c1f4b15 & 0x030f3fff) | (1 << 29))``, so ``crc32c(0x200f0b15)`` which is computed as ``crc32c(new Buffer('200f0b15','hex'))`` or ``crc32c(new Buffer([0x20,0xf,0xb,0x15]))`` or ``crc32c('ABCD')`` where ABCD are the characters corresponding to the ascii code of each byte.
In javascript a character outside of the normal ascii range like 'Á' will be interpreted as utf8 ``0xc381`` and ``crc32c.calculate('Á')`` will give ``b1cf5bcd``
But most of the c++ libraries does handle this byte by byte, so 'Á' will be interpreted as ``0xc1`` and ``crc32c.calculate('Á')`` will give ``639bf696``
## Related projects :
* [Ayms/bitcoin-wallets](https://github.com/Ayms/bitcoin-wallets)
* [Ayms/torrent-live](https://github.com/Ayms/torrent-live)
* [Ayms/node-Tor](https://github.com/Ayms/node-Tor)
* [Ayms/iAnonym](https://github.com/Ayms/iAnonym)
* [Interception Detector](http://www.ianonym.com/intercept.html)
* [Ayms/abstract-tls](https://github.com/Ayms/abstract-tls)
* [Ayms/websocket](https://github.com/Ayms/websocket)
* [Ayms/node-typedarray](https://github.com/Ayms/node-typedarray)
* [Ayms/node-dom](https://github.com/Ayms/node-dom)
* [Ayms/node-bot](https://github.com/Ayms/node-bot)
* [Ayms/node-gadgets](https://github.com/Ayms/node-gadgets)
<file_sep>var crc32c;
try {
crc32c=require('fast-crc32c');
} catch(ee) {
try {
crc32c=require("sse4_crc32");
} catch(ee) {}
};
var generate_id=function(ip,rand) { //rand 0-255
var id=new Buffer(20);
var buf=new Buffer(4);
ip=(new Buffer(ip.split('.'))).readUInt32BE();
buf.writeUInt32BE(((ip & 0x030f3fff) | (rand << 29))>>>0);
var c=crc32c.calculate(buf,0);
id[0]=(c>>24)&0xff;
id[1]=(c>>16)&0xff;
id[2]=((c>>8)&0xf8)|(parseInt(Math.random()*255)&0x7);
for (var i=3;i<19;i++) {id[i]=parseInt(Math.random()*255);}
id[19]=rand;
return id;
};
/* Other implementation
var generate_id=function(ip,rand) { //rand 0-255
var id=new Buffer(20);
var mask=[0x03,0x0f,0x3f,0xff];
ip=ip.split('.');
ip=ip.map(function(val,i) {return val&mask[i]});
var r=rand&0x7;
ip[0]|=r<<5;
var c=crc32c.calculate(new Buffer(ip),0);
id[0]=(c>>24)&0xff;
id[1]=(c>>16)&0xff;
id[2]=((c>>8)&0xf8)|(parseInt(Math.random()*255)&0x7);
for (var i=3;i<19;i++) {id[i]=parseInt(Math.random()*255);}
id[19]=rand;
return id;
};
*/
module.exports=generate_id;
|
f899691bc64460bc9811770265d3582f38c1a931
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Ayms/bittorrent-nodeid
|
47d34367471d45558b4fbcb59718868feb8825c6
|
0cdd3fd896a8a7b07b997f6dc9bf262c9c8912a7
|
refs/heads/master
|
<repo_name>shaohua/linode_basic_security_python<file_sep>/README.md
linode_basic_security_python
============================
A stack script for Linode
This is the minimum to get the system up and running so you can login with ssh
Then Fabric is going to do the heavy lifting.
<file_sep>/StackScripts_python_basic_security.sh
#!/bin/bash
#based on http://www.linode.com/stackscripts/view/?StackScriptID=131
# <UDF name="user_name" label="Unprivileged user account name" example="This is the account that you will be using to log in." />
# <UDF name="user_password" label="Unprivileged user password" />
# <UDF name="user_sshkey" label="Public Key for user" default="" example="Recommended method of authentication. It is more secure than password log in." />
# <UDF name="sshd_passwordauth" label="Use SSH password authentication" oneof="Yes,No" default="No" example="Turn off password authentication if you have added a Public Key." />
# <UDF name="sshd_permitrootlogin" label="Permit SSH root login" oneof="No,Yes" default="No" example="Root account should not be exposed." />
# <UDF name="user_shell" label="Shell" oneof="/bin/zsh,/bin/bash" default="/bin/bash" />
# <UDF name="sys_hostname" label="System hostname" default="myvps" example="Name of your server, i.e. linode1." />
set -e
set -u
#set -x
USER_GROUPS=sudo
exec &> /root/stackscript.log
source <ssinclude StackScriptID="1"> # StackScript Bash Library
system_update
source <ssinclude StackScriptID="124"> # lib-system
# Configure system
source <ssinclude StackScriptID="123"> # lib-system-ubuntu
system_update_hostname "$SYS_HOSTNAME"
# Create user account
system_add_user "$USER_NAME" "$USER_PASSWORD" "$USER_GROUPS" "$USER_SHELL"
if [ "$USER_SSHKEY" ]; then
system_user_add_ssh_key "$USER_NAME" "$USER_SSHKEY"
fi
# Configure sshd
system_sshd_permitrootlogin "$SSHD_PERMITROOTLOGIN"
system_sshd_passwordauthentication "$SSHD_PASSWORDAUTH"
touch /tmp/restart-ssh
# Lock user account if not used for login
if [ "SSHD_PERMITROOTLOGIN" == "No" ]; then
system_lock_user "root"
echo "Locked root account" # SS124
fi
restart_services
restart_initd_services
#added by sz
# Installs the REAL vim, wget, less, and enables color root prompt and the "ll" list long alias
goodstuff
|
a809ab016b58b18990b056632b5ede25cd2c52f7
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
shaohua/linode_basic_security_python
|
c439327904992d9da1710bb86b34294b916e6bcf
|
f1a6dee4d82aa192d5b6f651ad019a0a8b01b8db
|
refs/heads/master
|
<file_sep># natur-service
- [中文文档(无法访问试试翻墙)](https://www.empty916.site/zh/natur-service/)
- [document](https://www.empty916.site/natur-service/)
<file_sep>import { createStore } from 'natur';
import NaturService from '../src';
const count = {
state: 0,
actions: {
update: (ns: number) => ns,
},
maps: {
plus1: (s: number) => s + 1,
}
};
const count2 = {
state: 0,
actions: {
update: (ns: number) => ns,
},
maps: {
plus1: (s: number) => s + 1,
}
};
const count3 = {
state: {
value: 1,
list: [{d: 1, v: 1}, 1],
data: {
a: 2,
b: {
d: 1,
}
}
},
actions: {
update: (ns: number) => ({
value: ns,
list: [{d: ns, v: ns}, ns],
data: {
a: ns,
b: {
d: ns,
}
}
}),
},
maps: {
plus1: (s: {value: number}) => s.value + 1,
}
};
const count4 = {
state: {
value: 1,
list: [{d: 1, v: 1}, 1],
data: {
a: 2,
b: {
d: 1,
}
}
},
actions: {
update: (ns: number) => ({
value: ns,
list: [{d: ns, v: ns}, ns],
data: {
a: ns,
b: {
d: ns,
}
}
}),
},
maps: {
plus1: (s: {value: number}) => s.value + 1,
}
};
type M = {
count: typeof count;
count2: typeof count2;
count3: typeof count3;
count4: typeof count4;
};
let store = createStore({count, count2, count3, count4}, {});
const sleep = (time: number) => new Promise(res => setTimeout(res, time));
class BaseService extends NaturService<M, {}> {
constructor(s: typeof store = store) {
super(s);
this.start();
}
start() {}
}
beforeEach(() => {
store.destroy();
store = createStore({count, count2, count3, count4}, {});
});
test('watch module init', async () => {
let hasStarted = false;
let watcherHasRun = false;
class CountService extends BaseService {
start() {
hasStarted = true;
expect(this.store).toBe(store);
this.watch('count', ({actionName, state, type}) => {
watcherHasRun = true;
expect(type).toBe('init');
});
}
}
const cs = new CountService();
await sleep(10);
expect(hasStarted).toBe(true);
store.setModule('count', count);
return expect(watcherHasRun).toBe(true);
});
test('watch module remove', async () => {
class CountService extends BaseService {
start() {
this.watch('count', ({actionName, state, type}) => {
expect(type).toBe('remove');
});
}
}
const cs = new CountService();
await sleep(10);
store.removeModule('count');
});
test('watch module update', async () => {
const newState = Math.random();
const _oldCount = store.getModule('count');
class CountService extends BaseService {
start() {
this.watch('count', ({
type,
actionName,
state,
oldModule,
newModule,
}) => {
expect(type).toBe('update');
expect(actionName).toBe('update');
expect(state).toBe(newState);
expect(oldModule).toEqual(_oldCount);
expect(newModule).toEqual(store.getModule('count'));
});
}
}
const cs = new CountService();
await sleep(10);
store.dispatch('count', 'update', newState);
});
test('dispatch', async () => {
let callTime = 0;
class CountService extends BaseService {
start() {
this.watch('count', ({state}) => {
callTime++;
if (typeof state === 'number') {
this.dispatch('count2', 'update', state);
}
});
this.watch('count2', ({state}) => {
callTime++;
expect(state).toBe(store.getModule('count').state);
});
}
}
const cs = new CountService();
await sleep(10);
store.dispatch('count', 'update', 1);
store.dispatch('count', 'update', 2);
// expect(callTime).toBe(2);
});
test('dispatch lazyModule', async () => {
store.removeModule('count2');
let callTime = 0;
let dropOldDispatch = 0;
class CountService extends BaseService {
start() {
this.watch('count', ({state}) => {
if (typeof state === 'number') {
this.dispatch('count2', 'update', state);
}
});
this.watch('count2', ({state, type}) => {
if (type === 'update') {
expect(state).toBe(2);
}
callTime++;
});
}
dispatch: NaturService<M, {}>['dispatch'] = (...arg) => {
return super.dispatch(arg[0], arg[1], ...(arg as any).slice(2)).catch(e => {
if (e?.code === 0) {
dropOldDispatch++;
return;
}
throw e;
}) as any;
}
}
const cs = new CountService();
await sleep(10);
store.dispatch('count', 'update', 1);
store.dispatch('count', 'update', 2);
store.setModule('count2', count2);
await sleep(10);
expect(callTime).toBe(2);
expect(dropOldDispatch).toBe(1);
});
test('sync data', async () => {
class CountService extends BaseService {
start() {
}
}
const cs = new CountService();
await sleep(10);
store.dispatch('count3', 'update' ,11);
store.dispatch('count', 'update' ,11);
// cs.syncDataByKeyPath('count3', 'count4', 'state.value', 'data.a');
// cs.syncDataByKeyPath('count3', 'count4', 'state.value', 'data.b.d');
// cs.syncDataByKeyPath('count3', 'count4', 'maps.plus1', 'value');
// cs.syncDataByKeyPath('count', 'count2', 'state');
cs.syncDataWith('count3', 'count4', (s) => {
return s.state.value
}, (state, d) => {
return {
...state,
data: {
...state.data,
a: d,
}
}
});
cs.syncDataWith('count3', 'count4', (s) => {
return s.maps.plus1
}, (state, d) => {
return {
...state,
value: d,
}
})
cs.syncDataWith('count3', 'count4', (s) => {
return s.state.value
}, (state, d) => {
return {
...state,
data: {
...state.data,
b: {
...state.data.b,
d: d,
}
}
}
})
cs.syncDataWith('count', 'count2', (s) => {
return s.state
}, (state, d) => {
return d
})
await sleep(10);
expect(store.getModule('count4').state.data.a).toBe(11);
expect(store.getModule('count4').state.data.b.d).toBe(11);
expect(store.getModule('count4').state.value).toBe(12);
expect(store.getModule('count2').state).toBe(11);
})
test('watch sync data with', async () => {
class CountService extends BaseService {
start() {
this.watchAndSyncDataWith('count3', 'count4', sm => sm.state.value, (ts, nv) => ({
...ts,
data: {
...ts.data,
a: nv,
}
}));
this.watchAndSyncDataWith('count3', 'count4', sm => sm.maps.plus1, (ts, nv) => ({
...ts,
value: nv,
}));
this.watchAndSyncDataWith('count', 'count2', sm => sm.state, (_, nv) => nv);
}
}
const cs = new CountService();
await sleep(10);
store.dispatch('count3', 'update' ,11);
store.dispatch('count', 'update' ,11);
await sleep(10);
expect(store.getModule('count4').state.data.a).toBe(11);
expect(store.getModule('count4').state.value).toBe(12);
expect(store.getModule('count2').state).toBe(11);
})
test('destroy', async () => {
let callTime = 0;
store.removeModule('count2');
class CountService extends BaseService {
start() {
this.watch('count', ({state}) => {
callTime++;
state && this.dispatch('count2', 'update', state);
});
this.watch('count2', ({state}) => {
callTime++;
});
}
dispatch: NaturService<M, {}>['dispatch'] = (...arg) => {
return super.dispatch(arg[0], arg[1], ...(arg as any).slice(2)).catch(e => {
if (e?.code === 0) {
return;
}
throw e;
}) as any;
}
}
const cs = new CountService();
await sleep(10);
store.dispatch('count', 'update', 1);
cs.destroy();
store.dispatch('count', 'update', 2);
store.dispatch('count2', 'update', 2);
await sleep(10);
expect(callTime).toBe(1);
});
<file_sep>import { setValueFromObjByKeyPath } from '../src/utils';
test('setValueFromObjByKeyPath', () => {
expect(setValueFromObjByKeyPath({a: 1}, 'a', 2)).toEqual({a: 2});
expect(setValueFromObjByKeyPath({a: {b: 1}}, 'a', 2)).toEqual({a: 2});
expect(setValueFromObjByKeyPath({a: {b: 1}}, 'a.b', 2)).toEqual({a: {b: 2}});
expect(setValueFromObjByKeyPath({a: {b: [1]}}, 'a.b.0', 2)).toEqual({a: {b: [2]}});
expect(setValueFromObjByKeyPath({a: {b: [1,2]}}, 'a.b.length', 0)).toEqual({a: {b: []}});
})<file_sep>import { InjectStoreModules, ModuleEvent } from "natur";
import {
GenerateStoreType,
LazyStoreModules,
Modules,
Store,
} from "natur/dist/ts-utils";
import type {
ModuleEventType,
ServiceListenerParamsTypeMap,
} from "./utils";
// 停止上一次推送码
const STOP_THE_LAST_DISPATCH_CODE = 0;
export default class NaturService<
// S extends Store<Modules, LazyStoreModules>,
// M extends Modules = S extends Store<infer MV, LazyStoreModules> ? MV : never,
// LM extends LazyStoreModules = S extends Store<Modules, infer LMV> ? LMV : never,
// ST extends InjectStoreModules = GenerateStoreType<M, LM>,
M extends Modules,
LM extends LazyStoreModules,
S extends Store<M, LM> = Store<M, LM>,
ST extends InjectStoreModules = GenerateStoreType<M, LM>
> {
dispatchPromise: {
[type: string]: {
value: Promise<any> | undefined;
cancel: Function;
};
} = {};
store: S;
listener: Array<Function> = [];
constructor(s: S) {
this.store = s;
this.getStore = this.getStore.bind(this);
this._getModule = this._getModule.bind(this);
this.dispatch = (this.dispatch as any).bind(this);
this.watch = this.watch.bind(this);
this.destroy = this.destroy.bind(this);
}
protected async dispatch<
MN extends Extract<keyof ST, string>,
AN extends Extract<keyof ST[MN]["actions"], string>
>(
moduleName: MN,
actionName: AN,
...arg: Parameters<ST[MN]["actions"][AN]>
): Promise<ReturnType<ST[MN]["actions"][AN]>> {
const store = this.getStore();
if (store === undefined) {
throw new Error("natur-service: store is undefined!");
}
const type = `${moduleName}/${actionName}`;
if (store.hasModule(moduleName)) {
return store.dispatch(moduleName, actionName, ...arg);
} else {
if (!this.dispatchPromise[type]) {
this.dispatchPromise[type] = {
value: undefined,
cancel: () => {},
};
}
if (!!this.dispatchPromise[type].value) {
this.dispatchPromise[type].cancel();
}
this.dispatchPromise[type].value = new Promise<void>(
(resolve, reject) => {
const unsub = store.subscribe(moduleName, () => {
unsub();
resolve();
});
this.dispatchPromise[type].cancel = () => {
reject({
code: STOP_THE_LAST_DISPATCH_CODE,
message: "stop the last dispatch!",
});
unsub();
};
}
).then(() => store.dispatch(moduleName, actionName, ...arg));
return this.dispatchPromise[type].value;
}
}
private _getModule<M extends keyof ST>(moduleName: M) {
const store = this.getStore();
if (store === undefined) {
throw new Error("natur-service: store is undefined!");
}
if (!store.hasModule(moduleName as string)) {
return undefined;
}
return store.getModule(moduleName as string);
}
protected getStore(): S {
return this.store;
}
protected async watch<MN extends keyof ST>(
moduleName: MN,
watcher: <T extends ModuleEventType>(
me: ServiceListenerParamsTypeMap<ST, MN>[T]
) => any
) {
/**
* 在store的模块中,又可能引入service模块,
* 在service模块构造函数中,一般会调用watch方法,但是store有可能为初始化完成,
* 所以将watch放在promise队列中
*/
await Promise.resolve();
const store = this.getStore();
if (store === undefined) {
throw new Error("natur-service: store is undefined!");
}
const { _getModule } = this;
let oldModule = _getModule(moduleName);
const unwatch = store.subscribe(moduleName as any, (me) => {
const newModule = _getModule(moduleName);
watcher({
...me,
state: (newModule as any)?.state,
oldModule,
newModule,
} as any);
oldModule = newModule;
});
const destroyWatch = () => {
oldModule = undefined;
unwatch();
};
this.listener.push(destroyWatch);
}
/**
* synchronize the data of sourceModule to targetModule,
* when the data of sourceModule is update and different from the data of targetModule
* @param sourceModuleName
* @param targetModuleName
* @param sdGetter sourceModule data getter
* @param tsSetter
*/
watchAndSyncDataWith<
SMN extends keyof ST,
TMN extends Exclude<keyof ST, SMN>,
SDGetter extends (State: Pick<ST[SMN], 'state'|'maps'>) => any,
TSGetter extends (State: ST[TMN]["state"], data: ReturnType<SDGetter>) => ST[TMN]["state"]
>(
sourceModuleName: SMN,
targetModuleName: TMN,
sdGetter: SDGetter,
tsSetter: TSGetter
) {
this.watch(sourceModuleName, () => {
this.syncDataWith(
sourceModuleName,
targetModuleName,
sdGetter,
tsSetter
);
});
}
/**
* synchronize the data of sourceModule to targetModule, when the data of sourceModule is different from the data of targetModule
* @param sourceModuleName
* @param targetModuleName
* @param stateKey common key of sourceModule's state and targetModule's state
* @example
* this.syncDataByStateKey('sourceModuleName', 'targetModuleName', 'StateKey')
*/
syncDataWith<
SMN extends keyof ST,
TMN extends Exclude<keyof ST, SMN>,
SDGetter extends (State: Pick<ST[SMN], 'state'|'maps'>) => any,
TSGetter extends (State: ST[TMN]["state"], data: ReturnType<SDGetter>) => ST[TMN]["state"]
>(
sourceModuleName: SMN,
targetModuleName: TMN,
sdGetter: SDGetter,
tsSetter: TSGetter
) {
try {
const sourceModule = this.store.getModule(sourceModuleName as string);
const targetModule = this.store.getModule(targetModuleName as string);
if (sourceModule) {
const nsd = sdGetter(sourceModule);
const ntd = tsSetter(targetModule.state, nsd);
this.store.globalSetStates({
[targetModuleName]: ntd,
} as any);
}
} catch (error) {
console.warn(error);
}
}
destroy() {
Object.keys(this.dispatchPromise).forEach((key) => {
this.dispatchPromise[key].cancel();
this.dispatchPromise[key].value = undefined;
delete this.dispatchPromise[key];
});
this.store = null as any;
this.listener.forEach((unSub) => unSub());
this.listener = [];
}
}
<file_sep>import { InjectStoreModules, ModuleEvent } from 'natur';
export { getValueFromObjByKeyPath } from 'natur/dist/utils';
// export const isNumber = (data: any): data is number => !Number.isNaN(Number(i))
export const setValueFromObjByKeyPath = <O extends {[p: string]: any}>(obj: O, keyPath: string, newValue: any): O | undefined => {
const formatKeyArr = keyPath.replace(/\[/g, '.').replace(/\]/g, '').split('.');
const res = {...obj};
let value: any = res;
for(let i = 0; i < formatKeyArr.length; i ++) {
try {
if (i === formatKeyArr.length - 1) {
value[formatKeyArr[i]] = newValue;
return res;
} else {
if (Array.isArray(value[formatKeyArr[i]])) {
value[formatKeyArr[i]] = value[formatKeyArr[i]].slice();
} else {
value[formatKeyArr[i]] = {
...value[formatKeyArr[i]]
};
}
value = value[formatKeyArr[i]];
}
} catch (error) {
console.error('natur-service sync data error: ', error);
return undefined;
}
}
return value;
}
export type ModuleEventType = ModuleEvent["type"];
export type ServiceListenerParamsTypeMap<
StoreType extends InjectStoreModules,
M extends keyof StoreType
> = {
[t in ModuleEventType]: {
type: t;
actionName: t extends "update"
? keyof StoreType[M]["actions"] | "globalSetStates" | "globalResetStates"
: undefined;
oldModule: t extends "init" ? undefined : StoreType[M];
newModule: t extends "remove" ? undefined : StoreType[M];
state: t extends "remove" ? undefined : StoreType[M]["state"];
};
};
|
4470d5ce8270b7f00c7e8ed76982d9ba82484067
|
[
"Markdown",
"TypeScript"
] | 5
|
Markdown
|
empty916/natur-service
|
2c322a1a05cb75d507db3874fc4c3e60841017a0
|
77ab35d77a82411b7289da7c7a23c84f75bb406b
|
refs/heads/master
|
<repo_name>KMantas/storage<file_sep>/mongo/cache_manager_test.go
package mongo_test
import (
// Standard Library Imports
"testing"
"time"
// External Imports
"github.com/ory/fosite"
"github.com/pborman/uuid"
// Public Imports
"github.com/matthewhartstonge/storage"
)
func expectedSessionCache() storage.SessionCache {
return storage.SessionCache{
ID: uuid.New(),
CreateTime: time.Now().Unix(),
UpdateTime: time.Now().Unix() + 600,
Signature: "Yhte@ensa#ei!+suu$re%sta^viik&oss*aha(joaisiaut)ta-is+ie%to_n==",
}
}
func TestCacheManager_Create(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
expected := expectedSessionCache()
got, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected)
if err != nil {
AssertError(t, err, nil, "create should return no database errors")
}
if got != expected {
AssertError(t, got, expected, "cache object not equal")
}
}
func TestCacheManager_Create_ShouldConflict(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
expected := expectedSessionCache()
got, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected)
if err != nil {
AssertError(t, err, nil, "create should return no database errors")
}
if got != expected {
AssertError(t, got, expected, "cache object not equal")
}
_, err = store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected)
if err == nil {
AssertError(t, err, nil, "create should return an error on conflict")
}
if err != storage.ErrResourceExists {
AssertError(t, err, nil, "create should return conflict")
}
}
func TestCacheManager_Get(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
expected := expectedSessionCache()
created, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected)
if err != nil {
AssertError(t, err, nil, "create should return no database errors")
}
if created != expected {
AssertError(t, created, expected, "cache object not equal")
}
got, err := store.CacheManager.Get(ctx, storage.EntityCacheAccessTokens, expected.Key())
if err != nil {
AssertError(t, err, nil, "get should return no database errors")
}
if got != expected {
AssertError(t, got, expected, "cache object not equal")
}
}
func TestCacheManager_Get_ShouldReturnNotFound(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
expected := fosite.ErrNotFound
got, err := store.CacheManager.Get(ctx, storage.EntityCacheAccessTokens, "lolNotFound")
if err != expected {
AssertError(t, got, expected, "get should return not found")
}
}
func TestCacheManager_Update(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
expected := expectedSessionCache()
created, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected)
if err != nil {
AssertError(t, err, nil, "create should return no database errors")
}
if created != expected {
AssertError(t, created, expected, "cache object not equal")
}
// Perform an update..
updatedSignature := "something completely different!"
created.Signature = updatedSignature
got, err := store.CacheManager.Update(ctx, storage.EntityCacheAccessTokens, created)
if err != nil {
AssertError(t, err, nil, "update should return no database errors")
}
if expected.UpdateTime == 0 {
AssertError(t, got.UpdateTime, time.Now().Unix(), "update time was not set")
}
// override update time on expected with got. The time stamp received
// should match time.Now().Unix() but due to the nature of time based
// testing against time.Now().Unix(), it can fail on crossing over the
// second boundary.
expected.UpdateTime = got.UpdateTime
expected.Signature = updatedSignature
if got != expected {
AssertError(t, got, expected, "cache update object not equal")
}
}
func TestCacheManager_Update_ShouldReturnNotFound(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
_, err := store.CacheManager.Update(ctx, storage.EntityCacheAccessTokens, expectedSessionCache())
if err == nil {
AssertError(t, err, nil, "update should return an error on not found")
}
if err != fosite.ErrNotFound {
AssertError(t, err, nil, "update should return not found")
}
}
func TestCacheManager_Delete(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
expected := expectedSessionCache()
created, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected)
if err != nil {
AssertError(t, err, nil, "create should return no database errors")
}
if created != expected {
AssertError(t, created, expected, "cache object not equal")
}
err = store.CacheManager.Delete(ctx, storage.EntityCacheAccessTokens, created.Key())
if err != nil {
AssertError(t, err, nil, "delete should return no database errors")
}
// Double check that the original reference was deleted
expectedErr := fosite.ErrNotFound
got, err := store.CacheManager.Get(ctx, storage.EntityCacheAccessTokens, created.Key())
if err != expectedErr {
AssertError(t, got, expectedErr, "get should return not found")
}
}
func TestCacheManager_Delete_ShouldReturnNotFound(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
expected := expectedSessionCache()
err := store.CacheManager.Delete(ctx, storage.EntityCacheAccessTokens, expected.Key())
if err == nil {
AssertError(t, err, nil, "delete should return an error on not found")
}
if err != fosite.ErrNotFound {
AssertError(t, err, nil, "delete should return not found")
}
}
func TestCacheManager_DeleteByValue(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
expected := expectedSessionCache()
created, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected)
if err != nil {
AssertError(t, err, nil, "create should return no database errors")
}
if created != expected {
AssertError(t, created, expected, "cache object not equal")
}
err = store.CacheManager.DeleteByValue(ctx, storage.EntityCacheAccessTokens, created.Value())
if err != nil {
AssertError(t, err, nil, "DeleteByValue should return no database errors")
}
// Double check that the original reference was deleted
expectedErr := fosite.ErrNotFound
got, err := store.CacheManager.Get(ctx, storage.EntityCacheAccessTokens, created.Key())
if err != expectedErr {
AssertError(t, got, expectedErr, "get should return not found")
}
}
func TestCacheManager_DeleteByValue_ShouldReturnNotFound(t *testing.T) {
store, ctx, teardown := setup(t)
defer teardown()
expected := expectedSessionCache()
err := store.CacheManager.DeleteByValue(ctx, storage.EntityCacheAccessTokens, expected.Value())
if err == nil {
AssertError(t, err, nil, "DeleteByValue should return an error on not found")
}
if err != fosite.ErrNotFound {
AssertError(t, err, nil, "DeleteByValue should return not found")
}
}
<file_sep>/cache_manager.go
package storage
import "context"
// Cacher provides a generic interface for storing data in a cache
type Cacher interface {
Key() string
Value() string
}
// CacheManager provides a generic interface to key value cache objects in
// order to build a cache datastore.
type CacheManager interface {
Configurer
CacheStorer
}
// CacheStorer provides a way to create cache based objects in mongo
type CacheStorer interface {
Create(ctx context.Context, entityName string, cacheObject SessionCache) (SessionCache, error)
Get(ctx context.Context, entityName string, key string) (SessionCache, error)
Update(ctx context.Context, entityName string, cacheObject SessionCache) (SessionCache, error)
Delete(ctx context.Context, entityName string, key string) error
DeleteByValue(ctx context.Context, entityName string, value string) error
}
<file_sep>/README.md
# fosite-storage-mongo
[](https://coveralls.io/github/matthewhartstonge/storage?branch=master) [](https://goreportcard.com/report/github.com/matthewhartstonge/storage) [](https://travis-ci.org/matthewhartstonge/storage) [](https://app.fossa.io/projects/git%2Bgithub.com%2Fmatthewhartstonge%2Fstorage?ref=badge_shield)
fosite-storage-mongo provides a native Go based [Mongo backed database storage][mgo]
that conforms to *all the interfaces!* required by [fosite][fosite].
**Table of contents**
- [Compatibility](#compatibility)
- [Development](#development)
- [Testing](#testing)
- [Example](#example)
- [Disclaimer](#disclaimer)
## Compatibility
The following table lists the compatible versions of fosite-storage-mongo with
fosite. If you are currently using this in production, it would be awesome to
know what versions you are successfully paired with.
| storage version | minimum fosite version | maximum fosite version |
|----------------:|-----------------------:|-----------------------:|
| `v0.18.X` | `v0.27.X` | `v0.30.X` |
| `v0.17.X` | `v0.26.X` | `v0.26.X` |
| `v0.16.X` | `v0.25.X` | `v0.25.X` |
| `v0.15.X` | `v0.23.X` | `v0.24.X` |
| `v0.14.X` | `v0.22.X` | `v0.22.X` |
| `v0.13.X` | `v0.20.X` | `v0.21.X` |
| `v0.12.X` | `v0.11.0` | `v0.16.X` |
| `v0.11.X` | `v0.11.0` | `v0.16.X` |
## Development
To start hacking:
* Install [dep][dep] - A golang package manager
* Run `dep ensure`
* `go build` successfully!
### Testing
Since Go 1.9, we use `go test ./...` to discover our heinous crimes against
coding.
## Example
Following the [fosite-example/authorizationserver][fosite-example-server]
example, we can extend this to add support for Mongo storage via the compose
configuration.
```go
package authorizationserver
import (
"crypto/rand"
"crypto/rsa"
"net/http"
"time"
"github.com/matthewhartstonge/storage"
"github.com/ory/fosite/compose"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
)
func RegisterHandlers() {
// Set up oauth2 endpoints.
// You could also use gorilla/mux or any other router.
http.HandleFunc("/oauth2/auth", authEndpoint)
http.HandleFunc("/oauth2/token", tokenEndpoint)
// revoke tokens
http.HandleFunc("/oauth2/revoke", revokeEndpoint)
http.HandleFunc("/oauth2/introspect", introspectionEndpoint)
}
// NewExampleMongoStore allows us to create an example Mongo Datastore and
// panics if you don't have an unauthenticated mongo database that can be found
// at `localhost:27017`. NewExampleMongoStore has one Client and one User.
// Check out storage.NewExampleMongoStore() for the implementation/specific
// client/user details.
var store = storage.NewExampleMongoStore()
var config = new(compose.Config)
// Because we are using oauth2 and open connect id, we use this little helper
// to combine the two in one variable.
var strat = compose.CommonStrategy{
// alternatively you could use:
// OAuth2Strategy: compose.NewOAuth2JWTStrategy(mustRSAKey())
CoreStrategy: compose.NewOAuth2HMACStrategy(config, []byte("some-super-cool-secret-that-nobody-knows")),
// open id connect strategy
OpenIDConnectTokenStrategy: compose.NewOpenIDConnectStrategy(mustRSAKey()),
}
var oauth2 = compose.Compose(
config,
store,
strat,
// enabled handlers
compose.OAuth2AuthorizeExplicitFactory,
compose.OAuth2AuthorizeImplicitFactory,
compose.OAuth2ClientCredentialsGrantFactory,
compose.OAuth2RefreshTokenGrantFactory,
compose.OAuth2ResourceOwnerPasswordCredentialsFactory,
compose.OAuth2TokenRevocationFactory,
compose.OAuth2TokenIntrospectionFactory,
// Be aware that open id connect factories need to be added after oauth2
// factories to work properly.
compose.OpenIDConnectExplicitFactory,
compose.OpenIDConnectImplicitFactory,
compose.OpenIDConnectHybridFactory,
compose.OpenIDConnectRefreshFactory,
)
// A session is passed from the `/auth` to the `/token` endpoint. You probably
// want to store data like: "Who made the request", "What organization does
// that person belong to" and so on.
// For our use case, the session will meet the requirements imposed by JWT
// access tokens, HMAC access tokens and OpenID Connect ID Tokens plus a custom
// field.
// newSession is a helper function for creating a new session. This may look
// like a lot of code but since we are setting up multiple strategies it is a
// bit longer.
//
// Usually, you could do:
// session = new(fosite.DefaultSession)
//
func newSession(user string) *openid.DefaultSession {
return &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Issuer: "https://fosite.my-application.com",
Subject: user,
Audience: []string{"https://my-client.my-application.com"},
ExpiresAt: time.Now().Add(time.Hour * 6),
IssuedAt: time.Now(),
RequestedAt: time.Now(),
AuthTime: time.Now(),
},
Headers: &jwt.Headers{
Extra: make(map[string]interface{}),
},
}
}
func mustRSAKey() *rsa.PrivateKey {
key, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
panic(err)
}
return key
}
```
## Disclaimer
* Currently, OIDC clients are not supported.
* We are currently using this project in house with Storage `v0.18.5` and Fosite
`v0.30.x` with good success.
* My aim is to keep storage to date with Fosite releases, as always though, my
time is limited due to my human frame.
* If you are able to provide help in keeping storage up to date, feel free to
raise a github issue and discuss where you are able/willing to help. I'm
always happy to review PRs and merge code in :ok_hand:
* We haven't tested implementation with Hydra at all but theoretically this
should be compatible as Hydra uses Fosite to store it's data under the hood.
## Licensing
storage is under the Apache 2.0 License.
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fmatthewhartstonge%2Fstorage?ref=badge_large)
[//]: #
[mgo]: <https://github.com/globalsign/mgo>
[dep]: <https://github.com/golang/dep>
[fosite]: <https://github.com/ory/fosite>
[hydra]: <https://github.com/ory/hydra>
[fosite-example-server]: <https://github.com/ory/fosite-example/blob/master/authorizationserver/oauth2.go>
<file_sep>/mongo/cache_manager_internal_test.go
package mongo
import (
// Standard Library Imports
"testing"
// Internal Imports
"github.com/matthewhartstonge/storage"
)
func TestCacheMongoManager_ImplementsStorageConfigurer(t *testing.T) {
c := &CacheManager{}
var i interface{} = c
if _, ok := i.(storage.Configurer); !ok {
t.Error("CacheManager does not implement interface storage.Configurer")
}
}
func TestCacheMongoManager_ImplementsStorageCacheStorer(t *testing.T) {
c := &CacheManager{}
var i interface{} = c
if _, ok := i.(storage.CacheStorer); !ok {
t.Error("CacheManager does not implement interface storage.CacheStorer")
}
}
func TestCacheMongoManager_ImplementsStorageCacheManager(t *testing.T) {
c := &CacheManager{}
var i interface{} = c
if _, ok := i.(storage.CacheManager); !ok {
t.Error("CacheManager does not implement interface storage.CacheManager")
}
}
<file_sep>/go.mod
module github.com/matthewhartstonge/storage
go 1.13
require (
github.com/globalsign/mgo v0.0.0-20180615134936-113d3961e731
github.com/kr/pretty v0.1.0 // indirect
github.com/onsi/ginkgo v1.10.1 // indirect
github.com/onsi/gomega v1.7.0 // indirect
github.com/opentracing/opentracing-go v1.1.0
github.com/ory/fosite v0.30.1
github.com/pborman/uuid v1.2.0
github.com/pkg/errors v0.8.0
github.com/sirupsen/logrus v1.0.5
github.com/stretchr/testify v1.2.2
gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect
)
<file_sep>/mongo/mongo_test.go
package mongo_test
import (
// Standard Library Imports
"context"
"fmt"
"os"
"testing"
// External Imports
"github.com/globalsign/mgo"
// Public Imports
"github.com/matthewhartstonge/storage/mongo"
)
func TestMain(m *testing.M) {
// If needed, enable logging when debugging for tests
//mongo.SetLogger(logrus.New())
//mongo.SetDebug(true)
exitCode := m.Run()
os.Exit(exitCode)
}
func AssertError(t *testing.T, got interface{}, want interface{}, msg string) {
t.Errorf(fmt.Sprintf("Error: %s\n got: %#+v\n want: %#+v", msg, got, want))
}
func AssertFatal(t *testing.T, got interface{}, want interface{}, msg string) {
t.Fatalf(fmt.Sprintf("Fatal: %s\n got: %#+v\n want: %#+v", msg, got, want))
}
func setup(t *testing.T) (*mongo.Store, context.Context, func()) {
// Build our default mongo storage layer
store, err := mongo.NewDefaultStore()
if err != nil {
AssertFatal(t, err, nil, "mongo connection error")
}
mgo.SetStats(true)
// Build a context with a mongo session ready to use for testing
ctx := context.Background()
mgoSession := store.NewSession()
ctx = mongo.MgoSessionToContext(ctx, mgoSession)
return store, ctx, func() {
// Test for leaky sockets
stats := mgo.GetStats()
if stats.SocketsAlive > 0 {
AssertError(t, stats.SocketsAlive, 0, "sockets are being leaked")
}
// Close the inner (test) session.
mgoSession.Close()
// Close the database session.
err := store.DB.DropDatabase()
if err != nil {
t.Errorf("error dropping database on cleanup: %s", err)
}
store.Close()
}
}
<file_sep>/mongo/cache_manager.go
package mongo
import (
// Standard Library Imports
"context"
"time"
// External Imports
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/ory/fosite"
"github.com/sirupsen/logrus"
// Internal Imports
"github.com/matthewhartstonge/storage"
)
// CacheManager provides a cache implementation in MongoDB for auth
// sessions.
type CacheManager struct {
DB *mgo.Database
}
// Configure sets up the Mongo collection for cache resources.
func (c *CacheManager) Configure(ctx context.Context) error {
if err := c.configureAccessTokensCollection(ctx); err != nil {
return err
}
return c.configureRefreshTokensCollection(ctx)
}
// configureAccessTokensCollection sets indices for the Access Token Collection.
func (c *CacheManager) configureAccessTokensCollection(ctx context.Context) error {
log := logger.WithFields(logrus.Fields{
"package": "datastore",
"driver": "mongo",
"collection": storage.EntityCacheAccessTokens,
"method": "Configure",
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = c.DB.Session.Copy()
defer mgoSession.Close()
}
collection := c.DB.C(storage.EntityCacheAccessTokens).With(mgoSession)
// Ensure index on request id
index := mgo.Index{
Name: IdxCacheRequestID,
Key: []string{"id"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err := collection.EnsureIndex(index)
if err != nil {
log.WithError(err).Error(logError)
return err
}
// Ensure index on request signature
index = mgo.Index{
Name: IdxCacheRequestSignature,
Key: []string{"signature"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err = collection.EnsureIndex(index)
if err != nil {
log.WithError(err).Error(logError)
return err
}
return nil
}
// configureRefreshTokensCollection sets indices for the Refresh Token
// Collection.
func (c *CacheManager) configureRefreshTokensCollection(ctx context.Context) error {
log := logger.WithFields(logrus.Fields{
"package": "datastore",
"driver": "mongo",
"collection": storage.EntityCacheRefreshTokens,
"method": "Configure",
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = c.DB.Session.Copy()
defer mgoSession.Close()
}
collection := c.DB.C(storage.EntityCacheRefreshTokens).With(mgoSession)
// Ensure index on request id
index := mgo.Index{
Name: IdxCacheRequestID,
Key: []string{"id"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err := collection.EnsureIndex(index)
if err != nil {
log.WithError(err).Error(logError)
return err
}
// Ensure index on request signature
index = mgo.Index{
Name: IdxCacheRequestSignature,
Key: []string{"signature"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err = collection.EnsureIndex(index)
if err != nil {
log.WithError(err).Error(logError)
return err
}
return nil
}
// getConcrete returns a map of request id to token signature.
func (c *CacheManager) getConcrete(ctx context.Context, entityName, key string) (result storage.SessionCache, err error) {
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": entityName,
"method": "getConcrete",
"key": key,
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = c.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Build Query
query := bson.M{
"id": key,
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "CacheManager",
Method: "getConcrete",
Query: query,
})
defer span.Finish()
var sessionCache = storage.SessionCache{}
collection := c.DB.C(entityName).With(mgoSession)
if err := collection.Find(query).One(&sessionCache); err != nil {
if err == mgo.ErrNotFound {
log.WithError(err).Debug(logNotFound)
return result, fosite.ErrNotFound
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogErr(span, err)
return result, err
}
return sessionCache, nil
}
// Create creates a new Cache resource and returns the newly created Cache
// resource.
func (c *CacheManager) Create(ctx context.Context, entityName string, cacheObject storage.SessionCache) (result storage.SessionCache, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": entityName,
"method": "Create",
"key": cacheObject.Key(),
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = c.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
if cacheObject.CreateTime == 0 {
cacheObject.CreateTime = time.Now().Unix()
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "CacheManager",
Method: "Create",
})
defer span.Finish()
// Create resource
collection := c.DB.C(entityName).With(mgoSession)
err = collection.Insert(cacheObject)
if err != nil {
if mgo.IsDup(err) {
// Log to StdOut
log.WithError(err).Debug(logConflict)
// Log to OpenTracing
otLogErr(span, err)
return result, storage.ErrResourceExists
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogQuery(span, cacheObject)
otLogErr(span, err)
return result, err
}
return cacheObject, nil
}
// Get returns the specified Cache resource.
func (c *CacheManager) Get(ctx context.Context, entityName string, key string) (result storage.SessionCache, err error) {
return c.getConcrete(ctx, entityName, key)
}
// Update updates the Cache resource and attributes and returns the updated
// Cache resource.
func (c *CacheManager) Update(ctx context.Context, entityName string, updatedCacheObject storage.SessionCache) (result storage.SessionCache, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": entityName,
"method": "Update",
"key": updatedCacheObject.Key(),
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = c.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Update modified time
updatedCacheObject.UpdateTime = time.Now().Unix()
// Build Query
selector := bson.M{
"id": updatedCacheObject.ID,
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "CacheManager",
Method: "Update",
Selector: selector,
})
defer span.Finish()
collection := c.DB.C(entityName).With(mgoSession)
if err := collection.Update(selector, updatedCacheObject); err != nil {
if err == mgo.ErrNotFound {
// Log to StdOut
log.WithError(err).Debug(logNotFound)
// Log to OpenTracing
otLogErr(span, err)
return result, fosite.ErrNotFound
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogQuery(span, updatedCacheObject)
otLogErr(span, err)
return result, err
}
return updatedCacheObject, nil
}
// Delete deletes the specified Cache resource.
func (c *CacheManager) Delete(ctx context.Context, entityName string, key string) error {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": entityName,
"method": "Delete",
"key": key,
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = c.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Build Query
query := bson.M{
"id": key,
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "CacheManager",
Method: "Delete",
Query: query,
})
defer span.Finish()
collection := c.DB.C(entityName).With(mgoSession)
if err := collection.Remove(query); err != nil {
if err == mgo.ErrNotFound {
// Log to StdOut
log.WithError(err).Debug(logNotFound)
// Log to OpenTracing
otLogErr(span, err)
return fosite.ErrNotFound
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogErr(span, err)
return err
}
return nil
}
// DeleteByValue deletes a Cache resource by matching on value.
func (c *CacheManager) DeleteByValue(ctx context.Context, entityName string, value string) error {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": entityName,
"method": "DeleteByValue",
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = c.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Build Query
query := bson.M{
"signature": value,
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "CacheManager",
Method: "DeleteByValue",
Query: query,
})
defer span.Finish()
collection := c.DB.C(entityName).With(mgoSession)
if err := collection.Remove(query); err != nil {
if err == mgo.ErrNotFound {
// Log to StdOut
log.WithError(err).Debug(logNotFound)
// Log to OpenTracing
otLogErr(span, err)
return fosite.ErrNotFound
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogErr(span, err)
return err
}
return nil
}
<file_sep>/user_test.go
package storage
import (
"testing"
"github.com/stretchr/testify/assert"
)
func expectedUser() User {
return User{
ID: "cc935033-d1b0-4bd8-b209-e6fbffe6b624",
AllowedTenantAccess: []string{
"29c78d37-a555-4d90-a038-bdb67a82b461",
"5253ee1a-aaac-49b1-ab7c-85b6d0571366",
},
AllowedPersonAccess: []string{
"<PASSWORD>-a6b0-442e-aab0-ad<PASSWORD>",
"794a55bd-69d4-4668-b319-62bfa0cd59ac",
},
Username: "<EMAIL>",
Password: "<PASSWORD>",
Scopes: []string{
"cats:read",
"cats:delete",
},
FirstName: "Fluffy",
LastName: "McKittison",
ProfileURI: "",
}
}
func TestUser_EnableScopeAccess_None(t *testing.T) {
u := expectedUser()
expectedScopes := []string{
"cats:read",
"cats:delete",
}
u.EnableScopeAccess("cats:read")
assert.EqualValues(t, expectedScopes, u.Scopes)
u.EnableScopeAccess("cats:delete")
assert.EqualValues(t, expectedScopes, u.Scopes)
}
func TestUser_EnableScopeAccess_One(t *testing.T) {
u := expectedUser()
expectedScopes := []string{
"cats:read",
"cats:delete",
"cats:hug",
}
u.EnableScopeAccess("cats:hug")
assert.EqualValues(t, expectedScopes, u.Scopes)
u.EnableScopeAccess("cats:hug")
assert.EqualValues(t, expectedScopes, u.Scopes)
u.EnableScopeAccess("cats:read")
assert.EqualValues(t, expectedScopes, u.Scopes)
}
func TestUser_EnableScopeAccess_Many(t *testing.T) {
u := expectedUser()
expectedScopes := []string{
"cats:read",
"cats:delete",
"cats:hug",
"cats:purr",
"cats:meow",
}
u.EnableScopeAccess("cats:hug", "cats:purr", "cats:meow")
assert.EqualValues(t, expectedScopes, u.Scopes)
u.EnableScopeAccess("cats:hug", "cats:purr", "cats:meow")
assert.EqualValues(t, expectedScopes, u.Scopes)
}
func TestUser_DisableScopeAccess_None(t *testing.T) {
u := expectedUser()
expectedScopes := []string{
"cats:read",
"cats:delete",
}
u.DisableScopeAccess("cats:hug")
assert.EqualValues(t, expectedScopes, u.Scopes)
}
func TestUser_DisableScopeAccess_One(t *testing.T) {
u := expectedUser()
expectedScopes := []string{
"cats:delete",
}
u.DisableScopeAccess("cats:read")
assert.EqualValues(t, expectedScopes, u.Scopes)
u.DisableScopeAccess("cats:read")
assert.EqualValues(t, expectedScopes, u.Scopes)
u.DisableScopeAccess("cats:delete")
assert.EqualValues(t, expectedScopes[:len(expectedScopes)-1], u.Scopes)
u.DisableScopeAccess("cats:read")
assert.EqualValues(t, expectedScopes[:len(expectedScopes)-1], u.Scopes)
u.DisableScopeAccess("cats:mug")
assert.EqualValues(t, expectedScopes[:len(expectedScopes)-1], u.Scopes)
}
func TestUser_DisableScopeAccess_Many(t *testing.T) {
u := expectedUser()
expectedScopes := []string{
"cats:read",
}
u.Scopes = []string{
"cats:read",
"cats:delete",
"cats:hug",
"cats:purr",
"cats:meow",
}
u.DisableScopeAccess("cats:hug", "cats:purr", "cats:delete", "cats:meow")
assert.EqualValues(t, expectedScopes, u.Scopes)
u.DisableScopeAccess("cats:hug", "cats:purr", "cats:delete", "cats:meow")
assert.EqualValues(t, expectedScopes, u.Scopes)
}
func TestUser_EnableTenantAccess_None(t *testing.T) {
u := expectedUser()
expectedTenants := []string{
"29c78d37-a555-4d90-a038-bdb67a82b461",
"5253ee1a-aaac-49b1-ab7c-85b6d0571366",
}
u.EnableTenantAccess("29c78d37-a555-4d90-a038-bdb67a82b461")
assert.EqualValues(t, expectedTenants, u.AllowedTenantAccess)
u.EnableTenantAccess("5253ee1a-aaac-49b1-ab7c-85b6d0571366")
assert.EqualValues(t, expectedTenants, u.AllowedTenantAccess)
}
func TestUser_EnableTenantAccess_One(t *testing.T) {
u := expectedUser()
expectedTenantIDs := []string{
"29c78d37-a555-4d90-a038-bdb67a82b461",
"5253ee1a-aaac-49b1-ab7c-85b6d0571366",
"bc7f5c05-3698-4855-8244-b0aac80a3ec1",
}
u.EnableTenantAccess("bc7f5c05-3698-4855-8244-b0aac80a3ec1")
assert.EqualValues(t, expectedTenantIDs, u.AllowedTenantAccess)
u.EnableTenantAccess("bc7f5c05-3698-4855-8244-b0aac80a3ec1")
assert.EqualValues(t, expectedTenantIDs, u.AllowedTenantAccess)
u.EnableTenantAccess("5253ee1a-aaac-49b1-ab7c-85b6d0571366")
assert.EqualValues(t, expectedTenantIDs, u.AllowedTenantAccess)
}
func TestUser_EnableTenantAccess_Many(t *testing.T) {
u := expectedUser()
expectedTenantIDs := []string{
"29c78d37-a555-4d90-a038-bdb67a82b461",
"5253ee1a-aaac-49b1-ab7c-85b6d0571366",
"bc7f5c05-3698-4855-8244-b0aac80a3ec1",
"b1f8c420-81a0-4980-9bb0-432b2860fd05",
"c3414224-c98b-42f7-a017-ee0549cca762",
}
u.EnableTenantAccess(
"bc7f5c05-3698-4855-8244-b0aac80a3ec1",
"b1f8c420-81a0-4980-9bb0-432b2860fd05",
"c3414224-c98b-42f7-a017-ee0549cca762",
)
assert.EqualValues(t, expectedTenantIDs, u.AllowedTenantAccess)
u.EnableTenantAccess(
"bc7f5c05-3698-4855-8244-b0aac80a3ec1",
"b1f8c420-81a0-4980-9bb0-432b2860fd05",
"c3414224-c98b-42f7-a017-ee0549cca762",
)
assert.EqualValues(t, expectedTenantIDs, u.AllowedTenantAccess)
}
func TestUser_DisableTenantAccess_None(t *testing.T) {
u := expectedUser()
expectedTenantIDs := []string{
"29c78d37-a555-4d90-a038-bdb67a82b461",
"5253ee1a-aaac-49b1-ab7c-85b6d0571366",
}
u.DisableTenantAccess("bc7f5c05-3698-4855-8244-b0aac80a3ec1")
assert.EqualValues(t, expectedTenantIDs, u.AllowedTenantAccess)
}
func TestUser_DisableTenantAccess_One(t *testing.T) {
u := expectedUser()
expectedTenants := []string{
"29c78d37-a555-4d90-a038-bdb67a82b461",
}
u.DisableTenantAccess("5253ee1a-aaac-49b1-ab7c-85b6d0571366")
assert.EqualValues(t, expectedTenants, u.AllowedTenantAccess)
u.DisableTenantAccess("5253ee1a-aaac-49b1-ab7c-85b6d0571366")
assert.EqualValues(t, expectedTenants, u.AllowedTenantAccess)
u.DisableTenantAccess("29c78d37-a555-4d90-a038-bdb67a82b461")
assert.EqualValues(t, expectedTenants[:len(expectedTenants)-1], u.AllowedTenantAccess)
u.DisableTenantAccess("b1f8c420-81a0-4980-9bb0-432b2860fd05")
assert.EqualValues(t, expectedTenants[:len(expectedTenants)-1], u.AllowedTenantAccess)
u.DisableTenantAccess("c3414224-c98b-42f7-a017-ee0549cca762")
assert.EqualValues(t, expectedTenants[:len(expectedTenants)-1], u.AllowedTenantAccess)
}
func TestUser_DisableTenantAccess_Many(t *testing.T) {
u := expectedUser()
expectedTenants := []string{
"29c78d37-a555-4d90-a038-bdb67a82b461",
"5253ee1a-aaac-49b1-ab7c-85b6d0571366",
}
u.AllowedTenantAccess = []string{
"29c78d37-a555-4d90-a038-bdb67a82b461",
"5253ee1a-aaac-49b1-ab7c-85b6d0571366",
"bc7f5c05-3698-4855-8244-b0aac80a3ec1",
"b1f8c420-81a0-4980-9bb0-432b2860fd05",
"c3414224-c98b-42f7-a017-ee0549cca762",
}
u.DisableTenantAccess(
"bc7f5c05-3698-4855-8244-b0aac80a3ec1",
"b1f8c420-81a0-4980-9bb0-432b2860fd05",
"c3414224-c98b-42f7-a017-ee0549cca762",
)
assert.EqualValues(t, expectedTenants, u.AllowedTenantAccess)
u.DisableTenantAccess(
"bc7f5c05-3698-4855-8244-b0aac80a3ec1",
"b1f8c420-81a0-4980-9bb0-432b2860fd05",
"c3414224-c98b-42f7-a017-ee0549cca762",
)
assert.EqualValues(t, expectedTenants, u.AllowedTenantAccess)
}
func TestUser_Equal(t *testing.T) {
tests := []struct {
description string
x User
y User
expected bool
}{
{
description: "empty should be equal",
x: User{},
y: User{},
expected: true,
},
{
description: "non-empty should not be equal",
x: User{
ID: "lol",
},
y: User{},
expected: false,
},
{
description: "ID should be equal",
x: User{
ID: "1",
},
y: User{
ID: "1",
},
expected: true,
},
{
description: "ID should not be equal",
x: User{
ID: "1",
},
y: User{
ID: "2",
},
expected: false,
},
{
description: "Tenant IDs should be equal",
x: User{
AllowedTenantAccess: []string{"ten", "ants"},
},
y: User{
AllowedTenantAccess: []string{"ten", "ants"},
},
expected: true,
},
{
description: "Tenant IDs should not be equal",
x: User{
AllowedTenantAccess: []string{"ten", "ants"},
},
y: User{
AllowedTenantAccess: []string{"nine", "ants"},
},
expected: false,
},
{
description: "username should be equal",
x: User{
Username: "timmy",
},
y: User{
Username: "timmy",
},
expected: true,
},
{
description: "username should not be equal",
x: User{
Username: "timmy",
},
y: User{
Username: "jimmy",
},
expected: false,
},
{
description: "password should be equal",
x: User{
Password: "<PASSWORD>",
},
y: User{
Password: "<PASSWORD>",
},
expected: true,
},
{
description: "password should not be equal",
x: User{
Password: "<PASSWORD>",
},
y: User{
Password: "<PASSWORD>",
},
expected: false,
},
{
description: "scopes should be equal",
x: User{
Scopes: []string{"x2", "10x", "1x red-dot"},
},
y: User{
Scopes: []string{"x2", "10x", "1x red-dot"},
},
expected: true,
},
{
description: "scopes length should not be equal",
x: User{
Scopes: []string{"1x red-dot"},
},
y: User{
Scopes: []string{"1x red-dot", "x2", "10x"},
},
expected: false,
},
{
description: "scopes should not be equal",
x: User{
Scopes: []string{"x2", "10x", "1x red-dot"},
},
y: User{
Scopes: []string{"10x", "1x red-dot", "x2"},
},
expected: false,
},
{
description: "firstname should be equal",
x: User{
FirstName: "<NAME>",
},
y: User{
FirstName: "<NAME>",
},
expected: true,
},
{
description: "firstname should not be equal",
x: User{
FirstName: "<NAME>",
},
y: User{
FirstName: "<NAME>",
},
expected: false,
},
{
description: "lastname should be equal",
x: User{
LastName: "swagger",
},
y: User{
LastName: "swagger",
},
expected: true,
},
{
description: "lastname should not be equal",
x: User{
LastName: "swagger",
},
y: User{
LastName: "swaggerz",
},
expected: false,
},
{
description: "profile uri should be equal",
x: User{
ProfileURI: "https://cats.example.com/cat1.jpg",
},
y: User{
ProfileURI: "https://cats.example.com/cat1.jpg",
},
expected: true,
},
{
description: "profile uri should not be equal",
x: User{
ProfileURI: "https://cats.example.com/cat1.jpg",
},
y: User{
ProfileURI: "https://dogs.example.com/dog1.jpg",
},
expected: false,
},
{
description: "disabled should be equal",
x: User{
Disabled: false,
},
y: User{
Disabled: false,
},
expected: true,
},
{
description: "disabled should not be equal",
x: User{
Disabled: false,
},
y: User{
Disabled: true,
},
expected: false,
},
{
description: "user should be equal",
x: User{
ID: "1",
AllowedTenantAccess: []string{"apple", "lettuce"},
Username: "<EMAIL>",
Password: "<PASSWORD>",
Scopes: []string{"10x", "2x"},
FirstName: "<NAME>",
LastName: "Swagger",
ProfileURI: "https://marines.example.com/boblee.png",
Disabled: false,
},
y: User{
ID: "1",
AllowedTenantAccess: []string{"apple", "lettuce"},
Username: "<EMAIL>",
Password: "<PASSWORD>",
Scopes: []string{"10x", "2x"},
FirstName: "<NAME>",
LastName: "Swagger",
ProfileURI: "https://marines.example.com/boblee.png",
Disabled: false,
},
expected: true,
},
{
description: "user should not be equal",
x: User{
ID: "1",
AllowedTenantAccess: []string{"apple", "lettuce"},
Username: "<EMAIL>",
Password: "<PASSWORD>",
Scopes: []string{"10x", "2x"},
FirstName: "<NAME>",
LastName: "Swagger",
ProfileURI: "https://marines.example.com/boblee.png",
Disabled: false,
},
y: User{
ID: "1",
AllowedTenantAccess: []string{"apple", "lettuce"},
Username: "<EMAIL>",
Password: "<PASSWORD>",
Scopes: []string{"10x"},
FirstName: "<NAME>",
LastName: "Swagger",
ProfileURI: "https://marines.example.com/boblee.png",
Disabled: false,
},
expected: false,
},
}
for _, testcase := range tests {
assert.Equal(t, testcase.expected, testcase.x.Equal(testcase.y), testcase.description)
}
}
func TestUser_IsEmpty(t *testing.T) {
notEmptyUser := User{
ID: "lol-not-empty",
}
assert.Equal(t, notEmptyUser.IsEmpty(), false)
emptyUser := User{}
assert.Equal(t, emptyUser.IsEmpty(), true)
}
<file_sep>/mongo/logging.go
package mongo
import (
// External Imports
"github.com/globalsign/mgo"
"github.com/sirupsen/logrus"
)
const (
logError = "datastore error"
logConflict = "resource conflict"
logNotFound = "resource not found"
logNotHashable = "unable to hash secret"
)
// logger provides the package scoped logger implementation.
var logger storeLogger
// storeLogger provides a wrapper around the logrus logger in order to implement
// required database library logging interfaces.
type storeLogger struct {
*logrus.Logger
}
// Output implements mgo.logLogger
func (l *storeLogger) Output(calldepth int, s string) error {
meta := logrus.Fields{
"driver": "mgo",
"calldepth": calldepth,
}
l.WithFields(meta).Debug(s)
return nil
}
// SetDebug turns on debug level logging, including debug at the driver level.
// If false, disables driver level logging and sets logging to info level.
func SetDebug(isDebug bool) {
if isDebug {
logger.SetLevel(logrus.DebugLevel)
// Turn on mgo debugging
mgo.SetDebug(isDebug)
mgo.SetLogger(&logger)
} else {
logger.SetLevel(logrus.InfoLevel)
// Turn off mgo debugging
mgo.SetDebug(isDebug)
mgo.SetLogger(nil)
}
}
// SetLogger enables binding in your own customised logrus logger.
func SetLogger(log *logrus.Logger) {
logger = storeLogger{
Logger: log,
}
}
<file_sep>/mongo/mongo.go
package mongo
import (
// Standard Library Imports
"context"
"crypto/tls"
"fmt"
"net"
"time"
// External Imports
"github.com/globalsign/mgo"
"github.com/ory/fosite"
"github.com/sirupsen/logrus"
// Local Imports
"github.com/matthewhartstonge/storage"
)
func init() {
// Bind a logger, but only to panic level. Leave it to the user to decide
// whether they want datastore logging or not.
SetLogger(logrus.New())
logger.Level = logrus.PanicLevel
}
const (
defaultHost = "localhost"
defaultPort = 27017
defaultDatabaseName = "oauth2"
)
// Store provides a MongoDB storage driver compatible with fosite's required
// storage interfaces.
type Store struct {
// Internals
DB *mgo.Database
// Public API
Hasher fosite.Hasher
storage.Store
}
// NewSession returns a mongo session.
// Note: The session requires closing manually so no memory leaks occur.
// This is best achieved by calling `defer session.Close()` straight after
// obtaining the returned session object.
func (m *Store) NewSession() (session *mgo.Session) {
return m.DB.Session.Copy()
}
// Close terminates the mongo session.
func (m *Store) Close() {
m.DB.Session.Close()
}
// Config defines the configuration parameters which are used by GetMongoSession.
type Config struct {
Hostnames []string `default:"localhost" envconfig:"CONNECTIONS_MONGO_HOSTNAMES"`
Port uint16 `default:"27017" envconfig:"CONNECTIONS_MONGO_PORT"`
SSL bool `default:"false" envconfig:"CONNECTIONS_MONGO_SSL"`
AuthDB string `default:"admin" envconfig:"CONNECTIONS_MONGO_AUTHDB"`
Username string `default:"" envconfig:"CONNECTIONS_MONGO_USERNAME"`
Password string `default:"" envconfig:"CONNECTIONS_MONGO_PASSWORD"`
DatabaseName string `default:"" envconfig:"CONNECTIONS_MONGO_NAME"`
Replset string `default:"" envconfig:"CONNECTIONS_MONGO_REPLSET"`
Timeout uint `default:"10" envconfig:"CONNECTIONS_MONGO_TIMEOUT"`
TLSConfig *tls.Config `ignored:"true"`
}
// DefaultConfig returns a configuration for a locally hosted, unauthenticated mongo
func DefaultConfig() *Config {
return &Config{
Hostnames: []string{defaultHost},
Port: defaultPort,
DatabaseName: defaultDatabaseName,
}
}
// ConnectionInfo configures options for establishing a session with a MongoDB cluster.
func ConnectionInfo(cfg *Config) *mgo.DialInfo {
if len(cfg.Hostnames) == 0 {
cfg.Hostnames = []string{defaultHost}
}
if cfg.DatabaseName == "" {
cfg.DatabaseName = defaultDatabaseName
}
if cfg.Port > 0 {
for i := range cfg.Hostnames {
cfg.Hostnames[i] = fmt.Sprintf("%s:%d", cfg.Hostnames[i], cfg.Port)
}
}
if cfg.Timeout == 0 {
cfg.Timeout = 10
}
dialInfo := &mgo.DialInfo{
Addrs: cfg.Hostnames,
Database: cfg.DatabaseName,
Username: cfg.Username,
Password: <PASSWORD>,
Source: cfg.AuthDB,
ReplicaSetName: cfg.Replset,
Timeout: time.Second * time.Duration(cfg.Timeout),
}
if cfg.SSL {
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
return tls.Dial("tcp", addr.String(), cfg.TLSConfig)
}
}
return dialInfo
}
// Connect returns a connection to mongo.
func Connect(cfg *Config) (*mgo.Database, error) {
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"method": "Connect",
})
dialInfo := ConnectionInfo(cfg)
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
log.WithError(err).Error("Unable to connect to mongo! Have you configured your connection properly?")
return nil, err
}
// Monotonic consistency will start reading from a slave if possible
session.SetMode(mgo.Monotonic, true)
return session.DB(cfg.DatabaseName), nil
}
// New allows for custom mongo configuration and custom hashers.
func New(cfg *Config, hashee fosite.Hasher) (*Store, error) {
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"method": "NewFromConfig",
})
database, err := Connect(cfg)
if err != nil {
log.WithError(err).Error("Unable to connect to mongo! Are you sure mongo is running on localhost?")
return nil, err
}
if hashee == nil {
// Initialize default fosite Hasher.
hashee = &fosite.BCrypt{
WorkFactor: 10,
}
}
// Build up the mongo endpoints
mongoCache := &CacheManager{
DB: database,
}
mongoClients := &ClientManager{
DB: database,
Hasher: hashee,
}
mongoUsers := &UserManager{
DB: database,
Hasher: hashee,
}
mongoRequests := &RequestManager{
DB: database,
Cache: mongoCache,
Clients: mongoClients,
Users: mongoUsers,
}
// Init DB collections, indices e.t.c.
managers := []storage.Configurer{
mongoCache,
mongoClients,
mongoUsers,
mongoRequests,
}
// Use the main DB database to configure the mongo collections on first up.
mgoSession := database.Session.Copy()
defer mgoSession.Close()
ctx := MgoSessionToContext(context.Background(), mgoSession)
for _, manager := range managers {
err := manager.Configure(ctx)
if err != nil {
log.WithError(err).Error("Unable to configure mongo collections!")
return nil, err
}
}
return &Store{
DB: database,
Hasher: hashee,
Store: storage.Store{
CacheManager: mongoCache,
ClientManager: mongoClients,
RequestManager: mongoRequests,
UserManager: mongoUsers,
},
}, nil
}
// NewDefaultStore returns a Store configured with the default mongo
// configuration and default Hasher.
func NewDefaultStore() (*Store, error) {
cfg := DefaultConfig()
return New(cfg, nil)
}
<file_sep>/user.go
package storage
import (
// Standard Library Imports
"context"
"fmt"
// External Imports
"github.com/ory/fosite"
)
// User provides the specific types for storing, editing, deleting and
// retrieving a User record in mongo.
type User struct {
//// User Meta
// ID is the uniquely assigned uuid that references the user
ID string `bson:"id" json:"id" xml:"id"`
// createTime is when the resource was created in seconds from the epoch.
CreateTime int64 `bson:"createTime" json:"createTime" xml:"createTime"`
// updateTime is the last time the resource was modified in seconds from
// the epoch.
UpdateTime int64 `bson:"updateTime" json:"updateTime" xml:"updateTime"`
// AllowedTenantAccess contains the Tenant IDs that the user has been given
// rights to access.
// This helps in multi-tenanted situations where a user can be given
// explicit cross-tenant access.
AllowedTenantAccess []string `bson:"allowedTenantAccess" json:"allowedTenantAccess,omitempty" xml:"allowedTenantAccess,omitempty"`
// AllowedPersonAccess contains a list of Person IDs that the user is
// allowed access to.
// This helps in multi-tenanted situations where a user can be given
// explicit access to other people accounts, for example, parents to
// children records.
AllowedPersonAccess []string `bson:"allowedPersonAccess" json:"allowedPersonAccess,omitempty" xml:"allowedPersonAccess,omitempty"`
// Scopes contains the permissions that the user is entitled to request.
Scopes []string `bson:"scopes" json:"scopes" xml:"scopes"`
// PersonID is a uniquely assigned id that references a person within the
// system.
// This enables applications where an external person data store is present.
// This helps in multi-tenanted situations where the person is unique, but
// the underlying user accounts can exist per tenant.
PersonID string `bson:"personId" json:"personId" xml:"personId"`
// Disabled specifies whether the user has been disallowed from signing in
Disabled bool `bson:"disabled" json:"disabled" xml:"disabled"`
//// User Content
// Username is used to authenticate a user
Username string `bson:"username" json:"username" xml:"username"`
// Password of the user - will be a hash based on your fosite selected
// hasher.
// If using this model directly in an API, be sure to clear the password
// out when marshaling to json/xml.
Password string `bson:"password,omitempty" json:"password,omitempty" xml:"password,omitempty"`
// FirstName stores the user's Last Name
FirstName string `bson:"firstName" json:"firstName" xml:"firstName"`
// LastName stores the user's Last Name
LastName string `bson:"lastName" json:"lastName" xml:"lastName"`
// ProfileURI is a pointer to where their profile picture lives
ProfileURI string `bson:"profileUri" json:"profileUri,omitempty" xml:"profileUri,omitempty"`
}
// FullName concatenates the User's First Name and Last Name for templating
// purposes
func (u User) FullName() (fn string) {
return fmt.Sprintf("%s %s", u.FirstName, u.LastName)
}
// SetPassword takes a cleartext secret, hashes it with a hasher and sets it as
// the user's password
func (u *User) SetPassword(cleartext string, hasher fosite.Hasher) (err error) {
h, err := hasher.Hash(context.TODO(), []byte(cleartext))
if err != nil {
return err
}
u.Password = string(h)
return nil
}
// GetHashedSecret returns the Users's Hashed Secret as a byte array
func (u *User) GetHashedSecret() []byte {
return []byte(u.Password)
}
// Authenticate compares a cleartext string against the user's
func (u User) Authenticate(cleartext string, hasher fosite.Hasher) error {
return hasher.Compare(context.TODO(), u.GetHashedSecret(), []byte(cleartext))
}
// EnableTenantAccess enables user access to one or many tenants.
func (u *User) EnableTenantAccess(tenantIDs ...string) {
for i := range tenantIDs {
found := false
for j := range u.AllowedTenantAccess {
if tenantIDs[i] == u.AllowedTenantAccess[j] {
found = true
break
}
}
if !found {
u.AllowedTenantAccess = append(u.AllowedTenantAccess, tenantIDs[i])
}
}
}
// DisableTenantAccess disables user access to one or many tenants.
func (u *User) DisableTenantAccess(tenantIDs ...string) {
for i := range tenantIDs {
for j := range u.AllowedTenantAccess {
if tenantIDs[i] == u.AllowedTenantAccess[j] {
copy(u.AllowedTenantAccess[j:], u.AllowedTenantAccess[j+1:])
u.AllowedTenantAccess[len(u.AllowedTenantAccess)-1] = ""
u.AllowedTenantAccess = u.AllowedTenantAccess[:len(u.AllowedTenantAccess)-1]
break
}
}
}
}
// EnablePeopleAccess enables user access to the provided people
func (u *User) EnablePeopleAccess(personIDs ...string) {
for i := range personIDs {
found := false
for j := range u.AllowedPersonAccess {
if personIDs[i] == u.AllowedPersonAccess[j] {
found = true
break
}
}
if !found {
u.AllowedPersonAccess = append(u.AllowedPersonAccess, personIDs[i])
}
}
}
// DisablePeopleAccess disables user access to the provided people.
func (u *User) DisablePeopleAccess(personIDs ...string) {
for i := range personIDs {
for j := range u.AllowedPersonAccess {
if personIDs[i] == u.AllowedPersonAccess[j] {
copy(u.AllowedPersonAccess[j:], u.AllowedPersonAccess[j+1:])
u.AllowedPersonAccess[len(u.AllowedPersonAccess)-1] = ""
u.AllowedPersonAccess = u.AllowedPersonAccess[:len(u.AllowedPersonAccess)-1]
break
}
}
}
}
// EnableScopeAccess enables user access to one or many scopes.
func (u *User) EnableScopeAccess(scopes ...string) {
for i := range scopes {
found := false
for j := range u.Scopes {
if scopes[i] == u.Scopes[j] {
found = true
break
}
}
if !found {
u.Scopes = append(u.Scopes, scopes[i])
}
}
}
// DisableScopeAccess disables user access to one or many scopes.
func (u *User) DisableScopeAccess(scopes ...string) {
for i := range scopes {
for j := range u.Scopes {
if scopes[i] == u.Scopes[j] {
copy(u.Scopes[j:], u.Scopes[j+1:])
u.Scopes[len(u.Scopes)-1] = ""
u.Scopes = u.Scopes[:len(u.Scopes)-1]
break
}
}
}
}
// Equal enables checking equality as having a byte array in a struct stops
// allowing direct equality checks.
func (u User) Equal(x User) bool {
if u.ID != x.ID {
return false
}
if u.CreateTime != x.CreateTime {
return false
}
if u.UpdateTime != x.UpdateTime {
return false
}
if !stringArrayEquals(u.AllowedTenantAccess, x.AllowedTenantAccess) {
return false
}
if !stringArrayEquals(u.AllowedPersonAccess, x.AllowedPersonAccess) {
return false
}
if !stringArrayEquals(u.Scopes, x.Scopes) {
return false
}
if u.PersonID != x.PersonID {
return false
}
if u.Disabled != x.Disabled {
return false
}
if u.Username != x.Username {
return false
}
if u.Password != x.Password {
return false
}
if u.FirstName != x.FirstName {
return false
}
if u.LastName != x.LastName {
return false
}
if u.ProfileURI != x.ProfileURI {
return false
}
return true
}
// IsEmpty returns true if the current user holds no data.
func (u User) IsEmpty() bool {
return u.Equal(User{})
}
<file_sep>/cache.go
package storage
// SessionCache allows storing a map between a session ID and a session signature
type SessionCache struct {
// ID contains the unique identifier of the request.
ID string `bson:"id" json:"id" xml:"id"`
// createTime is when the resource was created in seconds from the epoch.
CreateTime int64 `bson:"createTime" json:"createTime" xml:"createTime"`
// updateTime is the last time the resource was modified in seconds from
// the epoch.
UpdateTime int64 `bson:"updateTime" json:"updateTime" xml:"updateTime"`
// Signature contains the unique token signature.
Signature string `bson:"signature" json:"signature" xml:"signature"`
}
// Key returns the key of the cached session map
func (s SessionCache) Key() string {
return s.ID
}
// Value returns session data as a string
func (s SessionCache) Value() string {
return s.Signature
}
<file_sep>/mongo/mongo_meta.go
package mongo
import (
// Standard Library Imports
"context"
// External Imports
"github.com/globalsign/mgo"
)
const (
// IdxCacheRequestID provides a mongo index based on request id.
IdxCacheRequestID = "idxRequestId"
// IdxCacheRequestSignature provides a mongo index based on token
// signature.
IdxCacheRequestSignature = "idxSignature"
// IdxClientID provides a mongo index based on clientId
IdxClientID = "idxClientId"
// IdxUserID provides a mongo index based on userId
IdxUserID = "idxUserId"
// IdxUsername provides a mongo index based on username
IdxUsername = "idxUsername"
// IdxSessionID provides a mongo index based on Session
IdxSessionID = "idxSessionId"
// IdxSignatureID provides a mongo index based on Signature
IdxSignatureID = "idxSignatureId"
// IdxCompoundRequester provides a mongo compound index based on Client ID
// and User ID for when filtering request records.
IdxCompoundRequester = "idxCompoundRequester"
)
// ctxMgoKey is an unexported type for context keys defined for mgo in this
// package. This prevents collisions with keys defined in other packages.
type ctxMgoKey int
const (
// mgoSessionKey is the key for *mgo.Session values in Contexts. It is
// unexported; clients use datastore.MgoSessionToContext and
// datastore.ContextToMgoSession instead of using this key directly.
mgoSessionKey ctxMgoKey = iota
)
// MgoSessionToContext provides a way to push a Mgo datastore session into the
// current session, which can then be passed on to other routes or functions.
func MgoSessionToContext(ctx context.Context, session *mgo.Session) context.Context {
return context.WithValue(ctx, mgoSessionKey, session)
}
// ContextToMgoSession provides a way to obtain a mgo session, if contained
// within the presented context.
func ContextToMgoSession(ctx context.Context) (sess *mgo.Session, ok bool) {
sess, ok = ctx.Value(mgoSessionKey).(*mgo.Session)
return
}
<file_sep>/mongo/user_manager.go
package mongo
import (
// Standard Library Imports
"context"
"time"
// External Imports
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/ory/fosite"
"github.com/pborman/uuid"
"github.com/sirupsen/logrus"
// Internal Imports
"github.com/matthewhartstonge/storage"
)
// UserManager provides a mongo backed implementation for user resources.
//
// Implements:
// - storage.Configurer
// - storage.AuthUserMigrator
// - storage.UserStorer
// - storage.UserManager
type UserManager struct {
DB *mgo.Database
Hasher fosite.Hasher
}
// Configure implements storage.Configurer.
func (u *UserManager) Configure(ctx context.Context) error {
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "Configure",
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = u.DB.Session.Copy()
defer mgoSession.Close()
}
collection := u.DB.C(storage.EntityUsers).With(mgoSession)
// Ensure Indexes on collections
index := mgo.Index{
Name: IdxUserID,
Key: []string{"id"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err := collection.EnsureIndex(index)
if err != nil {
log.WithError(err).Error(logError)
return err
}
index = mgo.Index{
Name: IdxUsername,
Key: []string{"username"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err = collection.EnsureIndex(index)
if err != nil {
log.WithError(err).Error(logError)
return err
}
return nil
}
// getConcrete returns an OAuth 2.0 User resource.
func (u *UserManager) getConcrete(ctx context.Context, userID string) (result storage.User, err error) {
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "getConcrete",
"userID": userID,
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Build Query
query := bson.M{
"id": userID,
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "getConcrete",
Query: query,
})
defer span.Finish()
user := storage.User{}
collection := u.DB.C(storage.EntityUsers).With(mgoSession)
if err := collection.Find(query).One(&user); err != nil {
if err == mgo.ErrNotFound {
log.WithError(err).Debug(logNotFound)
return result, fosite.ErrNotFound
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogErr(span, err)
return result, err
}
return user, nil
}
// List returns a list of User resources that match the provided inputs.
func (u *UserManager) List(ctx context.Context, filter storage.ListUsersRequest) (results []storage.User, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "List",
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Build Query
query := bson.M{}
if filter.AllowedTenantAccess != "" {
query["allowedTenantAccess"] = filter.AllowedTenantAccess
}
if filter.AllowedPersonAccess != "" {
query["allowedPersonAccess"] = filter.AllowedPersonAccess
}
if filter.PersonID != "" {
query["personId"] = filter.PersonID
}
if filter.Username != "" {
query["username"] = filter.Username
}
if len(filter.ScopesIntersection) > 0 {
query["scopes"] = bson.M{"$all": filter.ScopesUnion}
}
if len(filter.ScopesUnion) > 0 {
query["scopes"] = bson.M{"$in": filter.ScopesUnion}
}
if filter.FirstName != "" {
query["firstName"] = filter.FirstName
}
if filter.LastName != "" {
query["lastName"] = filter.LastName
}
if filter.Disabled {
query["disabled"] = filter.Disabled
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "List",
Query: query,
})
defer span.Finish()
var users []storage.User
collection := u.DB.C(storage.EntityUsers).With(mgoSession)
err = collection.Find(query).All(&users)
if err != nil {
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogErr(span, err)
return results, err
}
return users, nil
}
// Create creates a new User resource and returns the newly created User
// resource.
func (u *UserManager) Create(ctx context.Context, user storage.User) (result storage.User, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "Create",
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Enable developers to provide their own IDs
if user.ID == "" {
user.ID = uuid.New()
}
if user.CreateTime == 0 {
user.CreateTime = time.Now().Unix()
}
// Hash incoming secret
hash, err := u.Hasher.Hash(ctx, []byte(user.Password))
if err != nil {
log.WithError(err).Error(logNotHashable)
return result, err
}
user.Password = string(hash)
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "Create",
})
defer span.Finish()
// Create resource
collection := u.DB.C(storage.EntityUsers).With(mgoSession)
err = collection.Insert(user)
if err != nil {
if mgo.IsDup(err) {
// Log to StdOut
log.WithError(err).Debug(logConflict)
// Log to OpenTracing
otLogErr(span, err)
return result, storage.ErrResourceExists
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
user.Password = "<PASSWORD>"
otLogQuery(span, user)
otLogErr(span, err)
return result, err
}
return user, nil
}
// Get returns the specified User resource.
func (u *UserManager) Get(ctx context.Context, userID string) (result storage.User, err error) {
return u.getConcrete(ctx, userID)
}
// GetByUsername returns a user resource if found by username.
func (u *UserManager) GetByUsername(ctx context.Context, username string) (result storage.User, err error) {
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "GetByUsername",
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Build Query
query := bson.M{
"username": username,
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "getConcrete",
Query: query,
})
defer span.Finish()
user := storage.User{}
collection := u.DB.C(storage.EntityUsers).With(mgoSession)
if err := collection.Find(query).One(&user); err != nil {
if err == mgo.ErrNotFound {
log.WithError(err).Debug(logNotFound)
return result, fosite.ErrNotFound
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogErr(span, err)
return result, err
}
return user, nil
}
// Update updates the User resource and attributes and returns the updated
// User resource.
func (u *UserManager) Update(ctx context.Context, userID string, updatedUser storage.User) (result storage.User, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "Update",
"id": userID,
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
currentResource, err := u.getConcrete(ctx, userID)
if err != nil {
if err == fosite.ErrNotFound {
log.Debug(logNotFound)
return result, err
}
log.WithError(err).Error(logError)
return result, err
}
// Deny updating the entity Id
updatedUser.ID = userID
// Update modified time
updatedUser.UpdateTime = time.Now().Unix()
if currentResource.Password == updatedUser.Password || updatedUser.Password == "" {
// If the password/hash is blank or hash matches, set using old hash.
updatedUser.Password = currentResource.<PASSWORD>
} else {
newHash, err := u.Hasher.Hash(ctx, []byte(updatedUser.Password))
if err != nil {
log.WithError(err).Error(logNotHashable)
return result, err
}
updatedUser.Password = string(newHash)
}
// Build Query
selector := bson.M{
"id": userID,
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "Update",
Selector: selector,
})
defer span.Finish()
collection := u.DB.C(storage.EntityUsers).With(mgoSession)
if err := collection.Update(selector, updatedUser); err != nil {
if mgo.IsDup(err) {
// Log to StdOut
log.WithError(err).Debug(logConflict)
// Log to OpenTracing
otLogErr(span, err)
return result, storage.ErrResourceExists
}
if err == mgo.ErrNotFound {
// Log to StdOut
log.WithError(err).Debug(logNotFound)
// Log to OpenTracing
otLogErr(span, err)
return result, fosite.ErrNotFound
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogQuery(span, updatedUser)
otLogErr(span, err)
return result, err
}
return updatedUser, nil
}
// Migrate is provided solely for the case where you want to migrate users and
// upgrade their password using the AuthUserMigrator interface.
// This performs an upsert, either creating or overwriting the record with the
// newly provided full record. Use with caution, be secure, don't be dumb.
func (u *UserManager) Migrate(ctx context.Context, migratedUser storage.User) (result storage.User, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "Migrate",
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Generate a unique ID if not supplied
if migratedUser.ID == "" {
migratedUser.ID = uuid.New()
}
// Update create time
if migratedUser.CreateTime == 0 {
migratedUser.CreateTime = time.Now().Unix()
}
// Update modified time
migratedUser.UpdateTime = time.Now().Unix()
// Build Query
selector := bson.M{
"id": migratedUser.ID,
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "Migrate",
Selector: selector,
})
defer span.Finish()
collection := u.DB.C(storage.EntityUsers).With(mgoSession)
if _, err := collection.Upsert(selector, migratedUser); err != nil {
if err == mgo.ErrNotFound {
// Log to StdOut
log.WithError(err).Debug(logNotFound)
// Log to OpenTracing
otLogErr(span, err)
return result, fosite.ErrNotFound
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogQuery(span, migratedUser)
otLogErr(span, err)
return result, err
}
return migratedUser, nil
}
// Delete deletes the specified User resource.
func (u *UserManager) Delete(ctx context.Context, userID string) error {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "Delete",
"id": userID,
})
// Copy a new DB session if none specified
mgoSession, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession = u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Build Query
query := bson.M{
"id": userID,
}
// Trace how long the Mongo operation takes to complete.
span, _ := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "Delete",
Query: query,
})
defer span.Finish()
collection := u.DB.C(storage.EntityUsers).With(mgoSession)
if err := collection.Remove(query); err != nil {
if err == mgo.ErrNotFound {
// Log to StdOut
log.WithError(err).Debug(logNotFound)
// Log to OpenTracing
otLogErr(span, err)
return fosite.ErrNotFound
}
// Log to StdOut
log.WithError(err).Error(logError)
// Log to OpenTracing
otLogErr(span, err)
return err
}
return nil
}
// Authenticate confirms whether the specified password matches the stored
// hashed password within the User resource.
// The User resource returned is matched by username.
func (u *UserManager) Authenticate(ctx context.Context, username string, password string) (result storage.User, err error) {
return u.AuthenticateByUsername(ctx, username, password)
}
// AuthenticateByID confirms whether the specified password matches the stored
// hashed password within the User resource.
// The User resource returned is matched by User ID.
func (u *UserManager) AuthenticateByID(ctx context.Context, userID string, password string) (result storage.User, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "AuthenticateByID",
})
// Copy a new DB session if none specified
_, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession := u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Trace how long the Mongo operation takes to complete.
span, ctx := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "AuthenticateByID",
})
defer span.Finish()
user, err := u.getConcrete(ctx, userID)
if err != nil {
log.WithError(err).Warn(logError)
return result, err
}
if user.Disabled {
log.Debug("disabled user denied access")
return result, fosite.ErrAccessDenied
}
err = u.Hasher.Compare(ctx, []byte(user.Password), []byte(password))
if err != nil {
log.WithError(err).Warn("failed to authenticate user password")
return result, err
}
return user, nil
}
// AuthenticateByUsername confirms whether the specified password matches the
// stored hashed password within the User resource.
// The User resource returned is matched by username.
func (u *UserManager) AuthenticateByUsername(ctx context.Context, username string, password string) (result storage.User, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "AuthenticateByUsername",
})
// Copy a new DB session if none specified
_, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession := u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Trace how long the Mongo operation takes to complete.
span, ctx := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "AuthenticateByUsername",
})
defer span.Finish()
user, err := u.GetByUsername(ctx, username)
if err != nil {
log.WithError(err).Warn(logError)
return result, err
}
if user.Disabled {
log.Debug("disabled user denied access")
return result, fosite.ErrAccessDenied
}
err = u.Hasher.Compare(ctx, []byte(user.Password), []byte(password))
if err != nil {
log.WithError(err).Warn("failed to authenticate user password")
return result, err
}
return user, nil
}
// AuthenticateMigration enables developers to supply your own
// authentication function, which in turn, if true, will migrate the secret
// to the Hasher implemented within fosite.
func (u *UserManager) AuthenticateMigration(ctx context.Context, currentAuth storage.AuthUserFunc, userID string, password string) (result storage.User, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "AuthenticateMigration",
"id": userID,
})
// Copy a new DB session if none specified
_, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession := u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Trace how long the Mongo operation takes to complete.
span, ctx := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "AuthenticateMigration",
})
defer span.Finish()
// Authenticate with old Hasher
user, authenticated := currentAuth()
// Check for user not found
if user.IsEmpty() && !authenticated {
log.Debug(logNotFound)
return result, fosite.ErrNotFound
}
if user.Disabled {
log.Debug("disabled user denied access")
return result, fosite.ErrAccessDenied
}
if !authenticated {
// If user isn't authenticated, try authenticating with new Hasher.
err := u.Hasher.Compare(ctx, user.GetHashedSecret(), []byte(password))
if err != nil {
log.WithError(err).Warn("failed to authenticate user password")
return result, err
}
return user, nil
}
// If the user is found and authenticated, create a new hash using the new
// Hasher, update the database record and return the record with no error.
newHash, err := u.Hasher.Hash(ctx, []byte(password))
if err != nil {
log.WithError(err).Error(logNotHashable)
return result, err
}
// Save the new hash
user.Password = <PASSWORD>)
return u.Update(ctx, userID, user)
}
// GrantScopes grants the provided scopes to the specified User resource.
func (u *UserManager) GrantScopes(ctx context.Context, userID string, scopes []string) (result storage.User, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "GrantScopes",
"id": userID,
})
// Copy a new DB session if none specified
_, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession := u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Trace how long the Mongo operation takes to complete.
span, ctx := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "GrantScopes",
})
defer span.Finish()
user, err := u.getConcrete(ctx, userID)
if err != nil {
if err == fosite.ErrNotFound {
log.Debug(logNotFound)
return result, err
}
log.WithError(err).Error(logError)
return result, err
}
user.EnableScopeAccess(scopes...)
return u.Update(ctx, user.ID, user)
}
// RemoveScopes revokes the provided scopes from the specified User Resource.
func (u *UserManager) RemoveScopes(ctx context.Context, userID string, scopes []string) (result storage.User, err error) {
// Initialize contextual method logger
log := logger.WithFields(logrus.Fields{
"package": "mongo",
"collection": storage.EntityUsers,
"method": "RemoveScopes",
"id": userID,
})
// Copy a new DB session if none specified
_, ok := ContextToMgoSession(ctx)
if !ok {
mgoSession := u.DB.Session.Copy()
ctx = MgoSessionToContext(ctx, mgoSession)
defer mgoSession.Close()
}
// Trace how long the Mongo operation takes to complete.
span, ctx := traceMongoCall(ctx, dbTrace{
Manager: "UserManager",
Method: "RemoveScopes",
})
defer span.Finish()
user, err := u.getConcrete(ctx, userID)
if err != nil {
if err == fosite.ErrNotFound {
log.Debug(logNotFound)
return result, err
}
log.WithError(err).Error(logError)
return result, err
}
user.DisableScopeAccess(scopes...)
return u.Update(ctx, user.ID, user)
}
|
624c79d878559c3430c4042d70c6509bc24c291a
|
[
"Markdown",
"Go Module",
"Go"
] | 14
|
Go
|
KMantas/storage
|
2190b23588cb7e01acfed9308bfe1b3ef5698781
|
65858c0e53a3015a9b012109de713728597c0cd4
|
refs/heads/develop
|
<file_sep>package ethminer
import (
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/bmizerany/pat"
"net/http"
"os"
"path"
)
const jsonrpcVersion = "2.0"
type Server struct {
Port uint16
rpcServer *RPCService
server *http.Server
output smartpool.UserOutput
}
func (s *Server) Start() {
if SmartPool == nil {
panic("SmartPool instance must be initialized first.")
}
if SmartPool.Run() {
go func() {
<-SmartPool.SubmitterStopped
os.Exit(1)
}()
s.output.Printf("RPC Server is running...\n")
s.output.Printf("You can start mining now by running ethminer using following command:\n")
s.output.Printf("--------------------------\n")
s.output.Printf("ethminer -F localhost:1633/:worker_name/\n")
s.output.Printf("Change :worker_name to whichever name you want.\n")
s.output.Printf("--------------------------\n")
err := s.server.ListenAndServe()
if err != nil {
s.output.Printf("Stopped because of: %s\n", err.Error())
}
} else {
s.output.Printf("SmartPool couldn't run. Exit.\n")
}
}
func NewServer(output smartpool.UserOutput, port uint16) *Server {
mux := pat.New()
rpcService := NewRPCService()
statService := NewStatService()
statusService := NewStatusService()
webDir, _ := os.Executable()
statsDir := path.Join(path.Dir(webDir), "ethereum", "ethminer", "statistic")
mux.Get("/stats/", http.StripPrefix("/stats/", http.FileServer(http.Dir(statsDir))))
mux.Post("/:rig/", rpcService)
mux.Get("/status", statusService)
mux.Get("/:method/:scope", statService)
return &Server{port, rpcService, &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%d", port),
Handler: mux,
}, output}
}
<file_sep>package ethereum
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
)
type Solution struct {
Nonce types.BlockNonce
Hash common.Hash
MixDigest common.Hash
}
func (s *Solution) WorkID() string {
return s.Hash.Hex()
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
"math/big"
)
type testClaim struct {
c []smartpool.Share
}
func (c *testClaim) NumShares() *big.Int {
return big.NewInt(int64(len(c.c)))
}
func (c *testClaim) Difficulty() *big.Int {
return big.NewInt(100000)
}
func (c *testClaim) Min() *big.Int {
return big.NewInt(0)
}
func (c *testClaim) Max() *big.Int {
return big.NewInt(100)
}
func (c *testClaim) GetShare(index int) smartpool.Share {
return c.c[index]
}
func (c *testClaim) SetEvidence(shareIndex *big.Int) {
}
func (c *testClaim) AugMerkle() smartpool.SPHash {
return smartpool.SPHash{}
}
func (c *testClaim) CounterBranch() []*big.Int {
return []*big.Int{}
}
func (c *testClaim) HashBranch() []*big.Int {
return []*big.Int{}
}
<file_sep>package main
import (
"errors"
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/SmartPool/smartpool-client/ethereum/geth"
"github.com/ethereum/go-ethereum/common"
"golang.org/x/crypto/ssh/terminal"
"gopkg.in/urfave/cli.v1"
"math/big"
"os"
"syscall"
)
type Input struct {
RpcEndPoint string
KeystorePath string
ContractAddr string
MinerAddr string
From uint
To uint
}
func Initialize(c *cli.Context) *Input {
rpcEndPoint := c.String("rpc")
keystorePath := c.String("keystore")
contractAddr := c.String("ethash-contract")
minerAddr := c.String("account")
from := c.Uint("from")
to := c.Uint("to")
return &Input{
rpcEndPoint, keystorePath, contractAddr,
minerAddr, from, to,
}
}
func promptUserPassPhrase(acc string) (string, error) {
fmt.Printf("Using account address: %s\n", acc)
fmt.Printf("Please enter passphrase: ")
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Printf("\n")
if err != nil {
return "", err
} else {
return string(bytePassword), nil
}
}
func Run(c *cli.Context) error {
input := Initialize(c)
if input.KeystorePath == "" {
fmt.Printf("You have to specify keystore path by --keystore. Abort!\n")
return nil
}
gasprice := c.Uint("gasprice")
smartpool.Output = &smartpool.StdOut{}
address, ok, addresses := geth.GetAddress(
input.KeystorePath,
common.HexToAddress(input.MinerAddr),
)
if len(addresses) == 0 {
fmt.Printf("We couldn't find any private keys in your keystore path.\n")
fmt.Printf("Please make sure your keystore path exists.\nAbort!\n")
return nil
}
fmt.Printf("Using miner address: %s\n", address.Hex())
input.MinerAddr = address.Hex()
gethRPC, _ := geth.NewGethRPC(
input.RpcEndPoint, input.ContractAddr,
"", big.NewInt(1), "",
)
client, err := gethRPC.ClientVersion()
if err != nil {
fmt.Printf("Node RPC server is unavailable.\n")
fmt.Printf("Make sure you have Parity or Geth running.\n")
return err
}
fmt.Printf("Connected to Ethereum node: %s\n", client)
fmt.Printf("Epoch data will be submitted to contract at %s\n", input.ContractAddr)
if common.HexToAddress(input.ContractAddr).Big().Cmp(common.Big0) == 0 {
fmt.Printf("Contract address is not set on gateway. Abort!\n")
return errors.New("Contract address is not set")
}
var ethashContractClient *geth.EthashContractClient
for {
if ok {
passphrase, _ := promptUserPassPhrase(
input.MinerAddr,
)
ethashContractClient, err = geth.NewEthashContractClient(
common.HexToAddress(input.ContractAddr), gethRPC,
common.HexToAddress(input.MinerAddr),
input.RpcEndPoint, input.KeystorePath, passphrase,
uint64(gasprice),
)
if ethashContractClient != nil {
break
} else {
fmt.Printf("error: %s\n", err)
}
} else {
if input.KeystorePath == "" {
fmt.Printf("You have to specify keystore path by --keystore. Abort!\n")
} else {
fmt.Printf("Your keystore: %s\n", input.KeystorePath)
fmt.Printf("Your miner address: %s\n", input.MinerAddr)
if len(addresses) > 0 {
fmt.Printf("We couldn't find the private key of your miner address in the keystore path you specified. We found following addresses:\n")
for i, addr := range addresses {
fmt.Printf("%d. %s\n", i+1, addr.Hex())
}
fmt.Printf("Please make sure you entered correct miner address.\n")
} else {
fmt.Printf("We couldn't find any private keys in your keystore path.\n")
fmt.Printf("Please make sure your keystore path exists.\nAbort!\n")
}
}
return nil
}
}
ethereumContract := ethereum.NewEthashContract(ethashContractClient)
for i := int(input.From); i <= int(input.To); i++ {
fmt.Printf("Calculating epoch datas for epochs number %d...\n", i)
err = ethereumContract.SetEpochData(i)
if err != nil {
fmt.Printf("Got error: %s\n", err)
} else {
fmt.Printf("Succeeded.\n")
}
}
return nil
}
func BuildAppCommandLine() *cli.App {
app := cli.NewApp()
app.Description = "Commandline tool to calculate and submit epoch data for SmartPool"
app.Name = "SmartPool epoch tool"
app.Usage = "Submit epoch data to contract"
app.Version = smartpool.VERSION
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "rpc",
Value: "http://localhost:8545",
Usage: "RPC endpoint of Ethereum node",
},
cli.StringFlag{
Name: "keystore",
Usage: "Keystore path to your ethereum account private key. SmartPool will look for private key of the miner address you specified in that path.",
},
cli.StringFlag{
Name: "account",
Usage: "The address that is used to submit epoch data (Default: First account in your keystore.)",
},
cli.StringFlag{
Name: "ethash-contract",
Value: "0xd93c6293a076fc6c8f49d678b6d01aab3232fddc",
Usage: "Ethash contract address. Its default value is the official ethash contract maintained by SmartPool team",
},
cli.UintFlag{
Name: "gasprice",
Value: 50,
Usage: "Gas price in gwei to use in communication with the contract. Specify 0 if you let your Ethereum Client decide on gas price.",
},
cli.UintFlag{
Name: "from",
Usage: "Starting epoch number to calculate epoch data on.",
},
cli.UintFlag{
Name: "to",
Usage: "Ending epoch number to calculate epoch data on.",
},
}
app.Action = Run
return app
}
func main() {
app := BuildAppCommandLine()
app.Run(os.Args)
}
<file_sep>package protocol
type testUserOutput struct{}
func (out *testUserOutput) Printf(format string, a ...interface{}) (n int, err error) {
return 0, nil
}
<file_sep>package smartpool
import "fmt"
type StdOut struct{}
func (StdOut) Printf(format string, a ...interface{}) (n int, err error) {
return fmt.Printf(format, a...)
}
func (StdOut) Close() {}
<file_sep>// Package smartpool defines interfaces for interaction between SmartPool
// and user, SmartPool and external resources such as Ethereum client
// (geth, partity), ethminer, persistent storage.
//
// It also defines some core interfaces for its sub packages to interact
// to each other.
package smartpool
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"math/big"
"time"
)
// UserInput represents all necessary user specific inputs to run SmartPool
// client. Some of them can have default values depend on the actual structs
// implementing the interface.
type UserInput interface {
RPCEndpoint() string
KeystorePath() string
ShareThreshold() int
ClaimThreshold() int
ShareDifficulty() *big.Int
SubmitInterval() time.Duration
ContractAddress() string
MinerAddress() string
ExtraData() string
HotStop() bool
}
// Global output mechanism
var Output UserOutput = StdOut{}
// UserOutput accepts all the information that SmartPool wants to tell the user.
// It's only responsibility is to accept information. How the information is
// delivered to user is upto structs implementing the interface.
type UserOutput interface {
// TODO: Add necessary methods
// TODO: This might take information about internal detail such as:
// number of claim submitted, number of claim verified,
// number of claim accepted, number of share per claim on average,
// average hash rate,...
Printf(format string, a ...interface{}) (n int, err error)
Close()
}
// PersistentStorage is the gateway for smartpool to interact with external
// persistent storage such as a file system, a database or even a cloud based
// service.
// Smartpool should only persist something via this interface.
type PersistentStorage interface {
Persist(data interface{}, id string) error
Load(data interface{}, id string) (interface{}, error)
}
// Contract is the interface for smartpool to interact with contract side of
// SmartPool protocol.
// Contract can be used for only one caller (Ethereum account) per
// instance.
type Contract interface {
// Version return contract version which is useful for backward and forward
// compatibility when the contract is redeployed in some occasions.
Version() string
// IsRegistered returns true when the miner's address is already recognized
// as a user of the pool. It returns false otherwise.
IsRegistered() bool
// CanRegister returns true when the miner's address can actually register
// to the pool. It returns false when the contract side decided to refuse
// the address.
CanRegister() bool
// Register takes an address and register it to the pool.
Register(paymentAddress common.Address) error
// SubmitClaim takes some necessary parameters that represent a claim and
// submit to the contract using miner's address. The address should be
// unlocked first.
SubmitClaim(claim Claim, lastClaim bool) error
// GetShareIndex returns index of the share that is requested to submit
// proof to the contract to represent correctness of the submitted claims.
// GetShareIndex must be called after SubmitClaim to get shareIndex which
// is used to pass to VerifyClaim. If GetShareIndex is called before
// SubmitClaim, the index will have no meaning to contract.
// GetShareIndex returns 2 indexes, first is submission index, second is
// share index in the relevant submission (claim)
GetShareIndex(claim Claim) (*big.Int, *big.Int, error)
NumOpenClaims() (*big.Int, error)
ResetOpenClaims() error
// VerifyClaim takes some necessary parameters that provides complete proof
// of a share with index shareIndex in the cliam and submit to contract side
// in order to prove that the claim is valid so the miner can take credit
// of it.
VerifyClaim(submissionIndex *big.Int, shareIndex *big.Int, claim Claim) error
}
// NetworkClient represents client for blockchain network that miner is mining
// on. Network can be Ethereum, Ethereum Classic, ZCash, Bitcoin... For
// Ethereum, client can be Geth or Parity.
// Smartpool should only interact with network client via this interface and
// it doesn't care if the client is Geth or Partity or any other clients.
// Communication mechanism is upto structs implementing this interface.
type NetworkClient interface {
// GetWork returns a Work for SmartPool to give to the miner. How the work
// is formed is upto structs implementing this interface.
GetWork() Work
// SubmitSolution submits the solution that miner has submitted to SmartPool
// so the full block solution can take credits. It also maintain workflow
// between miner and the network client.
SubmitSolution(s Solution) bool
SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool
// ReadyToMine returns true when the network is ready to give and accept
// pow work and solution. It returns false otherwise.
ReadyToMine() bool
// Configure configs etherbase and extradata to the network client
Configure(etherbase common.Address, extradata string) error
}
// ShareReceiver represents SmartPool itself which accepts solutions from
// miners.
type ShareReceiver interface {
AcceptSolution(s Solution) Share
Persist(storage PersistentStorage) error
}
type PoolMonitor interface {
RequireClientUpdate() bool
RequireContractUpdate() bool
ContractAddress() common.Address
}
type StatRecorder interface {
RecordShare(status string, share Share, rig Rig)
RecordClaim(status string, claim Claim)
RecordHashrate(hashrate hexutil.Uint64, id common.Hash, rig Rig)
// Notify StatRecorder how many share were restored from last session
// so StatRecorder can track number of abandoned shares
ShareRestored(noshares uint64)
OverallFarmStat() interface{}
FarmStat(start uint64, end uint64) interface{}
OverallRigStat(rig Rig) interface{}
RigStat(rig Rig, start uint64, end uint64) interface{}
Persist(storage PersistentStorage) error
}
<file_sep>package protocol
import (
"errors"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"math/big"
"time"
)
type testContract struct {
Registered bool
Registerable bool
SubmitFailed bool
VerifyFailed bool
SubmitTime *time.Time
IndexRequestedTime *time.Time
claim *testClaim
DelayedVerification bool
}
func newTestContract() *testContract {
return &testContract{false, false, false, false, nil, nil, nil, false}
}
func (c *testContract) Version() string {
return "1.0.0"
}
func (c *testContract) IsRegistered() bool {
return c.Registered
}
func (c *testContract) CanRegister() bool {
return c.Registerable
}
func (c *testContract) Register(paymentAddress common.Address) error {
c.Registered = true
return nil
}
func (c *testContract) SubmitClaim(claim smartpool.Claim, lastClaim bool) error {
c.claim = claim.(*testClaim)
if c.SubmitFailed {
return errors.New("fail")
}
t := time.Now()
c.SubmitTime = &t
return nil
}
func (c *testContract) GetShareIndex(claim smartpool.Claim) (*big.Int, *big.Int, error) {
t := time.Now()
c.IndexRequestedTime = &t
return big.NewInt(0), big.NewInt(100), nil
}
func (c *testContract) VerifyClaim(claimIndex *big.Int, shareIndex *big.Int, claim smartpool.Claim) error {
if c.VerifyFailed {
return errors.New("fail")
}
if c.DelayedVerification {
time.Sleep(50 * time.Millisecond)
}
return nil
}
func (c *testContract) GetLastSubmittedClaim() *testClaim {
return c.claim
}
func (c *testContract) NumOpenClaims() (*big.Int, error) {
return big.NewInt(0), nil
}
func (c *testContract) ResetOpenClaims() error {
return nil
}
<file_sep>// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package ethash
import (
crand "crypto/rand"
"math"
"math/big"
"math/rand"
"runtime"
"sync"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/log"
)
// Seal implements consensus.Engine, attempting to find a nonce that satisfies
// the block's difficulty requirements.
func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
// If we're running a fake PoW, simply return a 0 nonce immediately
if ethash.fakeMode {
header := block.Header()
header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{}
return block.WithSeal(header), nil
}
// If we're running a shared PoW, delegate sealing to it
if ethash.shared != nil {
return ethash.shared.Seal(chain, block, stop)
}
// Create a runner and the multiple search threads it directs
abort := make(chan struct{})
found := make(chan *types.Block)
ethash.lock.Lock()
threads := ethash.threads
if ethash.rand == nil {
seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
ethash.lock.Unlock()
return nil, err
}
ethash.rand = rand.New(rand.NewSource(seed.Int64()))
}
ethash.lock.Unlock()
if threads == 0 {
threads = runtime.NumCPU()
}
if threads < 0 {
threads = 0 // Allows disabling local mining without extra logic around local/remote
}
var pend sync.WaitGroup
for i := 0; i < threads; i++ {
pend.Add(1)
go func(id int, nonce uint64) {
defer pend.Done()
ethash.mine(block, id, nonce, abort, found)
}(i, uint64(ethash.rand.Int63()))
}
// Wait until sealing is terminated or a nonce is found
var result *types.Block
select {
case <-stop:
// Outside abort, stop all miner threads
close(abort)
case result = <-found:
// One of the threads found a block, abort all others
close(abort)
case <-ethash.update:
// Thread count was changed on user request, restart
close(abort)
pend.Wait()
return ethash.Seal(chain, block, stop)
}
// Wait for all miners to terminate and return the block
pend.Wait()
return result, nil
}
// mine is the actual proof-of-work miner that searches for a nonce starting from
// seed that results in correct final block difficulty.
func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block) {
// Extract some data from the header
var (
header = block.Header()
hash = header.HashNoNonce().Bytes()
target = new(big.Int).Div(maxUint256, header.Difficulty)
number = header.Number.Uint64()
dataset = ethash.dataset(number)
)
// Start generating random nonces until we abort or find a good one
var (
attempts = int64(0)
nonce = seed
)
logger := log.New("miner", id)
logger.Trace("Started ethash search for new nonces", "seed", seed)
for {
select {
case <-abort:
// Mining terminated, update stats and abort
logger.Trace("Ethash nonce search aborted", "attempts", nonce-seed)
ethash.hashrate.Mark(attempts)
return
default:
// We don't have to update hash rate on every nonce, so update after after 2^X nonces
attempts++
if (attempts % (1 << 15)) == 0 {
ethash.hashrate.Mark(attempts)
attempts = 0
}
// Compute the PoW value of this nonce
digest, result := hashimotoFull(dataset, hash, nonce)
if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
// Correct nonce found, create a new header with it
header = types.CopyHeader(header)
header.Nonce = types.EncodeNonce(nonce)
header.MixDigest = common.BytesToHash(digest)
// Seal and return a block (if still needed)
select {
case found <- block.WithSeal(header):
logger.Trace("Ethash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
case <-abort:
logger.Trace("Ethash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
}
return
}
nonce++
}
}
}
<file_sep>package stat
import (
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"math/big"
"time"
)
type PeriodRigData struct {
MinedShare uint64 `json:"mined_share"`
ValidShare uint64 `json:"valid_share"`
TotalValidDifficulty *big.Int `json:"-"`
AverageShareDifficulty *big.Int `json:"average_share_difficulty"`
RejectedShare uint64 `json:"rejected_share"`
TotalHashrate *big.Int `json:"-"`
NoHashrateSubmission uint64 `json:"-"`
AverageReportedHashrate *big.Int `json:"reported_hashrate"`
AverageEffectiveHashrate *big.Int `json:"effective_hashrate"`
BlockFound uint64 `json:"block_found"`
TimePeriod uint64 `json:"time_period"`
StartTime time.Time `json:"start_time"`
}
func NewPeriodRigData(timePeriod uint64) *PeriodRigData {
return &PeriodRigData{
TotalHashrate: big.NewInt(0),
TotalValidDifficulty: big.NewInt(0),
AverageShareDifficulty: big.NewInt(0),
AverageReportedHashrate: big.NewInt(0),
AverageEffectiveHashrate: big.NewInt(0),
TimePeriod: timePeriod,
}
}
func (prd *PeriodRigData) updateAvgHashrate(t time.Time) {
if prd.NoHashrateSubmission > 0 {
prd.AverageReportedHashrate.Div(
prd.TotalHashrate,
big.NewInt(int64(prd.NoHashrateSubmission)),
)
}
}
func (prd *PeriodRigData) updateAvgEffHashrate(t time.Time) {
prd.AverageEffectiveHashrate.Div(
prd.TotalValidDifficulty,
big.NewInt(BaseTimePeriod),
)
}
func (prd *PeriodRigData) updateAvgShareDifficulty(t time.Time) {
if prd.ValidShare > 0 {
prd.AverageShareDifficulty.Div(
prd.TotalValidDifficulty,
big.NewInt(int64(prd.ValidShare)),
)
}
}
type OverallRigData struct {
LastMinedShare time.Time `json:"last_mined_share"`
LastValidShare time.Time `json:"last_valid_share"`
LastRejectedShare time.Time `json:"last_rejected_share"`
LastBlock time.Time `json:"last_block"`
MinedShare uint64 `json:"total_submitted_share"`
ValidShare uint64 `json:"total_accepted_share"`
TotalValidDifficulty *big.Int `json:"total_accepted_difficulty"`
AverageShareDifficulty *big.Int `json:"average_share_difficulty"`
RejectedShare uint64 `json:"total_rejected_share"`
TotalHashrate *big.Int `json:"total_hashrate"`
NoHashrateSubmission uint64 `json:"no_hashrate_submission"`
AverageReportedHashrate *big.Int `json:"reported_hashrate"`
AverageEffectiveHashrate *big.Int `json:"effective_hashrate"`
BlockFound uint64 `json:"total_block_found"`
StartTime time.Time `json:"start_time"`
}
type RigData struct {
RigID string
Datas map[uint64]*PeriodRigData
*OverallRigData
}
func NewRigData(rigID string) *RigData {
return &RigData{
RigID: rigID,
Datas: map[uint64]*PeriodRigData{},
OverallRigData: &OverallRigData{
TotalHashrate: big.NewInt(0),
TotalValidDifficulty: big.NewInt(0),
AverageShareDifficulty: big.NewInt(0),
AverageReportedHashrate: big.NewInt(0),
AverageEffectiveHashrate: big.NewInt(0),
},
}
}
func (rd *RigData) TruncateData(storage smartpool.PersistentStorage) error {
curPeriod := TimeToPeriod(time.Now())
var err error
for period, rigData := range rd.Datas {
if int64(curPeriod-period) > LongWindow/BaseTimePeriod {
if err = storage.Persist(rigData, fmt.Sprintf("rig-%s-data-%d", rd.RigID, period)); err != nil {
return err
}
}
}
return nil
}
func (rd *RigData) getData(t time.Time) *PeriodRigData {
timePeriod := TimeToPeriod(t)
data := rd.Datas[timePeriod]
if data == nil {
data = NewPeriodRigData(timePeriod)
rd.Datas[timePeriod] = data
}
return data
}
func (rd *RigData) AddShare(status string, share smartpool.Share, t time.Time) {
if rd.StartTime.IsZero() {
rd.StartTime = t
}
curPeriodData := rd.getData(t)
if curPeriodData.StartTime.IsZero() {
curPeriodData.StartTime = t
}
if status == "submitted" {
rd.LastMinedShare = t
rd.MinedShare++
curPeriodData.MinedShare++
} else if status == "accepted" {
rd.LastValidShare = t
rd.ValidShare++
rd.TotalValidDifficulty.Add(rd.TotalValidDifficulty, share.ShareDifficulty())
rd.updateAvgShareDifficulty(t)
rd.updateAvgEffHashrate(t)
curPeriodData.ValidShare++
curPeriodData.TotalValidDifficulty.Add(curPeriodData.TotalValidDifficulty, share.ShareDifficulty())
curPeriodData.updateAvgShareDifficulty(t)
curPeriodData.updateAvgEffHashrate(t)
} else if status == "rejected" {
rd.LastRejectedShare = t
rd.RejectedShare++
curPeriodData.RejectedShare++
} else if status == "fullsolution" {
rd.LastBlock = t
rd.LastValidShare = t
rd.ValidShare++
rd.TotalValidDifficulty.Add(rd.TotalValidDifficulty, share.ShareDifficulty())
rd.updateAvgShareDifficulty(t)
rd.updateAvgEffHashrate(t)
rd.BlockFound++
curPeriodData.ValidShare++
curPeriodData.TotalValidDifficulty.Add(curPeriodData.TotalValidDifficulty, share.ShareDifficulty())
curPeriodData.updateAvgShareDifficulty(t)
curPeriodData.updateAvgEffHashrate(t)
curPeriodData.BlockFound++
}
}
func (rd *RigData) PeriodReportedHashrate(t time.Time) *big.Int {
curPeriodData := rd.getData(t)
return curPeriodData.AverageReportedHashrate
}
func (rd *RigData) PeriodEffectiveHashrate(t time.Time) *big.Int {
curPeriodData := rd.getData(t)
return curPeriodData.AverageEffectiveHashrate
}
func (rd *RigData) AddHashrate(hashrate hexutil.Uint64, id common.Hash, t time.Time) {
if rd.StartTime.IsZero() {
rd.StartTime = t
}
curPeriodData := rd.getData(t)
if curPeriodData.StartTime.IsZero() {
curPeriodData.StartTime = t
}
rd.TotalHashrate.Add(rd.TotalHashrate, big.NewInt(int64(hashrate)))
rd.NoHashrateSubmission++
rd.updateAvgHashrate(t)
// fmt.Printf("Updated total hashrate: %d\n", rd.TotalHashrate.Uint64())
// fmt.Printf("Updated reported hashrate: %d\n", rd.AverageReportedHashrate.Uint64())
curPeriodData.TotalHashrate.Add(curPeriodData.TotalHashrate, big.NewInt(int64(hashrate)))
curPeriodData.NoHashrateSubmission++
curPeriodData.updateAvgHashrate(t)
}
func (rd *RigData) updateAvgHashrate(t time.Time) {
if rd.NoHashrateSubmission > 0 {
rd.AverageReportedHashrate.Div(
rd.TotalHashrate,
big.NewInt(int64(rd.NoHashrateSubmission)),
)
}
}
func (rd *RigData) updateAvgEffHashrate(t time.Time) {
rd.AverageEffectiveHashrate.Div(
rd.TotalValidDifficulty,
big.NewInt(BaseTimePeriod),
)
}
func (rd *RigData) updateAvgShareDifficulty(t time.Time) {
if rd.ValidShare > 0 {
rd.AverageShareDifficulty.Div(
rd.TotalValidDifficulty,
big.NewInt(int64(rd.ValidShare)),
)
}
}
<file_sep>package ethminer
import (
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/SmartPool/smartpool-client/protocol"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"math/big"
)
var SmartPool *protocol.SmartPool
type SmartPoolService struct {
rig *ethereum.Rig
}
func (sps *SmartPoolService) GetWork() ([3]string, error) {
var res [3]string
w := SmartPool.GetWork(sps.rig).(*ethereum.Work)
res[0] = w.PoWHash().Hex()
res[1] = w.SeedHash
n := big.NewInt(1)
n.Lsh(n, 255)
n.Div(n, w.ShareDifficulty)
n.Lsh(n, 1)
res[2] = common.BytesToHash(n.Bytes()).Hex()
return res, nil
}
func (sps *SmartPoolService) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool {
// nc := SmartPool.NetworkClient.(*ethereum.NetworkClient)
// return nc.SubmitHashrate(sps.rig, hashrate, id)
return SmartPool.SubmitHashrate(sps.rig, hashrate, id)
}
func (sps *SmartPoolService) SubmitWork(nonce types.BlockNonce, hash, mixDigest common.Hash) bool {
sol := ðereum.Solution{
Nonce: nonce,
Hash: hash,
MixDigest: mixDigest,
}
return SmartPool.AcceptSolution(sps.rig, sol)
}
func NewSmartPoolService(rigName string, rigIP string) *SmartPoolService {
return &SmartPoolService{ethereum.NewRig(rigName, rigIP)}
}
<file_sep>package ethereum
import (
"bufio"
"bytes"
"encoding/hex"
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum/ethash"
"github.com/SmartPool/smartpool-client/mtree"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rlp"
"io"
"log"
"math/big"
"os"
"time"
)
type Share struct {
blockHeader *types.Header
nonce types.BlockNonce
mixDigest common.Hash
shareDifficulty *big.Int
minerAddress string
SolutionState int
dt *mtree.DagTree
}
func (s *Share) Difficulty() *big.Int { return s.blockHeader.Difficulty }
func (s *Share) ShareDifficulty() *big.Int { return s.shareDifficulty }
func (s *Share) HashNoNonce() common.Hash { return s.blockHeader.HashNoNonce() }
func (s *Share) Nonce() uint64 { return s.nonce.Uint64() }
func (s *Share) MixDigest() common.Hash { return s.mixDigest }
func (s *Share) NumberU64() uint64 { return s.blockHeader.Number.Uint64() }
func (s *Share) MinerAddress() string { return s.minerAddress }
func (s *Share) NonceBig() *big.Int {
n := new(big.Int)
n.SetBytes(s.nonce[:])
return n
}
func (s *Share) FullSolution() bool {
return s.SolutionState == 2
}
func (s *Share) BlockHeader() *types.Header {
return s.blockHeader
}
func (s *Share) RlpHeaderWithoutNonce() ([]byte, error) {
buffer := new(bytes.Buffer)
err := rlp.Encode(buffer, []interface{}{
s.BlockHeader().ParentHash,
s.BlockHeader().UncleHash,
s.BlockHeader().Coinbase,
s.BlockHeader().Root,
s.BlockHeader().TxHash,
s.BlockHeader().ReceiptHash,
s.BlockHeader().Bloom,
s.BlockHeader().Difficulty,
s.BlockHeader().Number,
s.BlockHeader().GasLimit,
s.BlockHeader().GasUsed,
s.BlockHeader().Time,
s.BlockHeader().Extra,
})
fmt.Printf("RLP: 0x%s\n", hex.EncodeToString(buffer.Bytes()))
return buffer.Bytes(), err
}
func (s *Share) Timestamp() *big.Int {
return s.blockHeader.Time
}
// We use concatenation of timestamp and nonce
// as share counter
// Nonce in ethereum is 8 bytes so counter = timestamp << 64 + nonce
func (s *Share) Counter() *big.Int {
t := big.NewInt(0)
t.Set(s.Timestamp())
t.Lsh(t, 64)
n := big.NewInt(0).SetBytes(s.nonce[:])
return t.Add(t, n)
}
func (s *Share) Hash() (result smartpool.SPHash) {
h := s.blockHeader.HashNoNonce()
copy(result[:smartpool.HashLength], h[smartpool.HashLength:])
return
}
func processDuringRead(
datasetPath string, mt *mtree.DagTree) {
var f *os.File
var err error
for {
f, err = os.Open(datasetPath)
if err == nil {
break
} else {
smartpool.Output.Printf("Reading DAG file %s failed with %s. Retry in 10s...\n", datasetPath, err.Error())
time.Sleep(10 * time.Second)
}
}
r := bufio.NewReader(f)
buf := [128]byte{}
// ignore first 8 bytes magic number at the beginning
// of dataset. See more at https://gopkg.in/ethereum/wiki/wiki/Ethash-DAG-Disk-Storage-Format
_, err = io.ReadFull(r, buf[:8])
if err != nil {
log.Fatal(err)
}
var i uint32 = 0
for {
n, err := io.ReadFull(r, buf[:128])
if n == 0 {
if err == nil {
continue
}
if err == io.EOF {
break
}
log.Fatal(err)
}
if n != 128 {
log.Fatal("Malformed dataset")
}
mt.Insert(smartpool.Word(buf), i)
if err != nil && err != io.EOF {
log.Fatal(err)
}
i++
}
}
func (s *Share) buildDagTree() {
indices := ethash.Instance.GetVerificationIndices(
s.NumberU64(),
s.BlockHeader().HashNoNonce(),
s.Nonce(),
)
fmt.Printf("indices: %v\n", indices)
s.dt = mtree.NewDagTree()
s.dt.RegisterIndex(indices...)
ethash.MakeDAG(s.NumberU64(), ethash.DefaultDir)
fullSize := ethash.DAGSize(s.NumberU64())
fullSizeIn128Resolution := fullSize / 128
branchDepth := len(fmt.Sprintf("%b", fullSizeIn128Resolution-1))
s.dt.RegisterStoredLevel(uint32(branchDepth), uint32(10))
path := ethash.PathToDAG(uint64(s.NumberU64()/30000), ethash.DefaultDir)
processDuringRead(path, s.dt)
s.dt.Finalize()
}
func (s *Share) DAGElementArray() []*big.Int {
if s.dt == nil {
s.buildDagTree()
}
result := []*big.Int{}
for _, w := range s.dt.AllDAGElements() {
result = append(result, w.ToUint256Array()...)
}
return result
}
func (s *Share) DAGProofArray() []*big.Int {
if s.dt == nil {
s.buildDagTree()
}
result := []*big.Int{}
for _, be := range s.dt.AllBranchesArray() {
result = append(result, be.Big())
}
return result
}
func NewShare(h *types.Header, dif *big.Int, miner string) *Share {
return &Share{
h,
types.BlockNonce{},
common.Hash{},
dif,
miner,
0,
nil,
}
}
<file_sep>package ethminer
import (
"encoding/json"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"net/http"
"strings"
)
type RPCService struct{}
func (server *RPCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var (
err Error
e error
res interface{}
hashrate hexutil.Uint64
hashrateID common.Hash
nonce types.BlockNonce
hash common.Hash
mixDigest common.Hash
ip string
)
rigName := r.URL.Query().Get(":rig")
parts := strings.Split(r.RemoteAddr, ":")
if len(parts) == 0 {
ip = "unknown"
} else {
ip = parts[0]
}
service := NewSmartPoolService(rigName, ip)
method, rawParams, id, err := extractRPCMsg(r)
if err != nil {
res = createErrorResponse(id, err)
server.response(w, res)
return
}
if method == "eth_getWork" {
res, e = service.GetWork()
if e != nil {
err = &callbackError{e.Error()}
}
} else if method == "eth_submitHashrate" {
hashrate, hashrateID, err = parseHashrateArguments(rawParams)
if err == nil {
res = service.SubmitHashrate(hashrate, hashrateID)
}
} else if method == "eth_submitWork" {
nonce, hash, mixDigest, err = parseWorkArguments(rawParams)
if err == nil {
res = service.SubmitWork(nonce, hash, mixDigest)
}
}
if err != nil {
server.response(w, createErrorResponse(id, err))
} else {
server.response(w, createResponse(id, res))
}
return
}
func (server *RPCService) response(w http.ResponseWriter, resp interface{}) error {
encoder := json.NewEncoder(w)
return encoder.Encode(resp)
}
func NewRPCService() *RPCService {
return &RPCService{}
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
)
// ClaimRepo holds many claims but only 1 active clam at a time which is
// storing coming shares.
type ClaimRepo interface {
// AddShare stores share to current active claim
AddShare(s smartpool.Share) error
// GetCurrentClaim returns the active claim, seal it as closed claim and
// initialize a new active claim to store coming shares. In the mean time
// the sealed claim should be used by SmartPool to do the protocol.
// GetCurrentClaim returns nil when there are not enough shares in the claim
// as compared to the threshold.
GetCurrentClaim(threshold int) smartpool.Claim
PutOpenClaim(claim smartpool.Claim)
RemoveOpenClaim(claim smartpool.Claim)
GetOpenClaim(claimIndex int) smartpool.Claim
ResetOpenClaims()
NumOpenClaims() uint64
SealClaimBatch()
Persist(storage smartpool.PersistentStorage) error
NoActiveShares() uint64
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
"math/big"
)
type testShare struct {
c *big.Int
d *big.Int
h byte
}
func (s *testShare) Counter() *big.Int {
return s.c
}
func (s *testShare) Hash() smartpool.SPHash {
h := smartpool.SPHash{}
copy(h[:], []byte{s.h})
return h
}
func (s *testShare) ShareDifficulty() *big.Int {
return s.d
}
func (s *testShare) FullSolution() bool {
return true
}
<file_sep>package mtree
type BranchNode struct {
Hash NodeData
Left *BranchNode
Right *BranchNode
ElementOnTheLeft bool
}
func (b BranchNode) ToNodeArray() []NodeData {
if b.Left == nil && b.Right == nil {
return []NodeData{b.Hash}
}
left := b.Left.ToNodeArray()
right := b.Right.ToNodeArray()
if b.ElementOnTheLeft {
return append(left, right...)
} else {
return append(right, left...)
}
}
// explain the operation
func AcceptLeftSibling(b *BranchNode, h NodeData) *BranchNode {
return &BranchNode{
Hash: nil,
Left: &BranchNode{h, nil, nil, false},
Right: b,
ElementOnTheLeft: false,
}
}
func AcceptRightSibling(b *BranchNode, h NodeData) *BranchNode {
return &BranchNode{
Hash: nil,
Right: &BranchNode{h, nil, nil, false},
Left: b,
ElementOnTheLeft: true,
}
}
<file_sep>package smartpool
import (
"fmt"
"log"
"os"
"time"
)
type Log struct {
*log.Logger
f *os.File
}
func NewLog() *Log {
f, err := os.OpenFile("smartpool.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
return &Log{log.New(f, "", log.Lshortfile|log.LstdFlags), f}
}
func (l *Log) Close() {
l.f.Close()
}
func (l *Log) Printf(format string, a ...interface{}) (n int, err error) {
l.Logger.Printf(format, a...)
t := time.Now()
ts := t.Format(time.RFC3339)
fmt.Printf("%v ", ts)
return fmt.Printf(format, a...)
}
<file_sep>package mtree
type BranchTree struct {
RawData ElementData
HashedData NodeData
Root *BranchNode
}
func (t BranchTree) ToNodeArray() []NodeData {
return t.Root.ToNodeArray()
}
<file_sep>package mtree
import (
"container/list"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/crypto"
"math/big"
)
type DagData smartpool.SPHash
func (dd DagData) Copy() NodeData {
result := DagData{}
copy(result[:], dd[:])
return result
}
type DagTree struct {
MerkleTree
}
func _elementHash(data ElementData) NodeData {
// insert data into the mtbuf and aggregate the
// hashes
// because contract side is expecting the bytes
// to be reversed each 32 bytes on leaf nodes
first, second := conventionalWord(data.(smartpool.Word))
keccak := crypto.Keccak256(first, second)
result := DagData{}
copy(result[:smartpool.HashLength], keccak[smartpool.HashLength:])
return result
}
func _hash(a, b NodeData) NodeData {
var keccak []byte
left := a.(DagData)
right := b.(DagData)
keccak = crypto.Keccak256(
append([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, left[:]...),
append([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, right[:]...),
)
result := DagData{}
copy(result[:smartpool.HashLength], keccak[smartpool.HashLength:])
return result
}
func _modifier(data NodeData) {}
func NewDagTree() *DagTree {
mtbuf := list.New()
return &DagTree{
MerkleTree{
mtbuf,
_hash,
_elementHash,
_modifier,
false,
map[uint32]bool{},
[]uint32{},
0,
0,
[]NodeData{},
},
}
}
func (dt DagTree) RootHash() smartpool.SPHash {
if dt.finalized {
return smartpool.SPHash(dt.Root().(DagData))
}
panic("SP Merkle tree needs to be finalized by calling mt.Finalize()")
}
func (dt DagTree) MerkleNodes() []*big.Int {
if dt.finalized {
result := []*big.Int{}
for i := 0; i*2 < len(dt.exportNodes); i++ {
if i*2+1 >= len(dt.exportNodes) {
result = append(result,
smartpool.BranchElementFromHash(
smartpool.SPHash(DagData{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}),
smartpool.SPHash(dt.exportNodes[i*2].(DagData))).Big())
} else {
result = append(result,
smartpool.BranchElementFromHash(
smartpool.SPHash(dt.exportNodes[i*2+1].(DagData)),
smartpool.SPHash(dt.exportNodes[i*2].(DagData))).Big())
}
}
return result
}
panic("SP Merkle tree needs to be finalized by calling mt.Finalize()")
}
// return only one array with necessary hashes for each
// index in order. Element's hash and root are not included
// eg. registered indexes are 1, 2, each needs 2 hashes
// then the function return an array of 4 hashes [a1, a2, b1, b2]
// where a1, a2 are proof branch for element at index 1
// b1, b2 are proof branch for element at index 2
func (dt DagTree) AllBranchesArray() []smartpool.BranchElement {
if dt.finalized {
result := []smartpool.BranchElement{}
branches := dt.Branches()
for _, k := range dt.Indices() {
// p := proofs[k]
// fmt.Printf("Index: %d\nRawData: %s\nHashedData: %s\n", k, hex.EncodeToString(p.RawData[:]), proofs[k].HashedData.Hex())
hh := branches[k].ToNodeArray()[1:]
hashes := hh[:len(hh)-int(dt.StoredLevel())]
// fmt.Printf("Len proofs: %s\n", len(pfs))
for i := 0; i*2 < len(hashes); i++ {
// for anyone who is courious why i*2 + 1 comes before i * 2
// it's agreement between client side and contract side
if i*2+1 >= len(hashes) {
result = append(result,
smartpool.BranchElementFromHash(
smartpool.SPHash(DagData{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}),
smartpool.SPHash(hashes[i*2].(DagData))))
} else {
result = append(result,
smartpool.BranchElementFromHash(
smartpool.SPHash(hashes[i*2+1].(DagData)),
smartpool.SPHash(hashes[i*2].(DagData))))
}
}
}
return result
}
panic("SP Merkle tree needs to be finalized by calling mt.Finalize()")
}
func (dt DagTree) AllDAGElements() []smartpool.Word {
if dt.finalized {
result := []smartpool.Word{}
branches := dt.Branches()
for _, k := range dt.Indices() {
// p := branches[k]
// fmt.Printf("Index: %d\nRawData: %s\nHashedData: %s\n", k, hex.EncodeToString(p.RawData[:]), proofs[k].HashedData.Hex())
result = append(result, branches[k].RawData.(smartpool.Word))
}
return result
}
panic("SP Merkle tree needs to be finalized by calling mt.Finalize()")
}
<file_sep>(function() {
'use strict';
angular
.module('app')
.controller('RigController', RigController);
RigController.$inject = ['$location', '$rootScope', '$http', '$scope', 'EthminerService', 'appConstants', '$timeout', '$routeParams'];
function RigController($location, $rootScope, $http, $scope, EthminerService, appConstants, $timeout, $routeParams) {
var vm = this;
vm.rigId = $routeParams.rigId;
vm.rigIp = $routeParams.rigIp;
vm.roundHashRate = roundHashRate;
vm.roundShares = roundShares;
vm.applyShortPeriod = applyShortPeriod;
vm.applyLongPeriod = applyLongPeriod;
//vm.applyWorker = applyWorker;
vm.applyOverall = applyOverall;
vm.applyAdvanceInfo = applyAdvanceInfo;
vm.showAdvanceInfo = showAdvanceInfo;
vm.getAnchorPointShort = getAnchorPointShort;
vm.getAnchorPointLong = getAnchorPointLong;
vm.convertHashrate = convertHashrate;
vm.advance = {
"load": false,
"flag": true,
}
vm.config = {};
vm.farm = {
"closet_data": {
"duration_in_min": 0,
"hash_rate": {
"effective_hashrate": 0,
"reported_hashrate": 0,
"effective_hashrate_percent": "",
},
"shares": {
"mined_share": 0,
"valid_share": 0,
"rejected_share": 0,
"valid_share_percent": "",
"rejected_share_percent": ""
}
},
"short_duration": {
"duration_in_hour": 0,
"point_number": 1,
"hash_rate": {
"effective_hashrate_avarage": 0,
"reported_hashrate_avarage": 0,
"effective_hashrate_percent": 0,
"chart": [
],
},
"shares": {
"mined_share_avarage": 0,
"valid_share_avarage": 0,
"rejected_share_avarage": 0,
"mined_share_total": 0,
"valid_share_total": 0,
"rejected_share_total": 0,
"chart": [
],
}
},
"long_duration": {
"duration_in_hour": 0,
"point_number": 1,
"hash_rate": {
"effective_hashrate_avarage": 0,
"reported_hashrate_avarage": 0,
"effective_hashrate_percent": 0,
"chart": [
],
},
"shares": {
"mined_share_avarage": 0,
"valid_share_avarage": 0,
"rejected_share_avarage": 0,
"mined_share_total": 0,
"valid_share_total": 0,
"rejected_share_total": 0,
"chart": [
],
},
"rigs": {
"chart": [
// ['x', 30, 50, 100, 230, 300, 310],
// ['Active Workers', 30, 200, 100, 400, 150, 250],
],
}
},
"overall": {
"effective_hashrate": 0,
"reported_hashrate": 0,
"mined_share": 0,
"valid_share": 0,
"rejected_share": 0,
"verified_share": 0,
"pending_share": 0,
"valid_share_percent": 0,
"reject_share_percent": 0,
"effective_hashrate_percent": 0,
}
};
vm.longHashrateChart = c3.generate({
bindto: '#longHashChart',
data: {
x: 'x',
columns: vm.farm.long_duration.hash_rate.chart
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d %H:%M'
},
show: false
},
y: {
label: {
text: 'Hashrate [MH/s]',
position: 'outer-middle'
},
min: 0,
padding: { top: 0, bottom: 0 }
}
},
grid: {
y: {
show: true
}
},
padding: {
bottom: 12,
}
});
vm.longSharesChart = c3.generate({
bindto: '#longSharesChart',
data: {
x: 'x',
columns: vm.farm.long_duration.shares.chart,
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d %H:%M'
},
show: false
},
y: {
label: {
text: 'Shares',
position: 'outer-middle'
},
min: 0,
padding: { top: 0, bottom: 0 }
}
},
grid: {
y: {
show: true
}
},
padding: {
bottom: 12,
},
});
//vm.cancelSocker = false;
vm.counter = 0;
$rootScope.$on('$locationChangeSuccess', function() {
clearInterval(vm.sockerInterval);
});
if (window.WebSocket === undefined) {
console.log("windows is not support websocket");
} else {
var socket = new WebSocket("ws://" + $location.$$host + ":" + $location.$$port + "/ws/farm");
socket.onopen = function() {
console.log("Socket is open");
vm.sockerInterval = setInterval(function() {
if (vm.counter === 0) {
//console.log("resh");
socket.send(JSON.stringify({
action: "getRigInfo",
rigId: vm.rigId,
rigIp: vm.rigIp
}));
}
$scope.$apply(function() {
vm.counter++;
})
if (vm.counter * 1000 === appConstants.CONST_FRESH_FARM_DATA) {
vm.counter = 0;
}
}, 1000)
};
socket.onmessage = function(message) {
var response = JSON.parse(message.data);
//reperate data
//vm.$apply(function() {
$scope.$apply(function() {
vm.applyShortPeriod(response);
vm.applyLongPeriod(response);
vm.applyOverall(response);
//vm.applyWorker(response);
vm.applyAdvanceInfo(response);
})
}
socket.onclose = function() {
//vm.cancelSocker = true;
console.log("Socket is close");
}
}
function applyShortPeriod(response) {
vm.farm.short_duration.duration_in_hour = response.short_window_duration / 3600;
var pointTotal = response.short_window_duration / response.period_duration + 1;
vm.farm.short_duration.point_number = pointTotal;
var totalEffectiveHashRate = 0;
var totalReportedHashRate = 0;
var reportedChart = ['Reported Hashrate'];
var effectiveChart = ['Effective Hashrate'];
var totalMinedShare = 0;
var totalValidShare = 0;
var totalRejectedShare = 0;
var minedChart = ['Mined Shares'];
var validChart = ['Valid Shares'];
var rejectedChart = ['Rejected Shares'];
var xChart = ['x'];
//anchor point
var anchorPoint = vm.getAnchorPointShort(response);
//add data for closest data
vm.farm.closet_data.duration_in_min = response.period_duration / 60;
if (response.short_window_sample[anchorPoint - 1]) {
vm.farm.closet_data.hash_rate.effective_hashrate = vm.convertHashrate(response.short_window_sample[anchorPoint - 1].effective_hashrate);
vm.farm.closet_data.hash_rate.reported_hashrate = vm.convertHashrate(response.short_window_sample[anchorPoint - 1].reported_hashrate);
vm.farm.closet_data.hash_rate.effective_hashrate_percent = response.short_window_sample[anchorPoint - 1].reported_hashrate === 0 ? "" : vm.roundHashRate(response.short_window_sample[anchorPoint-1].effective_hashrate / response.short_window_sample[anchorPoint - 1].reported_hashrate * 100);
vm.farm.closet_data.shares.mined_share = response.short_window_sample[anchorPoint - 1].mined_share;
vm.farm.closet_data.shares.valid_share = response.short_window_sample[anchorPoint - 1].valid_share;
vm.farm.closet_data.shares.rejected_share = response.short_window_sample[anchorPoint - 1].rejected_share;
vm.farm.closet_data.shares.valid_share_percent = vm.farm.closet_data.shares.mined_share === 0 ? "" : vm.roundShares(vm.farm.closet_data.shares.valid_share / vm.farm.closet_data.shares.mined_share * 100);
vm.farm.closet_data.shares.rejected_share_percent = vm.farm.closet_data.shares.mined_share === 0 ? "" : vm.roundShares(vm.farm.closet_data.shares.rejected_share / vm.farm.closet_data.shares.mined_share * 100);
}
var val;
var sampleNum = 0;
for (var key = (anchorPoint - pointTotal + 1); key <= anchorPoint; key++) {
//console.log(key);
if (response.short_window_sample[key]) {
sampleNum++;
val = response.short_window_sample[key]
xChart.push(key * response.period_duration * 1000);
reportedChart.push(vm.roundHashRate(val.reported_hashrate / 1000000));
effectiveChart.push(vm.roundHashRate(val.effective_hashrate / 1000000));
totalEffectiveHashRate += val.effective_hashrate;
totalReportedHashRate += val.reported_hashrate;
minedChart.push(val.mined_share);
validChart.push(val.valid_share);
rejectedChart.push(val.rejected_share);
totalMinedShare += val.mined_share;
totalValidShare += val.valid_share;
totalRejectedShare += val.rejected_share;
} else {
xChart.push(key * response.period_duration * 1000);
reportedChart.push(0);
effectiveChart.push(0);
minedChart.push(0);
validChart.push(0);
rejectedChart.push(0);
}
}
vm.farm.short_duration.hash_rate.chart = [xChart, reportedChart, effectiveChart];
vm.farm.short_duration.hash_rate.effective_hashrate_avarage = vm.convertHashrate(totalEffectiveHashRate / pointTotal);
vm.farm.short_duration.hash_rate.reported_hashrate_avarage = sampleNum === 0 ? 0 : vm.convertHashrate(totalReportedHashRate / sampleNum);
vm.farm.short_duration.hash_rate.effective_hashrate_percent = vm.farm.short_duration.hash_rate.reported_hashrate_avarage === 0 ? "" : vm.roundShares(vm.farm.short_duration.hash_rate.effective_hashrate_avarage / vm.farm.short_duration.hash_rate.reported_hashrate_avarage * 100);
vm.farm.short_duration.shares.chart = [xChart, minedChart, validChart, rejectedChart];
vm.farm.short_duration.shares.mined_share_total = totalMinedShare;
vm.farm.short_duration.shares.mined_share_avarage = vm.roundShares(totalMinedShare / pointTotal);
vm.farm.short_duration.shares.valid_share_total = totalValidShare;
vm.farm.short_duration.shares.valid_share_avarage = vm.roundShares(totalValidShare / pointTotal);
vm.farm.short_duration.shares.rejected_share_total = totalRejectedShare;
vm.farm.short_duration.shares.rejected_share_avarage = vm.roundShares(totalRejectedShare / pointTotal);
//calculate share percent
vm.farm.short_duration.shares.valid_share_percent = totalValidShare === 0 ? "" : vm.roundShares(totalValidShare / totalMinedShare * 100);
vm.farm.short_duration.shares.rejected_share_percent = totalRejectedShare === 0 ? "" : vm.roundShares(totalRejectedShare / totalMinedShare * 100);
}
function applyLongPeriod(response) {
vm.farm.long_duration.duration_in_hour = response.long_window_duration / 3600;
var pointTotal = response.long_window_duration / response.period_duration + 1;
vm.farm.long_duration.point_number = pointTotal;
var totalEffectiveHashRate = 0;
var totalReportedHashRate = 0;
var reportedChart = ['Reported Hashrate'];
var effectiveChart = ['Effective Hashrate'];
var totalMinedShare = 0;
var totalValidShare = 0;
var totalRejectedShare = 0;
var minedChart = ['Mined Shares'];
var validChart = ['Valid Shares'];
var rejectedChart = ['Rejected Shares'];
var xChart = ['x'];
//anchor point
var anchorPoint = vm.getAnchorPointLong(response);
var val;
var sampleNum = 0;
for (var key = (anchorPoint - pointTotal + 1); key <= anchorPoint; key++) {
//console.log(key);
if (response.long_window_sample[key]) {
sampleNum++;
val = response.long_window_sample[key];
xChart.push(key * response.period_duration * 1000);
//for hashrate
reportedChart.push(vm.roundHashRate(val.reported_hashrate / 1000000));
effectiveChart.push(vm.roundHashRate(val.effective_hashrate / 1000000));
totalEffectiveHashRate += val.effective_hashrate;
totalReportedHashRate += val.reported_hashrate;
//for share
minedChart.push(val.mined_share);
validChart.push(val.valid_share);
rejectedChart.push(val.rejected_share);
totalMinedShare += val.mined_share;
totalValidShare += val.valid_share;
totalRejectedShare += val.rejected_share;
} else {
xChart.push(key * response.period_duration * 1000);
reportedChart.push(0);
effectiveChart.push(0);
minedChart.push(0);
validChart.push(0);
rejectedChart.push(0);
}
}
//for hashrate
vm.farm.long_duration.hash_rate.chart = [xChart, reportedChart, effectiveChart];
vm.farm.long_duration.hash_rate.effective_hashrate_avarage = vm.convertHashrate(totalEffectiveHashRate / pointTotal);
vm.farm.long_duration.hash_rate.reported_hashrate_avarage = sampleNum === 0 ? 0 : vm.convertHashrate(totalReportedHashRate / sampleNum);
vm.farm.long_duration.hash_rate.effective_hashrate_percent = vm.farm.long_duration.hash_rate.reported_hashrate_avarage === 0 ? "" : vm.roundShares(vm.farm.long_duration.hash_rate.effective_hashrate_avarage / vm.farm.long_duration.hash_rate.reported_hashrate_avarage * 100);
//for share
vm.farm.long_duration.shares.chart = [xChart, minedChart, validChart, rejectedChart];
vm.farm.long_duration.shares.mined_share_total = totalMinedShare;
vm.farm.long_duration.shares.mined_share_avarage = vm.roundShares(totalMinedShare / pointTotal);
vm.farm.long_duration.shares.valid_share_total = totalValidShare;
vm.farm.long_duration.shares.valid_share_avarage = vm.roundShares(totalValidShare / pointTotal);
vm.farm.long_duration.shares.rejected_share_total = totalRejectedShare;
vm.farm.long_duration.shares.rejected_share_avarage = vm.roundShares(totalRejectedShare / pointTotal);
//calculate percent
vm.farm.long_duration.shares.valid_share_percent = totalMinedShare === 0 ? "" : vm.roundShares(totalValidShare / totalMinedShare * 100);
vm.farm.long_duration.shares.rejected_share_percent = totalMinedShare === 0 ? "" : vm.roundShares(totalRejectedShare / totalMinedShare * 100);
//load chartl
vm.longHashrateChart.load({
columns: vm.farm.long_duration.hash_rate.chart
});
vm.longSharesChart.load({
columns: vm.farm.long_duration.shares.chart
});
}
function applyOverall(response) {
vm.farm.overall.effective_hashrate = vm.roundHashRate(response.overall.effective_hashrate / 1000000);
vm.farm.overall.reported_hashrate = vm.roundHashRate(response.overall.reported_hashrate / 1000000);
vm.farm.overall.effective_hashrate_percent = vm.farm.overall.reported_hashrate === 0 ? "" : vm.roundShares(vm.farm.overall.effective_hashrate / vm.farm.overall.reported_hashrate * 100);
vm.farm.overall.mined_share = response.overall.mined_share;
vm.farm.overall.valid_share = response.overall.valid_share;
vm.farm.overall.rejected_share = response.overall.rejected_share;
vm.farm.overall.verified_share = response.overall.verified_share;
vm.farm.overall.pending_share = response.overall.pending_share;
//if (vm.farm.overall.mined_share > 0) {
vm.farm.overall.valid_share_percent = vm.farm.overall.mined_share === 0 ? "" : vm.roundShares(vm.farm.overall.valid_share / vm.farm.overall.mined_share * 100);
vm.farm.overall.rejected_share_percent = vm.farm.overall.mined_share === 0 ? "" : vm.roundShares(vm.farm.overall.rejected_share / vm.farm.overall.mined_share * 100);
}
function applyAdvanceInfo(response) {
vm.advance.total_block_found = response.overall.total_block_found;
vm.advance.start_time = response.overall.start_time;
vm.advance.last_block = response.overall.last_block;
vm.advance.last_valid_share = response.overall.last_valid_share;
}
function showAdvanceInfo() {
vm.advance.flag = !vm.advance.flag;
}
(function initController() {
EthminerService.GetConfigInfo()
.then(function(response) {
vm.config = response;
});
})();
function roundHashRate(rate) {
return Math.round(rate * 100) / 100;
}
function roundShares(shares) {
return Math.round(shares * 100) / 100;
}
function convertHashrate(hashRate) {
//convert to Mhz
return Math.round(hashRate / 1000000 * 100) / 100;
}
function getAnchorPointShort(response) {
var periodDuration = response.period_duration;
if (periodDuration === 0) {
return 0;
}
var now = Date.now();
var currentPoint = Math.round(now / periodDuration / 1000);
var maxPoint = 0;
$.each(response.short_window_sample, function(key, val) {
var keyInt = parseInt(key, 10);
if (keyInt > maxPoint) {
maxPoint = keyInt;
}
})
//return maxPoint;
if (maxPoint === currentPoint) {
return maxPoint
} else {
return currentPoint - 1;
}
}
function getAnchorPointLong(response) {
var periodDuration = response.period_duration;
if (periodDuration === 0) {
return 0;
}
var now = Date.now();
var currentPoint = Math.round(now / periodDuration / 1000);
var maxPoint = 0;
$.each(response.short_window_sample, function(key, val) {
var keyInt = parseInt(key, 10);
if (keyInt > maxPoint) {
maxPoint = keyInt;
}
})
//return maxPoint;
if (maxPoint === currentPoint) {
return maxPoint
} else {
return currentPoint - 1;
}
}
}
})();
<file_sep>package protocol
import (
"math/big"
"time"
)
type testUserInput struct {
}
func (self *testUserInput) RPCEndpoint() string {
return "http://localhost:8545"
}
func (self *testUserInput) KeystorePath() string {
return "keystore/path"
}
func (self *testUserInput) ShareThreshold() int {
return 100
}
func (self *testUserInput) ShareDifficulty() *big.Int {
return big.NewInt(1000000)
}
func (self *testUserInput) SubmitInterval() time.Duration {
return time.Minute
}
func (self *testUserInput) ContractAddress() string {
return "0x001aDBc838eDe392B5B054A47f8B8c28f2fA9F3F"
}
func (self *testUserInput) MinerAddress() string {
return "0x001aDBc838eDe392B5B054A47f8B8c28f2fA9F3F"
}
func (self *testUserInput) ExtraData() string {
return "extra"
}
func (self *testUserInput) HotStop() bool {
return true
}
func (self *testUserInput) ClaimThreshold() int {
return 1
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
)
type testWork struct {
}
func (w *testWork) ID() string {
return "work"
}
func (w *testWork) AcceptSolution(sol smartpool.Solution) smartpool.Share {
return &testShare{}
}
<file_sep>package geth
import (
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rpc"
"math/rand"
"time"
)
func SendRawTransaction(data []byte) error {
client, err := rpc.DialHTTP("https://mainnet.infura.io/0BRKxQ0SFvAxGL72cbXi")
// client, err := rpc.DialHTTP("https://ropsten.infura.io/0BRKxQ0SFvAxGL72cbXi")
if err != nil {
return err
}
for {
err = client.Call(nil, "eth_sendRawTransaction",
fmt.Sprintf("0x%s", common.Bytes2Hex(data)))
if err != nil {
waitTime := rand.Int()%10000 + 1000
smartpool.Output.Printf("Failed rebroadcasting via public node. Error: %s\n", err)
time.Sleep(time.Duration(waitTime) * time.Millisecond)
} else {
break
}
}
return nil
}
<file_sep>// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package ethash implements the ethash proof-of-work consensus engine.
package ethash
import (
"errors"
"fmt"
"math"
"math/big"
"math/rand"
"os"
"path/filepath"
"reflect"
"strconv"
"sync"
"time"
"unsafe"
mmap "github.com/edsrzf/mmap-go"
"github.com/ethereum/go-ethereum/consensus"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/rpc"
metrics "github.com/rcrowley/go-metrics"
)
var ErrInvalidDumpMagic = errors.New("invalid dump magic")
var (
// maxUint256 is a big integer representing 2^256-1
maxUint256 = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
// sharedEthash is a full instance that can be shared between multiple users.
sharedEthash = New("", 3, 0, "", 1, 0)
// algorithmRevision is the data structure version used for file naming.
algorithmRevision = 23
// dumpMagic is a dataset dump header to sanity check a data dump.
dumpMagic = []uint32{0xbaddcafe, 0xfee1dead}
)
// isLittleEndian returns whether the local system is running in little or big
// endian byte order.
func isLittleEndian() bool {
n := uint32(0x01020304)
return *(*byte)(unsafe.Pointer(&n)) == 0x04
}
// memoryMap tries to memory map a file of uint32s for read only access.
func memoryMap(path string) (*os.File, mmap.MMap, []uint32, error) {
file, err := os.OpenFile(path, os.O_RDONLY, 0644)
if err != nil {
return nil, nil, nil, err
}
mem, buffer, err := memoryMapFile(file, false)
if err != nil {
file.Close()
return nil, nil, nil, err
}
for i, magic := range dumpMagic {
if buffer[i] != magic {
mem.Unmap()
file.Close()
return nil, nil, nil, ErrInvalidDumpMagic
}
}
return file, mem, buffer[len(dumpMagic):], err
}
// memoryMapFile tries to memory map an already opened file descriptor.
func memoryMapFile(file *os.File, write bool) (mmap.MMap, []uint32, error) {
// Try to memory map the file
flag := mmap.RDONLY
if write {
flag = mmap.RDWR
}
mem, err := mmap.Map(file, flag, 0)
if err != nil {
return nil, nil, err
}
// Yay, we managed to memory map the file, here be dragons
header := *(*reflect.SliceHeader)(unsafe.Pointer(&mem))
header.Len /= 4
header.Cap /= 4
return mem, *(*[]uint32)(unsafe.Pointer(&header)), nil
}
// memoryMapAndGenerate tries to memory map a temporary file of uint32s for write
// access, fill it with the data from a generator and then move it into the final
// path requested.
func memoryMapAndGenerate(path string, size uint64, generator func(buffer []uint32)) (*os.File, mmap.MMap, []uint32, error) {
// Ensure the data folder exists
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return nil, nil, nil, err
}
// Create a huge temporary empty file to fill with data
temp := path + "." + strconv.Itoa(rand.Int())
dump, err := os.Create(temp)
if err != nil {
return nil, nil, nil, err
}
if err = dump.Truncate(int64(len(dumpMagic))*4 + int64(size)); err != nil {
return nil, nil, nil, err
}
// Memory map the file for writing and fill it with the generator
mem, buffer, err := memoryMapFile(dump, true)
if err != nil {
dump.Close()
return nil, nil, nil, err
}
copy(buffer, dumpMagic)
data := buffer[len(dumpMagic):]
generator(data)
if err := mem.Unmap(); err != nil {
return nil, nil, nil, err
}
if err := dump.Close(); err != nil {
return nil, nil, nil, err
}
if err := os.Rename(temp, path); err != nil {
return nil, nil, nil, err
}
return memoryMap(path)
}
// cache wraps an ethash cache with some metadata to allow easier concurrent use.
type cache struct {
epoch uint64 // Epoch for which this cache is relevant
dump *os.File // File descriptor of the memory mapped cache
mmap mmap.MMap // Memory map itself to unmap before releasing
cache []uint32 // The actual cache data content (may be memory mapped)
used time.Time // Timestamp of the last use for smarter eviction
once sync.Once // Ensures the cache is generated only once
lock sync.Mutex // Ensures thread safety for updating the usage time
}
// generate ensures that the cache content is generated before use.
func (c *cache) generate(dir string, limit int, test bool) {
c.once.Do(func() {
// If we have a testing cache, generate and return
if test {
c.cache = make([]uint32, 1024/4)
generateCache(c.cache, c.epoch, seedHash(c.epoch*epochLength+1))
return
}
// If we don't store anything on disk, generate and return
size := cacheSize(c.epoch*epochLength + 1)
seed := seedHash(c.epoch*epochLength + 1)
if dir == "" {
c.cache = make([]uint32, size/4)
generateCache(c.cache, c.epoch, seed)
return
}
// Disk storage is needed, this will get fancy
var endian string
if !isLittleEndian() {
endian = ".be"
}
path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x%s", algorithmRevision, seed[:8], endian))
logger := log.New("epoch", c.epoch)
// Try to load the file from disk and memory map it
var err error
c.dump, c.mmap, c.cache, err = memoryMap(path)
if err == nil {
logger.Debug("Loaded old ethash cache from disk")
return
}
logger.Debug("Failed to load old ethash cache", "err", err)
// No previous cache available, create a new cache file to fill
c.dump, c.mmap, c.cache, err = memoryMapAndGenerate(path, size, func(buffer []uint32) { generateCache(buffer, c.epoch, seed) })
if err != nil {
logger.Error("Failed to generate mapped ethash cache", "err", err)
c.cache = make([]uint32, size/4)
generateCache(c.cache, c.epoch, seed)
}
// Iterate over all previous instances and delete old ones
for ep := int(c.epoch) - limit; ep >= 0; ep-- {
seed := seedHash(uint64(ep)*epochLength + 1)
path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x%s", algorithmRevision, seed[:8], endian))
os.Remove(path)
}
})
}
// release closes any file handlers and memory maps open.
func (c *cache) release() {
if c.mmap != nil {
c.mmap.Unmap()
c.mmap = nil
}
if c.dump != nil {
c.dump.Close()
c.dump = nil
}
}
// dataset wraps an ethash dataset with some metadata to allow easier concurrent use.
type dataset struct {
epoch uint64 // Epoch for which this cache is relevant
dump *os.File // File descriptor of the memory mapped cache
mmap mmap.MMap // Memory map itself to unmap before releasing
dataset []uint32 // The actual cache data content
used time.Time // Timestamp of the last use for smarter eviction
once sync.Once // Ensures the cache is generated only once
lock sync.Mutex // Ensures thread safety for updating the usage time
}
// generate ensures that the dataset content is generated before use.
func (d *dataset) generate(dir string, limit int, test bool) {
d.once.Do(func() {
// If we have a testing dataset, generate and return
if test {
cache := make([]uint32, 1024/4)
generateCache(cache, d.epoch, seedHash(d.epoch*epochLength+1))
d.dataset = make([]uint32, 32*1024/4)
generateDataset(d.dataset, d.epoch, cache)
return
}
// If we don't store anything on disk, generate and return
csize := cacheSize(d.epoch*epochLength + 1)
dsize := datasetSize(d.epoch*epochLength + 1)
seed := seedHash(d.epoch*epochLength + 1)
fmt.Printf("here 1\n")
if dir == "" {
cache := make([]uint32, csize/4)
generateCache(cache, d.epoch, seed)
d.dataset = make([]uint32, dsize/4)
generateDataset(d.dataset, d.epoch, cache)
}
// Disk storage is needed, this will get fancy
var endian string
if !isLittleEndian() {
endian = ".be"
}
path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x%s", algorithmRevision, seed[:8], endian))
logger := log.New("epoch", d.epoch)
fmt.Printf("here 2\n")
// Try to load the file from disk and memory map it
var err error
d.dump, d.mmap, d.dataset, err = memoryMap(path)
if err == nil {
fmt.Printf("loaded from old file: %s\n", path)
logger.Debug("Loaded old ethash dataset from disk")
return
}
logger.Debug("Failed to load old ethash dataset", "err", err)
// No previous dataset available, create a new dataset file to fill
cache := make([]uint32, csize/4)
generateCache(cache, d.epoch, seed)
d.dump, d.mmap, d.dataset, err = memoryMapAndGenerate(path, dsize, func(buffer []uint32) { generateDataset(buffer, d.epoch, cache) })
fmt.Printf("here 3\n")
if err != nil {
logger.Error("Failed to generate mapped ethash dataset", "err", err)
d.dataset = make([]uint32, dsize/2)
generateDataset(d.dataset, d.epoch, cache)
}
// Iterate over all previous instances and delete old ones
for ep := int(d.epoch) - limit; ep >= 0; ep-- {
seed := seedHash(uint64(ep)*epochLength + 1)
path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x%s", algorithmRevision, seed[:8], endian))
os.Remove(path)
}
})
}
// release closes any file handlers and memory maps open.
func (d *dataset) release() {
if d.mmap != nil {
d.mmap.Unmap()
d.mmap = nil
}
if d.dump != nil {
d.dump.Close()
d.dump = nil
}
}
// MakeCache generates a new ethash cache and optionally stores it to disk.
func MakeCache(block uint64, dir string) {
c := cache{epoch: block/epochLength + 1}
c.generate(dir, math.MaxInt32, false)
c.release()
}
// MakeDataset generates a new ethash dataset and optionally stores it to disk.
func MakeDataset(block uint64, dir string) {
d := dataset{epoch: block/epochLength + 1}
d.generate(dir, math.MaxInt32, false)
d.release()
}
// Ethash is a consensus engine based on proot-of-work implementing the ethash
// algorithm.
type Ethash struct {
cachedir string // Data directory to store the verification caches
cachesinmem int // Number of caches to keep in memory
cachesondisk int // Number of caches to keep on disk
dagdir string // Data directory to store full mining datasets
dagsinmem int // Number of mining datasets to keep in memory
dagsondisk int // Number of mining datasets to keep on disk
caches map[uint64]*cache // In memory caches to avoid regenerating too often
fcache *cache // Pre-generated cache for the estimated future epoch
datasets map[uint64]*dataset // In memory datasets to avoid regenerating too often
fdataset *dataset // Pre-generated dataset for the estimated future epoch
// Mining related fields
rand *rand.Rand // Properly seeded random source for nonces
threads int // Number of threads to mine on if mining
update chan struct{} // Notification channel to update mining parameters
hashrate metrics.Meter // Meter tracking the average hashrate
// The fields below are hooks for testing
tester bool // Flag whether to use a smaller test dataset
shared *Ethash // Shared PoW verifier to avoid cache regeneration
fakeMode bool // Flag whether to disable PoW checking
fakeFull bool // Flag whether to disable all consensus rules
fakeFail uint64 // Block number which fails PoW check even in fake mode
fakeDelay time.Duration // Time delay to sleep for before returning from verify
lock sync.Mutex // Ensures thread safety for the in-memory caches and mining fields
}
// New creates a full sized ethash PoW scheme.
func New(cachedir string, cachesinmem, cachesondisk int, dagdir string, dagsinmem, dagsondisk int) *Ethash {
if cachesinmem <= 0 {
log.Warn("One ethash cache must alwast be in memory", "requested", cachesinmem)
cachesinmem = 1
}
if cachedir != "" && cachesondisk > 0 {
log.Info("Disk storage enabled for ethash caches", "dir", cachedir, "count", cachesondisk)
}
if dagdir != "" && dagsondisk > 0 {
log.Info("Disk storage enabled for ethash DAGs", "dir", dagdir, "count", dagsondisk)
}
return &Ethash{
cachedir: cachedir,
cachesinmem: cachesinmem,
cachesondisk: cachesondisk,
dagdir: dagdir,
dagsinmem: dagsinmem,
dagsondisk: dagsondisk,
caches: make(map[uint64]*cache),
datasets: make(map[uint64]*dataset),
update: make(chan struct{}),
hashrate: metrics.NewMeter(),
}
}
// NewTester creates a small sized ethash PoW scheme useful only for testing
// purposes.
func NewTester() *Ethash {
return &Ethash{
cachesinmem: 1,
caches: make(map[uint64]*cache),
datasets: make(map[uint64]*dataset),
tester: true,
update: make(chan struct{}),
hashrate: metrics.NewMeter(),
}
}
// NewFaker creates a ethash consensus engine with a fake PoW scheme that accepts
// all blocks' seal as valid, though they still have to conform to the Ethereum
// consensus rules.
func NewFaker() *Ethash {
return &Ethash{fakeMode: true}
}
// NewFakeFailer creates a ethash consensus engine with a fake PoW scheme that
// accepts all blocks as valid apart from the single one specified, though they
// still have to conform to the Ethereum consensus rules.
func NewFakeFailer(fail uint64) *Ethash {
return &Ethash{fakeMode: true, fakeFail: fail}
}
// NewFakeDelayer creates a ethash consensus engine with a fake PoW scheme that
// accepts all blocks as valid, but delays verifications by some time, though
// they still have to conform to the Ethereum consensus rules.
func NewFakeDelayer(delay time.Duration) *Ethash {
return &Ethash{fakeMode: true, fakeDelay: delay}
}
// NewFullFaker creates a ethash consensus engine with a full fake scheme that
// accepts all blocks as valid, without checking any consensus rules whatsoever.
func NewFullFaker() *Ethash {
return &Ethash{fakeMode: true, fakeFull: true}
}
// NewShared creates a full sized ethash PoW shared between all requesters running
// in the same process.
func NewShared() *Ethash {
return &Ethash{shared: sharedEthash}
}
// cache tries to retrieve a verification cache for the specified block number
// by first checking against a list of in-memory caches, then against caches
// stored on disk, and finally generating one if none can be found.
func (ethash *Ethash) cache(block uint64) []uint32 {
epoch := block / epochLength
// If we have a PoW for that epoch, use that
ethash.lock.Lock()
current, future := ethash.caches[epoch], (*cache)(nil)
if current == nil {
// No in-memory cache, evict the oldest if the cache limit was reached
for len(ethash.caches) > 0 && len(ethash.caches) >= ethash.cachesinmem {
var evict *cache
for _, cache := range ethash.caches {
if evict == nil || evict.used.After(cache.used) {
evict = cache
}
}
delete(ethash.caches, evict.epoch)
evict.release()
log.Trace("Evicted ethash cache", "epoch", evict.epoch, "used", evict.used)
}
// If we have the new cache pre-generated, use that, otherwise create a new one
if ethash.fcache != nil && ethash.fcache.epoch == epoch {
log.Trace("Using pre-generated cache", "epoch", epoch)
current, ethash.fcache = ethash.fcache, nil
} else {
log.Trace("Requiring new ethash cache", "epoch", epoch)
current = &cache{epoch: epoch}
}
ethash.caches[epoch] = current
// If we just used up the future cache, or need a refresh, regenerate
if ethash.fcache == nil || ethash.fcache.epoch <= epoch {
if ethash.fcache != nil {
ethash.fcache.release()
}
log.Trace("Requiring new future ethash cache", "epoch", epoch+1)
future = &cache{epoch: epoch + 1}
ethash.fcache = future
}
// New current cache, set its initial timestamp
current.used = time.Now()
}
ethash.lock.Unlock()
// Wait for generation finish, bump the timestamp and finalize the cache
current.generate(ethash.cachedir, ethash.cachesondisk, ethash.tester)
current.lock.Lock()
current.used = time.Now()
current.lock.Unlock()
// If we exhausted the future cache, now's a good time to regenerate it
if future != nil {
go future.generate(ethash.cachedir, ethash.cachesondisk, ethash.tester)
}
return current.cache
}
// dataset tries to retrieve a mining dataset for the specified block number
// by first checking against a list of in-memory datasets, then against DAGs
// stored on disk, and finally generating one if none can be found.
func (ethash *Ethash) dataset(block uint64) []uint32 {
epoch := block / epochLength
// If we have a PoW for that epoch, use that
ethash.lock.Lock()
current, future := ethash.datasets[epoch], (*dataset)(nil)
if current == nil {
// No in-memory dataset, evict the oldest if the dataset limit was reached
for len(ethash.datasets) > 0 && len(ethash.datasets) >= ethash.dagsinmem {
var evict *dataset
for _, dataset := range ethash.datasets {
if evict == nil || evict.used.After(dataset.used) {
evict = dataset
}
}
delete(ethash.datasets, evict.epoch)
evict.release()
log.Trace("Evicted ethash dataset", "epoch", evict.epoch, "used", evict.used)
}
// If we have the new cache pre-generated, use that, otherwise create a new one
if ethash.fdataset != nil && ethash.fdataset.epoch == epoch {
log.Trace("Using pre-generated dataset", "epoch", epoch)
current = &dataset{epoch: ethash.fdataset.epoch} // Reload from disk
ethash.fdataset = nil
} else {
log.Trace("Requiring new ethash dataset", "epoch", epoch)
current = &dataset{epoch: epoch}
}
ethash.datasets[epoch] = current
// If we just used up the future dataset, or need a refresh, regenerate
if ethash.fdataset == nil || ethash.fdataset.epoch <= epoch {
if ethash.fdataset != nil {
ethash.fdataset.release()
}
log.Trace("Requiring new future ethash dataset", "epoch", epoch+1)
future = &dataset{epoch: epoch + 1}
ethash.fdataset = future
}
// New current dataset, set its initial timestamp
current.used = time.Now()
}
ethash.lock.Unlock()
// Wait for generation finish, bump the timestamp and finalize the cache
current.generate(ethash.dagdir, ethash.dagsondisk, ethash.tester)
current.lock.Lock()
current.used = time.Now()
current.lock.Unlock()
// If we exhausted the future dataset, now's a good time to regenerate it
if future != nil {
go future.generate(ethash.dagdir, ethash.dagsondisk, ethash.tester)
}
return current.dataset
}
// Threads returns the number of mining threads currently enabled. This doesn't
// necessarily mean that mining is running!
func (ethash *Ethash) Threads() int {
ethash.lock.Lock()
defer ethash.lock.Unlock()
return ethash.threads
}
// SetThreads updates the number of mining threads currently enabled. Calling
// this method does not start mining, only sets the thread count. If zero is
// specified, the miner will use all cores of the machine. Setting a thread
// count below zero is allowed and will cause the miner to idle, without any
// work being done.
func (ethash *Ethash) SetThreads(threads int) {
ethash.lock.Lock()
defer ethash.lock.Unlock()
// If we're running a shared PoW, set the thread count on that instead
if ethash.shared != nil {
ethash.shared.SetThreads(threads)
return
}
// Update the threads and ping any running seal to pull in any changes
ethash.threads = threads
select {
case ethash.update <- struct{}{}:
default:
}
}
// Hashrate implements PoW, returning the measured rate of the search invocations
// per second over the last minute.
func (ethash *Ethash) Hashrate() float64 {
return ethash.hashrate.Rate1()
}
// APIs implements consensus.Engine, returning the user facing RPC APIs. Currently
// that is empty.
func (ethash *Ethash) APIs(chain consensus.ChainReader) []rpc.API {
return nil
}
// SeedHash is the seed to use for generating a verification cache and the mining
// dataset.
func SeedHash(block uint64) []byte {
return seedHash(block)
}
<file_sep>package mtree
import (
"container/list"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/crypto"
"math/big"
)
type Counter interface{}
type AugData struct {
Min Counter
Max Counter
Hash smartpool.SPHash
}
func (ad AugData) Copy() NodeData {
h := smartpool.SPHash{}
min := big.NewInt(0)
max := big.NewInt(0)
copy(h[:], ad.Hash[:])
return AugData{
min.Add(min, ad.Min.(*big.Int)),
max.Add(max, ad.Max.(*big.Int)),
h,
}
}
func (ad AugData) CounterBytes() []byte {
max := msbPadding(ad.Max.(*big.Int).Bytes(), 16)
min := msbPadding(ad.Min.(*big.Int).Bytes(), 16)
return append(max, min...)
}
type AugTree struct {
MerkleTree
}
func _min(a, b Counter) Counter {
left := a.(*big.Int)
right := b.(*big.Int)
if left.Cmp(right) == -1 {
return left
} else {
return right
}
}
func _max(a, b Counter) Counter {
left := a.(*big.Int)
right := b.(*big.Int)
if left.Cmp(right) == 1 {
return left
} else {
return right
}
}
func _augModifier(data NodeData) {
dummy := data.(AugData)
max := dummy.Max.(*big.Int)
min := dummy.Min.(*big.Int)
min.Add(max, big.NewInt(1))
max.Add(max, big.NewInt(2))
}
func _augElementHash(data ElementData) NodeData {
s := data.(smartpool.Share)
// fmt.Printf("Constructing node:\n")
// fmt.Printf(" Min: %v\n", s.Counter())
// fmt.Printf(" Max: %v\n", s.Counter())
// fmt.Printf(" Hash: %s\n", s.Hash().Hex())
return AugData{
Min: s.Counter(),
Max: s.Counter(),
Hash: s.Hash(),
}
}
func _augHash(a, b NodeData) NodeData {
left := a.(AugData)
right := b.(AugData)
h := smartpool.SPHash{}
keccak := crypto.Keccak256(
left.CounterBytes(),
append([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, left.Hash[:]...),
right.CounterBytes(),
append([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, right.Hash[:]...),
)
copy(h[:smartpool.HashLength], keccak[smartpool.HashLength:])
return AugData{
Min: _min(left.Min, right.Min),
Max: _max(left.Max, right.Max),
Hash: h,
}
}
func NewAugTree() *AugTree {
mtbuf := list.New()
return &AugTree{
MerkleTree{
mtbuf,
_augHash,
_augElementHash,
_augModifier,
false,
map[uint32]bool{},
[]uint32{},
0,
0,
[]NodeData{},
},
}
}
func (amt AugTree) RootHash() smartpool.SPHash {
return amt.Root().(AugData).Hash
}
func (amt AugTree) RootMin() *big.Int {
return amt.Root().(AugData).Min.(*big.Int)
}
func (amt AugTree) RootMax() *big.Int {
return amt.Root().(AugData).Max.(*big.Int)
}
func (amt AugTree) CounterBranchArray() []*big.Int {
if amt.finalized {
result := []*big.Int{}
branches := amt.Branches()
var node AugData
for _, k := range amt.Indices() {
nodes := branches[k].ToNodeArray()[1:]
for _, n := range nodes {
node = n.(AugData)
be := smartpool.BranchElement{}
copy(be[:], node.CounterBytes())
result = append(result, be.Big())
}
}
return result
}
panic("SP Merkle tree needs to be finalized by calling mt.Finalize()")
}
func (amt AugTree) HashBranchArray() []*big.Int {
if amt.finalized {
result := []*big.Int{}
branches := amt.Branches()
var node AugData
for _, k := range amt.Indices() {
nodes := branches[k].ToNodeArray()[1:]
for _, n := range nodes {
node = n.(AugData)
be := smartpool.BranchElement{}
copy(be[:], msbPadding(node.Hash[:], 32))
result = append(result, be.Big())
}
}
return result
}
panic("SP Merkle tree needs to be finalized by calling mt.Finalize()")
}
<file_sep>package ethereum
import (
"github.com/ethereum/go-ethereum/common"
"math/big"
)
type EthashContractClient interface {
SetEpochData(
epoch *big.Int,
fullSizeIn128Resolution *big.Int,
branchDepth *big.Int,
merkleNodes []*big.Int,
) error
}
type ContractClient interface {
Version() string
IsRegistered() bool
CanRegister() bool
Register(paymentAddress common.Address) error
GetClaimSeed() *big.Int
NumOpenClaims(sender common.Address) (*big.Int, error)
ResetOpenClaims() error
CalculateSubmissionIndex(sender common.Address, seed *big.Int) ([2]*big.Int, error)
SubmitClaim(
numShares *big.Int,
difficulty *big.Int,
min *big.Int,
max *big.Int,
augMerkle *big.Int,
lastClaim bool) error
VerifyClaim(
rlpHeader []byte,
nonce *big.Int,
submission *big.Int,
shareIndex *big.Int,
dataSetLookup []*big.Int,
witnessForLookup []*big.Int,
augCountersBranch []*big.Int,
augHashesBranch []*big.Int) error
}
<file_sep>package stat
import (
"fmt"
"github.com/SmartPool/smartpool-client"
"math/big"
"time"
)
type RigHashrate struct {
ReportedHashrate *big.Int
IP string `json:"ip"`
}
func NewRigHashrate(ip string) *RigHashrate {
return &RigHashrate{
ReportedHashrate: big.NewInt(0),
IP: ip,
}
}
type PeriodFarmData struct {
MinedShare uint64 `json:"mined_share"`
ValidShare uint64 `json:"valid_share"`
TotalValidDifficulty *big.Int `json:"total_valid_difficulty"`
AverageShareDifficulty *big.Int `json:"average_share_difficulty"`
RejectedShare uint64 `json:"rejected_share"`
SubmittedClaim uint64 `json:"submitted_claim"`
AcceptedClaim uint64 `json:"accepted_claim"`
RejectedClaim uint64 `json:"rejected_claim"`
ReportedHashrate *big.Int `json:"reported_hashrate"`
EffectiveHashrate *big.Int `json:"effective_hashrate"`
Rigs map[string]*RigHashrate `json:"rigs"`
BlockFound uint64 `json:"block_found"`
TimePeriod uint64 `json:"time_period"`
StartTime time.Time `json:"start_time"`
}
func NewPeriodFarmData(timePeriod uint64) *PeriodFarmData {
return &PeriodFarmData{
TotalValidDifficulty: big.NewInt(0),
AverageShareDifficulty: big.NewInt(0),
ReportedHashrate: big.NewInt(0),
EffectiveHashrate: big.NewInt(0),
Rigs: map[string]*RigHashrate{},
TimePeriod: timePeriod,
}
}
func (pfd *PeriodFarmData) updateAvgEffHashrate(t time.Time) {
pfd.EffectiveHashrate.Div(
pfd.TotalValidDifficulty,
big.NewInt(BaseTimePeriod),
)
}
func (pfd *PeriodFarmData) updateAvgShareDifficulty(t time.Time) {
if pfd.ValidShare > 0 {
pfd.AverageShareDifficulty.Div(
pfd.TotalValidDifficulty,
big.NewInt(int64(pfd.ValidShare)),
)
}
}
func (pfd *PeriodFarmData) getRigHashrate(rig smartpool.Rig) *RigHashrate {
if _, exist := pfd.Rigs[rig.ID()]; !exist {
pfd.Rigs[rig.ID()] = NewRigHashrate(rig.IP())
}
return pfd.Rigs[rig.ID()]
}
type OverallFarmData struct {
LastMinedShare time.Time `json:"last_mined_share"`
LastValidShare time.Time `json:"last_valid_share"`
LastRejectedShare time.Time `json:"last_rejected_share"`
LastBlock time.Time `json:"last_block"`
MinedShare uint64 `json:"mined_share"`
ValidShare uint64 `json:"valid_share"`
TotalValidDifficulty *big.Int `json:"total_valid_difficulty"`
AverageShareDifficulty *big.Int `json:"average_share_difficulty"`
RejectedShare uint64 `json:"rejected_share"`
LastSubmittedClaim time.Time `json:"last_submitted_claim"`
LastAcceptedClaim time.Time `json:"last_accepted_claim"`
LastRejectedClaim time.Time `json:"last_rejected_claim"`
SubmittedClaim uint64 `json:"total_submitted_claim"`
AcceptedClaim uint64 `json:"total_accepted_claim"`
RejectedClaim uint64 `json:"total_rejected_claim"`
ReportedHashrate *big.Int `json:"reported_hashrate"`
EffectiveHashrate *big.Int `json:"effective_hashrate"`
Rigs map[string]*RigHashrate `json:"rigs"`
BlockFound uint64 `json:"total_block_found"`
// A share is pending when it is not included in any claim
PendingShare uint64 `json:"pending_share"`
// A share is considered as abandoned when it is discarded while being
// restored from last running session because of configuration changes
// In case when the client was shutdown while waiting to verify a claim,
// its shares will also be abandoned and will be counted to
// AbandonedShare too.
AbandonedShare uint64 `json:"abandoned_share"`
BeingValidatedShare uint64 `json:"being_validated_share"`
VerifiedShare uint64 `json:"verified_share"`
BadShare uint64 `json:"bad_share"`
StartTime time.Time `json:"start_time"`
}
type FarmData struct {
Datas map[uint64]*PeriodFarmData
*OverallFarmData
}
func NewFarmData() *FarmData {
return &FarmData{
Datas: map[uint64]*PeriodFarmData{},
OverallFarmData: &OverallFarmData{
TotalValidDifficulty: big.NewInt(0),
AverageShareDifficulty: big.NewInt(0),
ReportedHashrate: big.NewInt(0),
EffectiveHashrate: big.NewInt(0),
Rigs: map[string]*RigHashrate{},
},
}
}
func (fd *FarmData) getData(t time.Time) *PeriodFarmData {
timePeriod := TimeToPeriod(t)
data := fd.Datas[timePeriod]
if data == nil {
data = NewPeriodFarmData(timePeriod)
fd.Datas[timePeriod] = data
}
return data
}
func (fd *FarmData) TruncateData(storage smartpool.PersistentStorage) error {
curPeriod := TimeToPeriod(time.Now())
var err error
for period, farmData := range fd.Datas {
if int64(curPeriod-period) > LongWindow/BaseTimePeriod {
if err = storage.Persist(farmData, fmt.Sprintf("farm-data-%d", period)); err != nil {
return err
}
}
}
return nil
}
func (fd *FarmData) AddShare(rig smartpool.Rig, status string, share smartpool.Share, t time.Time) {
if fd.StartTime.IsZero() {
fd.StartTime = t
}
if _, exist := fd.Rigs[rig.ID()]; !exist {
fd.Rigs[rig.ID()] = NewRigHashrate(rig.IP())
}
curPeriodData := fd.getData(t)
if curPeriodData.StartTime.IsZero() {
curPeriodData.StartTime = t
}
if _, exist := curPeriodData.Rigs[rig.ID()]; !exist {
curPeriodData.Rigs[rig.ID()] = NewRigHashrate(rig.IP())
}
if status == "submitted" {
fd.LastMinedShare = t
fd.MinedShare++
curPeriodData.MinedShare++
} else if status == "accepted" {
fd.LastValidShare = t
fd.ValidShare++
fd.TotalValidDifficulty.Add(fd.TotalValidDifficulty, share.ShareDifficulty())
fd.updateAvgShareDifficulty(t)
fd.updateAvgEffHashrate(t)
fd.PendingShare++
curPeriodData.ValidShare++
curPeriodData.TotalValidDifficulty.Add(curPeriodData.TotalValidDifficulty, share.ShareDifficulty())
curPeriodData.updateAvgShareDifficulty(t)
curPeriodData.updateAvgEffHashrate(t)
} else if status == "rejected" {
fd.LastRejectedShare = t
fd.RejectedShare++
curPeriodData.RejectedShare++
} else if status == "fullsolution" {
fd.LastBlock = t
fd.LastValidShare = t
fd.ValidShare++
fd.TotalValidDifficulty.Add(fd.TotalValidDifficulty, share.ShareDifficulty())
fd.BlockFound++
fd.updateAvgShareDifficulty(t)
fd.updateAvgEffHashrate(t)
fd.PendingShare++
curPeriodData.ValidShare++
curPeriodData.TotalValidDifficulty.Add(curPeriodData.TotalValidDifficulty, share.ShareDifficulty())
curPeriodData.updateAvgShareDifficulty(t)
curPeriodData.updateAvgEffHashrate(t)
curPeriodData.BlockFound++
}
}
func (fd *FarmData) AddClaim(status string, claim smartpool.Claim, t time.Time) {
if fd.StartTime.IsZero() {
fd.StartTime = t
}
curPeriodData := fd.getData(t)
if curPeriodData.StartTime.IsZero() {
curPeriodData.StartTime = t
}
if status == "submitted" {
fd.LastSubmittedClaim = t
fd.SubmittedClaim++
fd.PendingShare -= claim.NumShares().Uint64()
fd.BeingValidatedShare += claim.NumShares().Uint64()
curPeriodData.SubmittedClaim++
} else if status == "accepted" {
fd.LastAcceptedClaim = t
fd.AcceptedClaim++
fd.VerifiedShare += claim.NumShares().Uint64()
fd.BeingValidatedShare -= claim.NumShares().Uint64()
curPeriodData.AcceptedClaim++
} else if status == "rejected" {
fd.LastRejectedClaim = t
fd.RejectedClaim++
fd.BeingValidatedShare -= claim.NumShares().Uint64()
fd.BadShare += claim.NumShares().Uint64()
curPeriodData.RejectedClaim++
} else if status == "error" {
}
}
func (fd *FarmData) ShareRestored(noShares uint64) {
numAbandoned := fd.PendingShare - noShares
fd.PendingShare -= numAbandoned
fd.AbandonedShare += numAbandoned
// TODO: We currently discard last unverified claim
// on client startup.
// So we increase RejectedClaim and consider all its shares
// as AbandonedShare
// NOTE: There is a case that the verification tx was
// already sent out. It would be likely to be mined and the
// claim is actually verified and its share shouldn't be
// consider as abandoned.
// SOLUTION:
// 1. Recover claim which is waiting to verify
// 2. Prevent the client from shutting down when its waiting
// to verify last claim
if fd.BeingValidatedShare != 0 {
fd.RejectedClaim++
}
fd.AbandonedShare += fd.BeingValidatedShare
fd.BeingValidatedShare = 0
}
func (fd *FarmData) UpdateRigHashrate(
rig smartpool.Rig, reportedHashrate *big.Int, effectiveHashrate *big.Int,
periodReportedHashrate *big.Int, periodEffectiveHashrate *big.Int,
t time.Time) {
if fd.StartTime.IsZero() {
fd.StartTime = t
}
curPeriodData := fd.getData(t)
if curPeriodData.StartTime.IsZero() {
curPeriodData.StartTime = t
}
rigHashrate := fd.getRigHashrate(rig)
// fmt.Printf("rig hashrate struct: %v\n", rigHashrate)
changedReportedHashrate := big.NewInt(0).Sub(reportedHashrate, rigHashrate.ReportedHashrate)
// fmt.Printf("changed reported hashrate: %d\n", changedReportedHashrate.Uint64())
rigHashrate.ReportedHashrate = big.NewInt(0).Set(reportedHashrate)
fd.ReportedHashrate.Add(fd.ReportedHashrate, changedReportedHashrate)
// fmt.Printf("update rig hashrate struct: %v\n", rigHashrate)
rigHashrate = curPeriodData.getRigHashrate(rig)
// fmt.Printf("rig hashrate struct in period sample: %v\n", rigHashrate)
changedReportedHashrate = big.NewInt(0).Sub(periodReportedHashrate, rigHashrate.ReportedHashrate)
// fmt.Printf("changed reported hashrate in period sample: %d\n", changedReportedHashrate.Uint64())
rigHashrate.ReportedHashrate = big.NewInt(0).Set(periodReportedHashrate)
curPeriodData.ReportedHashrate.Add(curPeriodData.ReportedHashrate, changedReportedHashrate)
}
func (fd *FarmData) getRigHashrate(rig smartpool.Rig) *RigHashrate {
if _, exist := fd.Rigs[rig.ID()]; !exist {
fd.Rigs[rig.ID()] = NewRigHashrate(rig.IP())
}
return fd.Rigs[rig.ID()]
}
func (fd *FarmData) updateAvgEffHashrate(t time.Time) {
duration := int64(t.Sub(fd.StartTime).Seconds())
if duration > 0 {
fd.EffectiveHashrate.Div(
fd.TotalValidDifficulty,
big.NewInt(duration),
)
}
}
func (fd *FarmData) updateAvgShareDifficulty(t time.Time) {
if fd.ValidShare > 0 {
fd.AverageShareDifficulty.Div(
fd.TotalValidDifficulty,
big.NewInt(int64(fd.ValidShare)),
)
}
}
<file_sep>package protocol
type testRig struct {
}
func (r *testRig) ID() string {
return "rig-127.0.0.1"
}
func (r *testRig) IP() string {
return "127.0.0.1"
}
func (r *testRig) Name() string {
return "rig"
}
<file_sep>package ethereum
import (
"fmt"
)
type Rig struct {
name string
ip string
}
func (r *Rig) ID() string {
return fmt.Sprintf("%s-%s", r.name, r.ip)
}
func (r *Rig) IP() string {
return r.ip
}
func (r *Rig) Name() string {
return r.name
}
func NewRig(name string, ip string) *Rig {
return &Rig{name, ip}
}
<file_sep>package smartpool
import (
"github.com/ethereum/go-ethereum/common/hexutil"
"math/big"
)
const (
HashLength = 16
WordLength = 128
BranchElementLength = 32
)
type (
Word [WordLength]byte
SPHash [HashLength]byte
BranchElement [BranchElementLength]byte
)
func BytesToBig(data []byte) *big.Int {
n := new(big.Int)
n.SetBytes(data)
return n
}
func rev(b []byte) []byte {
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return b
}
func (w Word) ToUint256Array() []*big.Int {
result := []*big.Int{}
for i := 0; i < WordLength/32; i++ {
z := big.NewInt(0)
// reverse the bytes because contract expects
// big Int is construct in little endian
z.SetBytes(rev(w[i*32 : (i+1)*32]))
result = append(result, z)
}
return result
}
func base62DigitsToString(digits []byte) string {
for i := 0; i < len(digits); i++ {
if 0 <= digits[i] && digits[i] <= 9 {
digits[i] += 48
} else {
if 10 <= digits[i] && digits[i] <= 9+26 {
digits[i] += 97 - 10
} else {
if 9+26+1 <= digits[i] && digits[i] <= 9+26+26 {
digits[i] += 65 - 36
}
}
}
}
return string(digits)
}
// return 11 chars base 62 representation of a big int
// base chars are 0-9 a-z A-Z
func BigToBase62(num *big.Int) string {
digits := []byte{}
n := big.NewInt(0)
n.Add(n, num)
zero := big.NewInt(0)
base := big.NewInt(62)
for {
mod := big.NewInt(0)
n, mod = n.DivMod(n, base, mod)
mBytes := mod.Bytes()
if len(mBytes) == 0 {
digits = append(digits, 0)
} else {
digits = append(digits, mod.Bytes()[0])
}
if n.Cmp(zero) == 0 {
break
}
}
l := len(digits)
for i := 0; i < 11-l; i++ {
digits = append(digits, 0)
}
return base62DigitsToString(digits)
}
func (h SPHash) Str() string { return string(h[:]) }
func (h SPHash) Bytes() []byte { return h[:] }
func (h SPHash) Big() *big.Int { return BytesToBig(h[:]) }
func (h SPHash) Hex() string { return hexutil.Encode(h[:]) }
func (h BranchElement) Str() string { return string(h[:]) }
func (h BranchElement) Bytes() []byte { return h[:] }
func (h BranchElement) Big() *big.Int { return BytesToBig(h[:]) }
func (h BranchElement) Hex() string { return hexutil.Encode(h[:]) }
func BranchElementFromHash(a, b SPHash) BranchElement {
result := BranchElement{}
copy(result[:], append(a[:], b[:]...)[:BranchElementLength])
return result
}
// Rig represents mining actor that will be directly interactive with smartpool.
type Rig interface {
ID() string
IP() string
Name() string
}
// Work represents SmartPool work that miner needs to solve to have valid
// shares. Work is easier (has smaller difficulty) than actual Ethereum
// work that the miner can get from the network.
type Work interface {
ID() string
// AcceptSolution takes solution to construct and return a Share representing
// the solution that came from miner.
AcceptSolution(sol Solution) Share
}
// Solution represents a solution for a work
type Solution interface {
// WorkID returns the ID to identify the work it is trying to solve
WorkID() string
}
// Share represent a solution of a Work that comes from the miner.
type Share interface {
// Counter returns the counter to be used in augmented merkle tree of a claim
// which contains many shares. This counter must be increasing as shares
// share coming. In other words, later share must have bigger counter.
Counter() *big.Int
// Difficulty returns the difficulty of the share that miner has solved.
ShareDifficulty() *big.Int
// Hash return the hash of the share to be used as leaf hash of the augmented
// merkle tree.
Hash() SPHash
// FullSolution returns true if the share is solution for its full block pow
// hash. It returns false otherwise.
FullSolution() bool
}
// Claim represent a batch of shares which needs to reorganize its shares in
// ascending order of share counter.
type Claim interface {
// NumShares returns number of shares that the claim is holding
NumShares() *big.Int
GetShare(index int) Share
// Difficulty returns the min difficulty across all of its shares
Difficulty() *big.Int
// Min returns the min counter of the augmented merkle root
Min() *big.Int
// Max returns the max counter of the augmented merkle root
Max() *big.Int
// AugMerkle returns the hash of the augmented merkle root
AugMerkle() SPHash
// SetEvidence sets the share index to be used to prove the claim
SetEvidence(shareIndex *big.Int)
// CounterBranch returns array of counters in proof branch of the share
CounterBranch() []*big.Int
// HashBranch returns array of hashes in proof branch of the share
HashBranch() []*big.Int
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
)
type testStatRecorder struct {
}
func (self *testStatRecorder) RecordShare(status string, share smartpool.Share, rig smartpool.Rig) {
}
func (self *testStatRecorder) RecordClaim(status string, claim smartpool.Claim) {
}
func (self *testStatRecorder) RecordHashrate(hashrate hexutil.Uint64, id common.Hash, rig smartpool.Rig) {
}
func (self *testStatRecorder) ShareRestored(noshares uint64) {
}
func (self *testStatRecorder) OverallFarmStat() interface{} {
return nil
}
func (self *testStatRecorder) FarmStat(start uint64, end uint64) interface{} {
return nil
}
func (self *testStatRecorder) OverallRigStat(rig smartpool.Rig) interface{} {
return nil
}
func (self *testStatRecorder) RigStat(rig smartpool.Rig, start uint64, end uint64) interface{} {
return nil
}
func (self *testStatRecorder) Persist(storage smartpool.PersistentStorage) error {
return nil
}
<file_sep>package stat
import (
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"sync"
"time"
)
const STATRECORDER_FILE string = "stat_recorder"
type StatRecorder struct {
mu sync.RWMutex
RigDatas map[string]*RigData
FarmData *FarmData
}
func loadStatRecorder(storage smartpool.PersistentStorage) (*StatRecorder, error) {
result := &StatRecorder{
mu: sync.RWMutex{},
RigDatas: map[string]*RigData{},
FarmData: NewFarmData(),
}
loadedStats, err := storage.Load(result, STATRECORDER_FILE)
result = loadedStats.(*StatRecorder)
return result, err
}
func NewStatRecorder(storage smartpool.PersistentStorage) *StatRecorder {
statRecorder, err := loadStatRecorder(storage)
if err != nil {
smartpool.Output.Printf("Couldn't load stat from last session. Initialize with fresh stat recorder.\n")
}
smartpool.Output.Printf("Stat persister is running...\n")
go func(sr *StatRecorder, storage smartpool.PersistentStorage) {
for {
smartpool.Output.Printf("Truncating stat datas...\n")
err := sr.truncateData(storage)
if err == nil {
smartpool.Output.Printf("Done truncating stat.\n")
} else {
smartpool.Output.Printf("Failed truncating stat. (%s)\n", err.Error())
}
time.Sleep(time.Minute)
}
}(statRecorder, storage)
smartpool.Output.Printf("Stat truncator is running...\n")
return statRecorder
}
func (sr *StatRecorder) Persist(storage smartpool.PersistentStorage) error {
sr.mu.RLock()
defer sr.mu.RUnlock()
smartpool.Output.Printf("Saving stats to disk...\n")
err := storage.Persist(sr, STATRECORDER_FILE)
if err == nil {
smartpool.Output.Printf("Done.\n")
} else {
smartpool.Output.Printf("Failed. (%s)\n", err.Error())
}
return err
}
func (sr *StatRecorder) truncateData(storage smartpool.PersistentStorage) error {
sr.mu.Lock()
defer sr.mu.Unlock()
var err error
if err = sr.FarmData.TruncateData(storage); err != nil {
return err
}
for _, rigData := range sr.RigDatas {
if err = rigData.TruncateData(storage); err != nil {
return err
}
}
return nil
}
func (sr *StatRecorder) getRigData(rig smartpool.Rig) *RigData {
data := sr.RigDatas[rig.ID()]
if data == nil {
data = NewRigData(rig.ID())
sr.RigDatas[rig.ID()] = data
}
return data
}
func (sr *StatRecorder) ShareRestored(noShares uint64) {
sr.mu.Lock()
defer sr.mu.Unlock()
sr.FarmData.ShareRestored(noShares)
}
func (sr *StatRecorder) RecordShare(status string, share smartpool.Share, rig smartpool.Rig) {
sr.mu.Lock()
defer sr.mu.Unlock()
t := time.Now().In(Zone)
rigData := sr.getRigData(rig)
rigData.AddShare(status, share, t)
sr.FarmData.AddShare(rig, status, share, t)
}
func (sr *StatRecorder) RecordClaim(status string, claim smartpool.Claim) {
sr.mu.Lock()
defer sr.mu.Unlock()
t := time.Now().In(Zone)
sr.FarmData.AddClaim(status, claim, t)
}
func (sr *StatRecorder) RecordHashrate(hashrate hexutil.Uint64, id common.Hash, rig smartpool.Rig) {
sr.mu.Lock()
defer sr.mu.Unlock()
t := time.Now().In(Zone)
rigData := sr.getRigData(rig)
rigData.AddHashrate(hashrate, id, t)
// fmt.Printf("going to update rig hashrate:\n")
// fmt.Printf("rig: %v\n", rig)
// fmt.Printf("reported hashrate: %v\n", rigData.AverageReportedHashrate.Uint64())
// fmt.Printf("effective hashrate: %v\n", rigData.AverageEffectiveHashrate.Uint64())
// fmt.Printf("period reported hashrate: %v\n", rigData.PeriodReportedHashrate(t).Uint64())
// fmt.Printf("period effective hashrate: %v\n", rigData.PeriodEffectiveHashrate(t).Uint64())
sr.FarmData.UpdateRigHashrate(
rig, rigData.AverageReportedHashrate, rigData.AverageEffectiveHashrate,
rigData.PeriodReportedHashrate(t), rigData.PeriodEffectiveHashrate(t),
t,
)
}
func (sr *StatRecorder) OverallFarmStat() interface{} {
sr.mu.RLock()
defer sr.mu.RUnlock()
return sr.FarmData.OverallFarmData
}
func (sr *StatRecorder) FarmStat(start uint64, end uint64) interface{} {
sr.mu.RLock()
defer sr.mu.RUnlock()
result := map[uint64]*PeriodFarmData{}
for period, data := range sr.FarmData.Datas {
if start <= period && period <= end {
result[period] = data
}
}
return result
}
func (sr *StatRecorder) OverallRigStat(rig smartpool.Rig) interface{} {
sr.mu.RLock()
defer sr.mu.RUnlock()
rigData := sr.getRigData(rig)
return rigData.OverallRigData
}
func (sr *StatRecorder) RigStat(rig smartpool.Rig, start, end uint64) interface{} {
sr.mu.RLock()
defer sr.mu.RUnlock()
rigData := sr.getRigData(rig)
result := map[uint64]*PeriodRigData{}
for period, data := range rigData.Datas {
if start <= period && period <= end {
result[period] = data
}
}
return result
}
<file_sep>package ethereum
import (
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"math/big"
)
type Contract struct {
client ContractClient
miner common.Address
}
func (c *Contract) Version() string {
return c.client.Version()
}
func (c *Contract) IsRegistered() bool {
return c.client.IsRegistered()
}
func (c *Contract) CanRegister() bool {
return c.client.CanRegister()
}
func (c *Contract) Register(paymentAddress common.Address) error {
return c.client.Register(paymentAddress)
}
func (c *Contract) SubmitClaim(claim smartpool.Claim, lastClaim bool) error {
smartpool.Output.Printf("Min: 0x%s - Max: 0x%s - Diff: 0x%s\n", claim.Min().Text(16), claim.Max().Text(16), claim.Difficulty().Text(16))
return c.client.SubmitClaim(
claim.NumShares(), claim.Difficulty(),
claim.Min(), claim.Max(), claim.AugMerkle().Big(), lastClaim)
}
func (c *Contract) GetShareIndex(claim smartpool.Claim) (*big.Int, *big.Int, error) {
seed := c.client.GetClaimSeed()
data, err := c.client.CalculateSubmissionIndex(c.miner, seed)
return data[0], data[1], err
}
func (c *Contract) NumOpenClaims() (*big.Int, error) {
return c.client.NumOpenClaims(c.miner)
}
func (c *Contract) ResetOpenClaims() error {
return c.client.ResetOpenClaims()
}
func (c *Contract) VerifyClaim(submissionIndex *big.Int, shareIndex *big.Int, claim smartpool.Claim) error {
share := claim.GetShare(int(shareIndex.Int64())).(*Share)
rlpHeader, _ := share.RlpHeaderWithoutNonce()
nonce := share.NonceBig()
claim.SetEvidence(shareIndex)
augCountersBranch := claim.CounterBranch()
augHashesBranch := claim.HashBranch()
dataSetLookup := share.DAGElementArray()
witnessForLookup := share.DAGProofArray()
return c.client.VerifyClaim(
rlpHeader,
nonce,
submissionIndex,
shareIndex,
dataSetLookup,
witnessForLookup,
augCountersBranch,
augHashesBranch,
)
}
func NewContract(client ContractClient, miner common.Address) *Contract {
return &Contract{client, miner}
}
<file_sep>package storage
import (
"encoding/gob"
"github.com/mitchellh/go-homedir"
"os"
"path/filepath"
"reflect"
"sync"
)
var SmartPoolDir = getSmartPoolDir()
func getSmartPoolDir() string {
result, err := homedir.Dir()
if err != nil {
panic(err)
}
return filepath.Join(result, ".smartpool")
}
func getFile(id string) string {
return filepath.Join(SmartPoolDir, id)
}
func getTempFile(id string) string {
return filepath.Join(SmartPoolDir, id+".temp")
}
func getRigDataFile() string {
return filepath.Join(SmartPoolDir, "rig_data")
}
type GobFileStorage struct {
mu sync.Mutex
registeredType map[string]bool
}
func getName(value interface{}) string {
// Default to printed representation for unnamed types
rt := reflect.TypeOf(value)
name := rt.String()
// But for named types (or pointers to them), qualify with import path (but see inner comment).
// Dereference one pointer looking for a named type.
star := ""
if rt.Name() == "" {
if pt := rt; pt.Kind() == reflect.Ptr {
star = "*"
// NOTE: The following line should be rt = pt.Elem() to implement
// what the comment above claims, but fixing it would break compatibility
// with existing gobs.
//
// Given package p imported as "full/p" with these definitions:
// package p
// type T1 struct { ... }
// this table shows the intended and actual strings used by gob to
// name the types:
//
// Type Correct string Actual string
//
// T1 full/p.T1 full/p.T1
// *T1 *full/p.T1 *p.T1
//
// The missing full path cannot be fixed without breaking existing gob decoders.
rt = pt
}
}
if rt.Name() != "" {
if rt.PkgPath() == "" {
name = star + rt.Name()
} else {
name = star + rt.PkgPath() + "." + rt.Name()
}
}
return name
}
func (gfs *GobFileStorage) register(value interface{}) {
name := getName(value)
if _, found := gfs.registeredType[name]; !found {
gob.Register(value)
gfs.registeredType[name] = true
}
}
func (gfs *GobFileStorage) persistToFile(data interface{}, id string) error {
err := os.MkdirAll(SmartPoolDir, 0766)
if err != nil {
return err
}
f, err := os.Create(getTempFile(id))
if err != nil {
return err
}
defer f.Close()
gfs.register(data)
enc := gob.NewEncoder(f)
return enc.Encode(data)
}
func (gfs *GobFileStorage) Persist(data interface{}, id string) error {
gfs.mu.Lock()
defer gfs.mu.Unlock()
if err := gfs.persistToFile(data, id); err != nil {
return err
}
return os.Rename(getTempFile(id), getFile(id))
}
func (gfs *GobFileStorage) Load(data interface{}, id string) (interface{}, error) {
gfs.mu.Lock()
defer gfs.mu.Unlock()
f, err := os.Open(getFile(id))
if err != nil {
return data, err
}
defer f.Close()
gfs.register(data)
dec := gob.NewDecoder(f)
err = dec.Decode(data)
return data, err
}
func NewGobFileStorage() *GobFileStorage {
return &GobFileStorage{
sync.Mutex{},
map[string]bool{},
}
}
<file_sep>package geth
import (
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"math/big"
"os"
)
type EthashContractClient struct {
contract *Ethash
transactor *bind.TransactOpts
node ethereum.RPCClient
sender common.Address
}
func (cc *EthashContractClient) SetEpochData(
epoch *big.Int,
fullSizeIn128Resolution *big.Int,
branchDepth *big.Int,
merkleNodes []*big.Int) error {
nodes := []*big.Int{}
start := big.NewInt(0)
fmt.Printf("No meaningful nodes: %d\n", len(merkleNodes))
for k, n := range merkleNodes {
nodes = append(nodes, n)
if len(nodes) == 40 || k == len(merkleNodes)-1 {
mnlen := big.NewInt(int64(len(nodes)))
blockNo, err := cc.node.BlockNumber()
blockNo.Add(blockNo, big.NewInt(1))
if err != nil {
smartpool.Output.Printf("Setting epoch data. Error: %s\n", err)
return err
}
fmt.Printf("Going to do tx\n")
fmt.Printf("Block Number: %d\n", blockNo.Int64())
if k < 440 && epoch.Uint64() == 128 {
start.Add(start, mnlen)
nodes = []*big.Int{}
continue
}
tx, err := cc.contract.SetEpochData(
cc.transactor, epoch, fullSizeIn128Resolution,
branchDepth, nodes, start, mnlen)
if err != nil {
smartpool.Output.Printf("Setting optimized epoch data. Error: %s\n", err)
return err
}
errCode, errInfo, err := GetTxResult(
tx, cc.transactor, cc.node, blockNo, SetEpochDataEventTopic,
cc.sender.Big())
if err != nil {
smartpool.Output.Printf("Tx: %s was not approved by the network in time.\n", tx.Hash().Hex())
start.Add(start, mnlen)
nodes = []*big.Int{}
continue
}
if errCode.Cmp(common.Big0) != 0 {
smartpool.Output.Printf("Error code: 0x%s - Error info: 0x%s\n", errCode.Text(16), errInfo.Text(16))
// return errors.New(ErrorMsg(errCode, errInfo))
}
start.Add(start, mnlen)
nodes = []*big.Int{}
}
}
return nil
}
func NewEthashContractClient(
contractAddr common.Address, node ethereum.RPCClient, miner common.Address,
ipc, keystorePath, passphrase string, gasprice uint64) (*EthashContractClient, error) {
client, err := getClient(ipc)
if err != nil {
smartpool.Output.Printf("Couldn't connect to Geth/Parity. Error: %s\n", err)
return nil, err
}
ethash, err := NewEthash(contractAddr, client)
if err != nil {
smartpool.Output.Printf("Couldn't get SmartPool information from Ethereum Blockchain. Error: %s\n", err)
return nil, err
}
account := GetAccount(keystorePath, miner, passphrase)
if account == nil {
smartpool.Output.Printf("Couldn't get any account from key store.\n")
return nil, err
}
keyio, err := os.Open(account.KeyFile())
if err != nil {
smartpool.Output.Printf("Failed to open key file: %s\n", err)
return nil, err
}
smartpool.Output.Printf("Unlocking account...\n")
auth, err := bind.NewTransactor(keyio, account.PassPhrase())
if err != nil {
smartpool.Output.Printf("Failed to create authorized transactor: %s\n", err)
return nil, err
}
if gasprice != 0 {
auth.GasPrice = big.NewInt(int64(gasprice * 1000000000))
smartpool.Output.Printf("Gas price is set to: %s wei.\n", auth.GasPrice.Text(10))
}
smartpool.Output.Printf("Done.\n")
return &EthashContractClient{ethash, auth, node, miner}, nil
}
<file_sep>package ethereum
import (
"github.com/SmartPool/smartpool-client"
"sync"
"time"
)
// workpool keeps track of pending works to ensure that each submitted solution
// can actually be accepted by a real pow work.
// workpool also implements ShareReceiver interface.
type WorkPool struct {
mu sync.RWMutex
works map[string]*Work
}
const (
WORKPOOL_FILE string = "workpool"
FullBlockSolution int = 2
ValidShare int = 1
InvalidShare int = 0
)
// AcceptSolution takes solution and find corresponding work and return
// associated share.
// It returns nil if the work is not found.
func (wp *WorkPool) AcceptSolution(s smartpool.Solution) smartpool.Share {
wp.mu.RLock()
defer wp.mu.RUnlock()
work := wp.works[s.WorkID()]
if work == nil {
smartpool.Output.Printf("work (%v) doesn't exist in workpool (len: %d)\n", s, len(wp.works))
return nil
}
share := work.AcceptSolution(s).(*Share)
if share.SolutionState == InvalidShare {
smartpool.Output.Printf("Solution (%v) is invalid\n", s)
return nil
} else {
// smartpool.Output.Printf(
// "Create share for work: ID: %s - createdAt: %s - timestamp: 0x%s\n",
// work.ID(),
// work.CreatedAt(),
// work.BlockHeader().Time.Text(16),
// )
return share
}
}
func (wp *WorkPool) AddWork(w *Work) {
wp.mu.Lock()
defer wp.mu.Unlock()
wp.works[w.ID()] = w
}
func (wp *WorkPool) RemoveWork(hash string) {
wp.mu.Lock()
defer wp.mu.Unlock()
delete(wp.works, hash)
}
func (wp *WorkPool) oldHashes() []string {
wp.mu.RLock()
defer wp.mu.RUnlock()
result := []string{}
for hash, work := range wp.works {
if time.Since(work.CreatedAt) > 200*(12*time.Second) {
result = append(result, hash)
}
}
return result
}
func (wp *WorkPool) Clean() {
oldHashes := wp.oldHashes()
for _, hash := range oldHashes {
wp.RemoveWork(hash)
}
if len(oldHashes) > 0 {
smartpool.Output.Printf("Cleaned %d old works.\n", len(oldHashes))
}
}
func (wp *WorkPool) RunCleaner() {
ticker := time.Tick(140 * time.Second)
for _ = range ticker {
wp.Clean()
}
}
func (wp *WorkPool) Persist(storage smartpool.PersistentStorage) error {
wp.mu.RLock()
defer wp.mu.RUnlock()
smartpool.Output.Printf("Saving workpool to disk...\n")
err := storage.Persist(&wp.works, WORKPOOL_FILE)
if err == nil {
smartpool.Output.Printf("Done.\n")
} else {
smartpool.Output.Printf("Failed. (%s)\n", err.Error())
}
return err
}
func NewWorkPool(storage smartpool.PersistentStorage) *WorkPool {
wp, err := loadWorkPool(storage)
if err != nil {
smartpool.Output.Printf("Couldn't load workpool from last session (%s). Initialize with empty workpool.\n", err)
}
smartpool.Output.Printf("Loaded %d works from last session.\n", len(wp.works))
return wp
}
func loadWorkPool(storage smartpool.PersistentStorage) (*WorkPool, error) {
wp := &WorkPool{sync.RWMutex{}, map[string]*Work{}}
works := map[string]*Work{}
loadedWorks, err := storage.Load(&works, WORKPOOL_FILE)
if err != nil {
return wp, err
}
wp.works = *loadedWorks.(*map[string]*Work)
return wp, err
}
<file_sep>package geth
import (
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/core/types"
"math/rand"
"time"
)
type TxProducer func() (*types.Transaction, error)
func EnsureTx(producer TxProducer, lower, upper int, action string) *types.Transaction {
var (
tx *types.Transaction
err error
)
for {
tx, err = producer()
if err != nil {
waitTime := rand.Int()%(upper-lower) + lower
smartpool.Output.Printf("%s failed. Error: %s. Retry in %d millisecond\n", action, err, waitTime)
time.Sleep(time.Duration(waitTime) * time.Millisecond)
} else {
break
}
}
return tx
}
<file_sep>package ethminer
import (
"encoding/json"
"math/big"
"net/http"
)
type StatusService struct{}
type StatusData struct {
RPCEndpoint string `json:"rpc_endpoint"`
ShareThreshold int `json:"share_threshold"`
ClaimThreshold int `json:"claim_threshold"`
ShareDiff *big.Int `json:"share_difficulty"`
Contract string `json:"contract_address"`
Miner string `json:"miner_address"`
Extra string `json:"extra_data"`
HotStop bool `json:"hotstop_mode"`
}
func (server *StatusService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
encoder := json.NewEncoder(w)
result := StatusData{
SmartPool.Input.RPCEndpoint(),
SmartPool.Input.ShareThreshold(),
SmartPool.Input.ClaimThreshold(),
SmartPool.Input.ShareDifficulty(),
SmartPool.Input.ContractAddress(),
SmartPool.Input.MinerAddress(),
SmartPool.Input.ExtraData(),
SmartPool.Input.HotStop(),
}
encoder.Encode(&result)
}
func NewStatusService() *StatusService {
return &StatusService{}
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/mtree"
"math/big"
"sort"
)
type Shares []smartpool.Share
func (s Shares) Len() int { return len(s) }
func (s Shares) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s Shares) Less(i, j int) bool {
return s[i].Counter().Cmp(s[j].Counter()) == -1
}
type Claim struct {
shares Shares
shareIndex *big.Int
amt *mtree.AugTree
pamt *mtree.AugTree
}
func NewClaim() *Claim {
return &Claim{Shares{}, nil, nil, nil}
}
func (c *Claim) AddShare(s smartpool.Share) {
c.shares = append(c.shares[:], s)
}
func (c *Claim) GetShare(index int) smartpool.Share {
return c.shares[index]
}
func (c *Claim) NumShares() *big.Int {
return big.NewInt(int64(c.shares.Len()))
}
func (c *Claim) Difficulty() *big.Int {
var m *big.Int
if len(c.shares) > 0 {
m = c.shares[0].ShareDifficulty()
for _, s := range c.shares {
if m.Cmp(s.ShareDifficulty()) >= 0 {
m = s.ShareDifficulty()
}
}
}
return m
}
func (c *Claim) Min() *big.Int {
if c.amt == nil {
c.buildAugTree()
}
return c.amt.RootMin()
}
func (c *Claim) Max() *big.Int {
if c.amt == nil {
c.buildAugTree()
}
return c.amt.RootMax()
}
func (c *Claim) AugMerkle() smartpool.SPHash {
if c.amt == nil {
c.buildAugTree()
}
return c.amt.RootHash()
}
func (c *Claim) SetEvidence(shareIndex *big.Int) {
c.shareIndex = shareIndex
}
func (c *Claim) GetEvidence() *big.Int {
return c.shareIndex
}
func (c *Claim) CounterBranch() []*big.Int {
if c.pamt == nil {
c.buildProofAugTree()
}
return c.pamt.CounterBranchArray()
}
func (c *Claim) HashBranch() []*big.Int {
if c.pamt == nil {
c.buildProofAugTree()
}
return c.pamt.HashBranchArray()
}
func (c *Claim) buildProofAugTree() {
sort.Sort(c.shares)
c.pamt = mtree.NewAugTree()
c.pamt.RegisterIndex(uint32(c.shareIndex.Int64()))
for i, s := range c.shares {
c.pamt.Insert(s, uint32(i))
}
c.pamt.Finalize()
}
func (c *Claim) buildAugTree() {
sort.Sort(c.shares)
c.amt = mtree.NewAugTree()
for i, s := range c.shares {
c.amt.Insert(s, uint32(i))
}
c.amt.Finalize()
}
<file_sep>package geth
import (
"bytes"
"errors"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"math/big"
"math/rand"
"time"
)
var (
GAS_INCREMENT = 110
GAS_PRICE_LIMIT = big.NewInt(60000000000)
WAIT_IN_MILLISECOND = 600000
)
// TxWatcher keeps track of pending transactions
// and acknowledge corresponding channel when a transaction is
// confirmed.
// It also captures event information emitted during the transaction
// and retry with higher gas price when the tx is not confirmed in time
type TxWatcher struct {
txs []*types.Transaction
verifiedTx *types.Transaction
transactor *bind.TransactOpts
node ethereum.RPCClient
block *big.Int
event *big.Int
sender *big.Int
verChan chan bool
}
func (tw *TxWatcher) isVerified() bool {
for _, tx := range tw.txs {
if tw.node.IsVerified(tx.Hash()) {
tw.verifiedTx = tx
smartpool.Output.Printf("tx %s is verified.\n", tx.Hash().Hex())
return true
}
}
return false
}
// loop to check transactions verification
// if a transaction is verified, send it to verChan
func (tw *TxWatcher) loop(timeout chan bool) {
for {
if tw.isVerified() {
tw.verChan <- true
return
}
select {
case <-timeout:
return
default:
time.Sleep(1 * time.Second)
}
}
}
func (tw *TxWatcher) lastTx() *types.Transaction {
return tw.txs[len(tw.txs)-1]
}
func (tw *TxWatcher) newTx(oldTx *types.Transaction) (*types.Transaction, error) {
newGasPrice := new(big.Int).Set(oldTx.GasPrice())
// setting new gas price as 25% higher than old gas price
newGasPrice.Mul(newGasPrice, big.NewInt(int64(GAS_INCREMENT)))
newGasPrice.Div(newGasPrice, big.NewInt(100))
newTx := types.NewTransaction(
oldTx.Nonce(), *oldTx.To(), oldTx.Value(),
oldTx.Gas(), newGasPrice, oldTx.Data())
return tw.transactor.Signer(types.HomesteadSigner{}, tw.transactor.From, newTx)
}
func (tw *TxWatcher) rebroadcastByPublicNode(signedTx *types.Transaction) error {
buff := bytes.NewBuffer([]byte{})
if err := signedTx.EncodeRLP(buff); err != nil {
return err
}
return SendRawTransaction(buff.Bytes())
}
func (tw *TxWatcher) rebroadcast(oldTx, signedTx *types.Transaction) error {
buff := bytes.NewBuffer([]byte{})
if err := signedTx.EncodeRLP(buff); err != nil {
return err
}
var (
hash common.Hash
err error
)
for {
hash, err = tw.node.Broadcast(buff.Bytes())
if err != nil {
waitTime := rand.Int()%10000 + 1000
smartpool.Output.Printf("Broadcast error: %s\n", err)
time.Sleep(time.Duration(waitTime) * time.Millisecond)
} else {
break
}
}
smartpool.Output.Printf(
"Rebroadcast tx: %s by tx: %s with gas price %d...\n",
oldTx.Hash().Hex(),
signedTx.Hash().Hex(),
signedTx.GasPrice().Uint64())
if hash.Big().Cmp(common.Big0) == 0 {
return errors.New("Rebroadcast tx got 0 tx hash. This is not supposed to happend.")
}
return nil
}
func (tw *TxWatcher) WaitAndRetry() (*big.Int, *big.Int, error) {
var oldTx *types.Transaction
for {
oldTx = tw.lastTx()
errCode, errInfo, err := tw.Wait()
if err != nil {
if oldTx.GasPrice().Cmp(GAS_PRICE_LIMIT) >= 0 {
break
}
signedTx, err := tw.newTx(oldTx)
if err == nil {
err = tw.rebroadcast(oldTx, signedTx)
if err == nil {
tw.txs = append(tw.txs, signedTx)
}
}
} else {
return errCode, errInfo, err
}
}
return nil, nil, errors.New("Gave up on current pending txs")
// errCode, errInfo, err := tw.Wait()
// if err != nil {
// oldTx := tw.lastTx()
// signedTx, err := tw.newTx(oldTx)
// if err != nil {
// return nil, nil, err
// }
// tw.txs = append(tw.txs, signedTx)
// err = tw.rebroadcast(oldTx, signedTx)
// if err != nil {
// return nil, nil, err
// }
// errCode, errInfo, err = tw.Wait()
// // if err != nil {
// // err = tw.rebroadcastByPublicNode(signedTx)
// // if err != nil {
// // smartpool.Output.Printf("Rebroadcast by public node of tx: %s failed. Error: %s\n", signedTx.Hash().Hex(), err)
// // }
// // }
// // errCode, errInfo, err = tw.Wait()
// }
// return errCode, errInfo, err
}
func (tw *TxWatcher) Wait() (*big.Int, *big.Int, error) {
smartpool.Output.Printf("Waiting for txs: [")
for _, tx := range tw.txs {
smartpool.Output.Printf("%s, ", tx.Hash().Hex())
}
smartpool.Output.Printf("] to be mined...\n")
timeout := make(chan bool, 1)
go tw.loop(timeout)
go func() {
time.Sleep(time.Duration(WAIT_IN_MILLISECOND) * time.Millisecond)
// push 2 timeouts for the above loop and below select
timeout <- true
timeout <- true
}()
select {
case <-tw.verChan:
break
case <-timeout:
return nil, nil, errors.New("timeout error")
}
errCode, errInfo := tw.node.GetLog(tw.txs, tw.block, tw.event, tw.sender)
return errCode, errInfo, nil
}
func GetTxResult(tx *types.Transaction, opts *bind.TransactOpts, node ethereum.RPCClient,
blockNo *big.Int, event *big.Int, sender *big.Int) (*big.Int, *big.Int, error) {
txWatcher := NewTxWatcher(tx, opts, node, blockNo, event, sender)
errCode, errInfo, err := txWatcher.WaitAndRetry()
if err != nil {
smartpool.Output.Printf("No tx in: [")
for _, tx := range txWatcher.txs {
smartpool.Output.Printf("%s, ", tx.Hash().Hex())
}
smartpool.Output.Printf("] was approved by the network in time.\n")
}
return errCode, errInfo, err
}
func NewTxWatcher(
tx *types.Transaction, opts *bind.TransactOpts, node ethereum.RPCClient,
blockNo *big.Int, event *big.Int, sender *big.Int) *TxWatcher {
return &TxWatcher{
[]*types.Transaction{tx}, nil,
opts, node, blockNo, event, sender, make(chan bool)}
}
<file_sep>package main
import (
"bufio"
"encoding/hex"
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum/ethash"
"github.com/SmartPool/smartpool-client/ethereum/geth"
"github.com/SmartPool/smartpool-client/mtree"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"io"
"log"
"math/big"
"os"
"path/filepath"
)
func processDuringRead(
datasetPath string, mt *mtree.DagTree) {
f, err := os.Open(datasetPath)
if err != nil {
log.Fatal(err)
}
r := bufio.NewReader(f)
buf := [128]byte{}
// ignore first 8 bytes magic number at the beginning
// of dataset. See more at https://github.com/ethereum/wiki/wiki/Ethash-DAG-Disk-Storage-Format
_, err = io.ReadFull(r, buf[:8])
if err != nil {
log.Fatal(err)
}
var i uint32 = 0
for {
n, err := io.ReadFull(r, buf[:128])
if n == 0 {
if err == nil {
continue
}
if err == io.EOF {
break
}
log.Fatal(err)
}
if n != 128 {
log.Fatal("Malformed dataset")
}
mt.Insert(smartpool.Word(buf), i)
if err != nil && err != io.EOF {
log.Fatal(err)
}
i++
}
}
func getClient(rpc string) (*ethclient.Client, error) {
return ethclient.Dial(rpc)
}
func main() {
client, err := getClient("http://localhost:8545")
if err != nil {
fmt.Printf("Couldn't connect to Geth via IPC file. Error: %s\n", err)
return
}
contractAddr := common.HexToAddress("0xda87714c91d62070ebc29675ec79a190e6ccdfba")
testClient, err := geth.NewTestClient(contractAddr, client)
if err != nil {
fmt.Printf("Couldn't bind. Error: %s\n", err)
return
}
account := geth.GetAccount(
"/Users/victor/Library/Ethereum/testnet/keystore",
common.HexToAddress("0xe034afdcc2ba0441ff215ee9ba0da3e86450108d"),
"hoctinhocsong")
if account == nil {
fmt.Printf("Couldn't get any account from key store.\n")
return
}
keyio, err := os.Open(account.KeyFile())
if err != nil {
fmt.Printf("Failed to open key file: %s\n", err)
return
}
fmt.Printf("Unlocking account...")
auth, err := bind.NewTransactor(keyio, account.PassPhrase())
if err != nil {
fmt.Printf("Failed to create authorized transactor: %s\n", err)
return
}
epoch := 24
fmt.Printf("Checking DAG file for epoch %d. Generate if needed...\n", epoch)
fullSize, _ := ethash.MakeDAGWithSize(uint64(epoch*30000), "")
fullSizeIn128Resolution := fullSize / 128
seedHash, err := ethash.GetSeedHash(uint64(epoch * 30000))
if err != nil {
panic(err)
}
path := filepath.Join(
ethash.DefaultDir,
fmt.Sprintf("full-R%s-%s", "23", hex.EncodeToString(seedHash[:8])),
)
branchDepth := len(fmt.Sprintf("%b", fullSizeIn128Resolution-1))
mt := mtree.NewDagTree()
mt.RegisterStoredLevel(uint32(branchDepth), uint32(10))
processDuringRead(path, mt)
mt.Finalize()
merkleNodes := []*big.Int{}
fmt.Printf("len nodes: %d\n", len(mt.MerkleNodes()))
start := big.NewInt(0)
var temp int
for k, n := range mt.MerkleNodes() {
merkleNodes = append(merkleNodes, n)
if len(merkleNodes) == 50 || k == len(mt.MerkleNodes())-1 {
mnlen := big.NewInt(int64(len(merkleNodes)))
tx, err := testClient.SetOptEpochData(
auth,
big.NewInt(int64(epoch)),
big.NewInt(int64(fullSizeIn128Resolution)),
big.NewInt(int64(branchDepth-10)),
merkleNodes,
start,
mnlen,
)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
return
}
fmt.Printf("Transaction: %s\n", tx.Hash().Hex())
start.Add(start, mnlen)
merkleNodes = []*big.Int{}
fmt.Scanf("%d", &temp)
}
}
}
<file_sep>package ethash
import (
"encoding/binary"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/sha3"
"os"
"os/user"
"path/filepath"
"runtime"
)
var (
Instance = New(defaultDir(), 3, 3, defaultDir(), 0, 3)
DefaultDir = defaultDir()
)
func defaultDir() string {
home := os.Getenv("HOME")
if user, err := user.Current(); err == nil {
home = user.HomeDir
}
if runtime.GOOS == "windows" {
return filepath.Join(home, "AppData", "Ethash")
}
return filepath.Join(home, ".ethash")
}
func DAGSize(blockNum uint64) uint64 {
return datasetSizes[blockNum/epochLength]
}
func (ethash *Ethash) GetVerificationIndices(blockNumber uint64, hash common.Hash, nonce uint64) []uint32 {
// Recompute the digest and PoW value and verify against the header
cache := ethash.cache(blockNumber)
size := datasetSize(blockNumber)
return hashimotoLightIndices(size, cache, hash.Bytes(), nonce)
}
func hashimotoLightIndices(size uint64, cache []uint32, hash []byte, nonce uint64) []uint32 {
keccak512 := makeHasher(sha3.NewKeccak512())
lookup := func(index uint32) []uint32 {
rawData := generateDatasetItem(cache, index, keccak512)
data := make([]uint32, len(rawData)/4)
for i := 0; i < len(data); i++ {
data[i] = binary.LittleEndian.Uint32(rawData[i*4:])
}
return data
}
return hashimotoIndices(hash, nonce, size, lookup)
}
func hashimotoIndices(hash []byte, nonce uint64, size uint64, lookup func(index uint32) []uint32) []uint32 {
result := []uint32{}
// Calculate the number of thoretical rows (we use one buffer nonetheless)
rows := uint32(size / mixBytes)
// Combine header+nonce into a 64 byte seed
seed := make([]byte, 40)
copy(seed, hash)
binary.LittleEndian.PutUint64(seed[32:], nonce)
seed = crypto.Keccak512(seed)
seedHead := binary.LittleEndian.Uint32(seed)
// Start the mix with replicated seed
mix := make([]uint32, mixBytes/4)
for i := 0; i < len(mix); i++ {
mix[i] = binary.LittleEndian.Uint32(seed[i%16*4:])
}
// Mix in random dataset nodes
temp := make([]uint32, len(mix))
for i := 0; i < loopAccesses; i++ {
parent := fnv(uint32(i)^seedHead, mix[i%len(mix)]) % rows
result = append(result, parent)
for j := uint32(0); j < mixBytes/hashBytes; j++ {
copy(temp[j*hashWords:], lookup(2*parent+j))
}
fnvHash(mix, temp)
}
return result
}
func MakeDAG(block uint64, dir string) {
MakeDataset(block-30000, dir)
}
func PathToDAG(epoch uint64, dir string) string {
seed := ethash.SeedHash(epoch*epochLength + 1)
var endian string
if !isLittleEndian() {
endian = ".be"
}
return filepath.Join(dir, fmt.Sprintf("full-R%d-%x%s", 23, seed[:8], endian))
}
<file_sep>The instructions below apply for running SmartPool on both Ethereum and Ethereum Classic.
## Architecture for a mining farm to use SmartPool
In traditional mining pools, every rig must be connected to the pool and submit shares to the pool directly, as shown in this figure.
<img src="https://github.com/SmartPool/smartpool-client/blob/develop/miscs/normalpool-farm.png" width="500" alt="Architecture of a mining farm when working with a centralized pool">
When using SmartPool, because the pool is maintained by a smart contract, only a few shares are needed to submit to the pool, so mining rigs won't submit the share to contract directly. Instead, they submit shares to a local server/ machine that acts as the gateway between the mining rigs and the SmartPool contract. The new structure for a farm is shown in this figure
<img src="https://github.com/SmartPool/smartpool-client/blob/develop/miscs/smartpool-farm.png" width="500" alt="Architecture of a mining farm when working with SmartPool">
In SmartPool, the local server will need to install an Ethereum client (either Geth or Parity) and a SmartPool client. The SmartPool client will interact with the mining rigs to collect all the shares. It also submit a few share to the SmartPool contract via the Ethereum client. Details on how to install these components are in the next section.
## Requirements and installations
The below instructions are for the the local-server of the farm which runs on linux. For the Windows platform, please check this [link](https://github.com/SmartPool/smartpool-client/blob/develop/CLOSED_BETA_TEST_WINDOWS.md)!
### Geth or Parity installed
You need to install a full-node client for Ethereum. We support both [Go-ethereum](https://github.com/ethereum/go-ethereum) and [Parity](https://github.com/paritytech/parity).
### Golang compiler
(You can skip this step if you already have Golang/Go installed when you installed Go-ethereum)
[Golang compiler](https://golang.org/) version 1.7 or higher.
### Install SmartPool client
Follow below instructions to install our client locally.
```
git clone https://github.com/SmartPool/smartpool-client
cd smartpool-client
git checkout develop
./compile.sh
```
The last command will create a `smartpool` executable file in your current directory.
## Running SmartPool for your farm
Before running SmartPool-client on your local server, you need to start the Etherem client and get it to sync with the latest Ethereum blockchain. You also need to enable several apis in your client. Specifically, you need to run:
`parity --jsonrpc-apis "web3,eth,net,parity,traces,rpc,parity_set"`
if you use Parity, or
`geth --rpc --rpcapi "db,eth,net,web3,miner,personal"`
if you use Geth.
At your smartpool-client folder, run
```
./smartpool --keystore <keystore_dir> --gateway 0x09077D92F7a71Ae3C4EAc8dC9f35cE9aa5A06F7B --share-threshold 36000 --claim-threshold 2 --spcontract 0xfc668AE14b0F7702c04b105448fE733D96C558DF --gasprice 4
```
The `<keystore_dir>` is normally `~/Library/Ethereum/testnet/keystore`, but it may be different depending on machines. You can figure out the meaning of these parameters in our client by running `./smartpool --help`. Two important parameters are `share-threshold` and `claim-threshold`. You can reduce these parameters to get your payment faster, but the average costs for transaction fees will be higher. The above setup `-share-threshold 36000 --claim-threshold 2` is for a miner of 20 GH/s to get paid every 4 hours (the average fees is ~0.6-1%). You can reduce either of the parameters to get paid faster (linearly) according to your hashrate. SmartPool client binds its rpc server address at 0.0.0.0:1633 for the mining rigs to submit shares. Now you can just let the SmartPool client runs, do not close it.
### Connect your rigs to SmartPool-client
SmartPool-cient will serve work and accept shares at `0.0.0.0:1633/<rig_or_worker_name>/`. The trailing `/` is a required. `rig_or_worker_name` must be different to `farm`, `rig` and `status`. They are reserved for collecting and showing statistics of the farm and the rigs.
For example:
`ethminer -F 192.168.1.100:1633/rig1/` if you mine with `ethminer`.
`EthDrcMiner64.exe -epool http://192.168.1.100/rig1/` if you mine with `claymore`.
Note: Remember to change `192.168.1.100` to the local IP address of the local server in your network.
### Collect stats to send us
SmartPool-client collects and views stats for the whole farm and each individual rig.
Farm stats is available at: `http://0.0.0.0:1633/farm`
Rig stats is available at: `http://0.0.0.0:1633/rig/<rig_or_worker_name>`
We need the stats to improve our protocol. If you are ok with sharing the farm stats with us, please go to the farm stats url, save the json file and send us at <EMAIL>.
<file_sep>package geth
import (
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common"
"math/big"
)
type MinerAccount struct {
keyFile string
passphrase string
address common.Address
}
func (ma MinerAccount) KeyFile() string { return ma.keyFile }
func (ma MinerAccount) PassPhrase() string { return ma.passphrase }
func (ma MinerAccount) Address() common.Address { return ma.address }
func GetAddress(keystorePath string, address common.Address) (common.Address, bool, []common.Address) {
keys := keystore.NewKeyStore(
keystorePath,
keystore.StandardScryptN,
keystore.StandardScryptP,
)
var acc *accounts.Account
addresses := []common.Address{}
for _, a := range keys.Accounts() {
addresses = append(addresses, a.Address)
}
defaultAcc := big.NewInt(0)
if address.Big().Cmp(defaultAcc) == 0 {
if len(keys.Accounts()) == 0 {
return address, false, addresses
}
acc = &keys.Accounts()[0]
} else {
for _, a := range keys.Accounts() {
if a.Address == address {
acc = &a
break
}
}
}
if acc == nil {
return address, false, addresses
}
return acc.Address, true, addresses
}
// Get the first account in key store
// Return nil if there's no account
func GetAccount(keystorePath string, address common.Address, passphrase string) *MinerAccount {
keys := keystore.NewKeyStore(
keystorePath,
keystore.StandardScryptN,
keystore.StandardScryptP,
)
var acc accounts.Account
for _, a := range keys.Accounts() {
if a.Address == address {
acc = a
break
}
}
return &MinerAccount{
acc.URL.Path,
passphrase,
acc.Address,
}
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
)
type testShareReceiver struct {
}
func (spc *testShareReceiver) AcceptSolution(s smartpool.Solution) smartpool.Share {
sol := s.(*testSolution)
return &testShare{c: sol.Counter}
}
func (spc *testShareReceiver) Persist(storage smartpool.PersistentStorage) error {
return nil
}
<file_sep>mustrun() {
"$@"
if [ $? != 0 ]; then
printf "Error when executing command: '$*'\n"
exit $ERROR_CODE
fi
}
export CC=x86_64-w64-mingw32-gcc
export CXX=x86_64-w64-mingw32-g++
export CGO_ENABLED=1
export GOOS=windows
export GOARCH=amd64
echo "Install dependencies..."
mustrun build/env.sh go get -v golang.org/x/crypto/ssh/terminal
mustrun build/env.sh go get -v gopkg.in/urfave/cli.v1
mustrun build/env.sh go get -v github.com/bmizerany/pat
mustrun build/env.sh go get -v github.com/mitchellh/go-homedir
mustrun build/env.sh go get -v golang.org/x/net/context
mustrun build/env.sh go get -v github.com/gorilla/websocket
mustrun build/env.sh go get -v github.com/ethereum/go-ethereum
echo "Compiling SmartPool client for Windows..."
mustrun build/env.sh go build -o smartpool.exe cmd/ropsten/ropsten.go
echo "Done. You can run SmartPool by ./smartpool --help"
<file_sep>// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// +build go1.8
package ethash
import "testing"
// Tests whether the dataset size calculator work correctly by cross checking the
// hard coded lookup table with the value generated by it.
func TestSizeCalculations(t *testing.T) {
var tests []uint64
// Verify all the cache sizes from the lookup table
defer func(sizes []uint64) { cacheSizes = sizes }(cacheSizes)
tests, cacheSizes = cacheSizes, []uint64{}
for i, test := range tests {
if size := cacheSize(uint64(i*epochLength) + 1); size != test {
t.Errorf("cache %d: cache size mismatch: have %d, want %d", i, size, test)
}
}
// Verify all the dataset sizes from the lookup table
defer func(sizes []uint64) { datasetSizes = sizes }(datasetSizes)
tests, datasetSizes = datasetSizes, []uint64{}
for i, test := range tests {
if size := datasetSize(uint64(i*epochLength) + 1); size != test {
t.Errorf("dataset %d: dataset size mismatch: have %d, want %d", i, size, test)
}
}
}
<file_sep>package smartpool
import (
"github.com/ethereum/go-ethereum/common"
"math/big"
"time"
)
type Input struct {
rpcEndPoint string
keystorePath string
shareThreshold int
claimThreshold int
shareDifficulty *big.Int
submitInterval time.Duration
contractAddr string
minerAddr string
extraData string
hotStop bool
}
func (i *Input) RPCEndpoint() string { return i.rpcEndPoint }
func (i *Input) KeystorePath() string { return i.keystorePath }
func (i *Input) ShareThreshold() int { return i.shareThreshold }
func (i *Input) ClaimThreshold() int { return i.claimThreshold }
func (i *Input) ShareDifficulty() *big.Int { return i.shareDifficulty }
func (i *Input) SubmitInterval() time.Duration { return i.submitInterval }
func (i *Input) ContractAddress() string { return i.contractAddr }
func (i *Input) MinerAddress() string { return i.minerAddr }
func (i *Input) ExtraData() string { return i.extraData }
func (i *Input) HotStop() bool { return i.hotStop }
func (i *Input) SetMinerAddress(addr common.Address) {
i.minerAddr = addr.Hex()
}
func (i *Input) SetExtraData(extra string) {
i.extraData = extra
}
func (i *Input) SetContractAddress(addr common.Address) {
i.contractAddr = addr.Hex()
}
func NewInput(
rpcEndPoint string,
keystorePath string,
shareThreshold int,
claimThreshold int,
shareDifficulty *big.Int,
submitInterval time.Duration,
contractAddr string,
minerAddr string,
extraData string,
hotStop bool,
) *Input {
return &Input{
rpcEndPoint, keystorePath, shareThreshold, claimThreshold, shareDifficulty,
submitInterval, contractAddr, minerAddr, extraData, hotStop,
}
}
<file_sep>package geth
import (
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"math/big"
)
var RegisterEventTopic = common.HexToHash("0x1d759fb22634fe2d322d688a4b46aaf185dd0a3db78ccf01a9218f00ac3df03f").Big()
var SubmitClaimEventTopic = common.HexToHash("0x53ab9d877ae22286591454f9a8d58501caa34a07c99eac2c09bc0066c065400d").Big()
var VerifyClaimEventTopic = common.HexToHash("0x096caf97202169a068288f02e51ff9fcc85f98e1477f6ad9acbf6ebf25dbcd00").Big()
var SetEpochDataEventTopic = common.HexToHash("0x5cd723400be8430351b9cbaa5ea421b3fb2528c6a7650c493f895e7d97750da1").Big()
var ResetOpenClaimsEventTopic = common.HexToHash("b4392733a0c6dd35350239f2e9eb97a9a9e574fc090445fb267bea4114f9d706").Big()
var ErrorMap = map[uint64][]string{
0x80000000: []string{"register", "miner id is already in use", "miner id"},
0x80000001: []string{"register", "payment address 0 is forbiden", ""},
0x81000000: []string{"submitClaim", "miner is not registered", ""},
0x81000001: []string{"submitClaim", "min counter is too low", "last submission counter value"},
0x82000000: []string{"setEpochData", "only owner can set data", "msg.sender"},
0x82000001: []string{"setEpochData", "epoch already set", "epoch number"},
0x83000000: []string{"verifyExtraData", "miner id not as expected", "miner id"},
0x83000001: []string{"verifyExtraData", "difficulty is not as expected", "encoded difficulty"},
0x84000000: []string{"verifyClaim", "contract balance is too low to pay", "payment"},
0x84000001: []string{"verifyClaim", "claim seed is 0", ""},
0x84000002: []string{"verifyClaim", "share index is not as expected", "expected index"},
0x84000003: []string{"verifyClaim", "there are no pending claims", ""},
0x84000004: []string{"verifyClaim", "extra data not as expected", "extra data"},
0x84000005: []string{"verifyClaim", "coinbase not as expected", "coinbase"},
0x84000006: []string{"verifyClaim", "counter is smaller than min", "counter"},
0x84000007: []string{"verifyClaim", "counter is smaller than max", "counter"},
0x84000008: []string{"verifyClaim", "verification of augmented merkle tree failed", ""},
0x84000009: []string{"verifyClaim", "ethash difficulty too low (or hashimoto verification failed)", "computed ethash value"},
0x8400000a: []string{"verifyClaim", "epoch data was not set", "epoch number"},
}
func ErrorMsg(errCode, errInfo *big.Int) string {
infos := ErrorMap[errCode.Uint64()]
if len(infos) == 0 {
smartpool.Output.Printf("Invalid errCode(0x%s)\n", errCode.Text(16))
return ""
} else if len(infos) != 3 {
smartpool.Output.Printf("ErrorMap is not welformed for errCode(0x%s)\n", errCode.Text(16))
return ""
} else {
msg := infos[1]
function := infos[0]
name := infos[2]
return fmt.Sprintf(
"Contract returned error code 0x%s. \n%s: %s. %s is 0x%s\n",
errCode.Text(16),
function,
msg,
name,
errInfo.Text(16),
)
}
}
<file_sep>// Package ethereum contains all necessary components to plug into smartpool
// to work with ethereum blockchain. Such as: Contract, Network Client,
// Share receiver...
// This package also provides interfaces for different ethereum clients to
// be able to work with smartpool.
package ethereum
import (
"encoding/binary"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"math/big"
"time"
)
var maxUint256 = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
// Work represents Ethereum pow work
type Work struct {
BlockHeader *types.Header
Hash string
SeedHash string
ShareDifficulty *big.Int
MinerAddress string
CreatedAt time.Time
}
func (w *Work) ID() string {
return w.Hash
}
func (w *Work) SolutionState(s *Share, shareDiff *big.Int) int {
hash := s.BlockHeader().HashNoNonce().Bytes()
seed := make([]byte, 40)
copy(seed, hash)
binary.LittleEndian.PutUint64(seed[32:], s.Nonce())
seed = crypto.Keccak512(seed)
hashimoto := new(big.Int).SetBytes(crypto.Keccak256(append(seed, s.MixDigest().Bytes()...)))
blockTarget := new(big.Int).Div(maxUint256, s.BlockHeader().Difficulty)
shareTarget := new(big.Int).Div(maxUint256, s.ShareDifficulty())
if hashimoto.Cmp(blockTarget) <= 0 {
return 2
}
if hashimoto.Cmp(shareTarget) <= 0 {
return 1
}
return 0
}
func (w *Work) AcceptSolution(sol smartpool.Solution) smartpool.Share {
solution := sol.(*Solution)
s := &Share{
blockHeader: w.BlockHeader,
nonce: solution.Nonce,
mixDigest: solution.MixDigest,
shareDifficulty: w.ShareDifficulty,
minerAddress: w.MinerAddress,
}
s.SolutionState = w.SolutionState(s, s.ShareDifficulty())
return s
}
func (w *Work) PoWHash() common.Hash {
return common.HexToHash(w.Hash)
}
func NewWork(h *types.Header, ph string, sh string, diff *big.Int, miner string) *Work {
return &Work{h, ph, sh, diff, miner, time.Now()}
}
<file_sep>package protocol
import (
"github.com/ethereum/go-ethereum/common"
"math/big"
"testing"
"time"
)
var rig *testRig = &testRig{}
func newTestSmartPool() *SmartPool {
return NewSmartPool(
&testPoolMonitor{},
&testShareReceiver{}, &testNetworkClient{},
&testClaimRepo{}, &testPersistentStorage{},
&testContract{},
&testStatRecorder{},
common.HexToAddress("0x001aDBc838eDe392B5B054A47f8B8c28f2fA9F3F"),
common.HexToAddress("0x001aDBc838eDe392B5B054A47f8B8c28f2fA9F3F"),
"extradata", time.Minute,
100, 1, true, &testUserInput{},
)
}
func TestSmartPoolRegisterMinerAfterRegister(t *testing.T) {
sp := newTestSmartPool()
testContract := sp.Contract.(*testContract)
testContract.Registered = true
if !sp.Register(common.Address{}) {
t.Fail()
}
}
func TestSmartPoolRegisterMinerWhenUnableToRegister(t *testing.T) {
sp := newTestSmartPool()
testContract := sp.Contract.(*testContract)
testContract.Registerable = false
if sp.Register(common.Address{}) {
t.Fail()
}
}
func TestSmartPoolRegisterMinerWhenAbleToRegister(t *testing.T) {
sp := newTestSmartPool()
testContract := sp.Contract.(*testContract)
testContract.Registerable = true
sp.Contract = testContract
if !sp.Register(common.Address{}) {
t.Fail()
}
}
func TestSmartPoolReturnAWorkToMiner(t *testing.T) {
sp := newTestSmartPool()
sp.GetWork(rig)
}
func TestSmartPoolAcceptSolution(t *testing.T) {
sp := newTestSmartPool()
if !sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(10)}) {
t.Fail()
}
}
func TestSmartPoolNotAcceptSolution(t *testing.T) {
sp := newTestSmartPool()
sp.LatestCounter = big.NewInt(10)
if sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)}) {
t.Fail()
}
}
func TestSmartPoolPackageAllCurrentShares(t *testing.T) {
sp := newTestSmartPool()
sp.LatestCounter = big.NewInt(5)
claim := sp.GetCurrentClaim(1)
if claim != nil {
t.Fail()
}
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)})
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(8)})
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(10)})
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(5)})
claim = sp.GetCurrentClaim(1)
if claim.NumShares().Cmp(big.NewInt(3)) != 0 {
t.Fail()
}
}
func TestSmartPoolSubmitCorrectClaim(t *testing.T) {
sp := newTestSmartPool()
sp.ShareThreshold = 1
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)})
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(8)})
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(10)})
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(5)})
sp.Submit()
testContract := sp.Contract.(*testContract)
claim := testContract.GetLastSubmittedClaim()
if claim.NumShares().Cmp(big.NewInt(4)) != 0 {
t.Fail()
}
}
func TestSmartPoolReturnFalseIfNoClaim(t *testing.T) {
sp := newTestSmartPool()
if ok, _ := sp.Submit(); ok {
t.Fail()
}
}
func TestSmartPoolSuccessfullySubmitAndVerifyClaim(t *testing.T) {
sp := newTestSmartPool()
sp.ShareThreshold = 1
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)})
if ok, _ := sp.Submit(); !ok {
t.Fail()
}
}
func TestSmartPoolGetCorrectShareIndex(t *testing.T) {
sp := newTestSmartPool()
sp.ShareThreshold = 1
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)})
sp.Submit()
c := sp.Contract.(*testContract)
if c.IndexRequestedTime == nil {
t.Fail()
}
}
func TestSmartPoolGetCorrectShareIndexAfterSubmitClaim(t *testing.T) {
sp := newTestSmartPool()
sp.ShareThreshold = 1
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)})
sp.Submit()
c := sp.Contract.(*testContract)
if (*c.SubmitTime).After(*c.IndexRequestedTime) {
t.Fail()
}
}
func TestSmartPoolSubmitReturnFalseWhenUnableToSubmit(t *testing.T) {
sp := newTestSmartPool()
c := sp.Contract.(*testContract)
c.SubmitFailed = true
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)})
if ok, _ := sp.Submit(); ok {
t.Fail()
}
}
func TestSmartPoolSubmitReturnFalseWhenUnableToVerify(t *testing.T) {
sp := newTestSmartPool()
c := sp.Contract.(*testContract)
c.VerifyFailed = true
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)})
if ok, _ := sp.Submit(); ok {
t.Fail()
}
}
func TestSmartPoolDoesntRunWhenMinerRegistered(t *testing.T) {
sp := newTestSmartPool()
if sp.Run() {
t.Fail()
}
}
func TestSmartPoolOnlySubmitPeriodly(t *testing.T) {
sp := newTestSmartPool()
ct := sp.Contract.(*testContract)
ct.Registered = true
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)})
c := sp.Contract.(*testContract)
sp.SubmitInterval = 40 * time.Millisecond
sp.ShareThreshold = 1
sp.Run()
if c.GetLastSubmittedClaim() != nil {
t.Fail()
}
time.Sleep(60 * time.Millisecond)
if c.GetLastSubmittedClaim() == nil {
t.Fail()
}
}
func TestSmartPoolOnlySubmitWhenMeetShareThreshold(t *testing.T) {
sp := newTestSmartPool()
sp.AcceptSolution(rig, &testSolution{Counter: big.NewInt(9)})
c := sp.Contract.(*testContract)
sp.SubmitInterval = 40 * time.Millisecond
sp.ShareThreshold = 3
sp.Run()
time.Sleep(60 * time.Millisecond)
if c.GetLastSubmittedClaim() != nil {
t.Fail()
}
}
func TestSmartPoolOnlyRunAfterNetworkReady(t *testing.T) {
sp := newTestSmartPool()
testContract := sp.Contract.(*testContract)
testContract.Registered = true
nw := sp.NetworkClient.(*testNetworkClient)
nw.NotReadyToMine = true
ran := make(chan bool, 1)
timeout := make(chan bool, 1)
go func() {
ran <- sp.Run()
}()
go func() {
time.Sleep(100 * time.Millisecond)
timeout <- true
}()
select {
case <-ran:
t.Fail()
case <-timeout:
break
}
}
func TestSmartPoolStopIfClientVersionChangedInHotStopMode(t *testing.T) {
sp := newTestSmartPool()
testContract := sp.Contract.(*testContract)
testContract.Registered = true
timeout := make(chan bool, 1)
sp.PoolMonitor.(*testPoolMonitor).ClientUpdate = true
sp.Run()
go func() {
time.Sleep(100 * time.Millisecond)
timeout <- true
}()
select {
case <-sp.SubmitterStopped:
break
case <-timeout:
t.Fail()
}
}
func TestSmartPoolDoesntStopIfHotStopModeIsDisabled(t *testing.T) {
sp := newTestSmartPool()
sp.HotStop = false
testContract := sp.Contract.(*testContract)
testContract.Registered = true
timeout := make(chan bool, 1)
sp.PoolMonitor.(*testPoolMonitor).ContractUpdate = true
sp.Run()
go func() {
time.Sleep(100 * time.Millisecond)
timeout <- true
}()
select {
case <-sp.SubmitterStopped:
t.Fail()
case <-timeout:
break
}
}
func TestSmartPoolStopIfContractAddressChangedInHotStopMode(t *testing.T) {
sp := newTestSmartPool()
testContract := sp.Contract.(*testContract)
testContract.Registered = true
timeout := make(chan bool, 1)
sp.PoolMonitor.(*testPoolMonitor).ContractUpdate = true
sp.Run()
go func() {
time.Sleep(100 * time.Millisecond)
timeout <- true
}()
select {
case <-sp.SubmitterStopped:
break
case <-timeout:
t.Fail()
}
}
<file_sep>package ethereum
import (
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum/ethash"
"github.com/SmartPool/smartpool-client/mtree"
"math/big"
)
type EthashContract struct {
ethashClient EthashContractClient
}
func (c *EthashContract) SetEpochData(epoch int) error {
var err error
smartpool.Output.Printf("Checking DAG file. Generate if needed...\n")
ethash.MakeDAG(uint64(epoch*30000), ethash.DefaultDir)
fullSize := ethash.DAGSize(uint64(epoch * 30000))
fullSizeIn128Resolution := fullSize / 128
path := ethash.PathToDAG(uint64(epoch), ethash.DefaultDir)
branchDepth := len(fmt.Sprintf("%b", fullSizeIn128Resolution-1))
mt := mtree.NewDagTree()
// TODO: 10 is just an experimental level
mt.RegisterStoredLevel(uint32(branchDepth), 10)
processDuringRead(path, mt)
mt.Finalize()
err = c.ethashClient.SetEpochData(
big.NewInt(int64(epoch)),
big.NewInt(int64(fullSizeIn128Resolution)),
big.NewInt(int64(branchDepth-10)),
mt.MerkleNodes(),
)
if err != nil {
fmt.Printf("Got error: %s\n", err)
return err
}
fmt.Printf("Done.\n")
return nil
}
func NewEthashContract(client EthashContractClient) *EthashContract {
return &EthashContract{client}
}
<file_sep>package ethereum
// DAGReader provides a way for smartpool to retrieve DAG dataset. How the DAG
// is retrieve is upto structs implementing the interface.
type DAGReader interface {
// NextWord return next data chunk of the DAG dataset. First 8 bytes must
// be ignored.
NextWord() ([]byte, error)
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
"math/big"
"reflect"
"sort"
"testing"
)
func newTestShares() Shares {
return Shares{
&testShare{c: big.NewInt(10), d: big.NewInt(10), h: 1},
&testShare{c: big.NewInt(1), d: big.NewInt(4), h: 2},
&testShare{c: big.NewInt(5), d: big.NewInt(5), h: 3},
&testShare{c: big.NewInt(8), d: big.NewInt(9), h: 4},
}
}
func TestSharesSortSharesAscendingCounter(t *testing.T) {
s := newTestShares()
sort.Sort(s)
for i, _ := range s[:] {
if i > 0 && s[i].Counter().Cmp(s[i-1].Counter()) < 0 {
t.Fail()
}
}
}
func TestClaimNumSharesReturnsNumberOfShare(t *testing.T) {
s := &Claim{Shares{
&testShare{big.NewInt(10), big.NewInt(10), 0}},
nil,
nil,
nil,
}
if s.NumShares().Int64() != 1 {
t.Fail()
}
}
func TestClaimAddShare(t *testing.T) {
s := NewClaim()
s.AddShare(&testShare{big.NewInt(10), big.NewInt(10), 0})
if s.NumShares().Int64() != 1 {
t.Fail()
}
}
func TestClaimDifficultyReturnMinDifficultyOfItsShares(t *testing.T) {
s := &Claim{newTestShares(), nil, nil, nil}
if s.Difficulty().Cmp(big.NewInt(4)) != 0 {
t.Fail()
}
}
func TestClaimMinReturnMinCounterOfItsShares(t *testing.T) {
s := &Claim{newTestShares(), nil, nil, nil}
if s.Min().Cmp(big.NewInt(1)) != 0 {
t.Fail()
}
}
func TestClaimMinReturnMaxCounterOfItsShares(t *testing.T) {
s := &Claim{newTestShares(), nil, nil, nil}
if s.Max().Cmp(big.NewInt(10)) != 0 {
t.Fail()
}
}
func TestClaimAugMerkle(t *testing.T) {
s := &Claim{newTestShares(), nil, nil, nil}
result := smartpool.SPHash{151, 170, 188, 143, 116, 177, 57, 134, 27, 7, 73, 156, 173, 26, 237, 226}
if !reflect.DeepEqual(s.AugMerkle(), result) {
t.Fail()
}
}
<file_sep>// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// +build go1.8
package ethash
import "math/big"
// cacheSize calculates and returns the size of the ethash verification cache that
// belongs to a certain block number. The cache size grows linearly, however, we
// always take the highest prime below the linearly growing threshold in order to
// reduce the risk of accidental regularities leading to cyclic behavior.
func cacheSize(block uint64) uint64 {
// If we have a pre-generated value, use that
epoch := int(block / epochLength)
if epoch < len(cacheSizes) {
return cacheSizes[epoch]
}
// No known cache size, calculate manually (sanity branch only)
size := uint64(cacheInitBytes + cacheGrowthBytes*uint64(epoch) - hashBytes)
for !new(big.Int).SetUint64(size / hashBytes).ProbablyPrime(1) { // Always accurate for n < 2^64
size -= 2 * hashBytes
}
return size
}
// datasetSize calculates and returns the size of the ethash mining dataset that
// belongs to a certain block number. The dataset size grows linearly, however, we
// always take the highest prime below the linearly growing threshold in order to
// reduce the risk of accidental regularities leading to cyclic behavior.
func datasetSize(block uint64) uint64 {
// If we have a pre-generated value, use that
epoch := int(block / epochLength)
if epoch < len(datasetSizes) {
return datasetSizes[epoch]
}
// No known dataset size, calculate manually (sanity branch only)
size := uint64(datasetInitBytes + datasetGrowthBytes*uint64(epoch) - mixBytes)
for !new(big.Int).SetUint64(size / mixBytes).ProbablyPrime(1) { // Always accurate for n < 2^64
size -= 2 * mixBytes
}
return size
}
<file_sep>// Package protocol implements smartpool secured protocol between client side
// and contract side. It works on high abstraction level of interfaces and
// types of smartpool package.
package protocol
import (
"errors"
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"math/big"
"os"
"os/signal"
"runtime/debug"
"sync"
"syscall"
"time"
)
const COUNTER_FILE string = "counter"
// SmartPool represent smartpool protocol which interacts smartpool high level
// interfaces and types together to do following procedures:
// 1. Register the miner if needed
// 2. Give miner works
// 3. Accept solutions from miners and construct corresponding shares to
// add into current active claim. It returns true when the share is
// successfully added, false otherwise.
// A share can only be added when it's counter is greater than the maximum
// counter of the last verified claim
// 4. Package shares into a claim after interval of an amount of time.
// 5. Then Submit the claim to the contract
// 6. Then If successful, submit the claim proof to the contract.
type SmartPool struct {
PoolMonitor smartpool.PoolMonitor
ShareReceiver smartpool.ShareReceiver
NetworkClient smartpool.NetworkClient
Contract smartpool.Contract
StatRecorder smartpool.StatRecorder
ClaimRepo ClaimRepo
Storage smartpool.PersistentStorage
LatestCounter *big.Int
ContractAddress common.Address
MinerAddress common.Address
ExtraData string
SubmitInterval time.Duration
ShareThreshold int
ClaimThreshold int
HotStop bool
loopStarted bool
ticker <-chan time.Time
counterMu sync.RWMutex
runMu sync.Mutex
SubmitterStopped chan bool
stopSubmitterChan chan bool
signal chan os.Signal
Input smartpool.UserInput
}
// Register registers miner address to the contract.
// It returns false if the miner address couldn't be able to register to the
// pool even though it didn't register before.
// It returns true otherwise, in this case, Register does nothing if the
// address registered before or registers the address if it didn't.
func (sp *SmartPool) Register(addr common.Address) bool {
if sp.Contract.IsRegistered() {
smartpool.Output.Printf("The address is already registered to the pool. Good to go.\n")
return true
}
if !sp.Contract.CanRegister() {
smartpool.Output.Printf("Your etherbase address couldn't register to the pool. You need to try another address.\n")
return false
}
smartpool.Output.Printf("Registering to the pool. Please wait...")
err := sp.Contract.Register(addr)
if err != nil {
smartpool.Output.Printf("Unable to register to the pool: %s\n", err)
return false
}
if !sp.Contract.IsRegistered() {
smartpool.Output.Printf("You are not accepted by the pool yet. Please wait about 30s and try again.\n")
return false
}
smartpool.Output.Printf("Done.\n")
return true
}
// GetWork returns miner work
func (sp *SmartPool) GetWork(rig smartpool.Rig) smartpool.Work {
return sp.NetworkClient.GetWork()
}
func (sp *SmartPool) SubmitHashrate(rig smartpool.Rig, hashrate hexutil.Uint64, id common.Hash) bool {
sp.StatRecorder.RecordHashrate(hashrate, id, rig)
return sp.NetworkClient.SubmitHashrate(hashrate, id)
}
// AcceptSolution accepts solutions from miners and construct corresponding
// shares to add into current active claim. It returns true when the share is
// successfully added, false otherwise.
// A share can only be added when it's counter is greater than the maximum
// counter of the last verified claim
func (sp *SmartPool) AcceptSolution(rig smartpool.Rig, s smartpool.Solution) bool {
share := sp.ShareReceiver.AcceptSolution(s)
sp.counterMu.RLock()
defer sp.counterMu.RUnlock()
if share != nil && share.FullSolution() {
smartpool.Output.Printf("-->Yay! We found potential block!<--\n")
sp.NetworkClient.SubmitSolution(s)
}
var success bool
if share == nil || share.Counter().Cmp(sp.LatestCounter) <= 0 {
smartpool.Output.Printf("Share is discarded.\n")
if share != nil && share.Counter().Cmp(sp.LatestCounter) <= 0 {
smartpool.Output.Printf("Share's counter (0x%s) is lower than last claim max counter (0x%s)\n", share.Counter().Text(16), sp.LatestCounter.Text(16))
}
success = false
} else {
err := sp.ClaimRepo.AddShare(share)
if err != nil {
smartpool.Output.Printf("Discarded because of %s.\n", err.Error())
success = false
} else {
fmt.Print(".")
success = true
}
}
go func() {
sp.StatRecorder.RecordShare("submitted", share, rig)
if success {
if share.FullSolution() {
sp.StatRecorder.RecordShare("fullsolution", share, rig)
} else {
sp.StatRecorder.RecordShare("accepted", share, rig)
}
} else {
sp.StatRecorder.RecordShare("rejected", share, rig)
}
}()
return success
}
// GetCurrentClaim returns new claim containing unsubmitted shares. If there
// is no new shares, it returns nil.
func (sp *SmartPool) GetCurrentClaim(threshold int) smartpool.Claim {
return sp.ClaimRepo.GetCurrentClaim(threshold)
}
func (sp *SmartPool) GetVerificationIndex(claim smartpool.Claim) (*big.Int, *big.Int) {
var claimIndex, shareIndex *big.Int
var err error
for {
claimIndex, shareIndex, err = sp.Contract.GetShareIndex(claim)
if err != nil {
smartpool.Output.Printf("Got error(%s) while trying to get verification index. Retry in 10s...\n", err.Error())
time.Sleep(10 * time.Second)
} else {
return claimIndex, shareIndex
}
}
}
func (sp *SmartPool) SealClaim() smartpool.Claim {
sp.counterMu.Lock()
defer sp.counterMu.Unlock()
claim := sp.GetCurrentClaim(sp.ShareThreshold)
if claim != nil {
sp.LatestCounter = claim.Max()
smartpool.Output.Printf("Set Latest Counter to 0x%s.\n", sp.LatestCounter.Text(16))
smartpool.Output.Printf("Persisting Latest Counter to storage...")
persistLatestCounter(sp.Storage, sp.LatestCounter)
smartpool.Output.Printf("Done.\n")
}
return claim
}
func persistLatestCounter(ps smartpool.PersistentStorage, counter *big.Int) error {
return ps.Persist(counter, COUNTER_FILE)
}
func (sp *SmartPool) consistencyCheck() error {
waited := 0
for {
numOpenClaimsContract, err := sp.Contract.NumOpenClaims()
if err != nil {
return err
}
if numOpenClaimsContract.Uint64() != sp.ClaimRepo.NumOpenClaims() {
if waited >= 140 {
smartpool.Output.Printf("Unrecoverable inconsistent state between client and contract. Resetting both sides...")
sp.ClaimRepo.ResetOpenClaims()
err := sp.Contract.ResetOpenClaims()
if err != nil {
return err
} else {
smartpool.Output.Printf("Done.\n")
}
break
} else {
smartpool.Output.Printf(
"Inconsistent open claim list between client(%d claims) and contract(%d claims). Recheck in 14s...\n",
sp.ClaimRepo.NumOpenClaims(),
numOpenClaimsContract.Uint64(),
)
time.Sleep(14 * time.Second)
waited += 14
}
} else {
break
}
}
return nil
}
// Submit does all the protocol that communicates with the contract to submit
// the claim then verify it.
// It returns true when the claim is fully verified and accepted by the
// contract. It returns false otherwise.
func (sp *SmartPool) Submit() (bool, error) {
claim := sp.SealClaim()
if claim == nil {
return false, nil
}
if err := sp.consistencyCheck(); err != nil {
return false, err
}
smartpool.Output.Printf("Submitting the claim with %d shares.\n", claim.NumShares().Int64())
var lastClaim bool
if int(sp.ClaimRepo.NumOpenClaims()+1) >= sp.ClaimThreshold {
lastClaim = true
} else {
lastClaim = false
}
sp.ClaimRepo.PutOpenClaim(claim)
smartpool.Output.Printf("The claim is successfully put into open claims queue.\n")
subErr := sp.Contract.SubmitClaim(claim, lastClaim)
if subErr != nil {
smartpool.Output.Printf("Got error submitting claim to contract: %s\n", subErr)
sp.ClaimRepo.RemoveOpenClaim(claim)
sp.StatRecorder.RecordClaim("error", claim)
return false, subErr
}
sp.StatRecorder.RecordClaim("submitted", claim)
smartpool.Output.Printf("The claim is successfully submitted.\n")
if lastClaim {
sp.ClaimRepo.SealClaimBatch()
smartpool.Output.Printf("Waiting for verification index...")
claimIndex, shareIndex := sp.GetVerificationIndex(claim)
smartpool.Output.Printf("Verification for share index(%d) in claim index(%d) has been requested.\n", shareIndex.Int64(), claimIndex.Int64())
claim = sp.ClaimRepo.GetOpenClaim(int(claimIndex.Int64()))
if claim == nil {
smartpool.Output.Printf("Got nil claim for share index(%d) in claim index(%d). This is a bug. Please report it to SmartPool Team.\n", shareIndex.Int64(), claimIndex.Int64())
return false, errors.New("Nil claim. Incorrect verification indexes")
}
smartpool.Output.Printf("Submitting claim verification...\n")
verErr := sp.Contract.VerifyClaim(claimIndex, shareIndex, claim)
if verErr != nil {
smartpool.Output.Printf("%s\n", verErr)
sp.StatRecorder.RecordClaim("rejected", claim)
return false, verErr
}
smartpool.Output.Printf("Claim is successfully verified.\n")
sp.StatRecorder.RecordClaim("accepted", claim)
}
return true, nil
}
func (sp *SmartPool) stopSubmitter() {
sp.stopSubmitterChan <- true
}
func (sp *SmartPool) monitor() {
for {
if sp.PoolMonitor.RequireContractUpdate() {
smartpool.Output.Printf(
"We deployed new contract at %s. Please restart SmartPool client with --spcontract %s.\n",
sp.PoolMonitor.ContractAddress().Hex(),
sp.PoolMonitor.ContractAddress().Hex())
if sp.HotStop {
sp.stopSubmitter()
return
}
}
if sp.PoolMonitor.RequireClientUpdate() {
smartpool.Output.Printf("Your SmartPool client is too old. Please update to new version by going to https://github.com/SmartPool/smartpool-client.\n")
if sp.HotStop {
sp.stopSubmitter()
return
}
}
time.Sleep(1 * time.Minute)
}
}
func (sp *SmartPool) SubmitterRunning() bool {
return sp.loopStarted
}
func (sp *SmartPool) shouldStop(err error) bool {
if err == nil {
return false
}
if err.Error() == "timeout error" {
smartpool.Output.Printf("The tx might not be verified. Current claim is dropped. Continue with next claim.\n")
return false
} else if sp.HotStop {
return true
} else {
return false
}
}
func (sp *SmartPool) runPersister() {
for {
sp.persist()
time.Sleep(time.Minute)
}
}
func (sp *SmartPool) persist() {
sp.ClaimRepo.Persist(sp.Storage)
sp.StatRecorder.Persist(sp.Storage)
sp.ShareReceiver.Persist(sp.Storage)
}
func (sp *SmartPool) actOnTick() {
defer func() {
if r := recover(); r != nil {
smartpool.Output.Printf("Recovered in actOnTick: %v\n", r)
debug.PrintStack()
}
}()
var err error
Loop:
for {
select {
case <-sp.ticker:
_, err = sp.Submit()
if sp.shouldStop(err) {
smartpool.Output.Printf("SmartPool stopped. If you want SmartPool to keep running, please use \"--no-hot-stop\" to disable Hot Stop mode.\n")
break Loop
}
case <-sp.stopSubmitterChan:
break Loop
}
}
sp.Exit()
}
func (sp *SmartPool) Exit() {
smartpool.Output.Printf("Persisting current state to disk...\n")
sp.persist()
smartpool.Output.Printf("Gracefully stopped SmartPool.\n")
sp.SubmitterStopped <- true
smartpool.Output.Printf("Close log file.\n")
smartpool.Output.Close()
}
// Run can be called at most once to start a loop to submit and verify claims
// after an interval.
// If the loop has not been started, it starts the loop and return true, it
// return false otherwise.
func (sp *SmartPool) Run() bool {
sp.runMu.Lock()
defer sp.runMu.Unlock()
if sp.Register(sp.MinerAddress) {
if sp.loopStarted {
smartpool.Output.Printf("Warning: calling Run() multiple times\n")
return false
}
err := sp.NetworkClient.Configure(
sp.ContractAddress,
sp.ExtraData,
)
if err != nil {
return false
}
for {
if sp.NetworkClient.ReadyToMine() {
smartpool.Output.Printf("The network is ready for mining.\n")
sp.ticker = time.Tick(sp.SubmitInterval)
go sp.monitor()
go sp.actOnTick()
smartpool.Output.Printf("Share collector is running...\n")
go sp.runPersister()
smartpool.Output.Printf("Share persister and stat persister are running...\n")
go sp.handleSignal()
sp.loopStarted = true
break
}
smartpool.Output.Printf("The network is not ready for mining yet. Retry in 10s...\n")
time.Sleep(10 * time.Second)
}
return true
} else {
return false
}
}
func (sp *SmartPool) handleSignal() {
<-sp.signal
smartpool.Output.Printf("Got shutdown signal:\n")
sp.Exit()
}
func loadLatestCounter(ps smartpool.PersistentStorage) (*big.Int, error) {
counter := big.NewInt(0)
loadedCounter, err := ps.Load(counter, COUNTER_FILE)
counter = loadedCounter.(*big.Int)
return counter, err
}
func NewSmartPool(
pm smartpool.PoolMonitor, sr smartpool.ShareReceiver,
nc smartpool.NetworkClient, cr ClaimRepo, ps smartpool.PersistentStorage,
co smartpool.Contract, stat smartpool.StatRecorder, ca common.Address,
ma common.Address, ed string, interval time.Duration, shareThreshold int,
claimThreshold int, hotStop bool, input smartpool.UserInput) *SmartPool {
counter, err := loadLatestCounter(ps)
if err != nil {
smartpool.Output.Printf("Couldn't load counter from storage. Initialize it to 0.\n")
counter = big.NewInt(0)
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
return &SmartPool{
PoolMonitor: pm,
ShareReceiver: sr,
NetworkClient: nc,
ClaimRepo: cr,
Storage: ps,
Contract: co,
StatRecorder: stat,
ContractAddress: ca,
MinerAddress: ma,
ExtraData: ed,
SubmitInterval: interval,
ShareThreshold: shareThreshold,
ClaimThreshold: claimThreshold,
HotStop: hotStop,
loopStarted: false,
LatestCounter: counter,
counterMu: sync.RWMutex{},
runMu: sync.Mutex{},
SubmitterStopped: make(chan bool, 1),
stopSubmitterChan: make(chan bool, 1),
Input: input,
signal: sig,
}
}
<file_sep>package geth
import (
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"strconv"
"strings"
)
// var PoolMonitorAddress = common.HexToAddress("0x7727D4535f1A9c9ECC59FB17B6bF8145C7d5D58c")
// var PoolMonitorAddress = common.HexToAddress("0xddcdad6b099b1b237bdb1341cc6881eb63ee3b28")
type PoolMonitor struct {
client *PoolMonitorClient
version [3]byte
contract common.Address
}
func (pm *PoolMonitor) ContractAddress() common.Address {
address, err := pm.client.PoolContract(nil)
if err != nil {
smartpool.Output.Printf("Getting pool contract from gateway failed. Error: %s\n", err)
}
return address
}
func (pm *PoolMonitor) RequireClientUpdate() bool {
version, err := pm.client.ClientVersion(nil)
if err != nil {
smartpool.Output.Printf("Getting client version from gateway failed. Error: %s\n", err)
return false
}
if version[0] != pm.version[0] || version[1] != pm.version[1] {
return true
}
return false
}
func (pm *PoolMonitor) RequireContractUpdate() bool {
addr, err := pm.client.PoolContract(nil)
if err != nil {
smartpool.Output.Printf("Getting contract address from gateway failed. Error: %s\n", err)
return false
}
return addr != pm.contract
}
func versionBytes(version string) [3]byte {
vs := strings.Split(version, ".")
major, _ := strconv.Atoi(vs[0])
minor, _ := strconv.Atoi(vs[1])
patch, _ := strconv.Atoi(vs[2])
return [3]byte{byte(major), byte(minor), byte(patch)}
}
func NewPoolMonitor(
gatewayAddr common.Address, contractAddr common.Address,
version string, ipc string) (*PoolMonitor, error) {
client, err := getClient(ipc)
if err != nil {
smartpool.Output.Printf("Couldn't connect to Geth via IPC file. Error: %s\n", err)
return nil, err
}
poolMonitor, err := NewPoolMonitorClient(gatewayAddr, client)
if err != nil {
smartpool.Output.Printf("Couldn't get SmartPool information from Ethereum Blockchain. Error: %s\n", err)
return nil, err
}
return &PoolMonitor{
poolMonitor,
versionBytes(version),
contractAddr}, nil
}
<file_sep>package protocol
import (
"github.com/ethereum/go-ethereum/common"
)
type testPoolMonitor struct {
ClientUpdate bool
ContractUpdate bool
ContractAddr common.Address
}
func (pm *testPoolMonitor) RequireClientUpdate() bool {
return pm.ClientUpdate
}
func (pm *testPoolMonitor) ContractAddress() common.Address {
return pm.ContractAddr
}
func (pm *testPoolMonitor) RequireContractUpdate() bool {
return pm.ContractUpdate
}
<file_sep>package protocol
import (
"math/big"
)
type testSolution struct {
Counter *big.Int
}
func (s *testSolution) WorkID() string {
return "work"
}
<file_sep>package ethereum
import (
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"math/big"
)
func BuildExtraData(address common.Address, diff *big.Int) string {
// id = address % (26+26+10)**11
base := big.NewInt(0)
base.Exp(big.NewInt(62), big.NewInt(11), nil)
id := big.NewInt(0)
id.Mod(address.Big(), base)
return fmt.Sprintf("SmartPool-%s%s", smartpool.BigToBase62(id), smartpool.BigToBase62(diff))
}
<file_sep>package protocol
import (
"math/big"
)
type testPersistentStorage struct{}
func (self *testPersistentStorage) Persist(data interface{}, id string) error {
return nil
}
func (self *testPersistentStorage) Load(data interface{}, id string) (interface{}, error) {
if id == COUNTER_FILE {
return big.NewInt(0), nil
}
return nil, nil
}
<file_sep># Smartpool - The first decentralized mining pool based on smart contract (alpha)
[](https://gitter.im/SmartPool/Lobby)
## Ropsten testnet
[Smartpool](http://smartpool.io) is [live on Ropsten testnet](https://ropsten.etherscan.io/address/0xf7d93bcb8e4372f46383ecee82f9adf1aa397ba9).
This repository consists of the client software.
The smart contract repository is [here](https://github.com/SmartPool/contracts).
### Requirements
#### OS
The client is currently tested only on Mac OS and Ubuntu.
#### Golang compiler
[Golang compiler](https://golang.org/) version 1.7 or higher.
#### Parity client
[Ethereum Parity client](https://github.com/paritytech/parity/releases) version 1.5.9 or higher.
#### Geth client
[Ethereum Geth client](https://github.com/ethereum/go-ethereum) needs to be compiled from source.
#### Ethminer
We support CPU and GPU mining with [ethminer](https://github.com/ethereum-mining/ethminer) version 1.2.9 or higher. Current versions do not do CPU mining so an older version is necessary to CPU mine on testnet.
#### ETH balance
To run smartpool you must have a Ropsten testnet account with least 0.5 Ether. You can get testnet Ethers from [metamask faucets](https://faucet.metamask.io/) or ping us on our [gitter channel](https://gitter.im/SmartPool/Lobby).
*Note:* To get Ether from metamask faucet, you need to install metamask browser add-on.
#### Installation
1. `git clone https://github.com/SmartPool/smartpool-client.git`
2. `cd smartpool-client`
3. `./compile.sh`
*Note:* If you are on MacOS, there is a issue with Go and XCode 8.3 that might make you see `killed ./smartpool` error. To fix this issue, please run `build/env.sh go build -o smartpool -ldflags -s cmd/ropsten/ropsten.go` instead of ./compile.sh.
### Running
1. Run Geth on Ropsten testnet: `geth --testnet --fast --rpc --rpcapi "db,eth,net,web3,miner"` or Parity: `parity --chain ropsten --jsonrpc-apis "web3,eth,net,parity,traces,rpc,parity_set"`
2. Run smartpool client `./smartpool --keystore keystore_path --miner account`.
Where
- `keystore_path` is a path to a directory that contains your account key. E.g., `$HOME/.local/share/io.parity.ethereum/keys/kovan/`.
- `account` is the address of your account. E.g., `0x2ba80fe2811f8e0ea5eabf8e07697f7e9f5ae56c`.
- E.g., `./smartpool --keystore ~/Library/Ethereum/testnet/keystore --miner 0xe034afdcc2ba0441ff215ee9ba0da3e86450108d`.
3. Enter your key passphrase.
4. Run `ethminer -F localhost:1633` or `ethminer -G -F localhost:1633` if you mine with your GPU.
## Kovan testnet
[Smartpool](http://smartpool.io) was [live on Kovan testnet](https://kovan.etherscan.io/address/0x0398ae5a974fe8179b6b0ab9baf4d5f366e932bf) altough since Kovan is PoA rather than PoW mining had to be faked. Smartpool no longer runs on Kovan, Ropsten must be used instead.
## Support
Contact us at [gitter](https://gitter.im/SmartPool/Lobby) for support.
<file_sep>package smartpool
const VERSION = "0.4.0"
<file_sep>package geth
import (
"errors"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"math/big"
"math/rand"
"os"
"time"
)
type GethContractClient struct {
// the contract implementation that holds all underlying
// communication with Ethereum Contract
pool *SmartPool
transactor *bind.TransactOpts
node ethereum.RPCClient
sender common.Address
}
func (cc *GethContractClient) Version() string {
v, err := cc.pool.Version(nil)
if err != nil {
smartpool.Output.Printf("Couldn't get contract version: %s\n", err)
return ""
}
return v
}
func (cc *GethContractClient) IsRegistered() bool {
ok, err := cc.pool.IsRegistered(nil, cc.sender)
if err != nil {
smartpool.Output.Printf("Couldn't check the address's registration: %s\n", err)
return false
}
return ok
}
func (cc *GethContractClient) CanRegister() bool {
ok, err := cc.pool.CanRegister(nil, cc.sender)
if err != nil {
smartpool.Output.Printf("Couldn't check slot availability for the address: %s\n", err)
return false
}
return ok
}
func (cc *GethContractClient) Register(paymentAddress common.Address) error {
blockNo, err := cc.node.BlockNumber()
if err != nil {
return err
}
tx := EnsureTx(
func() (*types.Transaction, error) {
return cc.pool.Register(cc.transactor, paymentAddress)
},
1000,
10000,
"Registering miner address to SmartPool contract",
)
errCode, errInfo, err := GetTxResult(tx, cc.transactor, cc.node, blockNo.Add(blockNo, common.Big1), RegisterEventTopic,
cc.sender.Big())
if err != nil {
smartpool.Output.Printf("Tx: %s was not approved by the network in time.\n", tx.Hash().Hex())
return err
}
if errCode.Cmp(common.Big0) != 0 {
smartpool.Output.Printf("Error code: 0x%s - Error info: 0x%s\n", errCode.Text(16), errInfo.Text(16))
return errors.New(ErrorMsg(errCode, errInfo))
}
smartpool.Output.Printf("Registered address %s to SmartPool contract. Tx %s is confirmed\n", paymentAddress.Hex(), tx.Hash().Hex())
return nil
}
func (cc *GethContractClient) CalculateSubmissionIndex(sender common.Address, seed *big.Int) ([2]*big.Int, error) {
return cc.pool.CalculateSubmissionIndex(nil, sender, seed)
}
func (cc *GethContractClient) NumOpenClaims(sender common.Address) (*big.Int, error) {
for {
data, err := cc.pool.DebugGetNumPendingSubmissions(nil, sender)
if err != nil {
waitTime := rand.Int()%10000 + 1000
smartpool.Output.Printf("Failed getting number of open claims in contract. Error: %s\n", err)
time.Sleep(time.Duration(waitTime) * time.Millisecond)
} else {
return data, nil
}
}
}
func (cc *GethContractClient) ResetOpenClaims() error {
blockNo, err := cc.node.BlockNumber()
if err != nil {
smartpool.Output.Printf("Submitting claim failed. Error: %s\n", err)
return err
}
tx := EnsureTx(
func() (*types.Transaction, error) {
return cc.pool.DebugResetSubmissions(cc.transactor)
},
1000,
10000,
"Resetting submissions",
)
errCode, errInfo, err := GetTxResult(
tx, cc.transactor, cc.node, blockNo.Add(blockNo, common.Big1), ResetOpenClaimsEventTopic,
cc.sender.Big())
if err != nil {
return err
}
if errCode.Cmp(common.Big0) != 0 {
smartpool.Output.Printf("Error code: 0x%s - Error info: 0x%s\n", errCode.Text(16), errInfo.Text(16))
return errors.New(ErrorMsg(errCode, errInfo))
}
return nil
}
func (cc *GethContractClient) StoreClaimSeed() error {
blockNo, err := cc.node.BlockNumber()
if err != nil {
smartpool.Output.Printf("Storing claim failed. Error: %s\n", err)
return err
}
tx := EnsureTx(
func() (*types.Transaction, error) {
return cc.pool.StoreClaimSeed(cc.transactor, cc.sender)
},
1000,
10000,
"Storing claim seed",
)
_, _, err = GetTxResult(
tx, cc.transactor, cc.node, blockNo.Add(blockNo, common.Big1), ResetOpenClaimsEventTopic,
cc.sender.Big())
return err
}
func (cc *GethContractClient) GetClaimSeed() *big.Int {
var seed *big.Int
var err error
// Wait for 30s because the seed is only available after several blocks
time.Sleep(30 * time.Second)
for {
seed, err = cc.pool.GetClaimSeed(nil, cc.sender)
if err != nil {
smartpool.Output.Printf("Getting claim seed failed. Error: %s\n", err)
} else {
if seed.Cmp(common.Big0) != 0 {
cc.StoreClaimSeed()
break
}
}
waitTime := rand.Int()%10000 + 14000
time.Sleep(time.Duration(waitTime) * time.Millisecond)
}
return seed
}
func (cc *GethContractClient) SubmitClaim(
numShares *big.Int, difficulty *big.Int,
min *big.Int, max *big.Int,
augMerkle *big.Int, lastClaim bool) error {
var (
tx *types.Transaction
blockNo *big.Int
err error
)
for {
blockNo, err = cc.node.BlockNumber()
if err != nil {
waitTime := rand.Int()%10000 + 1000
smartpool.Output.Printf("Submitting claim failed. Error: %s\n", err)
time.Sleep(time.Duration(waitTime) * time.Millisecond)
} else {
break
}
}
tx = EnsureTx(
func() (*types.Transaction, error) {
return cc.pool.SubmitClaim(cc.transactor,
numShares, difficulty, min, max, augMerkle, lastClaim)
},
1000,
10000,
"Submitting claim",
)
errCode, errInfo, err := GetTxResult(
tx, cc.transactor, cc.node, blockNo.Add(blockNo, common.Big1), SubmitClaimEventTopic,
cc.sender.Big())
if err != nil {
return err
}
if errCode.Cmp(common.Big0) != 0 {
smartpool.Output.Printf("Error code: 0x%s - Error info: 0x%s\n", errCode.Text(16), errInfo.Text(16))
return errors.New(ErrorMsg(errCode, errInfo))
}
return nil
}
func (cc *GethContractClient) VerifyClaim(
rlpHeader []byte,
nonce *big.Int,
submissionIndex *big.Int,
shareIndex *big.Int,
dataSetLookup []*big.Int,
witnessForLookup []*big.Int,
augCountersBranch []*big.Int,
augHashesBranch []*big.Int) error {
var (
blockNo *big.Int
err error
tx *types.Transaction
)
for {
blockNo, err = cc.node.BlockNumber()
if err != nil {
waitTime := rand.Int()%10000 + 1000
smartpool.Output.Printf("Verifying claim failed. Error: %s\n", err)
time.Sleep(time.Duration(waitTime) * time.Millisecond)
} else {
break
}
}
tx = EnsureTx(
func() (*types.Transaction, error) {
return cc.pool.VerifyClaim(cc.transactor,
rlpHeader, nonce, submissionIndex, shareIndex, dataSetLookup,
witnessForLookup, augCountersBranch, augHashesBranch)
},
1000,
10000,
"Verifying claim",
)
errCode, errInfo, err := GetTxResult(
tx, cc.transactor, cc.node, blockNo.Add(blockNo, common.Big1), VerifyClaimEventTopic,
cc.sender.Big())
if err != nil {
return err
}
if errCode.Cmp(common.Big0) != 0 {
smartpool.Output.Printf("Error code: 0x%s - Error info: 0x%s\n", errCode.Text(16), errInfo.Text(16))
return errors.New(ErrorMsg(errCode, errInfo))
}
return nil
}
func getClient(rpc string) (*ethclient.Client, error) {
return ethclient.Dial(rpc)
}
func NewGethContractClient(
contractAddr common.Address, node ethereum.RPCClient, miner common.Address,
ipc, keystorePath, passphrase string, gasprice uint64) (*GethContractClient, error) {
client, err := getClient(ipc)
if err != nil {
smartpool.Output.Printf("Couldn't connect to Geth/Parity. Error: %s\n", err)
return nil, err
}
pool, err := NewSmartPool(contractAddr, client)
if err != nil {
smartpool.Output.Printf("Couldn't get SmartPool information from Ethereum Blockchain. Error: %s\n", err)
return nil, err
}
account := GetAccount(keystorePath, miner, passphrase)
if account == nil {
smartpool.Output.Printf("Couldn't get any account from key store.\n")
return nil, err
}
keyio, err := os.Open(account.KeyFile())
if err != nil {
smartpool.Output.Printf("Failed to open key file: %s\n", err)
return nil, err
}
smartpool.Output.Printf("Unlocking account...\n")
auth, err := bind.NewTransactor(keyio, account.PassPhrase())
if err != nil {
smartpool.Output.Printf("Failed to create authorized transactor: %s\n", err)
return nil, err
}
if gasprice != 0 {
auth.GasPrice = big.NewInt(int64(gasprice * 1000000000))
smartpool.Output.Printf("Gas price is set to: %s wei.\n", auth.GasPrice.Text(10))
}
smartpool.Output.Printf("Done.\n")
return &GethContractClient{pool, auth, node, miner}, nil
}
<file_sep>package stat
import (
"fmt"
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"sync"
"testing"
"time"
)
var rig *ethereum.Rig = ethereum.NewRig("testrig", "192.168.1.2")
var rig2 *ethereum.Rig = ethereum.NewRig("anotherrig", "192.168.1.3")
func newStatRecorder() *StatRecorder {
return &StatRecorder{
mu: sync.RWMutex{},
RigDatas: map[string]*RigData{},
FarmData: NewFarmData(),
}
}
func TestRecordHashrate(t *testing.T) {
recorder := newStatRecorder()
recorder.RecordHashrate(
hexutil.Uint64(100),
common.Hash{},
rig,
)
recorder.RecordHashrate(
hexutil.Uint64(200),
common.Hash{},
rig,
)
overall := recorder.OverallFarmStat().(*OverallFarmData)
if overall.ReportedHashrate.Uint64() != 150 {
t.Fail()
}
if overall.Rigs[rig.ID()].ReportedHashrate.Uint64() != 150 {
t.Fail()
}
rig := recorder.OverallRigStat(rig).(*OverallRigData)
if rig.AverageReportedHashrate.Uint64() != 150 {
t.Fail()
}
}
func TestRecordHashrateFromMultipleRigs(t *testing.T) {
recorder := newStatRecorder()
recorder.RecordHashrate(hexutil.Uint64(100), common.Hash{}, rig)
recorder.RecordHashrate(hexutil.Uint64(200), common.Hash{}, rig)
recorder.RecordHashrate(hexutil.Uint64(500), common.Hash{}, rig2)
recorder.RecordHashrate(hexutil.Uint64(300), common.Hash{}, rig2)
overall := recorder.OverallFarmStat().(*OverallFarmData)
if overall.ReportedHashrate.Uint64() != 550 {
t.Fail()
}
if overall.Rigs[rig2.ID()].ReportedHashrate.Uint64() != 400 {
t.Fail()
}
period := TimeToPeriod(time.Now())
periodStats := recorder.FarmStat(period, period).(map[uint64]*PeriodFarmData)
periodData := periodStats[period]
if periodData.ReportedHashrate.Uint64() != 550 {
fmt.Printf("got: %d, expected: %d\n", periodData.ReportedHashrate.Uint64(), 550)
t.Fail()
}
rig2Stat := recorder.OverallRigStat(rig2).(*OverallRigData)
if rig2Stat.AverageReportedHashrate.Uint64() != 400 {
t.Fail()
}
periodRigStats := recorder.RigStat(rig2, period, period).(map[uint64]*PeriodRigData)
periodRigData := periodRigStats[period]
if periodRigData.AverageReportedHashrate.Uint64() != 400 {
t.Fail()
}
}
<file_sep>package ethereum
type testPersistentStorage struct{}
func (self *testPersistentStorage) Persist(data interface{}, id string) error {
return nil
}
func (self *testPersistentStorage) Load(data interface{}, id string) (interface{}, error) {
if id == ACTIVE_SHARE_FILE {
return &map[string]gobShare{}, nil
} else if id == ACTIVE_CLAIM_FILE {
return &gobClaims{}, nil
} else if id == OPEN_CLAIM_FILE {
return &gobClaims{}, nil
}
return nil, nil
}
<file_sep>package ethminer
import (
"encoding/json"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"net/http"
"strconv"
)
type jsonRequest struct {
Method string `json:"method"`
Version string `json:"jsonrpc"`
Id json.RawMessage `json:"id,omitempty"`
Payload json.RawMessage `json:"params,omitempty"`
}
type jsonError struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
type jsonErrResponse struct {
Version string `json:"jsonrpc"`
Id interface{} `json:"id,omitempty"`
Error jsonError `json:"error"`
}
type jsonSuccessResponse struct {
Version string `json:"jsonrpc"`
Id interface{} `json:"id,omitempty"`
Result interface{} `json:"result"`
}
func createResponse(id interface{}, reply interface{}) interface{} {
return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply}
}
func createErrorResponse(id interface{}, err Error) interface{} {
return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}}
}
func extractRPCMsg(r *http.Request) (string, json.RawMessage, interface{}, Error) {
var incomingMsg json.RawMessage
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&incomingMsg); err != nil {
return "", json.RawMessage{}, nil, &invalidRequestError{err.Error()}
}
var in jsonRequest
if err := json.Unmarshal(incomingMsg, &in); err != nil {
return "", json.RawMessage{}, nil, &invalidMessageError{err.Error()}
}
if err := checkReqId(in.Id); err != nil {
return "", json.RawMessage{}, nil, &invalidMessageError{err.Error()}
}
return in.Method, in.Payload, in.Id, nil
}
func checkReqId(reqId json.RawMessage) error {
if len(reqId) == 0 {
return fmt.Errorf("missing request id")
}
if _, err := strconv.ParseFloat(string(reqId), 64); err == nil {
return nil
}
var str string
if err := json.Unmarshal(reqId, &str); err == nil {
return nil
}
return fmt.Errorf("invalid request id")
}
func parseHashrateArguments(payload json.RawMessage) (hexutil.Uint64, common.Hash, Error) {
args := [2]json.RawMessage{}
if e := json.Unmarshal(payload, &args); e != nil {
return 0, common.Hash{}, &invalidMessageError{e.Error()}
}
hashrate := hexutil.Uint64(0)
if e := json.Unmarshal(args[0], &hashrate); e != nil {
return 0, common.Hash{}, &invalidMessageError{e.Error()}
}
id := common.Hash{}
if e := json.Unmarshal(args[1], &id); e != nil {
return 0, common.Hash{}, &invalidMessageError{e.Error()}
}
return hashrate, id, nil
}
func parseWorkArguments(payload json.RawMessage) (types.BlockNonce, common.Hash, common.Hash, Error) {
args := [3]json.RawMessage{}
if e := json.Unmarshal(payload, &args); e != nil {
return types.BlockNonce{}, common.Hash{}, common.Hash{}, &invalidMessageError{e.Error()}
}
nonce := types.BlockNonce{}
if e := json.Unmarshal(args[0], &nonce); e != nil {
return types.BlockNonce{}, common.Hash{}, common.Hash{}, &invalidMessageError{e.Error()}
}
hash := common.Hash{}
if e := json.Unmarshal(args[1], &hash); e != nil {
return types.BlockNonce{}, common.Hash{}, common.Hash{}, &invalidMessageError{e.Error()}
}
mixDigest := common.Hash{}
if e := json.Unmarshal(args[2], &mixDigest); e != nil {
return types.BlockNonce{}, common.Hash{}, common.Hash{}, &invalidMessageError{e.Error()}
}
return nonce, hash, mixDigest, nil
}
<file_sep>package stat
import (
"time"
)
const (
BaseTimePeriod int64 = 10 * 60
ShortWindow int64 = 2 * 6 * BaseTimePeriod
LongWindow int64 = 24 * 6 * BaseTimePeriod
)
var (
Zone = LoadTimeZone()
)
func LoadTimeZone() *time.Location {
loc, _ := time.LoadLocation("Local")
return loc
}
func TimeToPeriod(t time.Time) uint64 {
return uint64(t.Unix() / BaseTimePeriod)
}
<file_sep>mustrun() {
"$@"
if [ $? != 0 ]; then
printf "Error when executing command: '$*'\n"
exit $ERROR_CODE
fi
}
echo "Install dependencies..."
mustrun build/env.sh go get -v golang.org/x/crypto/ssh/terminal
mustrun build/env.sh go get -v gopkg.in/urfave/cli.v1
mustrun build/env.sh go get -v github.com/bmizerany/pat
mustrun build/env.sh go get -v github.com/mitchellh/go-homedir
mustrun build/env.sh go get -v golang.org/x/net/context
mustrun build/env.sh go get -v github.com/gorilla/websocket
mustrun build/env.sh go get -v github.com/ethereum/go-ethereum
echo "Compiling SmartPool client..."
mustrun build/env.sh go build -ldflags -s -o smartpool cmd/ropsten/ropsten.go
echo "Done. You can run SmartPool by ./smartpool --help"
<file_sep>package ethminer
import (
"encoding/json"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/SmartPool/smartpool-client/ethereum/stat"
"github.com/gorilla/websocket"
"net/http"
"time"
)
type StatService struct{}
func farmStat() map[string]interface{} {
t := time.Now()
curPeriod := stat.TimeToPeriod(t)
shortWindow := stat.TimeToPeriod(t.Add(-time.Duration(stat.ShortWindow) * time.Second))
longWindow := stat.TimeToPeriod(t.Add(-time.Duration(stat.LongWindow) * time.Second))
overall := SmartPool.StatRecorder.OverallFarmStat()
shortWindowStat := SmartPool.StatRecorder.FarmStat(shortWindow, curPeriod)
longWindowStat := SmartPool.StatRecorder.FarmStat(longWindow, curPeriod)
return map[string]interface{}{
"overall": overall,
"short_window_sample": shortWindowStat,
"short_window_duration": stat.ShortWindow,
"long_window_sample": longWindowStat,
"long_window_duration": stat.LongWindow,
"period_duration": stat.BaseTimePeriod,
"server_time": time.Now().In(stat.Zone),
}
}
func rigStat(rig smartpool.Rig) map[string]interface{} {
t := time.Now()
curPeriod := stat.TimeToPeriod(t)
shortWindow := stat.TimeToPeriod(t.Add(-time.Duration(stat.ShortWindow) * time.Second))
longWindow := stat.TimeToPeriod(t.Add(-time.Duration(stat.LongWindow) * time.Second))
overall := SmartPool.StatRecorder.OverallRigStat(rig)
shortWindowStat := SmartPool.StatRecorder.RigStat(rig, shortWindow, curPeriod)
longWindowStat := SmartPool.StatRecorder.RigStat(rig, longWindow, curPeriod)
return map[string]interface{}{
"overall": overall,
"short_window_sample": shortWindowStat,
"short_window_duration": stat.ShortWindow,
"long_window_sample": longWindowStat,
"long_window_duration": stat.LongWindow,
"period_duration": stat.BaseTimePeriod,
}
}
func (server *StatService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
method := r.URL.Query().Get(":method")
if method == "json" {
scope := r.URL.Query().Get(":scope")
if scope == "farm" {
result := farmStat()
encoder := json.NewEncoder(w)
encoder.Encode(&result)
} else if scope == "rig" {
rigID := r.URL.Query().Get(":rig")
rig := ethereum.NewRig(rigID, r.RemoteAddr)
result := rigStat(rig)
encoder := json.NewEncoder(w)
encoder.Encode(&result)
} else {
http.Error(w, "Only /json/farm and /json/rig/:id are supported", 404)
}
} else if method == "ws" {
if r.Header.Get("Origin") != "http://"+r.Host {
http.Error(w, "Origin not allowed", 403)
return
}
conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)
if err != nil {
http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
}
defer conn.Close()
server.handleMessages(conn)
} else {
http.Error(w, "Only /farm and /rig/:id are supported", 404)
}
}
func (server *StatService) handleMessages(conn *websocket.Conn) {
startTime := time.Now()
for {
if time.Since(startTime).Seconds() > 600 {
break
}
m := make(map[string]string)
err := conn.ReadJSON(&m)
if err == nil {
startTime = time.Now()
if m["action"] == "getFarmInfo" {
conn.WriteJSON(farmStat())
} else if m["action"] == "getRigInfo" {
rigID := m["rigId"]
rigIP := m["rigIP"]
rig := ethereum.NewRig(rigID, rigIP)
conn.WriteJSON(rigStat(rig))
}
} else {
break
}
}
}
func NewStatService() *StatService {
return &StatService{}
}
<file_sep>package mtree
import (
"github.com/SmartPool/smartpool-client"
)
func conventionalWord(data smartpool.Word) ([]byte, []byte) {
first := rev(data[:32])
first = append(first, rev(data[32:64])...)
second := rev(data[64:96])
second = append(second, rev(data[96:128])...)
return first, second
}
func rev(b []byte) []byte {
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return b
}
func msbPadding(a []byte, size uint32) []byte {
result := make([]byte, len(a))
copy(result, a)
for i := uint32(len(a)); i < size; i++ {
result = append([]byte{0}, result...)
}
return result
}
<file_sep>package main
import (
"bufio"
"encoding/hex"
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum/ethash"
"github.com/SmartPool/smartpool-client/ethereum/geth"
"github.com/SmartPool/smartpool-client/mtree"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"io"
"log"
"math/big"
"os"
"path/filepath"
)
func processDuringRead(
datasetPath string, mt *mtree.DagTree) {
f, err := os.Open(datasetPath)
if err != nil {
log.Fatal(err)
}
r := bufio.NewReader(f)
buf := [128]byte{}
// ignore first 8 bytes magic number at the beginning
// of dataset. See more at https://github.com/ethereum/wiki/wiki/Ethash-DAG-Disk-Storage-Format
_, err = io.ReadFull(r, buf[:8])
if err != nil {
log.Fatal(err)
}
var i uint32 = 0
for {
n, err := io.ReadFull(r, buf[:128])
if n == 0 {
if err == nil {
continue
}
if err == io.EOF {
break
}
log.Fatal(err)
}
if n != 128 {
log.Fatal("Malformed dataset")
}
mt.Insert(smartpool.Word(buf), i)
if err != nil && err != io.EOF {
log.Fatal(err)
}
i++
}
}
func getClient(rpc string) (*ethclient.Client, error) {
return ethclient.Dial(rpc)
}
func main() {
client, err := getClient("http://localhost:8545")
if err != nil {
fmt.Printf("Couldn't connect to Geth via IPC file. Error: %s\n", err)
return
}
contractAddr := common.HexToAddress("0xda87714c91d62070ebc29675ec79a190e6ccdfba")
testClient, err := geth.NewTestClient(contractAddr, client)
if err != nil {
fmt.Printf("Couldn't bind. Error: %s\n", err)
return
}
if err != nil {
fmt.Printf("Failed to create authorized transactor: %s\n", err)
return
}
epoch := 24
fmt.Printf("Checking DAG file for epoch %d. Generate if needed...\n", epoch)
seedHash, err := ethash.GetSeedHash(uint64(epoch * 30000))
if err != nil {
panic(err)
}
path := filepath.Join(
ethash.DefaultDir,
fmt.Sprintf("full-R%s-%s", "23", hex.EncodeToString(seedHash[:8])),
)
mt := mtree.NewDagTree()
indexes := []uint32{
6100258, 1679244, 7186452, 8548988, 5525504, 8591682, 7817920, 7707803, 3647301, 9632067, 9094506, 4755354, 2769219, 9468202, 1218192, 2887829, 1870009, 921735, 1366012, 1755583, 6391156, 9760105, 7323962, 7959186, 4833456, 2553397, 6345470, 6437303, 120678, 1919905, 8868019, 6865013, 9030547, 1369996, 5453685, 4696215, 3063135, 6757181, 2950714, 3222015, 231031, 8526593, 626784, 9121376, 2544823, 8974305, 8106659, 8366486, 1997695, 4428246, 7150657, 6338147, 7533776, 3443142, 8294240, 9186007, 8267176, 9324280, 4741270, 5541823, 4858294, 7689845, 7943904, 8895903,
}
mt.RegisterIndex(indexes...)
fullSize, _ := ethash.MakeDAGWithSize(uint64(epoch*30000), "")
fullSizeIn128Resolution := fullSize / 128
branchDepth := len(fmt.Sprintf("%b", fullSizeIn128Resolution-1))
mt.RegisterStoredLevel(uint32(branchDepth), uint32(10))
processDuringRead(path, mt)
mt.Finalize()
elements := []*big.Int{}
for _, w := range mt.AllDAGElements() {
elements = append(elements, w.ToUint256Array()...)
}
proof := []*big.Int{}
branch := mt.AllBranchesArray()
fmt.Printf("len branch: %d\n", len(branch))
for i := 0; i < len(branch); i++ {
proof = append(proof, branch[i].Big())
}
bigIndexes := []*big.Int{}
for _, i := range indexes {
bigIndexes = append(bigIndexes, big.NewInt(int64(i)))
}
result, err := testClient.TestOptimization(
nil,
bigIndexes,
elements,
proof,
big.NewInt(int64(epoch)),
)
fmt.Printf("Elements: [")
for _, e := range elements {
fmt.Printf("0x%s, ", e.Text(16))
}
fmt.Printf("]\n")
fmt.Printf("Proof: [")
for _, e := range proof {
fmt.Printf("0x%s, ", e.Text(16))
}
fmt.Printf("]\n")
fmt.Printf("Error: %v\n", err)
fmt.Printf("0x%s 0x%s 0x%s 0x%s", result[0].Text(16), result[1].Text(16), result[2].Text(16), result[3].Text(16))
}
<file_sep>package ethereum
// TODO: Add tests for contract
<file_sep>package ethereum
import (
"errors"
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"math/rand"
"strings"
"sync"
"time"
)
type NetworkClient struct {
rpc RPCClient
workpool *WorkPool
cachedWork *Work
mu sync.RWMutex
ticker <-chan time.Time
}
func (nc *NetworkClient) fetchNewWork() {
nc.mu.Lock()
defer nc.mu.Unlock()
work := nc.rpc.GetWork()
nc.cachedWork = work
nc.workpool.AddWork(work)
}
func (nc *NetworkClient) fetchOnTick() {
for _ = range nc.ticker {
nc.fetchNewWork()
}
}
func (nc *NetworkClient) fetchFromCache() smartpool.Work {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.cachedWork
}
func (nc *NetworkClient) GetWork() smartpool.Work {
for {
work := nc.fetchFromCache()
if work != nil {
return work
} else {
waitTime := rand.Int()%100 + 100
time.Sleep(time.Duration(waitTime) * time.Millisecond)
}
}
}
func (nc *NetworkClient) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool {
return nc.rpc.SubmitHashrate(hashrate, id)
}
func (nc *NetworkClient) SubmitSolution(s smartpool.Solution) bool {
sol := s.(*Solution)
return nc.rpc.SubmitWork(sol.Nonce, sol.Hash, sol.MixDigest)
}
func (nc *NetworkClient) ReadyToMine() bool {
return !nc.rpc.Syncing()
}
func (nc *NetworkClient) Configure(etherbase common.Address, extradata string) error {
client, err := nc.rpc.ClientVersion()
if err != nil {
return err
}
if strings.HasPrefix(client, "Geth") {
smartpool.Output.Printf("Trying to set etherbase to SmartPool contract address: %s...\n", etherbase.Hex())
err = nc.rpc.SetEtherbase(etherbase)
if err != nil {
smartpool.Output.Printf("Trying to set etherbase to SmartPool contract address failed: %s\n", err)
smartpool.Output.Printf("Please make sure you used Geth option --rpcapi \"db,eth,net,web3,miner\"\n")
return err
}
smartpool.Output.Printf("Done.\n")
smartpool.Output.Printf("Trying to set extradata to SmartPool extradata convention: %s...\n", extradata)
err = nc.rpc.SetExtradata(extradata)
if err != nil {
smartpool.Output.Printf("Trying to set extra data to SmartPool extradata convention failed: %s\n", err)
smartpool.Output.Printf("Please make sure you used Geth option --rpcapi \"db,eth,net,web3,miner\"\n")
return err
}
smartpool.Output.Printf("Done.\n")
} else if strings.HasPrefix(client, "Parity") {
smartpool.Output.Printf("Trying to set etherbase to SmartPool contract address: %s...\n", etherbase.Hex())
err = nc.rpc.SetEtherbase(etherbase)
if err != nil {
smartpool.Output.Printf("Trying to set author to SmartPool contract address failed: %s\n", err)
smartpool.Output.Printf("Please make sure you used Parity option --jsonrpc-apis \"web3,eth,net,parity,traces,rpc,parity_set\"\n")
return err
}
smartpool.Output.Printf("Done.\n")
smartpool.Output.Printf("Trying to set extradata to SmartPool extradata convention: %s...\n", extradata)
err = nc.rpc.SetExtradata(extradata)
if err != nil {
smartpool.Output.Printf("Trying to set extra data to SmartPool extradata convention failed: %s\n", err)
smartpool.Output.Printf("Please make sure you used Parity option --jsonrpc-apis \"web3,eth,net,parity,traces,rpc,parity_set\"\n")
return err
}
smartpool.Output.Printf("Done.\n")
} else {
return errors.New(
fmt.Sprintf("Unsupported client: %s", client))
}
return nil
}
func NewNetworkClient(rpc RPCClient, workpool *WorkPool) *NetworkClient {
networkClient := &NetworkClient{
rpc, workpool, nil, sync.RWMutex{}, time.Tick(50 * time.Millisecond),
}
go networkClient.fetchOnTick()
return networkClient
}
<file_sep>package geth
import (
"encoding/hex"
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rpc"
"math/big"
"math/rand"
"strings"
"time"
)
type jsonHeader struct {
ParentHash *common.Hash `json:"parentHash"`
UncleHash *common.Hash `json:"sha3Uncles"`
Coinbase *common.Address `json:"miner"`
Root *common.Hash `json:"stateRoot"`
TxHash *common.Hash `json:"transactionsRoot"`
ReceiptHash *common.Hash `json:"receiptsRoot"`
Bloom *types.Bloom `json:"logsBloom"`
Difficulty *hexutil.Big `json:"difficulty"`
Number *hexutil.Big `json:"number"`
GasLimit *hexutil.Big `json:"gasLimit"`
GasUsed *hexutil.Big `json:"gasUsed"`
Time *hexutil.Big `json:"timestamp"`
Extra *hexutil.Bytes `json:"extraData"`
MixDigest *common.Hash `json:"mixHash"`
Nonce *types.BlockNonce `json:"nonce"`
}
type GethRPC struct {
client *rpc.Client
ContractAddr common.Address
ExtraData []byte
ShareDifficulty *big.Int
MinerAddress string
}
func (g *GethRPC) ClientVersion() (string, error) {
result := ""
err := g.client.Call(&result, "web3_clientVersion")
return result, err
}
func (g *GethRPC) BlockNumber() (*big.Int, error) {
str := ""
err := g.client.Call(&str, "eth_blockNumber")
result := common.HexToHash(str).Big()
return result, err
}
func (g *GethRPC) GetPendingBlockHeader() (*types.Header, error) {
header := jsonHeader{}
err := g.client.Call(&header, "eth_getBlockByNumber", "pending", false)
if err != nil {
return nil, err
}
result := types.Header{}
result.ParentHash = *header.ParentHash
result.UncleHash = *header.UncleHash
result.Root = *header.Root
result.TxHash = *header.TxHash
result.ReceiptHash = *header.ReceiptHash
result.Difficulty = (*big.Int)(header.Difficulty)
result.Number = (*big.Int)(header.Number)
result.GasLimit = (*big.Int)(header.GasLimit)
result.GasUsed = (*big.Int)(header.GasUsed)
result.Time = (*big.Int)(header.Time)
result.Coinbase = g.ContractAddr
// result.Extra = []byte("0xd883010505846765746887676f312e372e348664617277696e")
result.Extra = []byte(g.ExtraData)
if header.Bloom == nil {
result.Bloom = types.Bloom{}
} else {
result.Bloom = *header.Bloom
}
result.MixDigest = common.Hash{}
result.Nonce = types.BlockNonce{}
return &result, nil
}
func (g *GethRPC) GetBlockHeader(number int) *types.Header {
header := types.Header{}
err := g.client.Call(&header, "eth_getBlockByNumber", number, false)
if err != nil {
smartpool.Output.Printf("Couldn't get latest block: %v", err)
return nil
}
return &header
}
type gethWork [3]string
func (w gethWork) PoWHash() string { return w[0] }
func (g *GethRPC) GetWork() *ethereum.Work {
w := gethWork{}
var h *types.Header
var err error
for {
h, err = g.GetPendingBlockHeader()
g.client.Call(&w, "eth_getWork")
if err == nil && w.PoWHash() != "" && w.PoWHash() == h.HashNoNonce().Hex() {
break
}
if err != nil {
smartpool.Output.Printf("getting pending block failed: %s. Retry in 1s...", err.Error())
}
waitTime := rand.Int()%2000 + 1000
time.Sleep(time.Duration(waitTime) * time.Millisecond)
}
return ethereum.NewWork(h, w[0], w[1], g.ShareDifficulty, g.MinerAddress)
}
func (g *GethRPC) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool {
var result bool
g.client.Call(&result, "eth_submitHashrate", hashrate, id)
return result
}
func (g *GethRPC) SubmitWork(nonce types.BlockNonce, hash, mixDigest common.Hash) bool {
var result bool
g.client.Call(&result, "eth_submitWork", nonce, hash, mixDigest)
return result
}
type filter struct {
FromBlock string `json:"fromBlock,omitempty"`
ToBlock string `json:"toBlock,omitempty"`
Topics []string `json:"topics,omitempty"`
}
type elog struct {
LogIndex string `json:"logIndex,omitempty"`
BlockNumber string `json:"blockNumber,omitempty"`
BlockHash string `json:"blockHash,omitempty"`
TransactionHash string `json:"transactionHash,omitempty"`
TransactionIndex string `json:"transactionIndex,omitempty"`
Address string `json:"address,omitempty"`
Data string `json:"data,omitempty"`
Topics []string `json:"topics,omitempty"`
}
type logs []elog
func (g *GethRPC) GetLog(
txs []*types.Transaction,
from *big.Int, event *big.Int,
sender *big.Int) (*big.Int, *big.Int) {
param := filter{
fmt.Sprintf("0x%s", from.Text(16)),
"latest",
[]string{
common.BigToHash(event).Hex(),
common.BigToHash(sender).Hex(),
},
}
result := logs{}
for {
err := g.client.Call(&result, "eth_getLogs", param)
if err != nil {
waitTime := rand.Int()%10000 + 1000
smartpool.Output.Printf("Failed getting logs. Error: %s\n", err)
time.Sleep(time.Duration(waitTime) * time.Millisecond)
} else {
break
}
}
var theLog elog
Loop:
for _, l := range result {
for _, tx := range txs {
if common.HexToHash(l.TransactionHash).Big().Cmp(tx.Hash().Big()) == 0 {
theLog = l
break Loop
}
}
}
if theLog.BlockNumber == "" {
smartpool.Output.Printf(
"Log not found. Contract unexpectedly threw. Topic: %v, sender: %s, from: %s %v\n",
len(result),
common.BigToHash(event).Hex(),
common.BigToHash(sender).Hex(),
fmt.Sprintf("0x%s", from.Text(16)),
)
return nil, nil
} else {
dataInByte, err := hex.DecodeString(theLog.Data[2:])
if err != nil {
smartpool.Output.Printf(
"Error while converting log data to bytes. Log(%s), Error(%v)\n",
theLog.Data, err,
)
}
errCode := big.NewInt(0)
errCode.SetBytes(dataInByte[:32])
errInfo := big.NewInt(0)
errInfo.SetBytes(dataInByte[32:])
return errCode, errInfo
}
}
type jsonTransaction struct {
BlockHash string `json:"blockHash"`
}
func (g *GethRPC) IsVerified(h common.Hash) bool {
result := jsonTransaction{}
g.client.Call(&result, "eth_getTransactionByHash", h)
return result.BlockHash != "" && result.BlockHash != "0x0000000000000000000000000000000000000000000000000000000000000000"
}
func (g *GethRPC) Syncing() bool {
result := ""
g.client.Call(&result, "net_peerCount")
peerCount := common.HexToHash(result).Big().Uint64()
smartpool.Output.Printf("peerCount: %d\n", peerCount)
return peerCount == uint64(0)
}
func (g *GethRPC) SetEtherbase(etherbase common.Address) error {
client, err := g.ClientVersion()
if err != nil {
return err
}
result := false
if strings.HasPrefix(client, "Geth") {
err = g.client.Call(&result, "miner_setEtherbase", etherbase)
} else {
// Client must be Parity
err = g.client.Call(&result, "parity_setAuthor", etherbase)
}
return err
}
func (g *GethRPC) SetExtradata(extradata string) error {
client, err := g.ClientVersion()
if err != nil {
return err
}
result := false
if strings.HasPrefix(client, "Geth") {
err = g.client.Call(&result, "miner_setExtra", extradata)
} else {
// Client must be Parity
err = g.client.Call(&result, "parity_setExtraData",
common.StringToHash(extradata))
}
return err
}
func (g *GethRPC) Broadcast(data []byte) (common.Hash, error) {
hash := common.Hash{}
err := g.client.Call(&hash, "eth_sendRawTransaction",
fmt.Sprintf("0x%s", common.Bytes2Hex(data)))
return hash, err
}
func NewGethRPC(endpoint, contractAddr, extraData string, diff *big.Int, miner string) (*GethRPC, error) {
client, err := rpc.DialHTTP(endpoint)
if err != nil {
return nil, err
}
return &GethRPC{client, common.HexToAddress(contractAddr), []byte(extraData), diff, miner}, nil
}
<file_sep>package ethereum
import (
// "encoding/json"
"errors"
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/protocol"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"math/big"
"os"
"sync"
)
var (
ACTIVE_SHARE_FILE string = "active_shares"
ACTIVE_CLAIM_FILE string = "active_claims"
OPEN_CLAIM_FILE string = "open_claims"
)
// TimestampClaimRepo only select shares that don't have most recent timestamp
// in order to make sure coming shares' counters are greater than selected
// shares
type TimestampClaimRepo struct {
activeShares map[string]*Share
mu sync.RWMutex
activeClaims []smartpool.Claim
openClaims []smartpool.Claim
claimMu sync.RWMutex
recentTimestamp *big.Int
noShares uint64
noRecentShares uint64
storage smartpool.PersistentStorage
diff *big.Int
miner string
coinbase string
}
func NewTimestampClaimRepo(diff *big.Int, miner, coinbase string, storage smartpool.PersistentStorage) *TimestampClaimRepo {
shares, err := loadActiveShares(storage)
if err != nil {
smartpool.Output.Printf("Couldn't load active shares from last session (%s). Initialize with empty share pool.\n", err)
}
activeClaims, err := loadActiveClaims(storage)
if err != nil {
smartpool.Output.Printf("Couldn't load active claims from last session (%s). Initialize with empty active claims list.\n", err)
}
openClaims, err := loadOpenClaims(storage)
if err != nil {
smartpool.Output.Printf("Couldn't load open claims from last session (%s). Initialize with empty open claims list.\n", err)
}
noShares := 0
noRecentShares := 0
currentTimestamp := big.NewInt(0)
changedDiff := false
changedMiner := false
changedCoinbase := false
if len(shares) > 0 {
for _, s := range shares {
if currentTimestamp.Cmp(s.Timestamp()) < 0 {
currentTimestamp.Add(s.Timestamp(), common.Big0)
}
}
for _, s := range shares {
if s.Timestamp().Cmp(currentTimestamp) == 0 {
noRecentShares++
} else {
noShares++
}
if s.ShareDifficulty().Cmp(diff) != 0 {
changedDiff = true
}
if s.MinerAddress() != miner {
changedMiner = true
}
if s.BlockHeader().Coinbase.Hex() != coinbase {
changedCoinbase = true
}
}
}
var oneShare *Share
if changedCoinbase {
smartpool.Output.Printf("SmartPool contract address changed. Discarded %d shares from last session.\n", len(shares))
shares = map[string]*Share{}
noShares = 0
noRecentShares = 0
currentTimestamp = big.NewInt(0)
} else if changedMiner {
for _, s := range shares {
oneShare = s
break
}
fmt.Printf("You have %d shares from last session with miner %s that were not submitted to the contract.\n", len(shares), oneShare.BlockHeader().Coinbase.Hex())
fmt.Printf("However you are going to run SmartPool with different miner %s.\n", miner)
fmt.Printf("Please choose one of following options:\n")
fmt.Printf("1. Discard those shares and continue running SmartPool with new miner.\n")
fmt.Printf("2. Abort SmartPool and rerun it with --miner %s\n", oneShare.MinerAddress())
var choice string
for {
fmt.Printf("Enter 1 or 2: ")
fmt.Scanf("%s", &choice)
if choice == "1" {
shares = map[string]*Share{}
activeClaims = []smartpool.Claim{}
openClaims = []smartpool.Claim{}
noShares = 0
noRecentShares = 0
currentTimestamp = big.NewInt(0)
smartpool.Output.Printf("You chose to discard the shares from last session.\n")
break
} else if choice == "2" {
os.Exit(1)
}
}
} else if changedDiff {
for _, s := range shares {
oneShare = s
break
}
fmt.Printf("You have %d shares from last session with difficulty %s that were not submitted to the contract.\n", len(shares), oneShare.ShareDifficulty().Text(10))
fmt.Printf("However you are going to run SmartPool with different share difficulty %s.\n", diff.Text(10))
fmt.Printf("Please choose one of following options:\n")
fmt.Printf("1. Discard those shares and continue running SmartPool with new difficulty.\n")
fmt.Printf("2. Abort SmartPool and rerun it with --diff %s\n", oneShare.ShareDifficulty().Text(10))
var choice string
for {
fmt.Printf("Enter 1 or 2: ")
fmt.Scanf("%s", &choice)
if choice == "1" {
shares = map[string]*Share{}
activeClaims = []smartpool.Claim{}
openClaims = []smartpool.Claim{}
noShares = 0
noRecentShares = 0
currentTimestamp = big.NewInt(0)
smartpool.Output.Printf("You chose to discard the shares from last session.\n")
break
} else if choice == "2" {
os.Exit(1)
}
}
}
cr := TimestampClaimRepo{
shares,
sync.RWMutex{},
activeClaims,
openClaims,
sync.RWMutex{},
currentTimestamp,
uint64(noShares),
uint64(noRecentShares),
storage,
diff,
miner,
coinbase,
}
smartpool.Output.Printf("Loaded %d valid shares\n", noShares)
smartpool.Output.Printf("Loaded timestamp: 0x%s\n", currentTimestamp.Text(16))
smartpool.Output.Printf("Loaded %d shares with current timestamp\n", noRecentShares)
return &cr
}
type gobShare struct {
BlockHeader *types.Header `json:"header"`
Nonce types.BlockNonce `json:"nonce"`
MixDigest common.Hash `json:"mix"`
ShareDifficulty *big.Int `json:"share_diff"`
MinerAddress string `json:"miner"`
SolutionState int `json:"state"`
}
type gobClaim struct {
Shares []gobShare
ShareIndex *big.Int
}
type gobClaims []gobClaim
func loadClaims(storage smartpool.PersistentStorage, file string) ([]smartpool.Claim, error) {
claims := gobClaims{}
loadedClaims, err := storage.Load(&claims, file)
claims = *loadedClaims.(*gobClaims)
if err != nil {
return []smartpool.Claim{}, err
}
result := []smartpool.Claim{}
for _, claim := range claims {
ss := claim.Shares
cl := protocol.NewClaim()
for _, s := range ss {
cl.AddShare(&Share{
s.BlockHeader,
s.Nonce,
s.MixDigest,
s.ShareDifficulty,
s.MinerAddress,
s.SolutionState,
nil,
})
}
cl.SetEvidence(claim.ShareIndex)
result = append(result, cl)
}
return result, nil
}
func loadOpenClaims(storage smartpool.PersistentStorage) ([]smartpool.Claim, error) {
return loadClaims(storage, OPEN_CLAIM_FILE)
}
func loadActiveClaims(storage smartpool.PersistentStorage) ([]smartpool.Claim, error) {
return loadClaims(storage, ACTIVE_CLAIM_FILE)
}
func loadActiveShares(storage smartpool.PersistentStorage) (map[string]*Share, error) {
shares := map[string]*Share{}
gobShares := map[string]gobShare{}
loadedGobShares, err := storage.Load(&gobShares, ACTIVE_SHARE_FILE)
gobShares = *loadedGobShares.(*map[string]gobShare)
if err != nil {
return shares, err
}
for k, gobShare := range gobShares {
shares[k] = &Share{
gobShare.BlockHeader,
gobShare.Nonce,
gobShare.MixDigest,
gobShare.ShareDifficulty,
gobShare.MinerAddress,
gobShare.SolutionState,
nil,
}
}
return shares, nil
}
func (cr *TimestampClaimRepo) NoActiveShares() uint64 {
return cr.noShares + cr.noRecentShares
}
func (cr *TimestampClaimRepo) Persist(storage smartpool.PersistentStorage) error {
smartpool.Output.Printf("Saving active shares to disk...\n")
cr.mu.RLock()
defer cr.mu.RUnlock()
gobShares := map[string]gobShare{}
var shareID string
for _, s := range cr.activeShares {
shareID = fmt.Sprintf(
"%s-%v",
s.BlockHeader().Hash().Hex(),
s.Nonce())
gobShares[shareID] = gobShare{
s.BlockHeader(),
s.nonce,
s.mixDigest,
s.shareDifficulty,
s.minerAddress,
s.SolutionState,
}
// shareJson, _ := json.Marshal(gobShares[shareID])
// fmt.Printf("share json: %s\n", shareJson)
}
if err := storage.Persist(&gobShares, ACTIVE_SHARE_FILE); err != nil {
smartpool.Output.Printf("Failed. (%s)\n", err.Error())
return err
} else {
smartpool.Output.Printf("Done.\n")
}
cr.claimMu.RLock()
defer cr.claimMu.RUnlock()
smartpool.Output.Printf("Saving active claims to disk...\n")
if err := cr.persistActiveClaims(storage); err != nil {
smartpool.Output.Printf("Failed. (%s)\n", err.Error())
return err
} else {
smartpool.Output.Printf("Done.\n")
}
smartpool.Output.Printf("Saving open claims to disk...\n")
if err := cr.persistOpenClaims(storage); err != nil {
smartpool.Output.Printf("Failed. (%s)\n", err.Error())
return err
} else {
smartpool.Output.Printf("Done.\n")
}
return nil
}
func (cr *TimestampClaimRepo) persistActiveClaims(storage smartpool.PersistentStorage) error {
return cr.persistClaims(cr.activeClaims, storage, ACTIVE_CLAIM_FILE)
}
func (cr *TimestampClaimRepo) persistOpenClaims(storage smartpool.PersistentStorage) error {
return cr.persistClaims(cr.openClaims, storage, OPEN_CLAIM_FILE)
}
func (cr *TimestampClaimRepo) persistClaims(claims []smartpool.Claim, storage smartpool.PersistentStorage, file string) error {
cs := gobClaims{}
for _, c := range claims {
shares := []gobShare{}
cc := c.(*protocol.Claim)
for i := 0; i < int(cc.NumShares().Int64()); i++ {
s := cc.GetShare(i).(*Share)
shares = append(shares, gobShare{
s.BlockHeader(),
s.nonce,
s.mixDigest,
s.shareDifficulty,
s.minerAddress,
s.SolutionState,
})
}
cs = append(cs, gobClaim{
shares,
cc.GetEvidence(),
})
}
return storage.Persist(&cs, file)
}
func (cr *TimestampClaimRepo) AddShare(s smartpool.Share) error {
cr.mu.Lock()
defer cr.mu.Unlock()
share := s.(*Share)
shareID := fmt.Sprintf(
"%s-%v",
share.BlockHeader().Hash().Hex(),
share.Nonce())
if share.BlockHeader().Coinbase.Hex() != cr.coinbase {
return errors.New(
fmt.Sprintf("inconsistent coinbase address: share(%s) vs. expected(%s)",
share.BlockHeader().Coinbase.Hex(),
cr.coinbase,
))
}
if share.ShareDifficulty().Cmp(cr.diff) != 0 {
return errors.New(
fmt.Sprintf("inconsistent difficulty (expected 0x%s, got 0x%s)", cr.diff.Text(16), share.ShareDifficulty().Text(16)))
}
if cr.activeShares[shareID] != nil {
return errors.New("duplicated share")
} else {
cr.activeShares[shareID] = share
}
if share.Timestamp().Cmp(cr.recentTimestamp) == 0 {
cr.noRecentShares++
} else if share.Timestamp().Cmp(cr.recentTimestamp) < 0 {
cr.noShares++
} else if share.Timestamp().Cmp(cr.recentTimestamp) > 0 {
cr.noShares += cr.noRecentShares
cr.noRecentShares = 1
cr.recentTimestamp = big.NewInt(0)
cr.recentTimestamp.Add(share.Timestamp(), common.Big0)
}
return nil
}
func (cr *TimestampClaimRepo) getCurrentClaim(threshold int) smartpool.Claim {
cr.mu.Lock()
defer cr.mu.Unlock()
smartpool.Output.Printf("Have %d valid shares\n", cr.noShares)
smartpool.Output.Printf("Current timestamp: 0x%s\n", cr.recentTimestamp.Text(16))
smartpool.Output.Printf("Shares with current timestamp: %d\n", cr.noRecentShares)
if cr.noShares < uint64(threshold) {
return nil
}
c := protocol.NewClaim()
newActiveShares := map[string]*Share{}
for _, s := range cr.activeShares {
if s.Timestamp().Cmp(cr.recentTimestamp) < 0 {
c.AddShare(s)
} else {
shareID := fmt.Sprintf(
"%s-%v",
s.BlockHeader().Hash().Hex(),
s.Nonce())
newActiveShares[shareID] = s
}
}
cr.activeShares = newActiveShares
cr.noShares = 0
return c
}
func (cr *TimestampClaimRepo) PutOpenClaim(claim smartpool.Claim) {
cr.claimMu.Lock()
defer cr.claimMu.Unlock()
cr.activeClaims = append(cr.activeClaims, claim)
}
func (cr *TimestampClaimRepo) RemoveOpenClaim(claim smartpool.Claim) {
cr.claimMu.Lock()
defer cr.claimMu.Unlock()
cr.activeClaims[len(cr.activeClaims)-1] = nil
cr.activeClaims = cr.activeClaims[:len(cr.activeClaims)-1]
}
func (cr *TimestampClaimRepo) GetOpenClaim(index int) smartpool.Claim {
cr.claimMu.Lock()
defer cr.claimMu.Unlock()
if index >= len(cr.openClaims) {
return nil
} else {
return cr.openClaims[index]
}
}
func (cr *TimestampClaimRepo) SealClaimBatch() {
cr.claimMu.Lock()
defer cr.claimMu.Unlock()
cr.openClaims = cr.activeClaims
cr.activeClaims = []smartpool.Claim{}
}
func (cr *TimestampClaimRepo) NumOpenClaims() uint64 {
cr.claimMu.Lock()
defer cr.claimMu.Unlock()
return uint64(len(cr.activeClaims))
}
func (cr *TimestampClaimRepo) ResetOpenClaims() {
cr.claimMu.Lock()
defer cr.claimMu.Unlock()
cr.activeClaims = []smartpool.Claim{}
}
func (cr *TimestampClaimRepo) GetCurrentClaim(threshold int) smartpool.Claim {
c := cr.getCurrentClaim(threshold)
cr.Persist(cr.storage)
return c
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
)
type testClaimRepo struct {
c []smartpool.Share
oc []smartpool.Claim
}
func newClaimRepo() *testClaimRepo {
return &testClaimRepo{[]smartpool.Share{}, []smartpool.Claim{}}
}
func (cr *testClaimRepo) GetCurrentClaim(threshold int) smartpool.Claim {
if len(cr.c) < threshold {
return nil
}
claim := &testClaim{cr.c}
cr.c = []smartpool.Share{}
cr.oc = []smartpool.Claim{claim}
return claim
}
func (cr *testClaimRepo) AddShare(s smartpool.Share) error {
cr.c = append(cr.c, s)
return nil
}
func (cr *testClaimRepo) NoActiveShares() uint64 {
return 0
}
func (cr *testClaimRepo) Persist(storage smartpool.PersistentStorage) error {
return nil
}
func (cr *testClaimRepo) PutOpenClaim(claim smartpool.Claim) {
}
func (cr *testClaimRepo) GetOpenClaim(claimIndex int) smartpool.Claim {
return cr.oc[0]
}
func (cr *testClaimRepo) ResetOpenClaims() {
}
func (cr *testClaimRepo) RemoveOpenClaim(claim smartpool.Claim) {
}
func (cr *testClaimRepo) NumOpenClaims() uint64 {
return 0
}
func (cr *testClaimRepo) SealClaimBatch() {
}
<file_sep>package mtree
import "container/list"
type ElementData interface{}
type NodeData interface {
Copy() NodeData
}
type node struct {
Data NodeData
NodeCount uint32
Branches *map[uint32]BranchTree
}
func (n node) Copy() node {
return node{n.Data.Copy(), n.NodeCount, &map[uint32]BranchTree{}}
}
type hashFunc func(NodeData, NodeData) NodeData
type elementHashFunc func(ElementData) NodeData
type dummyNodeModifierFunc func(NodeData)
type MerkleTree struct {
mtbuf *list.List
h hashFunc
eh elementHashFunc
dnf dummyNodeModifierFunc
finalized bool
indexes map[uint32]bool
orderedIndexes []uint32
storedLevel uint32
exportNodeCount uint32
exportNodes []NodeData
}
func (mt *MerkleTree) StoredLevel() uint32 {
return mt.storedLevel
}
func (mt *MerkleTree) RegisterStoredLevel(depth, level uint32) {
mt.storedLevel = level
mt.exportNodeCount = 1<<(depth-level+1) - 1
}
// register indexes to build branches
func (mt *MerkleTree) RegisterIndex(indexes ...uint32) {
for _, i := range indexes {
mt.indexes[i] = true
mt.orderedIndexes = append(mt.orderedIndexes, i)
}
}
func (mt *MerkleTree) SetHashFunction(_h hashFunc) {
mt.h = _h
}
func (mt *MerkleTree) SetElementHashFunction(_h elementHashFunc) {
mt.eh = _h
}
func (mt *MerkleTree) Insert(data ElementData, index uint32) {
_node := node{mt.eh(data), 1, &map[uint32]BranchTree{}}
// fmt.Printf("Inserted node for word (%s): %4s\n", hex.EncodeToString(data[:]), hex.EncodeToString(_node.Data[:]))
if mt.indexes[index] {
(*_node.Branches)[index] = BranchTree{
RawData: data,
HashedData: _node.Data,
Root: &BranchNode{
Hash: _node.Data,
Left: nil,
Right: nil,
},
}
}
mt.insertNode(_node)
}
func (mt *MerkleTree) insertNode(_node node) {
var e, prev *list.Element
var cNode, prevNode node
e = mt.mtbuf.PushBack(_node)
for {
prev = e.Prev()
cNode = e.Value.(node)
if prev == nil {
break
}
prevNode = prev.Value.(node)
if cNode.NodeCount != prevNode.NodeCount {
break
}
if prevNode.Branches != nil {
// fmt.Printf("Accepting right sibling\n")
for k, v := range *prevNode.Branches {
v.Root = AcceptRightSibling(v.Root, cNode.Data)
(*prevNode.Branches)[k] = v
// fmt.Printf("Proof: %v\n", v.String())
}
}
if cNode.Branches != nil {
// fmt.Printf("Accepting left sibling\n")
for k, v := range *cNode.Branches {
v.Root = AcceptLeftSibling(v.Root, prevNode.Data)
(*prevNode.Branches)[k] = v
// fmt.Printf("Proof: %v\n", v.String())
}
}
// fmt.Printf("Creating new Node: h(%4s, %4s) ", hex.EncodeToString(prevNode.Data[:]), hex.EncodeToString(cNode.Data[:]))
prevNode.Data = mt.h(prevNode.Data, cNode.Data)
// fmt.Printf("=> %4s\n", hex.EncodeToString(prevNode.Data[:]))
prevNode.NodeCount = cNode.NodeCount*2 + 1
if prevNode.NodeCount == mt.exportNodeCount {
mt.exportNodes = append(mt.exportNodes, prevNode.Data)
}
mt.mtbuf.Remove(e)
mt.mtbuf.Remove(prev)
e = mt.mtbuf.PushBack(prevNode)
}
}
func (mt *MerkleTree) Finalize() {
if !mt.finalized && mt.mtbuf.Len() > 1 {
for {
dupNode := mt.mtbuf.Back().Value.(node).Copy()
mt.dnf(dupNode.Data)
mt.insertNode(dupNode)
if mt.mtbuf.Len() == 1 {
break
}
}
}
mt.finalized = true
}
func (mt MerkleTree) Root() NodeData {
if mt.finalized {
return mt.mtbuf.Front().Value.(node).Data
}
panic("SP Merkle tree needs to be finalized by calling mt.Finalize()")
}
func (mt MerkleTree) ExportNodes() []NodeData {
return mt.exportNodes
}
func (mt MerkleTree) Branches() map[uint32]BranchTree {
if mt.finalized {
return *(mt.mtbuf.Front().Value.(node).Branches)
}
panic("SP Merkle tree needs to be finalized by calling mt.Finalize()")
}
func (mt MerkleTree) Indices() []uint32 {
return mt.orderedIndexes
}
<file_sep>package main
import (
"errors"
"fmt"
"github.com/SmartPool/smartpool-client"
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/SmartPool/smartpool-client/ethereum/ethminer"
"github.com/SmartPool/smartpool-client/ethereum/geth"
"github.com/SmartPool/smartpool-client/ethereum/stat"
"github.com/SmartPool/smartpool-client/protocol"
"github.com/SmartPool/smartpool-client/storage"
"github.com/ethereum/go-ethereum/common"
"golang.org/x/crypto/ssh/terminal"
"gopkg.in/urfave/cli.v1"
"io/ioutil"
"math/big"
"os"
"strings"
"syscall"
"time"
)
func Initialize(c *cli.Context) *smartpool.Input {
// Setting
rpcEndPoint := c.String("rpc")
keystorePath := c.String("keystore")
shareThreshold := int(c.Uint("share-threshold"))
claimThreshold := int(c.Uint("claim-threshold"))
shareDifficulty := big.NewInt(int64(c.Uint("diff")))
submitInterval := 1 * time.Minute
contractAddr := c.String("spcontract")
minerAddr := c.String("miner")
hotStop := !c.Bool("no-hot-stop")
if hotStop {
fmt.Printf("SmartPool is in Hot-Stop mode: It will exit immediately if the contract returns errors.\n")
}
extraData := ""
return smartpool.NewInput(
rpcEndPoint, keystorePath, shareThreshold, claimThreshold,
shareDifficulty, submitInterval, contractAddr, minerAddr,
extraData, hotStop,
)
}
func promptUserPassPhrase(acc string) (string, error) {
fmt.Printf("Using miner address: %s\n", acc)
fmt.Printf("Please enter passphrase: ")
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Printf("\n")
if err != nil {
return "", err
} else {
return string(bytePassword), nil
}
}
func Run(c *cli.Context) error {
input := Initialize(c)
if input.KeystorePath() == "" {
fmt.Printf("You have to specify keystore path by --keystore. Abort!\n")
return nil
}
gateway := common.HexToAddress(c.String("gateway"))
if gateway.Big().Cmp(common.Big0) == 0 {
fmt.Printf("Gateway address %s is invalid.\n", c.String("gateway"))
return nil
}
gasprice := c.Uint("gasprice")
smartpool.Output = smartpool.NewLog()
fileStorage := storage.NewGobFileStorage()
ethereumWorkPool := ethereum.NewWorkPool(fileStorage)
go ethereumWorkPool.RunCleaner()
address, ok, addresses := geth.GetAddress(
input.KeystorePath(),
common.HexToAddress(input.MinerAddress()),
)
if len(addresses) == 0 {
fmt.Printf("We couldn't find any private keys in your keystore path.\n")
fmt.Printf("Please make sure your keystore path exists.\nAbort!\n")
return nil
}
fmt.Printf("Using miner address: %s\n", address.Hex())
input.SetMinerAddress(address)
input.SetExtraData(ethereum.BuildExtraData(
common.HexToAddress(input.MinerAddress()),
input.ShareDifficulty()))
gethRPC, _ := geth.NewGethRPC(
input.RPCEndpoint(), input.ContractAddress(),
input.ExtraData(), input.ShareDifficulty(),
input.MinerAddress(),
)
client, err := gethRPC.ClientVersion()
if err != nil {
fmt.Printf("Node RPC server is unavailable.\n")
fmt.Printf("Make sure you have Geth or Parity installed. If you do, you can:\n")
fmt.Printf("Run Geth by following command:\n")
fmt.Printf("geth --testnet --rpc --rpcapi \"db,eth,net,web3,miner\"\n")
fmt.Printf("Or run Parity by following command:\n")
fmt.Printf("parity --chain ropsten --jsonrpc-apis \"web3,eth,net,parity,traces,rpc,parity_set\"\n")
return err
}
fmt.Printf("Connected to Ethereum node: %s\n", client)
ethereumNetworkClient := ethereum.NewNetworkClient(
gethRPC,
ethereumWorkPool,
)
ethereumPoolMonitor, err := geth.NewPoolMonitor(
gateway,
common.HexToAddress(input.ContractAddress()),
smartpool.VERSION,
input.RPCEndpoint(),
)
contractAddr := ethereumPoolMonitor.ContractAddress()
if err != nil {
fmt.Printf("Couln't connect to gateway.\n")
return err
}
if contractAddr.Big().Cmp(common.Big0) == 0 {
fmt.Printf("Couldn't get SmartPool contract address from gateway.\n")
return errors.New("Contract address is not set on the gateway")
}
var gethContractClient *geth.GethContractClient
for {
if ok {
if c.String("pass") != "" {
path := c.String("pass")
passbytes, err := ioutil.ReadFile(path)
if err != nil {
fmt.Printf("Couldn't read your passphrase file. Abort!\n")
return nil
}
passphrase := strings.TrimSpace(string(passbytes))
gethContractClient, err = geth.NewGethContractClient(
common.HexToAddress(input.ContractAddress()), gethRPC,
common.HexToAddress(input.MinerAddress()),
input.RPCEndpoint(), input.KeystorePath(), passphrase,
uint64(gasprice),
)
if gethContractClient != nil {
break
} else {
fmt.Printf("error: %s\n", err)
return nil
}
} else {
passphrase, _ := promptUserPassPhrase(
input.MinerAddress(),
)
gethContractClient, err = geth.NewGethContractClient(
common.HexToAddress(input.ContractAddress()), gethRPC,
common.HexToAddress(input.MinerAddress()),
input.RPCEndpoint(), input.KeystorePath(), passphrase,
uint64(gasprice),
)
if gethContractClient != nil {
break
} else {
fmt.Printf("error: %s\n", err)
}
}
} else {
if input.KeystorePath() == "" {
fmt.Printf("You have to specify keystore path by --keystore. Abort!\n")
} else {
fmt.Printf("Your keystore: %s\n", input.KeystorePath())
fmt.Printf("Your miner address: %s\n", input.MinerAddress())
if len(addresses) > 0 {
fmt.Printf("We couldn't find the private key of your miner address in the keystore path you specified. We found following addresses:\n")
for i, addr := range addresses {
fmt.Printf("%d. %s\n", i+1, addr.Hex())
}
fmt.Printf("Please make sure you entered correct miner address.\n")
} else {
fmt.Printf("We couldn't find any private keys in your keystore path.\n")
fmt.Printf("Please make sure your keystore path exists.\nAbort!\n")
}
}
return nil
}
}
statRecorder := stat.NewStatRecorder(fileStorage)
ethereumClaimRepo := ethereum.NewTimestampClaimRepo(
input.ShareDifficulty(),
common.HexToAddress(input.MinerAddress()).Hex(),
common.HexToAddress(input.ContractAddress()).Hex(),
fileStorage,
)
statRecorder.ShareRestored(ethereumClaimRepo.NoActiveShares())
ethereumContract := ethereum.NewContract(
gethContractClient, common.HexToAddress(input.MinerAddress()))
ethminer.SmartPool = protocol.NewSmartPool(
ethereumPoolMonitor, ethereumWorkPool, ethereumNetworkClient,
ethereumClaimRepo, fileStorage, ethereumContract, statRecorder,
common.HexToAddress(input.ContractAddress()),
common.HexToAddress(input.MinerAddress()),
input.ExtraData(), input.SubmitInterval(),
input.ShareThreshold(), input.ClaimThreshold(), input.HotStop(), input,
)
server := ethminer.NewServer(
smartpool.Output,
uint16(1633),
)
server.Start()
return nil
}
func BuildAppCommandLine() *cli.App {
app := cli.NewApp()
app.Description = "Efficient Decentralized Mining Pools for Existing Cryptocurrencies Based on Ethereum Smart Contracts"
app.Name = "SmartPool commandline tool"
app.Usage = "SmartPool client for ropsten ethereum chain"
app.Version = smartpool.VERSION
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "rpc",
Value: "http://localhost:8545",
Usage: "RPC endpoint of Ethereum node",
},
cli.StringFlag{
Name: "keystore",
Usage: "Keystore path to your ethereum account private key. SmartPool will look for private key of the miner address you specified in that path.",
},
cli.UintFlag{
Name: "share-threshold",
Value: 1040,
Usage: "Minimum number of shares in a claim. SmartPool will not submit the claim if it does not have more than or equal to this threshold numer of share.",
},
cli.UintFlag{
Name: "claim-threshold",
Value: 10,
Usage: "Number of claims in a payment.",
},
cli.UintFlag{
Name: "diff",
Value: 4000000000,
Usage: "Difficulty of a share.",
},
cli.UintFlag{
Name: "gasprice",
Value: 10,
Usage: "Gas price in gwei to use in communication with the contract. Specify 0 if you let your Ethereum Client decide on gas price.",
},
cli.StringFlag{
Name: "spcontract",
Value: "0x893DC419776635F8FD1b1fa9934BF529aeF25607",
Usage: "SmartPool latest contract address.",
},
cli.StringFlag{
Name: "gateway",
Value: "0x83f0a55a11f2767643d323ab5c06f5cb9ac05f4e",
Usage: "Gateway address. Its default value is the official gateway maintained by SmartPool team",
},
cli.StringFlag{
Name: "miner",
Usage: "The address that would be paid by SmartPool. This is often your address. (Default: First account in your keystore.)",
},
cli.StringFlag{
Name: "pass",
Value: "",
Usage: "Path to passphrase file.",
},
cli.BoolFlag{
Name: "no-hot-stop",
Usage: "If hot-stop is true, SmartPool will stop running once it got an error returned from the Contract",
},
}
app.Action = Run
return app
}
func main() {
app := BuildAppCommandLine()
app.Run(os.Args)
}
<file_sep>package ethereum
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"math/big"
)
type RPCClient interface {
ClientVersion() (string, error)
GetWork() *Work
SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool
SubmitWork(nonce types.BlockNonce, hash, mixDigest common.Hash) bool
IsVerified(h common.Hash) bool
Syncing() bool
BlockNumber() (*big.Int, error)
GetLog(txs []*types.Transaction, from *big.Int, event *big.Int, sender *big.Int) (*big.Int, *big.Int)
SetEtherbase(etherbase common.Address) error
SetExtradata(extradata string) error
Broadcast(raw []byte) (common.Hash, error)
}
<file_sep>package main
import (
"fmt"
"github.com/SmartPool/smartpool-client/ethereum"
"github.com/SmartPool/smartpool-client/ethereum/geth"
"github.com/SmartPool/smartpool-client/storage"
"math/big"
// "net/http"
"time"
)
func request(client *ethereum.NetworkClient, timeout chan bool, shutdown chan bool) {
for {
select {
case <-timeout:
shutdown <- true
return
default:
client.GetWork()
fmt.Print(".")
time.Sleep(200 * time.Millisecond)
}
}
}
func main() {
// http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 1000
fileStorage := storage.NewGobFileStorage()
ethereumWorkPool := ethereum.NewWorkPool(fileStorage)
gethRPC, _ := geth.NewGethRPC(
"http://localhost:8545", "0x4e899e19e31cb6d86aefc0f3d2b2122e613a3f5b",
"SmartPool-NsjdZFWvUonU0q00000000", big.NewInt(100000),
"0xe034afdcc2ba0441ff215ee9ba0da3e86450108d",
)
networkClient := ethereum.NewNetworkClient(gethRPC, ethereumWorkPool)
timeout := make(chan bool, 1)
shutdown := make(chan bool, 1)
for i := 0; i < 750; i++ {
go request(networkClient, timeout, shutdown)
}
time.Sleep(1800 * time.Second)
fmt.Printf("Shutting down...\n")
for i := 0; i < 750; i++ {
timeout <- true
}
for i := 0; i < 750; i++ {
<-shutdown
}
}
<file_sep>package protocol
import (
"github.com/SmartPool/smartpool-client"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
)
type testNetworkClient struct {
NotReadyToMine bool
}
func (n *testNetworkClient) GetWork() smartpool.Work {
return &testWork{}
}
func (n *testNetworkClient) SubmitSolution(s smartpool.Solution) bool {
return true
}
func (n *testNetworkClient) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool {
return true
}
func (n *testNetworkClient) Configure(etherbase common.Address, extradata string) error {
return nil
}
func (n *testNetworkClient) ReadyToMine() bool {
return !n.NotReadyToMine
}
|
de65e31cd80ee7b0669dceb1fd8d68413a0cd940
|
[
"JavaScript",
"Go",
"Markdown",
"Shell"
] | 82
|
Go
|
SmartPool/smartpool-client
|
5e51c4724602a97252e1bec37749c2903bed379d
|
086b80e3271547dfc3841323fc3ecf7c8909ddd1
|
refs/heads/master
|
<repo_name>PaperTiger/switchcraft<file_sep>/README.md
# Switchcraft
A Craft CMS Twig Extension for easier and human readable loop switcher.
Loop switcher, huh? Let's say in your template you want to display content inside a loop only for every 3rd loop, then on every 9th item, oh and every first and odd item too! Following code will be a way right? :
```Twig
{% for i in 1..10 %}
{% if loop.index is divisible by (3) %}
Content here display on every 3rd loop
{% endif %}
{% if loop.index is divisible by (9) %}
Content here display on every 9th loop
{% endif %}
{% if loop.index == 1 %}
Content here display on first loop
{% endif %}
{% if loop.index is odd %}
And content here display on every odd loop
{% endif %}
{% endfor %}
```
With **Switchcraft** you can just do this :
```Twig
{% for i in 1..10 %}
{% switchcraft loop.index %}
{% on 'every3Items' %}
Content here display on every 3rd loop
{% on 'every9Items' %}
Content here display on every 9th loop
{% on 'firstItem' %}
Content here display on first loop
{% on 'oddItem' %}
And content here display on every odd loop
{% endswitchcraft %}
{% endfor %}
```
And of course there are [more options](#usage)!
## Installation
1. Download ZIP and unzip file then place the `switchcraft` directory into your `craft/plugins` directory.
2. Install the plugin through Control Panel under `Settings > Plugins`
## Usage
**Switchcraft** comes with two methods : tag and filter, so you can choose them for your convenience.
### Tag
You can use following tag format `{% switchcraft %} … {% endswitchcraft %}`, there are two ways to use this tag :
#### Tag with direct checking
Format : `{% switchcraft loop.index on 'key' %} … {% endswitchcraft %}`
```Twig
{% for i in 1..10 %}
{% switchcraft loop.index on 'firstItem' %}
<p>This will be displayed on first loop</p>
{% endswitchcraft %}
{% switchcraft loop.index on 'oddItem' %}
<p>This will be displayed on odd loop</p>
{% endswitchcraft %}
{% switchcraft loop.index on 'every3Items' %}
<p>This will only be displayed on every 3rd loop</p>
{% endswitchcraft %}
...
{% endfor %}
```
#### Tag per block checking
Format : `{% switchcraft loop.index %} {% on 'key' %} ... {% endswitchcraft %}`
```Twig
{% for i in 1..10 %}
{% switchcraft loop.index %}
{% on 'lastItem' %}
<p>This will only be displayed on last loop</p>
{% on 'every9Items' %}
<p>This will only be displayed on every 9th loop</p>
{% on 'every5Items' %}
<p>This will only be displayed on every 5th loop</p>
...
{% endswitchcraft %}
{% endfor %}
```
### Filter
As with tag, **Switchcraft**'s filter name is like following : `switchcraft`. There are three types of paramaters you can pass :
1. [Array](#array) : `switchcraft({ key : 'value', ... })`
2. [Key + Value](#key+value) `switchcraft( 'key', 'value' )`
3. [Key Only](#keyonly) : `switchcraft( 'key' )`
#### Array
Example usage :
```Twig
{% for i in 1..10 %}
{% set className = loop.index | switchcraft({
firstItem : 'sample-first-class',
oddItem : 'sample-odd-class',
evenItem : 'sample-even-class',
every2Items : 'sample-2nd-class',
}) %}
<p class="{{ className }}"> Content here... </p>
{% endfor %}
```
Or if you prefer to pass directly instead store it to variable :
```Twig
{% for i in 1..10 %}
<p class="{{ loop.index | switchcraft({ firstItem : 'sample-first-class', oddItem : 'sample-odd-class' }) }}">
Content here...
</p>
{% endfor %}
```
#### Key + Value
Example usage :
```Twig
{% for i in 1..10 %}
<p class="{{ loop.index | switchcraft( 'every2Items', 'sample-2nd-class') }}">
Content here...
</p>
{% endfor %}
```
#### Key only
Especially for this type, **Switchcraft** will return a `boolean` value. Example usage :
```Twig
This will check if loop is in every 3rd loop
{% for i in 1..10 %}
{% if loop.index | switchcraft( 'every3Items' ) %}
<p> I will only be displayed on every 3rd loop </p>
{% endif %}
{% endfor %}
```
### loop.index
`loop.index` is a required parameter to read where you are. We're working on two additional support though : `loop.index0` and **context aware** inside loop.
### Available Keys
Following are available keys you can use :
- `firstItem` : every *first* loop
- `lastItem` : every *last* loop
- `oddItem` : every *odd* loop
- `evenItem` : every *even* loop
- `everyNItems` : Where **N** is an integer number.
## License
Switchcraft 2016 by <NAME> for Paper Tiger Marketing, LLC.
<file_sep>/SwitchcraftPlugin.php
<?php
/**
* Switchcraft
* A Craft CMS Twig Extension for easier and human readable loop switcher
*
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2016, Paper Tiger, Inc.
* @see http://papertiger.com
*/
namespace Craft;
class SwitchcraftPlugin extends BasePlugin
{
protected $name = 'Switchcraft';
protected $version = '1.0.0';
protected $developer = '<NAME>';
protected $developerUrl = 'http://papertiger.com';
protected $pluginUrl = 'https://github.com/papertiger/Switchcraft';
protected $docUrl = $this->getPluginUrl() . '/blob/master/README.md';
protected $relUrl = 'https://raw.githubusercontent.com/papertiger/Switchcraft/master/changelog.json';
public function getName()
{
return $this->name;
}
public function getVersion()
{
return $this->version;
}
public function getDeveloper()
{
return $this->developer;
}
public function getDeveloperUrl()
{
return $this->developerUrl;
}
public function getPluginUrl()
{
return $this->pluginUrl;
}
public function getDocumentationUrl()
{
return $this->docUrl;
}
public function getReleaseFeedUrl()
{
return $this->relUrl;
}
public function addTwigExtension()
{
Craft::import( 'plugins.switchcraft.twigextensions.SwitchcraftTwigExtension' );
return new SwitchcraftTwigExtension();
}
}
<file_sep>/twigextensions/SwitchcraftTokenParser.php
<?php
/**
* Class SwitchcraftTokenParser
*
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2016, Paper Tiger, Inc.
* @see http://papertiger.com
*/
namespace Craft;
class SwitchcraftTokenParser extends \Twig_TokenParser
{
/**
* Opening Tag Name
*
* @return string
*/
public function getTag()
{
return 'switchcraft';
}
/**
* Parses {% switchcraft %}...{% switchcraft %} tags.
*
* @param \Twig_Token $token
*
* @return Class
*/
public function parse( \Twig_Token $token )
{
/**
* Store Line, Stream and Cases
*
* @var Integer
* @var Object
* @var Array
*/
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$cases = [];
/**
* Loop Number (eg : loop.index)
*
* @var Integer
*/
$currentIndex = $this->parser->getExpressionParser()->parseExpression();
if( $stream->next()->getValue() == 'on' )
{
$type[] = $this->parser->getExpressionParser()->parsePrimaryExpression();
if ( $stream->nextIf( \Twig_Token::BLOCK_END_TYPE ) )
{
$body = $this->parser->subparse( array( $this, 'decideSwitchcraftEnd' ), true );
$cases[] = new \Twig_Node( array(
'type' => new \Twig_Node( $type ),
'body' => $body
));
}
$stream->expect( \Twig_Token::BLOCK_END_TYPE );
} else {
$end = false;
while ($stream->getCurrent()->getType() == \Twig_Token::TEXT_TYPE && trim($stream->getCurrent()->getValue()) == '')
{
$stream->next();
}
$stream->next();
while( !$end )
{
switch( $stream->getCurrent()->getValue() )
{
case 'on':
{
$stream->next();
$type = [];
$type[] = $this->parser->getExpressionParser()->parseExpression();
$stream->expect( \Twig_Token::BLOCK_END_TYPE );
$body = $this->parser->subparse( array( $this, 'decideSwitchcraftFork' ) );
$cases[] = new \Twig_Node( array(
'type' => new \Twig_Node( $type ),
'body' => $body
));
break;
}
case 'endswitchcraft':
{
$stream->next();
$stream->expect( \Twig_Token::BLOCK_END_TYPE );
$end = true;
break;
}
default:
{
throw new \Twig_Error_Syntax(sprintf('Unexpected end of template. Twig was looking for the following tags "on", or "endswitchcraft" to close the "switchcraft" block started at line %d)', $lineno), -1);
}
}
}
}
return new SwitchcraftNode( $currentIndex, new \Twig_Node( $cases ), $lineno, $this->getTag() );
}
/**
* Decide if we are at the end of stream or continue the stream
*
* @param \Twig_Token $token
*
* @return Mixed
*/
public function decideSwitchcraftFork( \Twig_Token $token )
{
return $token->test(array('on', 'endswitchcraft'));
}
/**
* Decide if we are at the end of stream
*
* @param \Twig_Token $token
*
* @return Bool
*/
public function decideSwitchcraftEnd( \Twig_Token $token )
{
return $token->test('endswitchcraft');
}
}
<file_sep>/twigextensions/SwitchcraftTwigExtension.php
<?php
/**
* Class SwitchcraftTwigExtension
*
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2016, Paper Tiger, Inc.
* @see http://papertiger.com
*/
namespace Craft;
use Twig_Extension;
use Twig_Filter_Method;
require_once( 'SwitchcraftTokenParser.php' );
require_once( 'SwitchcraftNode.php' );
class SwitchcraftTwigExtension extends \Twig_Extension
{
/**
* Default Parameters
*
* @var Array
*/
private static $defaultParams = [ 'firstItem', 'lastItem', 'oddItem', 'evenItem' ];
/**
* Extension Name
*
* @return String
*/
public function getName()
{
return 'Switchcraft';
}
/**
* Token Parser
*
* @return Array
*/
public function getTokenParsers()
{
return [
new SwitchcraftTokenParser(),
];
}
/**
* Filter
*
* @return Array
*/
public function getFilters()
{
return [
'switchcraft' => new \Twig_Filter_Method( $this, 'switchcraftFilter', [ 'needs_context' => true ] )
];
}
/**
* Add Switchcraft functionality into filter
*
* @param Array $context
* @param Int $currentIndex
* @param Mixed $cases
* @param String $return
*
* @return Mixed
*/
public function switchcraftFilter( $context, $currentIndex, $cases, $return = null )
{
if( is_array( $cases ) )
{
$output = [];
foreach($cases as $key => $case)
{
$output[] = $this->switchcraftCompiler( $context, $currentIndex, $key, $case );
}
return implode( $output , ' ');
} else {
return ( $return ) ?
$this->switchcraftCompiler( $context, $currentIndex, $cases, $return ) :
$this->switchcraftCompiler( $context, $currentIndex, $cases, $return, true ) ;
}
}
/**
* Compile data and return
*
* @param Array $context
* @param String $key
* @param Mixed $case
* @param Booleam $test
*
* @return Mixed
*/
private function switchcraftCompiler( $context, $currentIndex, $key, $case, $test = false )
{
if( in_array( $key, self::$defaultParams ))
{
switch ( $key )
{
case 'firstItem':
if( $context['loop']['first'] ) return $this->switchcraftDecider( $case, $test );
break;
case 'lastItem':
if( $currentIndex == $context['loop']['length'] ) return $this->switchcraftDecider( $case, $test );
break;
case 'oddItem':
if( $currentIndex % 2 != 0 ) return $this->switchcraftDecider( $case, $test );
break;
case 'evenItem':
if( $currentIndex % 2 == 0 ) return $this->switchcraftDecider( $case, $test );
break;
}
} else {
if( preg_match( '/every(.*)Items/', $key, $matches ) && $matches[1] )
{
if( $currentIndex % $matches[1] == 0 ) return $this->switchcraftDecider( $case, $test );
}
}
}
/**
* Decide whether returning data or boolean
*
* @param Mixed $case
* @param Boolean $test
*
* @return Mixed
*/
private function switchcraftDecider( $case, $test = false )
{
return ( $test ) ? true : $case ;
}
}<file_sep>/twigextensions/SwitchcraftNode.php
<?php
/**
* Class SwitchcraftNode
*
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2016, Paper Tiger, Inc.
* @see http://papertiger.com
*/
namespace Craft;
class SwitchcraftNode extends \Twig_Node
{
/**
* Construct
*
* @param Integer $currentIndex
* @param Twig_NodeInterface $cases
* @param Function $line
* @param String $tag
*
* @return Mixed
*/
public function __construct( $currentIndex, \Twig_NodeInterface $cases, $line, $tag = null )
{
parent::__construct( ['currentIndex' => $currentIndex], ['cases' => $cases], [], $line, $tag);
}
/**
* Compile Nodes
*
* @param \Twig_Compiler $compiler
*
* @return Null
*/
public function compile( \Twig_Compiler $compiler )
{
$currentIndex = $this->getNode( 'currentIndex' );
$compiler
->addDebugInfo( $this )
->raw( '$defaultParams = [ \'firstItem\', \'lastItem\', \'oddItem\', \'evenItem\' ];' )
;
foreach( $this->getAttribute( 'cases' ) as $case )
{
if( !$case->hasNode( 'body' ) || !$case->hasNode( 'type' ) ) continue;
$type = $case->getNode( 'type' );
$body = $case->getNode( 'body' );
$compiler
->write( 'if( in_array(' )
->subcompile( $type )
->raw( ', $defaultParams) ) {' )
->indent()
->raw( 'switch(' )
->subcompile( $type )
->raw( ') {' )
->indent()
->raw( 'case \'firstItem\':' )
->indent()
->raw( 'if($context[\'loop\'][\'first\']) {' )
->indent()
->subcompile( $body )
->outdent()
->raw( '}' )
->outdent()
->raw( 'break;' )
->raw( 'case \'lastItem\':' )
->indent()
->raw( 'if(' )
->subcompile( $currentIndex )
->raw( ' == $context[\'loop\'][\'length\']) {' )
->indent()
->subcompile( $body )
->outdent()
->raw( '}' )
->outdent()
->raw( 'break;' )
->raw( 'case \'oddItem\':' )
->indent()
->raw( 'if(' )
->subcompile( $currentIndex )
->raw( ' % 2 != 0) {' )
->indent()
->subcompile( $body )
->outdent()
->raw( '}' )
->raw( 'break;' )
->raw( 'case \'evenItem\':' )
->indent()
->raw( 'if(' )
->subcompile( $currentIndex )
->raw( ' % 2 == 0) {' )
->indent()
->subcompile( $body )
->outdent()
->raw ( '}' )
->outdent()
->raw( 'break;' )
->outdent()
->raw( '}' )
->outdent()
->raw( '} else {' )
->indent()
->raw( 'if(preg_match(\'/every(.*)Items/\',' )
->subcompile( $type )
->raw( ',$matches) && $matches[1]) {')
->indent()
->raw( 'if(' )
->subcompile( $currentIndex )
->raw( ' % $matches[1] == 0) {')
->indent()
->subcompile( $body )
->outdent()
->raw( '}' )
->outdent()
->outdent()
->raw( '}' )
->outdent()
->raw( '}' )
;
}
}
}
|
b4fc4e1bc51b94af4e73928836ca48e5bdb37581
|
[
"Markdown",
"PHP"
] | 5
|
Markdown
|
PaperTiger/switchcraft
|
83636f86c1580ca19ca409dc5d415a997073d370
|
2d07a0697d48406326ef6467587e3fb1009a3de7
|
refs/heads/master
|
<file_sep>package studio.nodroid.ebeat.utils
import android.app.Activity
import android.view.View
import android.view.inputmethod.InputMethodManager
import studio.nodroid.ebeat.model.Date
import studio.nodroid.ebeat.model.DateRange
import studio.nodroid.ebeat.model.PressureSeverity
import studio.nodroid.ebeat.model.Time
import java.text.SimpleDateFormat
import java.util.*
const val DAY = 1000 * 60 * 60 * 24 // 86400000
fun timestampFromTime(date: Date, time: Time): Long {
val timestampDate = Calendar.getInstance()
timestampDate.set(date.year, date.month - 1, date.day, time.hour, time.minute)
return timestampDate.timeInMillis
}
fun getPressureRating(systolic: Int?, diastolic: Int?): PressureSeverity {
return when {
diastolic == null || systolic == null || diastolic >= systolic -> PressureSeverity.ERROR
systolic > 180 || diastolic > 120 -> PressureSeverity.HYPERTENSION_CRISIS
systolic >= 140 || diastolic >= 90 -> PressureSeverity.HYPERTENSION_2
systolic in 130..139 || diastolic in 80..89 -> PressureSeverity.HYPERTENSION_1
systolic in 120..129 && diastolic < 80 -> PressureSeverity.ELEVATED
systolic < 120 && diastolic < 80 -> PressureSeverity.NORMAL
else -> PressureSeverity.ERROR
}
}
fun hideKeyboard(view: View) {
val imm = view.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
fun showKeyboard(view: View) {
view.requestFocus()
val imm = view.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, 0)
}
fun Long.toDate(): String {
val cal = Calendar.getInstance()
cal.timeInMillis = this
val sdf = SimpleDateFormat("dd.MM.yyyy", Locale.getDefault())
return sdf.format(cal.time)
}
fun Long.toTime(): String {
val cal = Calendar.getInstance()
cal.timeInMillis = this
val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
return sdf.format(cal.time)
}
fun Date.toTimestampStart(): Long {
val calendar = Calendar.getInstance()
calendar.set(year, month - 1, day, 0, 0, 0)
return calendar.timeInMillis
}
fun Date.toTimestampEnd(): Long {
val calendar = Calendar.getInstance()
calendar.set(year, month - 1, day, 23, 59, 59)
return calendar.timeInMillis
}
fun getPeriodTimestamps(dayPeriod: Int, date: Date? = null): DateRange {
val calendar = Calendar.getInstance()
date?.run {
calendar.set(date.year, date.month - 1, date.day, 23, 59, 59)
} ?: calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59)
val endStamp = calendar.timeInMillis
val startStamp = endStamp - (dayPeriod.toLong() * DAY)
return DateRange(startStamp, endStamp)
}<file_sep>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'io.fabric'
android {
compileSdkVersion 29
defaultConfig {
applicationId "studio.nodroid.ebeat"
minSdkVersion 21
targetSdkVersion 29
versionCode 3
versionName "1.0.1.1"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
resValue "string", "admob_pub_id", 'pub-9002747894812216'
resValue "string", "admob_app_id", 'ca-app-pub-9002747894812216~3336404117'
resValue "string", "admob_banner_non_native", 'ca-app-pub-9002747894812216/6779947764'
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
resValue "string", "admob_pub_id", 'pub-9002747894812216'
resValue "string", "admob_app_id", 'ca-app-pub-9002747894812216~3336404117'
resValue "string", "admob_banner_non_native", 'ca-app-pub-9002747894812216/6779947764'
applicationIdSuffix '.debug'
versionNameSuffix '-DEBUG'
debuggable true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
def room = "2.2.2"
def navigation = "2.2.0-rc03"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.50"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta3'
implementation 'com.google.android.material:material:1.2.0-alpha02'
implementation 'androidx.core:core-ktx:1.1.0'
implementation "org.koin:koin-androidx-viewmodel:2.0.1"
implementation "androidx.room:room-runtime:$room"
kapt "androidx.room:room-compiler:$room"
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
implementation 'com.squareup.phrase:phrase:1.1.0'
implementation 'com.google.firebase:firebase-core:17.2.1'
implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
implementation "androidx.navigation:navigation-fragment-ktx:$navigation"
implementation "androidx.navigation:navigation-ui-ktx:$navigation"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-rc03"
implementation "dev.chrisbanes:insetter:0.1.1"
implementation "dev.chrisbanes:insetter-ktx:0.1.1"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
apply plugin: 'com.google.gms.google-services'
<file_sep>package studio.nodroid.ebeat.ui.flow.readingsList
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.VERTICAL
import androidx.transition.TransitionInflater
import com.google.android.material.chip.Chip
import dev.chrisbanes.insetter.doOnApplyWindowInsets
import kotlinx.android.synthetic.main.fragment_graphs.icon
import kotlinx.android.synthetic.main.fragment_readings_list.*
import org.koin.android.ext.android.inject
import studio.nodroid.ebeat.R
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsScreen
import studio.nodroid.ebeat.model.PressureDataDB
import studio.nodroid.ebeat.model.User
import studio.nodroid.ebeat.ui.dateTime.DatePickDialog
import studio.nodroid.ebeat.utils.dpPx
import studio.nodroid.ebeat.utils.startDotAnimation
class ReadingsListFragment : Fragment() {
private val viewModel by inject<ReadingsListViewModel>()
private val analytics by inject<Analytics>()
private val readingHistoryAdapter by lazy { ReadingHistoryAdapter(onReadingSelected) }
private val onReadingSelected: (PressureDataDB) -> Unit = {
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (savedInstanceState == null) {
analytics.logScreenEvent(AnalyticsScreen.HISTORY_LIST)
}
sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
return inflater.inflate(R.layout.fragment_readings_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
motionLayout.doOnApplyWindowInsets { target, insets, initialState ->
target.updatePadding(
bottom = initialState.paddings.bottom + insets.systemWindowInsetBottom
)
}
readingList.doOnApplyWindowInsets { target, insets, initialState ->
target.updatePadding(
top = initialState.paddings.top + insets.systemWindowInsetTop
)
}
icon.startDotAnimation()
motionLayout.transitionToState(R.id.initial)
readingList.layoutManager = LinearLayoutManager(requireContext())
val decoration = DividerItemDecoration(requireContext(), VERTICAL)
readingList.addItemDecoration(decoration)
readingList.adapter = readingHistoryAdapter
viewModel.userList.observe(viewLifecycleOwner, Observer { list ->
when (list.size) {
1 -> viewModel.selectedUser(list[0])
else -> showUserPicker(list)
}
})
viewModel.events.observe(viewLifecycleOwner, Observer { action ->
when (action) {
is ReadingsListViewModel.Action.ShowUserPicker -> motionLayout.transitionToState(R.id.chooseUser)
is ReadingsListViewModel.Action.ShowRangePicker -> motionLayout.transitionToState(R.id.chooseRange)
is ReadingsListViewModel.Action.ShowRangeDialog -> showDatePickerDialog()
is ReadingsListViewModel.Action.ShowReadingList -> {
if (action.isEmpty) {
motionLayout.transitionToState(R.id.selectionEmpty)
} else {
motionLayout.transitionToState(R.id.listVisible)
}
}
}
})
viewModel.readings.observe(viewLifecycleOwner, Observer {
it?.sortedByDescending { item -> item.timestamp }
?.run { readingHistoryAdapter.setData(this) }
})
timeAll.setOnClickListener { viewModel.allReadingsSelected() }
timeMonth.setOnClickListener { viewModel.time30selected() }
timeRange.setOnClickListener { viewModel.timeRangeSelected() }
changeSelection.setOnClickListener { viewModel.selectedChangeSelection() }
emptyChangeSelection.setOnClickListener { viewModel.selectedChangeSelection() }
emptyDismiss.setOnClickListener { it.findNavController().popBackStack() }
dismiss.setOnClickListener { it.findNavController().popBackStack() }
dismissUsers.setOnClickListener { it.findNavController().popBackStack() }
}
private fun showUserPicker(list: List<User>) {
motionLayout.transitionToState(R.id.chooseUser)
list.forEach { user ->
val chip = layoutInflater.inflate(R.layout.item_user, null) as Chip
val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
layoutParams.marginStart = requireContext().dpPx(8f)
chip.layoutParams = layoutParams
chip.text = user.name
chip.setOnClickListener { viewModel.selectedUser(user) }
chipGroup.addView(chip)
}
}
private fun showDatePickerDialog(which: Int = 0) {
if (which > 1) return
DatePickDialog().apply {
this@apply.onDateChosen = {
viewModel.dateSelected(which == 0, it)
showDatePickerDialog(which + 1)
}
}.show(childFragmentManager, "")
}
}<file_sep>package studio.nodroid.ebeat.model
import androidx.annotation.Keep
import androidx.room.Entity
import androidx.room.PrimaryKey
@Keep
@Entity
data class PressureDataDB(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val systolic: Int,
val diastolic: Int,
val pulse: Int,
val timestamp: Long,
val description: String?,
val userId: Int
)<file_sep>package studio.nodroid.ebeat.room
import androidx.lifecycle.LiveData
import androidx.room.*
import studio.nodroid.ebeat.model.User
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(user: User)
@Query("SELECT * FROM User")
fun getAllUsers(): LiveData<List<User>>
@Query("SELECT * FROM User")
fun getAllUsersNow(): List<User>
@Delete
fun deleteUser(user: User)
@Update
fun updateUser(user: User)
@Query("SELECT * FROM User WHERE id = :userId LIMIT 1")
fun getUserById(userId: Int): User
}<file_sep>package studio.nodroid.ebeat.ui.splash
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import org.koin.androidx.viewmodel.ext.android.viewModel
import studio.nodroid.ebeat.ui.flow.FlowActivity
import studio.nodroid.ebeat.ui.flow.flowUpdateWelcome.FlowUpdateWelcomeActivity
class SplashActivity : AppCompatActivity() {
private val viewModel by viewModel<SplashViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.requirementsMet.observe(this, Observer { event ->
when (event) {
SplashViewModel.Event.SHOW_MAIN -> startMain()
SplashViewModel.Event.SHOW_FLOW_UPDATE_WELCOME -> startFlowUpdateWelcome()
null -> Unit // noop
}
})
}
private fun startMain() {
startActivity(Intent(this, FlowActivity::class.java))
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
finish()
}
private fun startFlowUpdateWelcome() {
startActivity(Intent(this, FlowUpdateWelcomeActivity::class.java))
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
finish()
}
}<file_sep>package studio.nodroid.ebeat.analytics
import android.app.Application
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
class Analytics(app: Application) {
private val firebase = FirebaseAnalytics.getInstance(app)
fun logEvent(event: AnalyticsEvent, bundle: Bundle = Bundle()) {
bundle.putString("name", event.eventName)
firebase.logEvent("user_action", bundle)
}
fun logScreenEvent(event: AnalyticsScreen) {
val bundle = Bundle()
bundle.putString("name", event.screenName)
firebase.logEvent("screen_open", bundle)
}
}
enum class AnalyticsScreen(val screenName: String) {
ACTIONS("Actions"),
ADD_READING("Add reading"),
HISTORY_LIST("History list"),
HISTORY_GRAPH("History graph"),
MANAGE_USERS("Manage users"),
APP_INFO("App info"),
FLOW_UPDATE_WELCOME("Flow update welcome")
}
enum class AnalyticsEvent(val eventName: String) {
READING_ADDED("Reading added"),
READING_DISCARDED("Reading discarded"),
VIEWED_LIST("Viewed list"),
VIEWED_GRAPH("Viewed graph"),
USER_ADDED("User added"),
USER_DELETED("User deleted")
}<file_sep>package studio.nodroid.ebeat.room
import androidx.lifecycle.LiveData
import androidx.room.*
import studio.nodroid.ebeat.model.PressureDataDB
@Dao
interface PressureDataDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertPressureData(data: PressureDataDB)
@Query("SELECT * FROM PressureDataDB ORDER BY timestamp")
fun getAllPressureDataLive(): LiveData<List<PressureDataDB>>
@Query("SELECT * FROM PressureDataDB")
fun getAllPressureData(): List<PressureDataDB>
@Query("SELECT * FROM PressureDataDB WHERE userId = :userId")
fun getUserPressureData(userId: Int): List<PressureDataDB>
@Delete
fun deletePressureData(data: PressureDataDB)
@Update
fun updatePressureData(data: PressureDataDB)
@Query("SELECT * FROM PressureDataDB WHERE timestamp > :start AND timestamp < :end")
fun getDataForRange(start: Long, end: Long): List<PressureDataDB>
@Query("SELECT * FROM PressureDataDB WHERE userId = :userId AND timestamp > :start AND timestamp < :end")
fun getDataForUserAndRange(userId: Int, start: Long, end: Long): LiveData<List<PressureDataDB>>
@Query("SELECT * FROM PressureDataDB WHERE id = :id")
fun getById(id: Int): PressureDataDB
}<file_sep>package studio.nodroid.ebeat.room
import android.util.Log
import androidx.lifecycle.LiveData
import kotlinx.coroutines.*
import studio.nodroid.ebeat.model.PressureDataDB
class PressureDataRepositoryImpl(private val pressureDataDao: PressureDataDao) : PressureDataRepository {
override suspend fun addReading(reading: PressureDataDB) = coroutineScope {
launch(Dispatchers.IO) {
Log.d("findme", "Saving $reading")
pressureDataDao.insertPressureData(reading)
}
}
override fun getAllReadings(): LiveData<List<PressureDataDB>> = pressureDataDao.getAllPressureDataLive()
override suspend fun getAllReadingsFor(userId: Int): List<PressureDataDB> {
return withContext(Dispatchers.IO) {
pressureDataDao.getUserPressureData(userId)
}
}
override suspend fun getReadingById(id: Int): PressureDataDB = coroutineScope {
return@coroutineScope withContext(Dispatchers.IO) { pressureDataDao.getById(id) }
}
override suspend fun deleteReading(value: PressureDataDB): Job = coroutineScope {
launch(Dispatchers.IO) {
pressureDataDao.deletePressureData(value)
}
}
}
interface PressureDataRepository {
suspend fun addReading(reading: PressureDataDB): Job
fun getAllReadings(): LiveData<List<PressureDataDB>>
suspend fun getAllReadingsFor(userId: Int): List<PressureDataDB>
suspend fun getReadingById(id: Int): PressureDataDB
suspend fun deleteReading(value: PressureDataDB): Job
}
<file_sep>package studio.nodroid.ebeat.ui.flow.reading
import android.os.Bundle
import androidx.lifecycle.*
import kotlinx.coroutines.*
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsEvent
import studio.nodroid.ebeat.model.*
import studio.nodroid.ebeat.room.PressureDataRepository
import studio.nodroid.ebeat.room.UserRepository
import studio.nodroid.ebeat.time.TimeProvider
import studio.nodroid.ebeat.utils.SingleLiveEvent
import studio.nodroid.ebeat.utils.getPressureRating
import studio.nodroid.ebeat.utils.timestampFromTime
class ReadingViewModel(
userRepository: UserRepository,
private val pressureRepo: PressureDataRepository,
private val timeProvider: TimeProvider,
private val analytics: Analytics
) : ViewModel() {
private val job = Job()
private val scope = CoroutineScope(Dispatchers.Main + job)
val userList: LiveData<List<User>> = userRepository.getAllUsers()
val selectedUser = MutableLiveData<User>()
val selectedTime = MutableLiveData<Long>()
val selectedSystolic = MutableLiveData<Int>()
val selectedDiastolic = MutableLiveData<Int>()
val selectedPulse = MutableLiveData<Int>()
val selectedDescription = MutableLiveData<String>()
val events = SingleLiveEvent<State>()
val readingSeverity = MediatorLiveData<PressureSeverity>()
private var tempDate: Date? = null
private var timer: Job? = null
private val analyticsBundle = Bundle()
private val severityCalc = Observer<Int> { readingSeverity.value = getPressureRating(selectedSystolic.value, selectedDiastolic.value) }
init {
readingSeverity.addSource(selectedSystolic, severityCalc)
readingSeverity.addSource(selectedDiastolic, severityCalc)
}
fun selectedUser(user: User) {
selectedUser.value = user
}
fun readingTakenNow() {
selectedTime.value = timeProvider.getCurrentTime()
analyticsBundle.putString("time", "now")
}
fun timeNotNowSelected() {
analyticsBundle.putString("time", "custom")
events.value = State.DateNeeded
}
fun timeSelected(time: Time) {
tempDate?.let {
selectedTime.value = timestampFromTime(it, time)
tempDate = null
}
}
fun dateSelected(date: Date) {
tempDate = date
events.value = State.TimeNeeded
}
fun systolicPressureEntered(value: String) {
try {
selectedSystolic.value = value.toInt()
} catch (e: NumberFormatException) {
//noop
}
}
fun diastolicPressureEntered(value: String) {
try {
selectedDiastolic.value = value.toInt()
} catch (e: NumberFormatException) {
//noop
}
}
fun pulseEntered(value: String) {
try {
selectedPulse.value = value.toInt()
} catch (e: NumberFormatException) {
//noop
}
}
fun descriptionEntered(description: String) {
selectedDescription.value = description
}
fun saveReading() {
scope.launch {
pressureRepo.addReading(
PressureDataDB(
systolic = selectedSystolic.value!!,
diastolic = selectedDiastolic.value!!,
pulse = selectedPulse.value!!,
timestamp = selectedTime.value!!,
description = selectedDescription.value,
userId = selectedUser.value!!.id
)
).join()
events.value = State.Saved
analyticsBundle.putString("description", (!selectedDescription.value.isNullOrBlank()).toString())
analyticsBundle.putString("severity", readingSeverity.value?.name)
analytics.logEvent(AnalyticsEvent.READING_ADDED, analyticsBundle)
}
timer = scope.launch {
withContext(Dispatchers.IO) {
delay(3000)
}
events.value = State.Done
}
}
fun doRecord(sys: Int, dia: Int, p: Int, t: Long, De: String) {
scope.launch {
pressureRepo.addReading(
PressureDataDB(
systolic = sys,
diastolic = dia,
pulse = p,
timestamp = t,
description = De,
userId = 8
)
)
}
}
fun discardReading() {
events.value = State.AskDiscard(selectedDescription.value?.isNotEmpty() ?: false)
}
fun savedNotificationDismissed() {
timer?.cancel()
}
fun confirmedDiscard() {
analytics.logEvent(AnalyticsEvent.READING_DISCARDED)
events.value = State.Done
}
fun abortedDiscard() {
events.value = State.FinishedDiscard(selectedDescription.value?.isNotEmpty() ?: false)
}
sealed class State {
object TimeNeeded : State()
object DateNeeded : State()
object Saved : State()
object Done : State()
data class AskDiscard(val isDescriptionSet: Boolean) : State()
data class FinishedDiscard(val isDescriptionSet: Boolean) : State()
}
}
data class ReadingData(val user: User? = null, val time: Long? = null, val systolic: Int? = null, val diastolic: Int? = null, val pulse: Int? = null)
<file_sep>package studio.nodroid.ebeat.ui.flow.flowUpdateWelcome
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updatePadding
import dev.chrisbanes.insetter.doOnApplyWindowInsets
import kotlinx.android.synthetic.main.activity_flow_update_welcome.*
import org.koin.android.ext.android.inject
import studio.nodroid.ebeat.R
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsScreen
import studio.nodroid.ebeat.sharedPrefs.SharedPrefs
import studio.nodroid.ebeat.ui.flow.FlowActivity
import studio.nodroid.ebeat.utils.startDotAnimation
class FlowUpdateWelcomeActivity : AppCompatActivity() {
private val analytics by inject<Analytics>()
private val sharedPrefs by inject<SharedPrefs>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
setContentView(R.layout.activity_flow_update_welcome)
analytics.logScreenEvent(AnalyticsScreen.FLOW_UPDATE_WELCOME)
motionLayout.doOnApplyWindowInsets { target, insets, initialState ->
target.updatePadding(
bottom = initialState.paddings.bottom + insets.systemWindowInsetBottom
)
}
motionLayout.transitionToState(R.id.visible)
icon.startDotAnimation()
icon.transitionName = "dot_animation"
start.setOnClickListener {
startMain()
}
}
private fun startMain() {
sharedPrefs.setFlowUpdateWelcomeSeen()
motionLayout.transitionToState(R.id.hidden)
startActivity(Intent(this, FlowActivity::class.java))
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
finish()
}
}<file_sep>package studio.nodroid.ebeat.ui.flow.actions
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.transition.TransitionInflater
import dev.chrisbanes.insetter.doOnApplyWindowInsets
import kotlinx.android.synthetic.main.fragment_actions.*
import org.koin.android.ext.android.inject
import studio.nodroid.ebeat.R
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsScreen
import studio.nodroid.ebeat.ui.WebViewActivity
import studio.nodroid.ebeat.utils.startDotAnimation
class ActionsFragment : Fragment() {
private val analytics by inject<Analytics>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (savedInstanceState == null) {
analytics.logScreenEvent(AnalyticsScreen.ACTIONS)
}
sharedElementReturnTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
return inflater.inflate(R.layout.fragment_actions, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
motionLayout.doOnApplyWindowInsets { target, insets, initialState ->
target.updatePadding(
bottom = initialState.paddings.bottom + insets.systemWindowInsetBottom
)
}
motionLayout.transitionToState(R.id.visible)
icon.startDotAnimation()
icon.transitionName = "dot_animation"
actionAddReading.setOnClickListener {
val sharedElements = FragmentNavigatorExtras(
icon to "dot_animation"
)
it.findNavController().navigate(R.id.action_actionsFragment_to_readingFragment, null, null, sharedElements)
}
actionManageUsers.setOnClickListener {
val sharedElements = FragmentNavigatorExtras(
icon to "dot_animation"
)
it.findNavController().navigate(R.id.action_actionsFragment_to_usersFragment, null, null, sharedElements)
}
actionViewGraph.setOnClickListener {
val sharedElements = FragmentNavigatorExtras(
icon to "dot_animation"
)
it.findNavController().navigate(R.id.action_actionsFragment_to_graphsFragment, null, null, sharedElements)
}
actionViewReadings.setOnClickListener {
val sharedElements = FragmentNavigatorExtras(
icon to "dot_animation"
)
it.findNavController().navigate(R.id.action_actionsFragment_to_readingsListFragment, null, null, sharedElements)
}
actionEditSettings.setOnClickListener {
startActivity(Intent(requireContext(), WebViewActivity::class.java))
}
}
}<file_sep>package studio.nodroid.ebeat.ui.flow.graphs
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsEvent
import studio.nodroid.ebeat.model.Date
import studio.nodroid.ebeat.model.PressureDataDB
import studio.nodroid.ebeat.model.User
import studio.nodroid.ebeat.room.PressureDataRepository
import studio.nodroid.ebeat.room.UserRepository
import studio.nodroid.ebeat.utils.getPeriodTimestamps
import studio.nodroid.ebeat.utils.toTimestampEnd
import studio.nodroid.ebeat.utils.toTimestampStart
class GraphsViewModel(
userRepository: UserRepository,
private val readingRepo: PressureDataRepository,
private val analytics: Analytics
) : ViewModel() {
private val job = Job()
private val scope = CoroutineScope(Dispatchers.Main + job)
val userList: LiveData<List<User>> = userRepository.getAllUsers()
val readings = MutableLiveData<List<PressureDataDB>>()
val events: MutableLiveData<Action> = MutableLiveData()
private var selectedUser: User? = null
private var firstDate: Date? = null
// init {
// scope.launch {
// userRepository.getAllUsersList().forEach { Log.d("findme", it.toString()) }
// }
/*
scope.launch {
for (i in 0..180) {
val sys = Random.nextInt(115, 125)
val dia = Random.nextInt(65, 75)
val puls = Random.nextInt(60, 80)
val reading = PressureDataDB(systolic = sys, diastolic = dia, pulse = puls, timestamp = System.currentTimeMillis() - i * DAY, userId = 1, description = "Whatever")
readingRepo.addReading(reading).join()
}
}
*/
// }
fun selectedUser(user: User) {
selectedUser = user
events.value = Action.ShowRangePicker
}
fun allReadingsSelected() {
periodSelected("all")
scope.launch {
readings.value = readingRepo.getAllReadingsFor(selectedUser!!.id)
events.value = Action.ShowReadingGraph(readings.value?.isEmpty() ?: true)
}
}
fun time30selected() {
periodSelected("month")
scope.launch {
val period = getPeriodTimestamps(30)
readings.value = readingRepo.getAllReadingsFor(selectedUser!!.id).filter { it.timestamp in period.startStamp..period.endStamp }.sortedBy { it.timestamp }
events.value = Action.ShowReadingGraph(readings.value?.isEmpty() ?: true)
}
}
fun timeRangeSelected() {
events.value = Action.ShowRangeDialog
}
fun dateSelected(isInitial: Boolean, chosenDate: Date) {
if (isInitial) {
firstDate = chosenDate
} else {
scope.launch {
val dateRange = if (firstDate!!.before(chosenDate)) {
Pair(firstDate!!.toTimestampStart(), chosenDate.toTimestampEnd())
} else {
Pair(chosenDate.toTimestampStart(), firstDate!!.toTimestampEnd())
}
readings.value = readingRepo.getAllReadingsFor(selectedUser!!.id).filter { it.timestamp in dateRange.first..dateRange.second }.sortedBy { it.timestamp }
periodSelected("custom")
firstDate = null
events.value = Action.ShowReadingGraph(readings.value?.isEmpty() ?: true)
}
}
}
fun changeSelectionSelected() {
firstDate = null
if (userList.value!!.size > 1) {
selectedUser = null
events.value = Action.ShowUserPicker
} else {
events.value = Action.ShowRangePicker
}
}
private fun periodSelected(period: String) {
val analyticsBundle = Bundle()
analyticsBundle.putString("period", period)
analytics.logEvent(AnalyticsEvent.VIEWED_GRAPH, analyticsBundle)
}
sealed class Action {
object ShowUserPicker : Action()
object ShowRangePicker : Action()
data class ShowReadingGraph(val isEmpty: Boolean) : Action()
object ShowRangeDialog : Action()
}
}<file_sep>package studio.nodroid.ebeat.ui.view
import com.github.mikephil.charting.formatter.ValueFormatter
import java.text.SimpleDateFormat
import java.util.*
class DateAxisFormatter : ValueFormatter() {
private val calendar = Calendar.getInstance()
private val sdf = SimpleDateFormat("dd.MM.yyyy", Locale.getDefault())
override fun getFormattedValue(value: Float): String {
calendar.timeInMillis = value.toLong()
return sdf.format(calendar.time)
}
}<file_sep>package studio.nodroid.ebeat.ui.flow.users
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsEvent
import studio.nodroid.ebeat.model.User
import studio.nodroid.ebeat.room.UserRepository
import studio.nodroid.ebeat.utils.SingleLiveEvent
class UsersViewModel(
private val userRepo: UserRepository,
private val analytics: Analytics
) : ViewModel() {
private val job = Job()
private val scope = CoroutineScope(Dispatchers.Main + job)
val users = userRepo.getAllUsers()
val state = SingleLiveEvent<State>().apply { value = State.SelectAction }
private var markedUser: User? = null
fun newUserNameConfirmed(name: String) {
analytics.logEvent(AnalyticsEvent.USER_ADDED)
scope.launch {
userRepo.addUser(User(name = name))
state.value = State.SelectAction
}
}
fun selectedNewUser() {
state.value = State.NewUser
}
fun selectedDeleteUser() {
state.value = State.DeleteUser.Choose
}
fun canceledDeleteUser() {
markedUser = null
state.value = State.SelectAction
}
fun selectedUser(user: User) {
if (state.value == State.DeleteUser.Choose) {
markedUser = user
state.value = State.DeleteUser.Confirm(user.name)
}
}
fun confirmedDeleteUser() {
analytics.logEvent(AnalyticsEvent.USER_DELETED)
markedUser?.let { user ->
scope.launch {
userRepo.deleteUser(user)
markedUser = null
state.value = State.SelectAction
}
}
}
sealed class State {
object SelectAction : State()
object NewUser : State()
sealed class DeleteUser : State() {
object Choose : DeleteUser()
data class Confirm(val name: String) : DeleteUser()
}
}
}<file_sep>package studio.nodroid.ebeat.ui.flow.graphs
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.findNavController
import androidx.transition.TransitionInflater
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.LargeValueFormatter
import com.google.android.material.chip.Chip
import dev.chrisbanes.insetter.doOnApplyWindowInsets
import kotlinx.android.synthetic.main.fragment_graphs.*
import org.koin.android.ext.android.inject
import studio.nodroid.ebeat.R
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsScreen
import studio.nodroid.ebeat.model.User
import studio.nodroid.ebeat.ui.dateTime.DatePickDialog
import studio.nodroid.ebeat.ui.view.DateAxisFormatter
import studio.nodroid.ebeat.utils.DAY
import studio.nodroid.ebeat.utils.dpPx
import studio.nodroid.ebeat.utils.startDotAnimation
class GraphsFragment : Fragment() {
private val viewModel by inject<GraphsViewModel>()
private val analytics by inject<Analytics>()
private val systolicDataSet by lazy { generateSystolicGraphLine(requireContext()) }
private val diastolicDataSet by lazy { generateDiastolicGraphLine(requireContext()) }
private val pulseDataSet by lazy { generatePulseGraphLine(requireContext()) }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (savedInstanceState == null) {
analytics.logScreenEvent(AnalyticsScreen.HISTORY_GRAPH)
}
sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
return inflater.inflate(R.layout.fragment_graphs, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
motionLayout.doOnApplyWindowInsets { target, insets, initialState ->
target.updatePadding(
bottom = initialState.paddings.bottom + insets.systemWindowInsetBottom,
top = initialState.paddings.top + insets.systemWindowInsetTop
)
}
motionLayout.transitionToState(R.id.initial)
icon.startDotAnimation()
setupGraph()
viewModel.userList.observe(viewLifecycleOwner, Observer { list ->
when (list.size) {
1 -> viewModel.selectedUser(list[0])
else -> showUserPicker(list)
}
})
viewModel.events.observe(viewLifecycleOwner, Observer { action ->
when (action) {
is GraphsViewModel.Action.ShowUserPicker -> motionLayout.transitionToState(R.id.chooseUser)
is GraphsViewModel.Action.ShowRangePicker -> motionLayout.transitionToState(R.id.chooseRange)
is GraphsViewModel.Action.ShowRangeDialog -> showDatePickerDialog()
is GraphsViewModel.Action.ShowReadingGraph -> {
if (action.isEmpty) {
motionLayout.transitionToState(R.id.selectionEmpty)
} else {
motionLayout.transitionToState(R.id.graphVisible)
}
}
}
})
viewModel.readings.observe(viewLifecycleOwner, Observer { list ->
if (list != null && list.isNotEmpty()) {
systolicDataSet.clear()
diastolicDataSet.clear()
pulseDataSet.clear()
val sortedList = list.sortedBy { it.timestamp }
systolicDataSet.values = sortedList.map { pressureData -> Entry(pressureData.timestamp.toFloat(), pressureData.systolic.toFloat()) }
diastolicDataSet.values = sortedList.map { pressureData -> Entry(pressureData.timestamp.toFloat(), pressureData.diastolic.toFloat()) }
pulseDataSet.values = sortedList.map { pressureData -> Entry(pressureData.timestamp.toFloat(), pressureData.pulse.toFloat()) }
lineChart.data = LineData(systolicDataSet, diastolicDataSet, pulseDataSet)
lineChart.xAxis.granularity = 1f
lineChart.fitScreen()
}
})
timeAll.setOnClickListener { viewModel.allReadingsSelected() }
timeMonth.setOnClickListener { viewModel.time30selected() }
timeRange.setOnClickListener { viewModel.timeRangeSelected() }
changeSelection.setOnClickListener { viewModel.changeSelectionSelected() }
emptyChangeSelection.setOnClickListener { viewModel.changeSelectionSelected() }
emptyDismiss.setOnClickListener { it.findNavController().popBackStack() }
dismiss.setOnClickListener { it.findNavController().popBackStack() }
dismissUsers.setOnClickListener { it.findNavController().popBackStack() }
}
private fun showUserPicker(list: List<User>) {
motionLayout.transitionToState(R.id.chooseUser)
list.forEach { user ->
val chip = layoutInflater.inflate(R.layout.item_user, null) as Chip
val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
layoutParams.marginStart = requireContext().dpPx(8f)
chip.layoutParams = layoutParams
chip.text = user.name
chip.setOnClickListener { viewModel.selectedUser(user) }
chipGroup.addView(chip)
}
}
private fun showDatePickerDialog(which: Int = 0) {
if (which > 1) return
DatePickDialog().apply {
this@apply.onDateChosen = {
viewModel.dateSelected(which == 0, it)
showDatePickerDialog(which + 1)
}
}.show(childFragmentManager, "")
}
private fun setupGraph() {
lineChart.isAutoScaleMinMaxEnabled = true
lineChart.description = null
lineChart.setVisibleXRangeMinimum(DAY.toFloat())
lineChart.setVisibleYRangeMinimum(50f, YAxis.AxisDependency.LEFT)
lineChart.legend.isEnabled = false
// lineChart.legend.form = Legend.LegendForm.NONE
// lineChart.legend.setDrawInside(true)
// lineChart.legend.xEntrySpace = 16f
// lineChart.legend.textSize = 14f
// lineChart.legend.textColor = ResourcesCompat.getColor(resources, R.color.color_on_background, requireActivity().theme)
lineChart.xAxis.granularity = DAY.toFloat()
lineChart.xAxis.setAvoidFirstLastClipping(false)
lineChart.xAxis.valueFormatter = DateAxisFormatter()
lineChart.xAxis.gridColor = ResourcesCompat.getColor(resources, R.color.transparentWhite, requireActivity().theme)
lineChart.xAxis.axisLineColor = ResourcesCompat.getColor(resources, R.color.color_on_background, requireActivity().theme)
lineChart.xAxis.textColor = ResourcesCompat.getColor(resources, R.color.color_on_background, requireActivity().theme)
// lineChart.axisLeft.textSize = 14f
// lineChart.axisLeft.setDrawGridLines(false)
lineChart.axisLeft.gridColor = ResourcesCompat.getColor(resources, R.color.transparentWhite, requireActivity().theme)
lineChart.axisLeft.axisLineColor = ResourcesCompat.getColor(resources, R.color.color_on_background, requireActivity().theme)
lineChart.axisLeft.textColor = ResourcesCompat.getColor(resources, R.color.color_on_background, requireActivity().theme)
lineChart.axisRight.isEnabled = false
}
private fun generateSystolicGraphLine(context: Context): LineDataSet {
val set = LineDataSet(mutableListOf(), context.resources.getString(R.string.systolic))
set.mode = LineDataSet.Mode.HORIZONTAL_BEZIER
set.color = ResourcesCompat.getColor(context.resources, R.color.color_on_background, context.theme)
set.setCircleColor(ResourcesCompat.getColor(context.resources, R.color.color_on_background, context.theme))
set.valueTextSize = 10f
set.valueTextColor = ResourcesCompat.getColor(context.resources, R.color.color_on_background, context.theme)
set.lineWidth = 2f
set.isHighlightEnabled = false
set.valueFormatter = LargeValueFormatter()
return set
}
private fun generateDiastolicGraphLine(context: Context): LineDataSet {
val set = LineDataSet(mutableListOf(), context.resources.getString(R.string.diastolic))
set.mode = LineDataSet.Mode.HORIZONTAL_BEZIER
set.color = ResourcesCompat.getColor(context.resources, R.color.color_on_background, context.theme)
set.setCircleColor(ResourcesCompat.getColor(context.resources, R.color.color_on_background, context.theme))
set.valueTextColor = ResourcesCompat.getColor(context.resources, R.color.color_on_background, context.theme)
set.lineWidth = 2f
set.valueTextSize = 10f
set.isHighlightEnabled = false
set.valueFormatter = LargeValueFormatter()
return set
}
private fun generatePulseGraphLine(context: Context): LineDataSet {
val set = LineDataSet(mutableListOf(), context.resources.getString(R.string.pulse))
set.mode = LineDataSet.Mode.HORIZONTAL_BEZIER
set.color = ResourcesCompat.getColor(context.resources, R.color.color_on_background, context.theme)
set.setCircleColor(ResourcesCompat.getColor(context.resources, R.color.color_on_background, context.theme))
set.valueTextColor = ResourcesCompat.getColor(context.resources, R.color.color_on_background, context.theme)
set.valueTextSize = 10f
set.lineWidth = 1f
set.enableDashedLine(15f, 10f, 0f)
set.isHighlightEnabled = false
set.valueFormatter = LargeValueFormatter()
return set
}
}<file_sep>package studio.nodroid.ebeat.room
import androidx.lifecycle.LiveData
import kotlinx.coroutines.*
import studio.nodroid.ebeat.model.User
class UserRepositoryImpl(private val userDao: UserDao) : UserRepository {
override fun getAllUsers(): LiveData<List<User>> {
return userDao.getAllUsers()
}
override suspend fun getAllUsersList(): List<User> {
return withContext(Dispatchers.IO) {
userDao.getAllUsersNow()
}
}
override suspend fun deleteUser(user: User) = coroutineScope {
withContext(Dispatchers.IO) {
userDao.deleteUser(user)
}
}
override suspend fun addUser(user: User) = coroutineScope {
launch(Dispatchers.IO) {
userDao.insert(user)
}
}
override suspend fun updateUser(user: User) = coroutineScope {
withContext(Dispatchers.IO) {
userDao.updateUser(user)
}
}
}
interface UserRepository {
suspend fun deleteUser(user: User)
fun getAllUsers(): LiveData<List<User>>
suspend fun getAllUsersList(): List<User>
suspend fun addUser(user: User): Job
suspend fun updateUser(user: User)
}<file_sep>package studio.nodroid.ebeat.ui.dateTime
import android.app.DatePickerDialog
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.widget.DatePicker
import androidx.fragment.app.DialogFragment
import studio.nodroid.ebeat.model.Date
import java.util.*
class DatePickDialog : DialogFragment(), DatePickerDialog.OnDateSetListener {
var onDateChosen: (Date) -> Unit = {}
var onDismiss: () -> Unit = {}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Use the current date as the default date in the picker
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
// Create a new instance of DatePickDialog and return it
return DatePickerDialog(requireContext(), this, year, month, day)
}
override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
onDateChosen(Date(year, month + 1, day))
dismiss()
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
onDismiss()
}
}<file_sep>package studio.nodroid.ebeat.sharedPrefs
import android.content.SharedPreferences
class SharedPrefsImpl(private val sharedPreferences: SharedPreferences) : SharedPrefs {
private val lastUserId = "last_user_id"
private val shouldShowFlowUpdateWelcome = "shouldShowFlowUpdateWelcome"
override fun saveLastUserId(id: Int) {
sharedPreferences.edit().putInt(lastUserId, id).apply()
}
override fun getLastUserId(): Int {
return sharedPreferences.getInt(lastUserId, -1)
}
override fun shouldShowFlowUpdateWelcome(): Boolean {
return sharedPreferences.getBoolean(shouldShowFlowUpdateWelcome, true)
}
override fun setFlowUpdateWelcomeSeen() {
sharedPreferences.edit().putBoolean(shouldShowFlowUpdateWelcome, false).apply()
}
}
// override fun setPersonalisedOk() {
// sharedPreferences.edit().putInt(adSettings, 1).apply()
// }
//
// override fun setAdsDisabled() {
// sharedPreferences.edit().putInt(adSettings, 0).apply()
// }
//
// override fun setPersonalisedNotOk() {
// sharedPreferences.edit().putInt(adSettings, 2).apply()
// }
//
// override fun getAdStatus(): AdStatus {
// return when (sharedPreferences.getInt(adSettings, 0)) {
// 1 -> AdStatus.PERSONALISED
// 2 -> AdStatus.NON_PERSONALISED
// else -> AdStatus.DISABLED
// }
// }
interface SharedPrefs {
fun saveLastUserId(id: Int)
fun getLastUserId(): Int
fun shouldShowFlowUpdateWelcome(): Boolean
fun setFlowUpdateWelcomeSeen()
// fun setPersonalisedOk()
// fun setAdsDisabled()
// fun setPersonalisedNotOk()
// fun getAdStatus(): AdStatus
}
//enum class AdStatus {
// DISABLED, NON_PERSONALISED, PERSONALISED
//}<file_sep>package studio.nodroid.ebeat.model
enum class PressureSeverity {
ERROR, NORMAL, ELEVATED, HYPERTENSION_1, HYPERTENSION_2, HYPERTENSION_CRISIS
}<file_sep>package studio.nodroid.ebeat.time
class TimeProvider {
fun getCurrentTime(): Long {
return System.currentTimeMillis()
}
}<file_sep>package studio.nodroid.ebeat.room
import androidx.room.Database
import androidx.room.RoomDatabase
import studio.nodroid.ebeat.model.PressureDataDB
import studio.nodroid.ebeat.model.User
@Database(entities = [User::class, PressureDataDB::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun pressureDataDao(): PressureDataDao
}<file_sep>package studio.nodroid.ebeat.ui
import android.os.Bundle
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updatePadding
import dev.chrisbanes.insetter.doOnApplyWindowInsets
import kotlinx.android.synthetic.main.activity_webview.*
import org.koin.android.ext.android.inject
import studio.nodroid.ebeat.R
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsScreen
class WebViewActivity : AppCompatActivity() {
private val analytics by inject<Analytics>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
setContentView(R.layout.activity_webview)
if (savedInstanceState == null) {
analytics.logScreenEvent(AnalyticsScreen.APP_INFO)
}
webview.doOnApplyWindowInsets { target, insets, initialState ->
target.updatePadding(
bottom = initialState.paddings.bottom + insets.systemWindowInsetBottom,
top = initialState.paddings.top + insets.systemWindowInsetTop
)
}
close.doOnApplyWindowInsets { target, insets, initialState ->
target.updatePadding(
top = initialState.paddings.top + insets.systemWindowInsetTop
)
}
webview.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
view?.scrollTo(0, 0)
}
}
webview.loadUrl(getString(R.string.privacy_policy_url))
close.setOnClickListener { finish() }
}
}<file_sep>package studio.nodroid.ebeat.utils
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.text.Spannable
import android.text.SpannableString
import android.text.style.StyleSpan
import android.util.TypedValue
import android.widget.ImageView
import androidx.vectordrawable.graphics.drawable.Animatable2Compat
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import com.squareup.phrase.Phrase
import studio.nodroid.ebeat.R
fun boldFormat(placeholder: String, firstInset: String, secondInset: String? = null): CharSequence {
val styledFirst = SpannableString(firstInset)
styledFirst.setSpan(
StyleSpan(Typeface.ITALIC),
0,
firstInset.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
val styledSecond = secondInset?.run {
val styled = SpannableString(this)
styled.setSpan(
StyleSpan(Typeface.ITALIC),
0,
this.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
styled
}
val phrase = Phrase.from(placeholder)
.put("first", styledFirst)
styledSecond?.run {
phrase.put("second", this)
}
return phrase.format()
}
fun Context.dpPx(dp: Float): Int {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics).toInt()
}
fun ImageView.startDotAnimation() {
val animatedVectorDrawableCompat = AnimatedVectorDrawableCompat.create(context, R.drawable.ic_e_beat_logo_dot)
animatedVectorDrawableCompat?.registerAnimationCallback(
object : Animatable2Compat.AnimationCallback() {
override fun onAnimationEnd(drawable: Drawable?) {
post { animatedVectorDrawableCompat.start() }
}
})
setImageDrawable(animatedVectorDrawableCompat)
animatedVectorDrawableCompat?.start()
}<file_sep>package studio.nodroid.ebeat.ui.splash
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import studio.nodroid.ebeat.model.User
import studio.nodroid.ebeat.room.UserRepository
import studio.nodroid.ebeat.sharedPrefs.SharedPrefs
class SplashViewModel(
userRepository: UserRepository,
private val sharedPrefs: SharedPrefs
) : ViewModel() {
private val job = Job()
private val scope = CoroutineScope(Dispatchers.Main + job)
val requirementsMet = MutableLiveData<Event>()
init {
scope.launch {
val userList = userRepository.getAllUsersList()
when {
userList.isNullOrEmpty() -> {
userRepository.addUser(User(name = "Default")).join()
sharedPrefs.setFlowUpdateWelcomeSeen()
requirementsMet.value = Event.SHOW_MAIN
}
sharedPrefs.shouldShowFlowUpdateWelcome() -> requirementsMet.value = Event.SHOW_FLOW_UPDATE_WELCOME
else -> requirementsMet.value = Event.SHOW_MAIN
}
}
}
enum class Event {
SHOW_MAIN, SHOW_FLOW_UPDATE_WELCOME
}
}<file_sep>package studio.nodroid.ebeat.model
data class DateRange(val startStamp: Long, val endStamp: Long)<file_sep>package studio.nodroid.ebeat.model
data class Date(val year: Int, val month: Int, val day: Int) {
override fun toString(): String = "$day.$month.$year"
fun before(other: Date): Boolean {
return (year < other.year)
|| (year == other.year && month < other.month)
|| (year == other.year && month == other.month && day < other.day)
}
}<file_sep>package studio.nodroid.ebeat.ui.flow.users
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.findNavController
import androidx.transition.TransitionInflater
import com.google.android.material.chip.Chip
import dev.chrisbanes.insetter.doOnApplyWindowInsets
import kotlinx.android.synthetic.main.fragment_users.*
import org.koin.android.ext.android.inject
import studio.nodroid.ebeat.R
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsScreen
import studio.nodroid.ebeat.utils.boldFormat
import studio.nodroid.ebeat.utils.hideKeyboard
class UsersFragment : Fragment() {
private val viewModel by inject<UsersViewModel>()
private val analytics by inject<Analytics>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (savedInstanceState == null) {
analytics.logScreenEvent(AnalyticsScreen.MANAGE_USERS)
}
sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
return inflater.inflate(R.layout.fragment_users, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
motionLayout.doOnApplyWindowInsets { target, insets, initialState ->
target.updatePadding(
bottom = initialState.paddings.bottom + insets.systemWindowInsetBottom
)
}
motionLayout.transitionToState(R.id.initial)
viewModel.users.observe(viewLifecycleOwner, Observer { userList ->
if (userList != null && userList.isNotEmpty()) {
userChips.removeAllViews()
userList.forEach { user ->
val chip = layoutInflater.inflate(R.layout.item_user, null) as Chip
chip.text = user.name
chip.setOnClickListener {
viewModel.selectedUser(user)
}
userChips.addView(chip)
}
}
if (userList.size == 1) {
deleteUser.visibility = View.GONE
} else if (userList.size > 1) {
deleteUser.visibility = View.VISIBLE
}
})
viewModel.state.observe(viewLifecycleOwner, Observer { maybeState ->
maybeState?.let { state ->
when (state) {
UsersViewModel.State.SelectAction -> motionLayout.transitionToState(R.id.actionQuestion)
UsersViewModel.State.NewUser -> motionLayout.transitionToState(R.id.actionAddUser)
UsersViewModel.State.DeleteUser.Choose -> motionLayout.transitionToState(R.id.actionDeleteUser)
is UsersViewModel.State.DeleteUser.Confirm -> {
confirmDeleteQuestion.text = boldFormat(resources.getString(R.string.question_confirm_delete_user), state.name)
motionLayout.transitionToState(R.id.actionConfirmDeleteUser)
}
}
}
})
/**
*
* Pick action
*
*/
createUser.setOnClickListener {
viewModel.selectedNewUser()
}
deleteUser.setOnClickListener {
viewModel.selectedDeleteUser()
}
done.setOnClickListener {
motionLayout.findNavController().popBackStack()
}
/**
*
* Add user
*
*/
newUserValue.setOnEditorActionListener { v, _, _ ->
confirmedUserName(v)
true
}
newUserConfirm.setOnClickListener {
confirmedUserName(it)
}
/**
*
* Delete user
*
*/
abortDeletePick.setOnClickListener {
viewModel.canceledDeleteUser()
}
cancelDeleteUser.setOnClickListener {
viewModel.canceledDeleteUser()
}
confirmDeleteUser.setOnClickListener {
viewModel.confirmedDeleteUser()
}
}
private fun confirmedUserName(view: View) {
val enteredText = newUserValue.text.toString()
if (enteredText.isNotBlank()) {
viewModel.newUserNameConfirmed(enteredText)
hideKeyboard(view)
newUserValue.text.clear()
}
}
}<file_sep>package studio.nodroid.ebeat.ui.flow
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import studio.nodroid.ebeat.R
class FlowActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
setContentView(R.layout.activity_flow)
}
}<file_sep>package studio.nodroid.ebeat.ui.flow.settings
import androidx.fragment.app.Fragment
class SettingsFragment : Fragment()<file_sep>package studio.nodroid.ebeat
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
import studio.nodroid.ebeat.di.appModule
class App : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@App)
modules(appModule)
}
// val mobAdAppId = if (BuildConfig.DEBUG) {
// "ca-app-pub-3940256099942544~3347511713"
// } else {
// "ca-app-pub-9002747894812216~3336404117"
// }
}
}<file_sep>package studio.nodroid.ebeat.ui.flow.readingsList
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_reading.view.*
import studio.nodroid.ebeat.R
import studio.nodroid.ebeat.model.PressureDataDB
import studio.nodroid.ebeat.utils.toDate
import studio.nodroid.ebeat.utils.toTime
class ReadingHistoryAdapter(private val onReadingSelected: (PressureDataDB) -> Unit) : RecyclerView.Adapter<ReadingHolder>() {
private val items = mutableListOf<PressureDataDB>()
override fun getItemCount() = items.size
fun setData(data: List<PressureDataDB>) {
items.clear()
items.addAll(data)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReadingHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_reading, parent, false)
return ReadingHolder(view)
}
override fun onBindViewHolder(holder: ReadingHolder, position: Int) {
holder.bind(items[position], onReadingSelected)
}
}
class ReadingHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(reading: PressureDataDB, onReadingSelected: (PressureDataDB) -> Unit) {
view.systolic.text = reading.systolic.toString()
view.diastolic.text = reading.diastolic.toString()
view.pulse.text = reading.pulse.toString()
view.range.text = reading.timestamp.toDate()
view.time.text = reading.timestamp.toTime()
view.description.text = reading.description
view.setOnClickListener { onReadingSelected(reading) }
}
}<file_sep>package studio.nodroid.ebeat.ui.flow.reading
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.findNavController
import androidx.transition.TransitionInflater
import com.google.android.material.chip.Chip
import dev.chrisbanes.insetter.doOnApplyWindowInsets
import kotlinx.android.synthetic.main.fragment_reading.*
import org.koin.android.ext.android.inject
import studio.nodroid.ebeat.R
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.analytics.AnalyticsScreen
import studio.nodroid.ebeat.model.PressureSeverity
import studio.nodroid.ebeat.model.User
import studio.nodroid.ebeat.ui.dateTime.DatePickDialog
import studio.nodroid.ebeat.ui.dateTime.TimePickDialog
import studio.nodroid.ebeat.utils.*
class ReadingFragment : Fragment() {
private val timePicker by lazy {
TimePickDialog().apply {
this@apply.onTimeChosen = {
viewModel.timeSelected(it)
}
}
}
private val datePicker by lazy {
DatePickDialog().apply {
this@apply.onDateChosen = {
viewModel.dateSelected(it)
}
}
}
private val viewModel by inject<ReadingViewModel>()
private val analytics by inject<Analytics>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (savedInstanceState == null) {
analytics.logScreenEvent(AnalyticsScreen.ADD_READING)
}
sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
return inflater.inflate(R.layout.fragment_reading, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
motionLayout.doOnApplyWindowInsets { target, insets, initialState ->
target.updatePadding(
bottom = initialState.paddings.bottom + insets.systemWindowInsetBottom,
top = initialState.paddings.top + insets.systemWindowInsetTop
)
}
motionLayout.transitionToState(R.id.initial)
icon.startDotAnimation()
viewModel.userList.observe(viewLifecycleOwner, Observer { list ->
when (list.size) {
1 -> setUser(list[0])
else -> showUserPicker(list)
}
})
viewModel.selectedUser.observe(viewLifecycleOwner, Observer { it?.run { showUserSelected(this) } })
viewModel.selectedTime.observe(viewLifecycleOwner, Observer { it?.run { showTimeSelected(this) } })
viewModel.selectedSystolic.observe(viewLifecycleOwner, Observer { it?.run { showSystolicSelected(this) } })
viewModel.selectedDiastolic.observe(viewLifecycleOwner, Observer { it?.run { showDiastolicSelected(this) } })
viewModel.selectedPulse.observe(viewLifecycleOwner, Observer { it?.run { showPulseSelected(this) } })
viewModel.selectedDescription.observe(viewLifecycleOwner, Observer { it?.run { showDescriptionSelected(this) } })
viewModel.readingSeverity.observe(viewLifecycleOwner, Observer { showPressureSeverity(it) })
timeNow.setOnClickListener { viewModel.readingTakenNow() }
timeOther.setOnClickListener { viewModel.timeNotNowSelected() }
systolicValueConfirm.setOnClickListener {
viewModel.systolicPressureEntered(systolicValue.text.toString())
}
systolicValue.setOnEditorActionListener { _, _, _ ->
viewModel.systolicPressureEntered(systolicValue.text.toString())
true
}
diastolicValueConfirm.setOnClickListener {
viewModel.diastolicPressureEntered(diastolicValue.text.toString())
}
diastolicValue.setOnEditorActionListener { _, _, _ ->
viewModel.diastolicPressureEntered(diastolicValue.text.toString())
true
}
pulseValueConfirm.setOnClickListener {
viewModel.pulseEntered(pulseValue.text.toString())
hideKeyboard(it)
}
pulseValue.setOnEditorActionListener { v, _, _ ->
viewModel.pulseEntered(pulseValue.text.toString())
hideKeyboard(v)
true
}
descriptionValueConfirm.setOnClickListener {
viewModel.descriptionEntered(descriptionValue.text.toString())
hideKeyboard(it)
}
descriptionValue.setOnEditorActionListener { v, _, _ ->
viewModel.descriptionEntered(descriptionValue.text.toString())
hideKeyboard(v)
true
}
actionDescription.setOnClickListener {
motionLayout.transitionToState(R.id.enterDescription)
showKeyboard(descriptionValue)
}
actionDiscardConfirm.setOnClickListener { viewModel.confirmedDiscard() }
actionDiscardAbort.setOnClickListener { viewModel.abortedDiscard() }
actionSave.setOnClickListener { viewModel.saveReading() }
actionDiscard.setOnClickListener { viewModel.discardReading() }
actionDone.setOnClickListener {
viewModel.savedNotificationDismissed()
navigateBack()
}
viewModel.events.observe(viewLifecycleOwner, Observer { event ->
when (event) {
is ReadingViewModel.State.TimeNeeded -> timePicker.show(childFragmentManager, "time")
is ReadingViewModel.State.DateNeeded -> datePicker.show(childFragmentManager, "date")
is ReadingViewModel.State.Saved -> showSavedReading()
is ReadingViewModel.State.Done -> navigateBack()
is ReadingViewModel.State.AskDiscard -> showDiscard(event.isDescriptionSet)
is ReadingViewModel.State.FinishedDiscard -> showActions(event.isDescriptionSet)
null -> {/*noop*/
}
}
})
}
private fun showPressureSeverity(bpSeverity: PressureSeverity?) {
severity.text = when (bpSeverity) {
PressureSeverity.ERROR -> getString(R.string.severity_error)
PressureSeverity.NORMAL -> getString(R.string.severity_normal)
PressureSeverity.ELEVATED -> getString(R.string.severity_elevated)
PressureSeverity.HYPERTENSION_1 -> getString(R.string.severity_hypertension1)
PressureSeverity.HYPERTENSION_2 -> getString(R.string.severity_hypertension2)
PressureSeverity.HYPERTENSION_CRISIS -> getString(R.string.severity_crisis)
null -> getString(R.string.severity_error)
}
}
private fun showActions(isDescriptionSet: Boolean) {
if (isDescriptionSet) {
motionLayout.transitionToState(R.id.chooseActionDesc)
} else {
motionLayout.transitionToState(R.id.chooseActionNoDesc)
}
}
private fun showDiscard(isDescriptionSet: Boolean) {
if (isDescriptionSet) {
motionLayout.transitionToState(R.id.discardDesc)
} else {
motionLayout.transitionToState(R.id.discardNoDesc)
}
}
private fun showSavedReading() {
motionLayout.transitionToState(R.id.readingSaved)
}
private fun navigateBack() {
user.findNavController().popBackStack()
}
/**
*
* User picking
*
*/
private fun showUserSelected(selectedUser: User) {
user.text = boldFormat(getString(R.string.reading_user), selectedUser.name)
motionLayout.transitionToState(R.id.selectDate)
}
private fun showUserPicker(list: List<User>) {
motionLayout.transitionToState(R.id.selectUser)
list.forEach { user ->
val chip = layoutInflater.inflate(R.layout.item_user, null) as Chip
val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
layoutParams.marginStart = requireContext().dpPx(8f)
chip.layoutParams = layoutParams
chip.text = user.name
chip.setOnClickListener { viewModel.selectedUser(user) }
chipGroup.addView(chip)
}
}
private fun setUser(user: User) {
viewModel.selectedUser(user)
}
/**
*
* Time and date picking
*
*/
private fun showTimeSelected(time: Long) {
dateTime.text = boldFormat(getString(R.string.reading_date), time.toDate(), time.toTime())
motionLayout.transitionToState(R.id.enterSystolic)
systolicValue.requestFocus()
showKeyboard(systolicValue)
}
/**
*
* Systolic handling
*
*/
private fun showSystolicSelected(sys: Int) {
systolic.text = boldFormat(getString(R.string.reading_systolic), sys.toString())
motionLayout.transitionToState(R.id.enterDiastolic)
diastolicValue.requestFocus()
showKeyboard(diastolicValue)
}
/**
*
* Diastolic handling
*
*/
private fun showDiastolicSelected(dia: Int) {
diastolic.text = boldFormat(getString(R.string.reading_diastolic), dia.toString())
motionLayout.transitionToState(R.id.enterPulse)
pulseValue.requestFocus()
showKeyboard(pulseValue)
}
/**
*
* Pulse handling
*
*/
private fun showPulseSelected(pul: Int) {
pulse.text = boldFormat(getString(R.string.reading_pulse), pul.toString())
motionLayout.transitionToState(R.id.chooseActionNoDesc)
}
/**
*
* Description handling
*
*/
private fun showDescriptionSelected(desc: String) {
if (desc.isEmpty()) {
motionLayout.transitionToState(R.id.chooseActionNoDesc)
} else {
description.text = boldFormat("{first}", desc)
actionDescription.visibility = View.GONE
motionLayout.transitionToState(R.id.chooseActionDesc)
}
}
}
<file_sep>package studio.nodroid.ebeat.model
import androidx.annotation.Keep
import androidx.room.Entity
import androidx.room.PrimaryKey
@Keep
@Entity
data class User(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val name: String
)<file_sep>package studio.nodroid.ebeat.di
import android.content.Context
import android.content.SharedPreferences
import androidx.room.Room
import org.koin.android.ext.koin.androidApplication
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
import studio.nodroid.ebeat.analytics.Analytics
import studio.nodroid.ebeat.room.*
import studio.nodroid.ebeat.sharedPrefs.SharedPrefs
import studio.nodroid.ebeat.sharedPrefs.SharedPrefsImpl
import studio.nodroid.ebeat.time.TimeProvider
import studio.nodroid.ebeat.ui.flow.graphs.GraphsViewModel
import studio.nodroid.ebeat.ui.flow.reading.ReadingViewModel
import studio.nodroid.ebeat.ui.flow.readingsList.ReadingsListViewModel
import studio.nodroid.ebeat.ui.flow.users.UsersViewModel
import studio.nodroid.ebeat.ui.splash.SplashViewModel
private const val DATABASE_NAME = "app_database"
private const val SHARED_PREFS_NAME = "shared_prefs"
val appModule = module {
single<SharedPreferences> { androidApplication().getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE) }
single<SharedPrefs> { SharedPrefsImpl(get()) }
single { Analytics(androidApplication()) }
single { TimeProvider() }
single { Room.databaseBuilder(androidApplication(), AppDatabase::class.java, DATABASE_NAME).build() }
single { get<AppDatabase>().userDao() }
single { get<AppDatabase>().pressureDataDao() }
single<UserRepository> { UserRepositoryImpl(get()) }
single<PressureDataRepository> { PressureDataRepositoryImpl(get()) }
viewModel { SplashViewModel(get(), get()) }
viewModel { ReadingViewModel(get(), get(), get(), get()) }
viewModel { UsersViewModel(get(), get()) }
viewModel { GraphsViewModel(get(), get(), get()) }
viewModel { ReadingsListViewModel(get(), get(), get()) }
}<file_sep>package studio.nodroid.ebeat.model
data class Time(val hour: Int, val minute: Int) {
override fun toString(): String = "${hour.timeDisplayValue()}:${minute.timeDisplayValue()}"
}
fun Int.timeDisplayValue(): String = this.toString().padStart(2, '0')<file_sep>package studio.nodroid.ebeat.ui.dateTime
import android.app.Dialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.widget.TimePicker
import androidx.fragment.app.DialogFragment
import studio.nodroid.ebeat.model.Time
import java.util.*
class TimePickDialog : DialogFragment(), TimePickerDialog.OnTimeSetListener {
var onTimeChosen: (Time) -> Unit = {}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Use the current time as the default values for the picker
val c = Calendar.getInstance()
val hour = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)
// Create a new instance of TimePickerDialog and return it
return TimePickerDialog(activity, this, hour, minute, true)
}
override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
onTimeChosen(Time(hourOfDay, minute))
}
}
|
fddcb1941ca8db747b2cb5efbd912e66dc8d9e8b
|
[
"Kotlin",
"Gradle"
] | 37
|
Kotlin
|
MarijanGazica/e.beat
|
744eba536ba9db8b010da0f9f62a2dd76cbd2779
|
b6971d4c8e1371342dc5e29036bc9bc2178d092e
|
refs/heads/master
|
<repo_name>kangliqiang/cloud-asr<file_sep>/app/asr.py
from kaldi.decoders import PyOnlineLatgenRecogniser
from kaldi.utils import lattice_to_nbest, wst2dict
from StringIO import StringIO
import wave
recogniser = None
wst = None
def asr_init(basedir):
create_recogniser(basedir)
create_dictionary(basedir)
def create_recogniser(basedir):
global recogniser
recogniser = PyOnlineLatgenRecogniser()
argv = ['--config=%s/models/mfcc.conf' % basedir,
'--verbose=0', '--max-mem=10000000000', '--lat-lm-scale=15', '--beam=12.0',
'--lattice-beam=6.0', '--max-active=5000',
'%s/models/tri2b_bmmi.mdl' % basedir,
'%s/models/HCLG_tri2b_bmmi.fst' % basedir,
'1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25',
'%s//models/tri2b_bmmi.mat' % basedir]
recogniser.setup(argv)
def create_dictionary(basedir):
global wst
wst = wst2dict('%s/models/words.txt' % basedir)
def recognize_wav(data, def_sample_width=2, def_sample_rate=16000):
wav = load_wav_from_request_data(data, def_sample_width)
pcm = convert_wav_to_pcm(wav, def_sample_rate)
recognize_chunk(pcm)
return nbest_hypotheses(n=10)
return create_response(hypotheses)
def recognize_chunk(pcm):
global recogniser
decoded_frames = 0
recogniser.frame_in(pcm)
dec_t = recogniser.decode(max_frames=10)
while dec_t > 0:
decoded_frames += dec_t
dec_t = recogniser.decode(max_frames=10)
return recogniser.get_best_path()
def nbest_hypotheses(n=10):
global recogniser
recogniser.prune_final()
utt_lik, lat = recogniser.get_lattice()
recogniser.reset()
return [(prob, path_to_text(path)) for (prob, path) in lattice_to_nbest(lat, n=10)]
def path_to_text(path):
global wst
return u' '.join([unicode(wst[w]) for w in path])
def load_wav_from_request_data(data, def_sample_width):
wav = wave.open(StringIO(data), 'r')
if wav.getnchannels() != 1:
raise Exception('Input wave is not in mono')
if wav.getsampwidth() != def_sample_width:
raise Exception('Input wave is not in %d Bytes' % def_sample_width)
return wav
def convert_wav_to_pcm(wav, def_sample_rate):
try:
chunk = 1024
pcm = b''
pcmPart = wav.readframes(chunk)
while pcmPart:
pcm += str(pcmPart)
pcmPart = wav.readframes(chunk)
return resample_to_def_sample_rate(pcm, wav.getframerate(), def_sample_rate)
except EOFError:
raise Exception('Input PCM is corrupted: End of file.')
def resample_to_def_sample_rate(pcm, sample_rate, def_sample_rate):
if sample_rate != def_sample_rate:
import audioop
pcm, state = audioop.ratecv(pcm, 2, 1, sample_rate, def_sample_rate, None)
return pcm
def create_response(hypotheses):
return {
"result": [
{
"alternative": [{"transcript": t, "confidence": c} for (c,t) in hypotheses],
"final": True,
},
],
"result_index": 0
}
<file_sep>/install/base.sh
#!/bin/bash
set -e # Stop on any error
# --------------- SETTINGS ----------------
# Other settings
export DEBIAN_FRONTEND=noninteractive
sudo apt-get update
sudo apt-get install -y sox git python-dev python-pip python-setuptools libatlas-base-dev portaudio19-dev build-essential
sudo pip install cython pyyaml pystache flask flask-socketio
# install pyaudio
pushd /tmp
wget http://people.csail.mit.edu/hubert/pyaudio/packages/python-pyaudio_0.2.8-1_amd64.deb
sudo dpkg -i python-pyaudio_0.2.8-1_amd64.deb
popd # /tmp
if [ ! -f ~/runonce ]
then
echo 'export LANG=en_US.UTF-8' >> ~/.bashrc
echo 'export LC_ALL="$LANG"' >> ~/.bashrc
echo 'export LANGUAGE="$LANG"' >> ~/.bashrc
# have to reboot for drivers to kick in, but only the first time of course
sudo reboot
touch ~/runonce
fi
<file_sep>/app/static/js/SpeechRecognition.js
(function(window){
var SpeechRecognition = function() {
this.continuous = true;
this.interimResults = true;
this.onstart = function() {};
this.onresult = function(event) {};
this.onerror = function(event) {};
this.onend = function() {};
var recognizer = this;
var recorder = createRecorder();
var socket = createSocket();
this.start = function() {
socket.emit('begin', {'lang':'cs'});
recorder.record();
this.onstart();
};
this.stop = function() {
socket.emit('end', {});
recorder.stop();
this.onend();
};
var handleResult = function(results) {
recognizer.onresult(results.result);
};
var handleError = function(error) {
recognizer.onerror(error);
};
var handleEnd = function() {
recognizer.onend();
};
function createSocket() {
socket = io.connect();
socket.on("connection", function() {
console.log("Socket connected");
});
socket.on("result", function(results) {
handleResult(results);
});
socket.on("error", function(error) {
handleError(error);
});
socket.on("end", function(error) {
handleEnd();
});
return socket;
}
function createRecorder() {
recorder = new Recorder({
bufferCallback: handleChunk
});
recorder.init();
return recorder;
}
function handleChunk(chunk) {
socket.emit("chunk", {chunk: floatTo16BitPCM(chunk[0])});
}
function floatTo16BitPCM(chunk){
result = [];
for( i = 0; i < chunk.length; i++ ) {
var s = Math.max(-1, Math.min(1, chunk[i]));
result[i] = Math.round(s < 0 ? s * 0x8000 : s * 0x7FFF);
}
return result;
}
}
window.SpeechRecognition = SpeechRecognition;
})(window);
<file_sep>/tests/test_online_recognition.py
import os
import sys
import wave
import struct
from socketIO_client import SocketIO
def frames_to_pcm_array(frames):
return [struct.unpack('h', frames[i:i+2])[0] for i in range(0, len(frames), 2)]
def chunks(wav):
while True:
frames = wav.readframes(16384)
if len(frames) == 0:
break
yield frames_to_pcm_array(frames)
def print_response(*args):
print "result: ", args
def end(*args):
sys.exit(1)
basedir = os.path.dirname(os.path.realpath(__file__))
wav = wave.open('%s/../resources/test.wav' % basedir, 'rb')
with SocketIO('192.168.10.10', 80) as socketIO:
socketIO.on('result', print_response)
socketIO.on('end', end)
socketIO.emit('begin', {'lang': 'cs'})
for chunk in chunks(wav):
socketIO.emit('chunk', {'chunk': chunk})
socketIO.emit('end', {})
socketIO.wait()
<file_sep>/app/models/download_models.sh
#!/bin/bash
wget -NS https://vystadial.ms.mff.cuni.cz/download/alex/resources/asr/voip_cs/kaldi/mfcc.conf
wget -NS https://vystadial.ms.mff.cuni.cz/download/alex/resources/asr/voip_cs/kaldi/tri2b_bmmi.mdl
wget -NS https://vystadial.ms.mff.cuni.cz/download/alex/resources/asr/voip_cs/kaldi/tri2b_bmmi.mat
wget -NS https://vystadial.ms.mff.cuni.cz/download/alex/applications/PublicTransportInfoCS/hclg/models/HCLG_tri2b_bmmi.fst
wget -NS https://vystadial.ms.mff.cuni.cz/download/alex/applications/PublicTransportInfoCS/hclg/models/words.txt
<file_sep>/Vagrantfile
# -*- mode: ruby -*- # vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "precise64-alsa"
config.vm.box_url = "http://files.vagrantup.com/precise64.box"
config.vm.network "private_network", ip: "192.168.10.10"
config.vm.synced_folder "app/", "/var/www/speech-api", type: "nfs"
config.vm.provider :virtualbox do |vb|
vb.memory = 2048
vb.cpus = 1
end
config.vm.provision :shell, :path => "install/base.sh"
config.vm.provision :shell, :path => "install/pykaldi.sh"
config.vm.provision :shell, :path => "install/nginx.sh"
config.vm.provision :shell, :path => "install/supervisord.sh"
config.vm.provision :shell, :path => "install/zeromq.sh"
end
<file_sep>/tests/test_batch_recognition.py
import os
import urllib2
import StringIO
basedir = os.path.dirname(os.path.realpath(__file__))
wav = open('%s/../resources/test.wav' % basedir, 'rb').read()
headers = {'Content-Type': 'audio/x-wav; rate=44100;'}
request = urllib2.Request('http://192.168.10.10/recognize', wav, headers)
response = urllib2.urlopen(request).read()
print response
<file_sep>/install/supervisord.sh
#!/bin/bash
sudo pip install supervisor
sudo ln -s /vagrant/supervisord.conf /etc/supervisord.conf
sudo cat <<EOF > /etc/init/supervisord.conf
description "supervisord"
start on vagrant-mounted
stop on runlevel [016]
pre-start script
echo \$MOUNTPOINT >> /var/run/mount.log
[ \$MOUNTPOINT = "/vagrant" ] && touch /var/run/vagrant_mounted
[ \$MOUNTPOINT = "/var/www/speech-api" ] && touch /var/run/api_mounted
[ -f /var/run/vagrant_mounted -a -f /var/run/api_mounted ] || stop
end script
respawn
exec /usr/local/bin/supervisord --nodaemon --configuration /etc/supervisord.conf
EOF
sudo start supervisord
<file_sep>/app/server.py
from flask import Flask, render_template, request, jsonify
from flask.ext.socketio import SocketIO, emit, session
from background_asr import recognize_wav
from online_asr import OnlineASR
app = Flask(__name__)
app.config.from_object(__name__)
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/recognize', methods=['POST'])
def recognize():
response = recognize_wav(request.data)
return jsonify(response)
@socketio.on('begin')
def begin_recognition(message):
session['recognizer'] = OnlineASR(emit)
@socketio.on('chunk')
def recognize_chunk(message):
session['recognizer'].recognize_chunk(message)
@socketio.on('end')
def end_recognition(message):
session['recognizer'].end()
if __name__ == '__main__':
app.secret_key = 12345
socketio.run(app)
<file_sep>/install/nginx.sh
#!/bin/bash
sudo sh -c 'echo "deb http://ppa.launchpad.net/nginx/stable/ubuntu lucid main" > /etc/apt/sources.list.d/nginx-stable-lucid.list'
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C300EE8C
sudo apt-get update
sudo apt-get install -y nginx
sudo cat <<SPEECH-API > /etc/nginx/sites-available/speech-api
server {
location / {
proxy_pass http://127.0.0.1:5000;
}
location /socket.io {
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
SPEECH-API
sudo rm /etc/nginx/sites-enabled/default
sudo ln -s /etc/nginx/sites-available/speech-api /etc/nginx/sites-enabled/speech-api
sudo /etc/init.d/nginx restart
<file_sep>/install/zeromq.sh
#!/bin/bash
set -e
sudo apt-get install -y libtool autoconf automake uuid-dev build-essential
cd ~
wget http://download.zeromq.org/zeromq-3.2.2.tar.gz
tar zxvf zeromq-3.2.2.tar.gz && cd zeromq-3.2.2
./configure
make && sudo make install
sudo pip install pyzmq
<file_sep>/app/worker.py
from asr import asr_init, recognize_wav, create_response
import os
import zmq
from datetime import datetime
def log(message):
print "%s\t%s" % (str(datetime.now()), message)
log('Loading models.')
basedir = os.path.dirname(os.path.realpath(__file__))
asr_init(basedir)
log('Models loaded.')
port = "5560"
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.connect("tcp://localhost:%s" % port)
log('Worker initialized.')
while True:
wav = socket.recv()
log('Received wav for speech recognition.')
best_hypotheses = recognize_wav(wav)
socket.send_json(create_response(best_hypotheses))
log('Recognized hypotheses sent.')
<file_sep>/app/background_asr.py
import zmq
def recognize_wav(data):
port = 5559
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:%s" % port)
socket.send(data)
return socket.recv_json()
<file_sep>/install/pykaldi.sh
#!/bin/bash
set -e # Stop on any error
git clone https://github.com/UFAL-DSG/pykaldi pykaldi
cd pykaldi
pushd tools
make atlas openfst_tgt
pushd openfst
./configure --prefix=/usr
sudo make install
popd
git clone https://github.com/UFAL-DSG/pyfst.git pyfst
pushd pyfst
sudo python setup.py install
popd
popd
pushd src
./configure && \
make depend && \
make && \
make test && \
echo 'KALDI LIBRARY INSTALLED OK'
pushd onl-rec && \
make depend && \
make && \
make test && \
echo 'OnlineLatgenRecogniser build OK'
popd # onl-rec
pushd pykaldi
make && sudo make install && echo 'INSTALLATION Works OK'
sudo python setup.py install && echo 'PYKALDI LIBRARY INSTALLED OK'
popd # pykaldi
popd # src
<file_sep>/app/online_asr.py
import zmq
import struct
class OnlineASR:
def __init__(self, emit):
port = "5660"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.connect("tcp://localhost:%s" % port)
print "Socket created"
self.socket = socket
self.emit = emit
def recognize_chunk(self, message):
print "PCM received"
pcm = b''.join([struct.pack('h', i) for i in message['chunk']])
print self.socket.send(pcm)
print "Waiting for result"
msg = self.socket.recv_json()
print "Sending interim result"
self.emit('result', msg['result'])
def end(self):
self.socket.send("end")
print "Ending socket"
while True:
msg = self.socket.recv_json()
if msg['type'] == 'end':
self.emit('end', {})
self.socket.close()
break
self.emit('result', msg['result'])
<file_sep>/README.md
cloud-asr
=========
Cloud ASR using PyKaldi
<file_sep>/app/online_worker.py
from asr import asr_init, recognize_chunk, nbest_hypotheses, create_response, resample_to_def_sample_rate
import os
import zmq
from datetime import datetime
def log(message):
print "%s\t%s" % (str(datetime.now()), message)
log('Loading models.')
basedir = os.path.dirname(os.path.realpath(__file__))
asr_init(basedir)
log('Models loaded.')
log('Worker initialized.')
while True:
port = "5660"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.bind("tcp://*:%s" % port)
log('Socket created')
while True:
log("Waiting for chunk")
msg = socket.recv()
if msg == 'end':
best_hypotheses = nbest_hypotheses(n=10)
socket.send_json({'type': 'result', 'result': create_response(best_hypotheses)})
socket.send_json({'type': 'end'})
log('Final hypothesis sent')
break
pcm = resample_to_def_sample_rate(msg, 44100, 16000)
best_hypothesis = recognize_chunk(pcm)
socket.send_json({'type': 'result', 'result': create_response([best_hypothesis])})
log("Interim results sent")
<file_sep>/app/static/js/main.js
var lastResult;
$(document).ready(function() {
var speechRecognition = new SpeechRecognition();
speechRecognition.onresult = function(results) {
if (results.length > 0 && results[0].final == true) {
var transcript = results[0].alternative[0].transcript;
$('#result').prepend(transcript + '<br>');
};
}
speechRecognition.onstart = function(e) {
$('#record').html('<i class="icon-stop"></i>Stop recording');
}
speechRecognition.onend = function(e) {
$('#record').html('<i class="icon-bullhorn"></i>Start recording');
}
var recording = false;
$('#record').click(function() {
if(!recording) {
speechRecognition.start();
} else {
speechRecognition.stop();
}
recording = !recording;
});
});
|
07bb948376729715813233bcbc23f92e99af7f06
|
[
"Ruby",
"JavaScript",
"Markdown",
"Python",
"Shell"
] | 18
|
Python
|
kangliqiang/cloud-asr
|
1213b125f0c36b05ab89ce89f721bc3c59a24b7f
|
b6d0d87740823f4783fade8f9c29aed69c9df36a
|
refs/heads/main
|
<repo_name>conda-forge/ldas-tools-al-swig-feedstock<file_sep>/recipe/install-python.sh
#!/bin/bash
set -ex
pushd ${SRC_DIR}/build
# get python options
if [ "${PY3K}" -eq 1 ]; then
PYTHON_BUILD_OPTS="-DENABLE_SWIG_PYTHON2=no -DENABLE_SWIG_PYTHON3=yes -DPYTHON3_EXECUTABLE=${PYTHON}"
else
PYTHON_BUILD_OPTS="-DENABLE_SWIG_PYTHON3=no -DENABLE_SWIG_PYTHON2=yes -DPYTHON2_EXECUTABLE=${PYTHON}"
fi
# configure
cmake .. \
-DCMAKE_INSTALL_PREFIX=${PREFIX} \
-DCMAKE_BUILD_TYPE=RelWithBuildInfo \
-DCMAKE_EXPORT_COMPILE_COMMANDS=1 \
${PYTHON_BUILD_OPTS}
# build
cmake --build python -- -j${CPU_COUNT}
# install
cmake --build python --target install
# test
if [[ "${CONDA_BUILD_CROSS_COMPILATION:-}" != "1" || "${CROSSCOMPILING_EMULATOR}" != "" ]]; then
ctest -V
fi
popd
<file_sep>/recipe/build.sh
#!/bin/bash
mkdir -p build
pushd build
# configure
cmake ${CMAKE_ARGS} .. \
-DCMAKE_INSTALL_PREFIX=${PREFIX} \
-DCMAKE_BUILD_TYPE=Release \
-DENABLE_SWIG_PYTHON2=no \
-DENABLE_SWIG_PYTHON3=no
# build
cmake --build . -- -j${CPU_COUNT}
# test
if [[ "${CONDA_BUILD_CROSS_COMPILATION:-}" != "1" || "${CROSSCOMPILING_EMULATOR}" != "" ]]; then
ctest -V
fi
# install [NOTE: we don't install because this package is essentially empty]
cmake --build . --target install
|
a05db185e115ee2eb70a7594f8816cba6c3194c0
|
[
"Shell"
] | 2
|
Shell
|
conda-forge/ldas-tools-al-swig-feedstock
|
a9779241ebbc572d21d7ae8eb3d645acc296fa5a
|
5800e6336d3aaaf8d9aaab66c0484aec57183eb2
|
refs/heads/master
|
<repo_name>ChrisWhite12/JSTesting<file_sep>/server/index.js
function repeatMessage(message, repeatNo){
let messageToShow = ''
for (let i = 0; i < repeatNo; i++) {
messageToShow += message;
}
return messageToShow;
}
function calSum(inputArr){
var total = 0;
for (let i = 0; i < inputArr.length; i++) {
const el = inputArr[i]
if(typeof(el) == "number"){
total += el
}
else{
throw("Wrong data detected")
}
}
return total
}
const express = require('express')
const app = express()
const port = 3000
app.use(express.json())
app.get('/', (req, res) => {
// res.send('Hello World!')
res.json({
message: "Hello World!"
})
})
app.post('/names',(req,res) => {
let incData = request.body.namesArray;
console.log(incData);
res.json({
firstName: incData[0]
})
})
const server = app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
// app = coded-up routes & server inst
// server = server that is running & visitable by users
module.exports = {
app,
server,
repeatMessage,
calSum
}<file_sep>/testing/index.test.js
const { TestScheduler } = require('jest')
let { repeatMessage } = require('../server/index')
test("Example Test", () => {
expect("truthy string").toBeTruthy();
})
describe('multiple tests', () => {
test("repeatMessage test1", () => {
expect(repeatMessage('hello',3)).toEqual('hellohellohello');
})
test("repeatMessage test2", () => {
expect(repeatMessage('hello',0)).toEqual('');
})
test("repeatMessage test3", () => {
expect(repeatMessage('a',4)).toEqual('aaaa');
})
test('should be a func', () => {
expect(typeof(repeatMessage))
})
})
const request = require('supertest')
var {server,app} = require('../server/index')
afterAll(async (done) => {
await server.close()
await new Promise(resolve => setTimeout(() => resolve(),500))
done()
})
describe('Express server home', () => {
test('return 200 status code', async (done) => {
const response = await request(app).get('/');
expect(response.statusCode).toEqual(200)
done();
})
})
describe('Express server home', () => {
test('show hello world', async (done) => {
const response = await request(app).get('/');
expect(response.body.message).toEqual("Hello World!")
done();
})
})
describe('/names page functionality', () => {
test('should return Luke', async () => {
const response = await request(app)
.post('/names')
.send({
names: ['Luke', 'Ash', 'Nandini']
})
expect(response.body.firstName).toEqual("Luke")
})
})
|
f4abdbe8db6ac58d7eabd80a1801b321cb657c46
|
[
"JavaScript"
] | 2
|
JavaScript
|
ChrisWhite12/JSTesting
|
6c515f4e583df91ebf7ba3c6b88a20cfaf498679
|
f2b502def30eef2eebde2cb2c1431c8599291777
|
refs/heads/master
|
<file_sep># cook your dish here
def check(arr1,arr2,N):
for i in range(N):
for j in range(N):
if arr1[i][j]!=arr2[i][j]:
return False
return True
def transpose(arr,n):
for i in range(n):
for j in range(i,n):
arr[i][j],arr[j][i]=arr[j][i],arr[i][j]
for _ in range(int(input())):
N=int(input())
ori_mat=[]
cnt=1
for i in range(N):
ori_mat.append([])
for j in range(N):
ori_mat[i].append(cnt)
cnt+=1
curr_matrix=[]
for i in range(N):
temp=[int(j) for j in input().split()][:N]
curr_matrix.append(temp)
ans=0
for x in range(N,1,-1):
if curr_matrix[0][x-1]!=x:
ans+=1
transpose(curr_matrix,x)
print(ans)
<file_sep>import java.io.*;
import java.util.*;
class C {
//lexographically best moves...
public static int dx[] = { 1, 0, 0, -1 };
public static int dy[] = { 0, -1, 1, 0 };
public static int n;
public static long x;
public static long sum[],mod=1000000007;
public static Map<Integer, ArrayList<Integer>> adj;
//public static PriorityQueue<Long> q;
public static ArrayList<Long> q;
public static FastOutput fo;
public static void dfs(int node,int parent_node) {
for(int adj_node:adj.get(node)) {
if(adj_node!=parent_node) {
dfs(adj_node,node);
}
}
for(int adj_node:adj.get(node)) {
if(adj_node!=parent_node) {
q.add(sum[adj_node]);
}
}
Collections.sort(q,Collections.reverseOrder());
long cnt=0L,val=1,temp;
for (int i=0;i<q.size();i++) {
temp=Math.abs(q.get(i));
temp=(temp+1)*val;
val++;
cnt+=temp;
}
q.clear();
sum[node]=cnt;
}
public static void main(String[] args) throws FileNotFoundException {
FastScanner fs = new FastScanner();
fo = new FastOutput(System.out);
long initial_time = System.currentTimeMillis();
int testcases = fs.nextInt();
for (int tt = 0; tt < testcases; tt++) {
//main code
n=fs.nextInt();
x=fs.nextLong();
sum=new long[n+1];
adj=new TreeMap<>();
//q=new PriorityQueue<>();
q=new ArrayList<>();
for(int i=1;i<n+1;i++) {
adj.put(i, new ArrayList<>());
}
int u,v;
for(int i=0;i<n-1;i++) {
u=fs.nextInt();
v=fs.nextInt();
adj.get(u).add(v);
adj.get(v).add(u);
}
//now use dfs to traverse the tree and assign correct values to all the nodes using priority queue...........
dfs(1,0);
sum[1]++;
long ans=sum[1]%mod*x%mod;
fo.println(ans);
}
//fo.time(initial_time);
fo.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() throws FileNotFoundException {
//if (System.getProperty("ONLINE_JUDGE") == null) {
//Read from the File...
// File file = new File("src\\input");
// br = new BufferedReader(new FileReader(file));
//} else {
//Read from the System...
br = new BufferedReader(new InputStreamReader(System.in));
//}
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class FastOutput extends PrintWriter {
public FastOutput(PrintStream out) {
super(out);
}
void time(long init) {
if (System.getProperty("ONLINE_JUDGE") == null) {
this.println(System.currentTimeMillis() - init + "ms");
}
}
}
}
<file_sep>/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//Scanner sc=new Scanner(System.in);
FastReader sc=new FastReader();
int testcase=sc.nextInt();
for(int t=0;t<testcase;t++) {
long N=sc.nextLong();
if(N==1 || N==2) {
System.out.println(0);
}
else {
long totalsum=(N*(N+1))/2;
if(totalsum%2==0){
long need=totalsum/2;
long fulfill=(long)(Math.sqrt(4*totalsum+1)-1)/2;
long need1=(fulfill*(fulfill+1))/2;
long diff=need-need1;
if(diff!=0) {
System.out.println(N-fulfill);
}
else {
long ans=N-fulfill;
long x=(fulfill*(fulfill-1))/2;
long temp=N-fulfill;
long y=(temp*(temp-1))/2;
System.out.println(x+y+ans);
}
}
else {
System.out.println(0);
}
}
}
}
}
<file_sep>from collections import OrderedDict
for _ in range(int(input())):
S=input()
P=input()
precedence=OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26})
scount=OrderedDict({'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't':0, 'u':0, 'v':0, 'w':0, 'x':0, 'y':0, 'z':0})
pcount=OrderedDict({'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't':0, 'u':0, 'v':0, 'w':0, 'x':0, 'y':0, 'z':0})
for i in P:
pcount[i]+=1
for i in S:
scount[i]+=1
for i in pcount:
scount[i]-=pcount[i]
#print(pcount)
#print(scount)
target=precedence[P[0]]
ans=''
for i in scount:
if precedence[i]<target or precedence[i]>target:
ans+=(i*scount[i])
elif precedence[i]==target:
temp1=ans+(i*scount[i])+P
temp2=ans+P+(i*scount[i])
if temp1<=temp2:
ans=temp1
else:
ans=temp2
#ans+=(i*scount[i])+P
print(ans)
<file_sep>import java.io.*;
import java.util.*;
class A {
//lexographically best moves...
public static int dx[] = { 1, 0, 0, -1 };
public static int dy[] = { 0, -1, 1, 0 };
public static int mod=1000000007;
//(x^y)%mod;
public static long power(long x,long y){
long res = 1;
x = x % mod;
while (y > 0){
if ((y & 1) > 0)
res = (res * x) % mod;
y = y >> 1;
x = (x * x) % mod;
}
return res%mod;
}
public static void main(String[] args) throws FileNotFoundException {
FastScanner fs = new FastScanner();
FastOutput fo = new FastOutput(System.out);
long initial_time = System.currentTimeMillis();
int testcases = fs.nextInt();
for (int tt = 0; tt < testcases; tt++) {
//main code
int n=fs.nextInt();
fo.println(power(2, n-1));
}
//fo.time(initial_time);
fo.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() throws FileNotFoundException {
//if (System.getProperty("ONLINE_JUDGE") == null) {
//Read from the File...
// File file = new File("src\\input");
// br = new BufferedReader(new FileReader(file));
//} else {
//Read from the System...
br = new BufferedReader(new InputStreamReader(System.in));
//}
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class FastOutput extends PrintWriter {
public FastOutput(PrintStream out) {
super(out);
}
void time(long init) {
if (System.getProperty("ONLINE_JUDGE") == null) {
this.println(System.currentTimeMillis() - init + "ms");
}
}
}
}
<file_sep># Codechef
I will upload those solutions of codechef long challenges problems which are really challenging!
Enjoy the Code :)
<file_sep>from collections import defaultdict,Counter
def calefficiency(arr,s,e,K):
#print(s,e)
total=Counter(arr[s:e+1])
#print(total)
x=list(total.keys())
cnt=K
for i in x:
if total[i]>1:
cnt+=total[i]
return cnt
def check(arr,s,e,value,K):
index=-1
mini=value
for i in range(s,e):
ans1=calefficiency(arr,s,i,K)
ans2=calefficiency(arr,i+1,e,K)
#print(ans1+ans2)
if (ans1+ans2)<=mini:
index=i
mini=ans1+ans2
return index,mini
for _ in range(int(input())):
N,K=map(int,input().split())
l=[int(i) for i in input().split()][:N]
if K==1:
cnt=1
d=defaultdict(bool)
for i in range(N):
if not d[l[i]]:
d[l[i]]=True
else:
cnt+=1
d=defaultdict(bool)
d[l[i]]=True
print(cnt)
else:
stack=[[0,N-1]]
#print(cnt)
#ifnotfinal=calefficiency(l,0,N-1,K)
final=[]
fix=[]
while len(stack)>0:
temp=stack.pop()
ineffi=calefficiency(l,temp[0],temp[1],K)
final.append([temp[0],temp[1],ineffi])
newindex,newmini=check(l,temp[0],temp[1],ineffi,K)
#print(newindex,newmini)
if newindex!=-1:
final.pop()
stack.append([newindex+1,temp[1]])
stack.append([temp[0],newindex])
else:
fix.append(final.pop())
#print(stack)
#print(final)
#print(fix)
ans=0
while len(final)>0:
temp=final.pop()
ans+=temp[2]
while len(fix)>0:
temp=fix.pop()
ans+=temp[2]
print(ans)
'''print(finalans,ifnotfinal)
if finalans!=0:
print(finalans)
else:
print(ifnotfinal)'''
<file_sep># cook your dish here
import math
for _ in range(int(input())):
N=int(input())
if N==1 or N==2:
print(0)
elif N==3:
print(2)
else:
totalsum=(N*(N+1))//2
if totalsum%2==0:
need=totalsum//2
fulfill=int(math.sqrt(4*totalsum+1)-1)//2
need1=(fulfill*(fulfill+1))//2
diff=need-need1
#print(totalsum)
#print(need)
#print(fulfill)
#print(need1)
#print("diff"+str(diff))
#print(N-fulfill)
#if fulfill+diff<=N:
if diff!=0:
print(N-fulfill)
else:
ans=N-fulfill
x=(fulfill*(fulfill-1))//2
temp=N-fulfill
y=(temp*(temp-1))//2
print(x+y+ans)
#else:
#print(diff+1)
else:
print(0)
<file_sep># cook your dish here
for _ in range(int(input())):
N=int(input())
l=[int(i) for i in input().split()][:N]
ans=len(set(l))
if l.count(0)>0:
print(ans-1)
else:
print(ans)
<file_sep>import java.io.*;
import java.util.*;
class C {
//lexographically best moves...
public static int dx[] = { 1, 0, 0, -1 };
public static int dy[] = { 0, -1, 1, 0 };
public static void main(String[] args) throws FileNotFoundException {
FastScanner fs = new FastScanner();
FastOutput fo = new FastOutput(System.out);
long initial_time = System.currentTimeMillis();
long mp[]=new long[1000001];
int testcases = fs.nextInt();
for (int tt = 0; tt < testcases; tt++) {
//main code
int n=fs.nextInt(),m=fs.nextInt();
long cnt=0;
for(int i=0;i<n+1;i++){
mp[i]=1;
}
int temp;
for(int i=2;i<n+1;i++) {
temp=m%i;
cnt+=mp[temp];
for(int j=temp;j<n+1;j+=i) {
mp[j]++;
}
}
fo.println(cnt);
}
//fo.time(initial_time);
fo.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() throws FileNotFoundException {
//if (System.getProperty("ONLINE_JUDGE") == null) {
//Read from the File...
// File file = new File("src\\input");
// br = new BufferedReader(new FileReader(file));
//} else {
//Read from the System...
br = new BufferedReader(new InputStreamReader(System.in));
//}
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class FastOutput extends PrintWriter {
public FastOutput(PrintStream out) {
super(out);
}
void time(long init) {
if (System.getProperty("ONLINE_JUDGE") == null) {
this.println(System.currentTimeMillis() - init + "ms");
}
}
}
}
<file_sep>/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws java.lang.Exception
{
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int testcase=sc.nextInt();
for(int i=0;i<testcase;i++) {
int N=sc.nextInt();
Set<Integer> ans=new HashSet<Integer>();
for(int j=0;j<N;j++) {
int temp=sc.nextInt();
if(temp!=0) {
ans.add(temp);
}
}
int finalans=ans.size();
System.out.println(finalans);
}
}
}
|
ebe0d26a99325c198c49279c7d580365dc3a5c43
|
[
"Markdown",
"Java",
"Python"
] | 11
|
Python
|
Akshaymishra211/Codechef
|
e065a05b8355d281cce481fe25e3c82b7d16d9e1
|
fd1e8c1df9a88c8776c615ec1cc9e538b259cf4c
|
refs/heads/master
|
<file_sep>//
// PersonalInfo.swift
// HadyCard
//
// Created by Hady on 7/3/20.
// Copyright © 2020 HadyOrg. All rights reserved.
//
import SwiftUI
struct PersonalInfo: View {
var imageName : String
var text : String
var body: some View {
RoundedRectangle(cornerRadius: 25).fill(Color.white).frame(height: 50).overlay(HStack {
Image(systemName: imageName).foregroundColor(.green)
Text(text)
})
}
}
struct PersonalInfo_Previews: PreviewProvider {
static var previews: some View {
PersonalInfo(imageName: "phone.fill", text: "+2001117876186" )
.previewLayout(.sizeThatFits)
}
}
<file_sep>//
// ContentView.swift
// HadyCard
//
// Created by Hady on 7/2/20.
// Copyright © 2020 HadyOrg. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack{ Color(red: 0.09, green: 0.63, blue: 0.52).edgesIgnoringSafeArea(.all)
VStack{
Image("Hady H").resizable().aspectRatio(contentMode: .fit).frame(width: 150, height: 150).clipShape(Circle()).overlay(
Circle().stroke(Color.white , lineWidth: 5)
)
Text("<NAME>").font(.system(size: 40)).foregroundColor(.white).bold()
Text("iOS Developer").font(.system(size: 25)).foregroundColor(.black)
Divider()
PersonalInfo(imageName: "phone.fill", text: "+2001117876186")
PersonalInfo(imageName: "envelope.fill", text: "<EMAIL>")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
<file_sep># Hady-Card
## SwiftUI Design
* personal ID card.
* Coded up the front-end by SwiftUI framework and Swift 5.0.
|
586d4a0f984dcf517617517c44582083d16edce3
|
[
"Swift",
"Markdown"
] | 3
|
Swift
|
hadyhelal/Hady-Card
|
a4f2bc25495c48ce173f4a3af961c62f57ccf722
|
69f563aa46cd73c31dfec16e04bd4a7ba55fe9f9
|
refs/heads/master
|
<repo_name>Lan-Yang/TwitterSentiment<file_sep>/word_list.py
words = [
'party',
]
<file_sep>/application.py
from gevent import monkey
monkey.patch_all()
import tweepy
from flask import Flask, jsonify, render_template, request, session
from flask.ext.socketio import SocketIO, emit
from flask.ext.sqlalchemy import SQLAlchemy
from threading import Thread
import cred_db
import sys
import os
from word_list import words
import cred_twitter as twc
import cred_aws
import cred_conf
import boto.sqs, boto.sns
from boto.sqs.message import Message
import json
import time
import logging
FORMAT = r'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(stream=sys.stderr, level=logging.INFO, format=FORMAT)
sqs = boto.sqs.connect_to_region(
"us-east-1",
aws_access_key_id=cred_aws.aws_access_key_id,
aws_secret_access_key=cred_aws.aws_secret_access_key)
my_queue = sqs.get_queue('myqueue') or sqs.create_queue('myqueue')
sns = boto.sns.connect_to_region(
"us-east-1",
aws_access_key_id=cred_aws.aws_access_key_id,
aws_secret_access_key=cred_aws.aws_secret_access_key)
topicarn = cred_aws.aws_sns_topicarn
# Flask app object
application = app = Flask(__name__)
app.config.from_object(cred_conf)
app.config['SQLALCHEMY_DATABASE_URI'] = cred_db.SQLALCHEMY_DATABASE_URI
daemon = None
# Dabatase connection
db = SQLAlchemy(app)
class Twit(db.Model):
twit_id = db.Column(db.Integer, primary_key=True) # auto-inc
longitude = db.Column(db.Float)
latitude = db.Column(db.Float)
time = db.Column(db.DateTime)
words = db.Column(db.String(256))
# db.drop_all()
# db.create_all()
# WebSocket
socketio = SocketIO(app)
socket_count = 0
# Daemon
class CustomStreamListener(tweepy.StreamListener):
# db_count = 0
twit_count = 0
flag_stop = False
def fake_stop(self):
self.flag_stop = True
def fake_start(self):
self.flag_stop = False
def on_status(self, status):
if not status.coordinates:
return True
if self.flag_stop:
return True
# drop half twits
self.twit_count += 1
if self.twit_count % 2 == 0:
if self.twit_count > 10000:
self.twit_count = 0
return True
# self.db_count += 1
longitude, latitude = status.coordinates['coordinates']
text = status.text#.encode('utf-8')
# print type(status.text)
time = status.created_at
# Twit.query.delete()
# db.session.commit()
# return True
# add new twit to db
# self.db_count = 0
# self.twit_count = 0
twit = Twit(longitude=longitude, latitude=latitude, time=time, words=text)
db.session.add(twit)
db.session.commit()
# add new twit to sqs
m = Message()
sqs_m = {
'id': twit.twit_id,
'content': text
}
m.set_body(json.dumps(sqs_m))
my_queue.write(m)
# emit new twit to client
socketio.emit('twit', {
'text': text,
'longitude': longitude,
'latitude': latitude,
'time': time,
'id': twit.twit_id
})
def on_error(self, status_code):
logging.warning('[tweepy] Error with status code:', status_code)
if status_code == 420:
time.sleep(60)
return True # Don't kill the stream
def on_timeout(self):
logging.warning('[tweepy] Timeout...')
return True # Don't kill the stream
def on_disconnect(self, notice):
logging.warning('[tweepy] Disconnect: %s' % notice)
return True
# Twitter Stream API
listener = CustomStreamListener()
def get_tweet():
while True:
try:
auth = tweepy.OAuthHandler(twc.consumer_key, twc.consumer_secret)
auth.set_access_token(twc.access_token, twc.access_token_secret)
sapi = tweepy.streaming.Stream(auth, listener)
sapi.filter(locations=[-130, -60, 70, 60], track=words)
except KeyboardInterrupt: # on Ctrl-C, break
break
except BaseException as e:
print e
pass
def init():
global daemon, listener
listener.fake_start()
if not daemon:
daemon = Thread(target=get_tweet)
logging.info("daemon start")
daemon.start()
@app.before_first_request
def init_bf_req():
init()
# main pages
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def on_connect(data):
logging.info("connect")
global socket_count
socket_count += 1
init()
@socketio.on('disconnect')
def on_disconnect():
logging.info("disconnect")
global listener, socket_count
socket_count -= 1
if socket_count <= 0:
listener.fake_stop()
@app.route('/sns', methods=['POST'])
def sns_endpoint():
'''http://192.168.127.12:5000/sns'''
try:
logging.info("/sns: %s" % request.data)
data = json.loads(request.data)
if data['Type'] == 'SubscriptionConfirmation':
sns.confirm_subscription(topicarn, data['Token'])
elif data['Type'] == 'Notification':
msg = json.loads(data['Message'])
logging.info("emit sentiment %s" % msg['id'])
socketio.emit('sentiment', {
'id': msg['id'],
'sentiment': msg['senti']
})
# print request.data
return ""
except BaseException as e:
logging.warning("Exception in /sns: %s" % e)
return ("Exception in /sns: %s" % e)
# @app.route('/data/<word>')
# def search(word):
# result = []
# cur = Twit.query.order_by(Twit.twit_id.desc()).limit(500)
# for record in cur:
# if word == '-ALL-' or word in record.words.split():
# result.append({
# 'longitude': record.longitude,
# 'latitude': record.latitude
# })
# return jsonify(data=result)
# Error Handler
@app.errorhandler(404)
def not_found(error):
return 'Page Not Found', 404
@app.errorhandler(500)
def internal_server_error(error):
return 'Internal Server Error', 500
if __name__ == '__main__':
# app.run(host='0.0.0.0', port=5000)
socketio.run(
app, host="0.0.0.0", port=80,
policy_server=False,
transports=['websocket', 'xhr-polling', 'xhr-multipart'])
<file_sep>/Dockerfile
FROM centos:7
RUN yum -y update && yum clean all
# Install pip
RUN yum install -y python-setuptools gcc python-devel
RUN easy_install pip
# Add and install Python modules
RUN yum -y install pkg-config libffi-devel openssl-devel
ADD requirements.txt /twitter-senti/requirements.txt
RUN cd /twitter-senti; pip install -r requirements.txt
# Bundle app source
ADD . /twitter-senti
WORKDIR /twitter-senti
# Expose
EXPOSE 80
# Run
CMD ["python", "/twitter-senti/application.py"]
<file_sep>/requirements.txt
flask
pg8000
Flask-SQLAlchemy
flask-socketio
boto
requests[security]
tweepy
<file_sep>/README.md
# TwitterSentiment
This is the web/app server for a twitter sentiment analysis app.
## Framework
Server built with python flask framework. Weksocket is used for server-side
pushing. The whole app is built in Docker, for easier deployment on Elastic
Beanstalk.
## Twit Stream
A daemon thread runing with the server collects twits. Every twit is inserted
into database(Postgre on RDS), written to SQS, and pushed to all connected
clients.
## Twit Sentiment
Twit Sentiment are POSTed to /sns endpoint by SNS, and then pushed to all
connected clients.
## Client side
All twits are marked on google heat map in realtime, and the sentiment trend
are also updated in realtime.
|
eed9a30643c89d093ecb000c01cc74c375fa3a86
|
[
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 5
|
Python
|
Lan-Yang/TwitterSentiment
|
57d2ca7f6526e48de7a411e6145531c08189f124
|
268168c922b9b808ecd862e1dfb543381f2420b6
|
refs/heads/master
|
<repo_name>moneytech/CN_Vec<file_sep>/README.md
# CN_Vec
A C library that implements C++ Vectors in C.
C is a different, and less forgiving language (Depending on how you take it) compared to C++. You have to manage memory yourself, and you have to program all of the data structures yourself if you actually want to use them. In C++, you have STL which implements doubly-linked lists, hash tables, maps, etc. But one of the first data structures you learn is the Vector, a dynamically resizable array.
With the "realloc" command, it is entirely possible to recreate the fan-favourite Vector class in C as a library of functions and a struct. That's exactly what I did. :)
Welcome to the CN_Vec library, where dynamically resizable memory is now at your fingertips.
Full documentation at: <a href = "http://web.eecs.utk.edu/~ssmit285/lib/cn_vec/index.html">http://web.eecs.utk.edu/~ssmit285/lib/cn_vec/index.html</a></br>The documentation has details and examples on every single function in the library, as well as a guide comparing it to C++ Vectors.
<file_sep>/examples/struct_example.c
/*
* Simple Struct example with CN_Vecs
*
* CN_Vecs hold any datatype as long as the size specified on initialization.
* It also copies the bytes of a struct into the vector. Hence what we will
* demonstrate in the code below.
*
* This application will make a struct, set some values, push it to the vector.
* Afterwards, it will modify that struct, then push another copy. Then print
* out the values of the two structs to stdout.
*/
#include <stdio.h>
#include <stdlib.h>
#include "../cn_vec.h"
typedef struct thing {
int a, b;
} THING;
main() {
CN_VEC vec = cn_vec_init(THING);
THING a;
a.a = 2;
a.b = 3;
cn_vec_push_back(vec, &a); //Push a copy of "a" to vec
//Update the original struct
a.a++;
a.b = a.a + a.b;
cn_vec_push_back(vec, &a); //Push another copy of "a" to vec
THING* ii = 0; //Iterator
cn_vec_traverse(vec, ii) {
printf("STRUCT { A: %d, B: %d }\n", ii->a, ii->b);
}
cn_vec_free(vec);
}
<file_sep>/examples/simple_int.c
/*
* Simple Integer Vector Test
*
* Tests CN_Vec and how they can be used to store integers and
* print them out in the order that they were added to the vec.
*
* This application stores 0 through 9 in the vector and then
* prints them out in that order by iterating through.
*/
#include <stdio.h>
#include <stdlib.h>
#include "../cn_vec.h"
main() {
//Initialize the vec
CN_VEC vec = cn_vec_init(int);
int a;
for (a = 0; a < 10; a++)
cn_vec_push_back(vec, &a); //Pushes the value of "a" into the vec
int i = 0;
for (; i < cn_vec_size(vec); i++)
printf("%d\n", cn_vec_get(vec, int, i)); //Prints to stdout.
//Free the vec
cn_vec_free(vec);
}
|
1d0f70e4757fe24710aa6f216aa68f76f9b08cd9
|
[
"Markdown",
"C"
] | 3
|
Markdown
|
moneytech/CN_Vec
|
f67e47ad5a4f73fe31ac2ff08a6db683239fba3a
|
eab56d84c79754f4e8765193b4f73e223ec2dba7
|
refs/heads/main
|
<repo_name>ediboy/track<file_sep>/app/Models/Project.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Project extends Model
{
use SoftDeletes;
protected $table = 'projects';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'description'
];
// RELATIONSHIPS
/**
* Get all of the users that are assigned this project.
*/
public function users()
{
return $this->morphedByMany('User', 'projectable');
}
/**
* Get all of the teams that are assigned this project.
*/
public function teams()
{
return $this->morphedByMany('Team', 'projectable');
}
}
<file_sep>/database/seeds/ProfilesSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Models\Profile;
class ProfilesSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// PERSONAL
Profile::create([
"name" => "<NAME>",
"type" => "image",
"order" => 1,
"required" => false,
"group" => "personal",
"locked" => false
]);
Profile::create([
"name" => "Firstname",
"type" => "text",
"order" => 2,
"required" => true,
"group" => "personal",
"locked" => true
]);
Profile::create([
"name" => "Lastname",
"type" => "text",
"order" => 3,
"required" => true,
"group" => "personal",
"locked" => true
]);
Profile::create([
"name" => "Middlename",
"type" => "text",
"order" => 4,
"required" => false,
"group" => "personal",
"locked" => false
]);
Profile::create([
"name" => "Adddress",
"type" => "textarea",
"order" => 5,
"required" => false,
"group" => "personal",
"locked" => false
]);
Profile::create([
"name" => "Civil Status",
"value" => [
"Single" => "Single",
"Married" => "Married",
"Separated" => "Separated",
"Divorced" => "Divorced",
"Widowed" => "Widowed"
],
"type" => "select",
"order" => 6,
"required" => true,
"group" => "personal",
"locked" => false
]);
Profile::create([
"name" => "Birthday",
"type" => "date",
"order" => 7,
"required" => true,
"group" => "personal",
"locked" => false
]);
Profile::create([
"name" => "Email",
"type" => "email",
"order" => 8,
"required" => true,
"group" => "personal",
"locked" => true
]);
Profile::create([
"name" => "<NAME>",
"type" => "text",
"order" => 9,
"required" => false,
"group" => "personal",
"locked" => false
]);
Profile::create([
"name" => "<NAME>",
"type" => "text",
"order" => 10,
"required" => false,
"group" => "personal",
"locked" => false
]);
Profile::create([
"name" => "<NAME>",
"type" => "text",
"order" => 11,
"required" => false,
"group" => "personal",
"locked" => false
]);
Profile::create([
"name" => "<NAME>",
"type" => "text",
"order" => 12,
"required" => false,
"group" => "personal",
"locked" => false
]);
Profile::create([
"name" => "Course",
"type" => "text",
"order" => 13,
"required" => false,
"group" => "personal",
"locked" => false
]);
// WORK
Profile::create([
"name" => "<NAME>",
"type" => "text",
"order" => 1,
"required" => true,
"group" => "work",
"locked" => true
]);
Profile::create([
"name" => "Position",
"value" => [
"CEO" => "CEO",
"Finance Manager" => "Finance Manager",
"Lead Developer" => "Lead Developer",
"Administrator" => "Administrator",
"Web Developer" => "Web Developer",
"Graphic Designer" => "Graphic Designer",
"Graphic Artist" => "Graphic Artist",
"Multimedia Artist" => "Multimedia Artist",
"Elearning Specialist" => "Elearning Specialist",
"Website Administrator" => "Administrator",
"Business Strategy Consultant" => "Business Strategy Consultant",
"Quality Assurance Specialist" => "Quality Assurance Specialist",
"Mobile Developer" => "Mobile Developer",
"Service Implementation Lead" => "Service Implementation Lead",
"Voice over Talent" => "Voice over Talent",
"Maintenance" => "Maintenance",
"Team Leader" => "Team Leader",
"Project Lead" => "Project Lead",
],
"type" => "select",
"order" => 2,
"required" => true,
"group" => "work",
"locked" => false
]);
Profile::create([
"name" => "Start Date",
"type" => "date",
"order" => 3,
"required" => true,
"group" => "work",
"locked" => false
]);
Profile::create([
"name" => "<NAME>",
"type" => "date",
"order" => 4,
"required" => false,
"group" => "work",
"locked" => false
]);
Profile::create([
"name" => "<NAME>",
"type" => "text",
"order" => 5,
"required" => true,
"group" => "work",
"locked" => true
]);
Profile::create([
"name" => "Status",
"value" => [
"Regular" => "Regular",
"Probationary" => "Probationary",
"Intern" => "Intern",
"OJT" => "OJT",
"Part Time" => "Part Time",
"Endo" => "Endo"
],
"type" => "select",
"order" => 6,
"required" => true,
"group" => "work",
"locked" => true
]);
// Other
Profile::create([
"name" => "<NAME>",
"type" => "text-copy",
"order" => 1,
"required" => false,
"group" => "other",
"locked" => false
]);
Profile::create([
"name" => "SSS Number",
"type" => "text-copy",
"order" => 2,
"required" => false,
"group" => "other",
"locked" => false
]);
Profile::create([
"name" => "Pag-Ibig Number",
"type" => "text-copy",
"order" => 3,
"required" => false,
"group" => "other",
"locked" => false
]);
Profile::create([
"name" => "<NAME>",
"type" => "text-copy",
"order" => 4,
"required" => false,
"group" => "other",
"locked" => false
]);
Profile::create([
"name" => "<NAME>",
"type" => "text-copy",
"order" => 5,
"required" => false,
"group" => "other",
"locked" => false
]);
}
}
<file_sep>/app/Transformers/User/UserTransformer.php
<?php
namespace App\Transformers\User;
use App\Transformers\Transformer;
use Illuminate\Support\Facades\Storage;
class UserTransformer extends Transformer
{
/**
* Transform user profile
*
* @param Collection $item
* @return array
*/
public function transform($item)
{
$employeeNumber = $item->profiles->where('name', 'Employee Number')->first()->pivot->value ?? null;
$profilePicture = $item->profiles->where('name', 'Profile Picture')->first()->pivot->value ?? 'default.png';
$profilePicture = Storage::url('public/profiles/' . $profilePicture);
return [
'id' => $item->id,
'name' => $item->reverseFullname,
'employee_number' => $employeeNumber,
'profile_picture' => $profilePicture,
];
}
}
<file_sep>/app/Models/Team.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Team extends Model
{
use SoftDeletes;
protected $table = 'teams';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'description'
];
// RELATIONSHIPS
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany('App\Models\User');
}
/**
* Get all of the projects for the team.
*/
public function projects()
{
return $this->morphToMany('Project', 'projectable');
}
}
<file_sep>/app/Transformers/Transformer.php
<?php
namespace App\Transformers;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
abstract class Transformer
{
/**
* Transform a collection
*
* @param array $items
* @return Collection
*/
public function transformCollection($items)
{
return collect($items)->map(function ($item) {
return $this->transform($item);
});
}
/**
* Transform a single item
*
* @param array $item
* @return array
*/
abstract public function transform($item);
}
<file_sep>/resources/js/response.js
export default {
data() {
return {
response: {
show: false,
type: '',
errors: [],
successMessage: '',
status: ''
}
}
},
methods: {
$responseShow(response) {
this.$root.response.show = true;
if(!!response.data.errors) {
this.$root.response.type = 'error';
this.$root.response.errors = response.data.errors;
this.$root.response.status = response.status;
} else {
this.$root.response.type = 'success';
this.$root.response.successMessage = response.statusText
}
},
$responseClose() {
this.$root.response.show = false;
}
},
};
<file_sep>/database/seeds/CreateSuperAdminSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class CreateSuperAdminSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// Create User
$user = User::create([
"firstname" => env('SUPER_FIRSTNAME'),
"lastname" => env('SUPER_LASTNAME'),
"email" => env('SUPER_EMAIL'),
"password" => <PASSWORD>(env('SUPER_<PASSWORD>')),
'remember_token' => Str::random(10),
'email_verified_at' => now()
]);
// Assign role to user
$user->assignRole('super-admin');
}
}
<file_sep>/tests/Browser/Pages/UserTest.php
<?php
namespace Tests\Browser\Pages;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use RolesAndPermissionsSeeder;
use ProfilesSeeder;
use App\Models\User;
/**
* @group user
*/
class UserTest extends DuskTestCase
{
use DatabaseMigrations;
private $user;
public function setUp() :void
{
parent::setUp();
$this->seed(RolesAndPermissionsSeeder::class);
$this->seed(ProfilesSeeder::class);
$this->user = factory(User::class)->create();
foreach (static::$browsers as $browser) {
$browser->driver->manage()->deleteAllCookies();
}
}
/**
* Simulate user CRUD
*
* @test
*/
public function can_create_view_update_delete_user()
{
$this->browse(function (Browser $browser) {
$browser->loginAs($this->user)
// Create user
->visit('/users')
->assertSee('Users')
->click('.user-create')
->assertSee('Create User')
->type('Firstname', "Juan")
->type('Lastname', "<NAME>")
->select('Civil Status', "Single")
->click('input[name="Birthday"]')
->waitFor('.vdatetime-popup')
->click('.vdatetime-popup__actions__button--confirm')
->type('Email', "<EMAIL>")
->type('Employee Number', "12345")
->select('Position', "CEO")
->click('input[name="Start Date"]')
->waitFor('.vdatetime-popup')
->click('.vdatetime-popup__actions__button--confirm')
->type('Hourly Rate', "500")
->select('Status', "Regular")
->pause(500)
->press('CREATE')
->waitFor('.response')
->assertSee('Success')
->click('.response-close')
// View user
->click('.user-list')
->waitForLocation('/users')
->assertSee('Dela Cruz, Juan')
->click('.user-view')
->waitForLocation('/users/2')
->assertSee('<NAME>')
->assertSee('Single')
->assertSee('12345')
->assertSee('CEO')
// Edit user
->click('.user-list')
->waitForLocation('/users')
->assertSee('<NAME>')
->click('.user-edit')
->waitForLocation('/users/2/edit')
->assertSee('Edit User')
->type('Firstname', "Pedro")
->type('Lastname', "<NAME>")
->press('SAVE')
->waitFor('.response')
->assertSee('Success')
->click('.response-close')
// Delete user
->click('.user-delete')
->assertSee('Are you sure you want to delete?')
->press("Delete")
->waitForLocation('/users')
->assertDontSee('<NAME>, Pedro');
});
}
}
<file_sep>/app/Http/Controllers/TeamController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Team;
use User;
use TeamTransformer;
use UserTransformer;
use Cache;
use UserService;
use TeamService;
class TeamController extends Controller
{
protected $teamTransformer;
protected $userTransformer;
protected $userService;
protected $teamService;
/**
* Construct the controller
*
* @param App\Transformers\Team\TeamTransformer $teamTransformer
* @param App\Transformers\User\UserTransformer $userTransformer
* @param App\Services\UserService $userTransformer
* @param App\Services\TeamService $teamTransformer
* @return void
*/
public function __construct(TeamTransformer $teamTransformer, UserTransformer $userTransformer, UserService $userService, TeamService $teamService)
{
$this->teamTransformer = $teamTransformer;
$this->userTransformer = $userTransformer;
$this->userService = $userService;
$this->teamService = $teamService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$teams = $this->teamService->allTeams();
return response()->json($this->teamTransformer->transformCollection($teams));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$users = $this->userService->allUsers();
return response()->json($this->userTransformer->transformCollection($users));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Cache::forget('teams');
$this->validate(request(), [
'title' => 'required',
'description' => 'required'
]);
$team = Team::create($request->all());
$team->users()->sync(request('users'));
return response()->json();
}
/**
* Display the specified resource.
*
* @param App\Models\Team $team
* @return \Illuminate\Http\Response
*/
public function show(Team $team)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param App\Models\Team $team
* @return \Illuminate\Http\Response
*/
public function edit(Team $team)
{
$users = $this->userService->allUsers()->whereNotIn('id', $team->users->pluck('id'))->values()->all();
return response()->json([
'team' => $this->teamTransformer->transform($team),
'users' => $this->userTransformer->transformCollection($users),
'assignedUsers' => $this->userTransformer->transformCollection($team->users)
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param App\Models\Team $team
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Team $team)
{
Cache::forget('teams');
$this->validate(request(), [
'title' => 'required',
'description' => 'required'
]);
$team->update($request->all());
$team->users()->sync(request('users'));
return response()->json();
}
/**
* Remove the specified resource from storage.
*
* @param App\Models\Team $team
* @return \Illuminate\Http\Response
*/
public function destroy(Team $team)
{
Cache::forget('teams');
$team->delete();
return response()->json();
}
}
<file_sep>/app/Transformers/Profile/ProfileTransformer.php
<?php
namespace App\Transformers\Profile;
use App\Transformers\Transformer;
class ProfileTransformer extends Transformer
{
/**
* Transform user field
*
* @param Collection $field
* @return array
*/
public function transform($field)
{
return [
'id' => $field['id'],
'name' => $field['name'],
'value' => $field['value'],
'type' => $field['type'],
'order' => $field['order'],
'required' => $field['required'],
'group' => $field['group'],
'locked' => $field['locked'],
'content' => $this->mapContent($field),
];
}
public function mapContent($item)
{
if ($item->users->isEmpty()) {
return null;
}
if ($item->users[0]->pivot->value) {
if ($item['type'] == 'image') {
return Storage::url('public/profiles/' . $item->users[0]->pivot->value);
}
return $item->users[0]->pivot->value;
}
return null;
}
}
<file_sep>/app/Services/TeamService.php
<?php
namespace App\Services;
use Team;
use Illuminate\Support\Facades\Cache;
class TeamService
{
/**
* @return \Illuminate\Support\Collection
*/
public function allTeams()
{
if ($teams = Cache::get('teams')) {
return $teams;
}
$teams = new Team;
// Sort
$sortBy = request('sortBy', 'title');
$sort = request('sort', 'ASC');
$teams = $teams->withCount('users')->orderBy($sortBy, $sort)->get();
Cache::forever('teams', $teams);
return $teams;
}
}
<file_sep>/app/Transformers/Profile/ProfileUserTransformer.php
<?php
namespace App\Transformers\Profile;
use App\Transformers\Transformer;
class ProfileUserTransformer extends Transformer
{
/**
* Transform user field
*
* @param Collection $field
* @return array
*/
public function transform($item)
{
return [
'name' => $item->name,
'value' => $item->pivot->value
];
}
}
<file_sep>/app/Transformers/User/UserProfileTransformer.php
<?php
namespace App\Transformers\User;
use App\Transformers\Transformer;
use ProfileUserTransformer;
use Storage;
class UserProfileTransformer extends Transformer
{
protected $profileUserTransformer;
/**
* Transform user profile
*
* @param Collection $item
* @return array
*/
public function transform($item)
{
$position = $item->profiles->where('name', 'Position')->first()->pivot->value ?? null;
$profilePicture = $item->profiles->where('name', 'Profile Picture')->first()->pivot->value ?? 'default.png';
$profilePicture = Storage::url('public/profiles/' . $profilePicture);
$profiles = $this->processProfiles($item->profiles);
$this->profileUserTransformer = new ProfileUserTransformer;
return [
'id' => $item->id,
'name' => $item->fullname,
'position' => $position,
'profile_picture' => $profilePicture,
'profile_picture' => $profilePicture,
'personal' => isset($profiles['personal']) ? $this->profileUserTransformer->transformCollection($profiles['personal']) : null,
'work' => isset($profiles['work']) ? $this->profileUserTransformer->transformCollection($profiles['work']) : null,
'other' => isset($profiles['other']) ? $this->profileUserTransformer->transformCollection($profiles['other']) : null,
];
}
public function processProfiles($profiles)
{
// Remove profile picture
$profiles = $profiles->filter(function ($item) {
// Convert date to string
if ($item->type == 'date' && $item->pivot->value) {
return $item->pivot->value = date('F d, Y', strtotime($item->pivot->value));
;
}
// Exclude profile picture
if ($item->name != 'Profile Picture') {
return true;
}
});
return $profiles->groupBy('group');
}
}
<file_sep>/app/Models/Benefits.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Benefits extends Model
{
use SoftDeletes;
protected $table = 'benefits';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'description', 'type', 'value', 'schedule'
];
}
<file_sep>/app/Models/Profile.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Profile extends Model
{
use SoftDeletes;
protected $table = 'profiles';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'value', 'type', 'position', 'required', 'group',
];
protected $casts = [
'value' => 'array'
];
// RELATIONSHIPS
/**
* The profiles that belong to the user.
*/
public function users()
{
return $this->belongsToMany('App\Models\User')->withPivot('value');
}
}
<file_sep>/app/Models/User.php
<?php
namespace App\Models;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use HasApiTokens, Notifiable, HasRoles;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'firstname', 'lastname', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $appends = ['fullname'];
// RELATIONSHIPS
/**
* The profiles that belong to the user.
*/
public function profiles()
{
return $this->belongsToMany('Profile')->withPivot('value');
}
/**
* The teams that belong to the user.
*/
public function teams()
{
return $this->belongsToMany('Team');
}
/**
* Get all of the projects for the user.
*/
public function projects()
{
return $this->morphToMany('Project', 'projectable');
}
// ATTRIBUTES
/**
* Return the full name of user
*
* @return string
*/
public function getFullnameAttribute()
{
return $this->firstname . ' ' . $this->lastname;
}
/**
* Return the reverse full name of user
*
* @return string
*/
public function getReverseFullnameAttribute()
{
return $this->lastname . ', ' . $this->firstname;
}
}
<file_sep>/tests/Browser/Pages/TeamTest.php
<?php
namespace Tests\Browser\Pages;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use RolesAndPermissionsSeeder;
use ProfilesSeeder;
use App\Models\User;
use App\Models\Team;
/**
* @group team
*/
class TeamTest extends DuskTestCase
{
use DatabaseMigrations;
private $user;
public function setUp() :void
{
parent::setUp();
$this->seed(RolesAndPermissionsSeeder::class);
$this->seed(ProfilesSeeder::class);
$this->user = factory(User::class)->create();
foreach (static::$browsers as $browser) {
$browser->driver->manage()->deleteAllCookies();
}
}
/**
* Simulate team CRUD
*
* @test
*/
public function can_create_view_update_delete_team()
{
$this->browse(function (Browser $browser) {
$browser->loginAs($this->user)
// Create team
->visit('/teams')
->assertSee('Teams')
->click('.team-create')
->assertSee('Create Team')
->type('title', "Team1")
->type('description', "Sample team")
->click('.unassigned-user')
->press('CREATE')
->waitForLocation('/teams')
->waitFor('.response')
->assertSee('Success')
->click('.response-close')
// View team
->waitForLocation('/teams')
->assertSee('Team1')
->assertSee('Sample team')
->assertSee('1')
->assertSee('MEMBERS')
// Edit team
->click('.team-edit')
->waitForLocation('/teams/1/edit')
->assertSee('Edit Team')
->type('title', "Team2")
->type('description', "Sample team2")
->click('.assigned-user')
->press('SAVE')
->waitForLocation('/teams')
->waitFor('.response')
->assertSee('Success')
->click('.response-close')
// View team updated
->waitForLocation('/teams')
->assertSee('Team2')
->assertSee('Sample team2')
->assertSee('0')
->assertSee('MEMBERS')
// Delete team
->click('.team-edit')
->waitForLocation('/teams/1/edit')
->click('.team-delete')
->assertSee('Are you sure you want to delete?')
->press("Delete")
->waitForLocation('/teams')
->assertDontSee('Team2');
});
}
}
<file_sep>/tests/Browser/Pages/LoginTest.php
<?php
namespace Tests\Browser\Pages;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use App\Models\User;
/**
* @group login
*/
class LoginTest extends DuskTestCase
{
use DatabaseMigrations;
public function setUp() :void
{
parent::setUp();
foreach (static::$browsers as $browser) {
$browser->driver->manage()->deleteAllCookies();
}
}
/** @test */
public function user_can_login_with_correct_credentials()
{
$user = factory(User::class)->create();
$this->browse(function (Browser $browser) use ($user) {
$browser->visit('/login')
->assertSee('Login')
->type('email', $user->email)
->type('password', '<PASSWORD>')
->press('Login')
->assertPathIs('/');
});
}
/** @test */
public function user_cannot_login_with_incorrect_credentials()
{
$user = factory(User::class)->create();
$this->browse(function (Browser $browser) use ($user) {
$browser->visit('/login')
->assertSee('Login')
->type('email', $user->email)
->type('password', '<PASSWORD>')
->press('Login')
->assertPathIs('/login');
});
}
}
<file_sep>/app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use User;
use Profile;
use ProfileTransformer;
use UserProfileTransformer;
use UserTransformer;
use Image;
use Storage;
use Carbon\Carbon;
use Validator;
use Cache;
use UserService;
class UserController extends Controller
{
protected $userTransformer;
protected $userService;
/**
* Construct the controller
*
* @param App\Transformers\UserTransformer $userTransformer
* @return void
*/
public function __construct(UserTransformer $userTransformer, UserService $userService)
{
$this->userTransformer = $userTransformer;
$this->userService = $userService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = $this->userService->allUsers();
return response()->json((new UserTransformer)->transformCollection($users));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$fields = Profile::all();
$fields = (new ProfileTransformer)->transformCollection($fields);
$fields = $fields->groupBy('group');
return response()->json($fields);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Cache::forget('users');
$images = Profile::where('type', 'image')->select('name')->get();
$images = $images->pluck('name');
$this->validate(request(), [
'Firstname' => 'required',
'Lastname' => 'required',
'Civil Status' => 'required',
'Birthday' => 'required',
'Email' => 'required|email',
'Employee Number' => 'required',
'Position' => 'required',
'Start Date' => 'required',
'Hourly Rate' => 'required',
'Status' => 'required'
]);
$user = User::create([
'firstname' => request('Firstname'),
'lastname' => request('Lastname'),
'email' => request('Email'),
'password' => \Hash::make(env('USER_DEFAULT_PASSWORD'))
]);
foreach (request()->all() as $detailName => $detailValue) {
if ($detailValue) {
$detail = Profile::where('name', '=', $detailName)->first();
if ($detail) {
if ($detail->type == 'image') {
$image = Image::make(request($detail->name));
$detailValue = md5(microtime()) . '.png';
$image->fit(500, 500, function ($constraint) {
$constraint->aspectRatio();
});
Storage::put('public/profiles/'. $detailValue, (string) $image->encode());
}
$user->profiles()->attach($detail->id, ['value' => $detailValue]);
}
}
}
return response()->json();
}
/**
* Display the specified resource.
*
* @param App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function show(User $user)
{
return response()->json((new UserProfileTransformer)->transform($user));
}
/**
* Show the form for editing the specified resource.
*
* @param App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function edit(User $user)
{
$fields = Profile::with(['users' => function ($q) use ($user) {
$q->select('firstname')->where('users.id', $user->id);
}])->get();
$fields = (new ProfileTransformer)->transformCollection($fields);
$fields = $fields->groupBy('group');
return response()->json($fields);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
Cache::forget('users');
$images = Profile::where('type', 'image')->select('name')->get();
$images = $images->pluck('name');
$this->validate(request(), [
'Firstname' => 'required',
'Lastname' => 'required',
'Civil Status' => 'required',
'Birthday' => 'required',
'Email' => 'required|email',
'Employee Number' => 'required',
'Position' => 'required',
'Start Date' => 'required',
'Hourly Rate' => 'required',
'Status' => 'required'
]);
$user->update([
'firstname' => request('Firstname'),
'lastname' => request('Lastname'),
'email' => request('Email')
]);
foreach (request()->all() as $detailName => $detailValue) {
if ($detailValue) {
$detail = Profile::where('name', '=', $detailName)->first();
if ($detail) {
if ($detail->type == 'image') {
if (str_contains(request($detail->name), 'base64') == 1) {
$image = Image::make(request($detail->name));
$detailValue = md5(microtime()) . '.png';
$image->fit(500, 500, function ($constraint) {
$constraint->aspectRatio();
});
Storage::put('public/profiles/'. $detailValue, (string) $image->encode());
} else {
$detailValue = explode("/storage/profiles/", request($detail->name));
$detailValue = $detailValue[1];
}
}
if ($user->profiles->contains($detail->id)) {
$user->profiles()->updateExistingPivot($detail->id, ['value' => $detailValue]);
} else {
$user->profiles()->attach($detail->id, ['value' => $detailValue]);
}
}
}
}
return response()->json();
}
/**
* Remove the specified resource from storage.
*
* @param App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function destroy(User $user)
{
Cache::forget('users');
Cache::forget('teams');
$user->delete();
return response()->json();
}
}
<file_sep>/resources/js/app.js
import './bootstrap';
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import Datetime from 'vue-datetime';
import 'vue-datetime/dist/vue-datetime.css';
import Croppa from 'vue-croppa';
import Response from './response';
import ConfirmDeletion from './confirm-deletion';
Vue.use(VueRouter);
Vue.use(Datetime);
Vue.use(Croppa);
Vue.mixin(Response);
Vue.mixin(ConfirmDeletion);
Vue.mixin({
methods: {
$pluck(array, key) {
return array.map(function(item) {
return item[key];
});
},
$sortyByName(a, b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
},
$sortyByTitle(a, b) {
if (a.title < b.title)
return -1;
if (a.title > b.title)
return 1;
return 0;
}
}
})
let app = new Vue({
el: '#app',
router: new VueRouter(routes),
});
<file_sep>/database/seeds/RolesAndPermissionsSeeder.php
<?php
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class RolesAndPermissionsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// Reset cached roles and permissions
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
// projects permissions
Permission::create(['name' => 'view projects']);
Permission::create(['name' => 'add projects']);
Permission::create(['name' => 'edit projects']);
Permission::create(['name' => 'delete projects']);
// tasks permissions
Permission::create(['name' => 'view tasks']);
Permission::create(['name' => 'add tasks']);
Permission::create(['name' => 'edit tasks']);
Permission::create(['name' => 'delete tasks']);
// teams permissions
Permission::create(['name' => 'view teams']);
Permission::create(['name' => 'add teams']);
Permission::create(['name' => 'edit teams']);
Permission::create(['name' => 'delete teams']);
// employees permissions
Permission::create(['name' => 'view employees']);
Permission::create(['name' => 'add employees']);
Permission::create(['name' => 'edit employees']);
Permission::create(['name' => 'delete employees']);
// attendance permissions
Permission::create(['name' => 'view attendance']);
Permission::create(['name' => 'add attendance']);
Permission::create(['name' => 'edit attendance']);
Permission::create(['name' => 'delete attendance']);
// payroll permissions
Permission::create(['name' => 'view payroll']);
Permission::create(['name' => 'add payroll']);
Permission::create(['name' => 'edit payroll']);
Permission::create(['name' => 'delete payroll']);
// benefits permissions
Permission::create(['name' => 'view benefits']);
Permission::create(['name' => 'add benefits']);
Permission::create(['name' => 'edit benefits']);
Permission::create(['name' => 'delete benefits']);
// deductions permissions
Permission::create(['name' => 'view deductions']);
Permission::create(['name' => 'add deductions']);
Permission::create(['name' => 'edit deductions']);
Permission::create(['name' => 'delete deductions']);
// holidays permissions
Permission::create(['name' => 'view holidays']);
Permission::create(['name' => 'add holidays']);
Permission::create(['name' => 'edit holidays']);
Permission::create(['name' => 'delete holidays']);
// bonus permissions
Permission::create(['name' => 'view bonus']);
Permission::create(['name' => 'add bonus']);
Permission::create(['name' => 'edit bonus']);
Permission::create(['name' => 'delete bonus']);
// loans permissions
Permission::create(['name' => 'view loans']);
Permission::create(['name' => 'add loans']);
Permission::create(['name' => 'edit loans']);
Permission::create(['name' => 'delete loans']);
Permission::create(['name' => 'request loans']);
Permission::create(['name' => 'approve loans']);
// cash advances permissions
Permission::create(['name' => 'view cash advances']);
Permission::create(['name' => 'add cash advances']);
Permission::create(['name' => 'edit cash advances']);
Permission::create(['name' => 'delete cash advances']);
Permission::create(['name' => 'request cash advances']);
Permission::create(['name' => 'approve cash advances']);
// allowances permissions
Permission::create(['name' => 'view allowances']);
Permission::create(['name' => 'add allowances']);
Permission::create(['name' => 'edit allowances']);
Permission::create(['name' => 'delete allowances']);
// overtime permissions
Permission::create(['name' => 'view overtime']);
Permission::create(['name' => 'add overtime']);
Permission::create(['name' => 'edit overtime']);
Permission::create(['name' => 'delete overtime']);
Permission::create(['name' => 'request overtime']);
Permission::create(['name' => 'approve overtime']);
// leaves permissions
Permission::create(['name' => 'view leaves']);
Permission::create(['name' => 'add leaves']);
Permission::create(['name' => 'edit leaves']);
Permission::create(['name' => 'delete leaves']);
Permission::create(['name' => 'request leaves']);
Permission::create(['name' => 'approve leaves']);
// announcements permissions
Permission::create(['name' => 'view announcements']);
Permission::create(['name' => 'add announcements']);
Permission::create(['name' => 'edit announcements']);
Permission::create(['name' => 'delete announcements']);
// rewards permissions
Permission::create(['name' => 'view rewards']);
Permission::create(['name' => 'add rewards']);
Permission::create(['name' => 'edit rewards']);
Permission::create(['name' => 'delete rewards']);
// slider permissions
Permission::create(['name' => 'view slider']);
Permission::create(['name' => 'add slider']);
Permission::create(['name' => 'edit slider']);
Permission::create(['name' => 'delete slider']);
// statistics permissions
Permission::create(['name' => 'view statistics']);
Permission::create(['name' => 'add statistics']);
Permission::create(['name' => 'edit statistics']);
Permission::create(['name' => 'delete statistics']);
// statistics permissions
Permission::create(['name' => 'view settings']);
Permission::create(['name' => 'add settings']);
Permission::create(['name' => 'edit settings']);
Permission::create(['name' => 'delete settings']);
// assign peromission to admin
$role = Role::create(['name' => 'admin'])
->givePermissionTo([
'view projects',
'add projects',
'edit projects',
'delete projects',
'view tasks',
'add tasks',
'edit tasks',
'delete tasks',
'view teams',
'add teams',
'edit teams',
'delete teams',
'view employees',
'add employees',
'edit employees',
'delete employees',
'view attendance',
'add attendance',
'edit attendance',
'delete attendance',
'view payroll',
'add payroll',
'edit payroll',
'delete payroll',
'view benefits',
'add benefits',
'edit benefits',
'delete benefits',
'view deductions',
'add deductions',
'edit deductions',
'delete deductions',
'view holidays',
'add holidays',
'edit holidays',
'delete holidays',
'view bonus',
'add bonus',
'edit bonus',
'delete bonus',
'view loans',
'add loans',
'edit loans',
'delete loans',
'request loans',
'approve loans',
'view cash advances',
'add cash advances',
'edit cash advances',
'delete cash advances',
'request cash advances',
'approve cash advances',
'view allowances',
'add allowances',
'edit allowances',
'delete allowances',
'view overtime',
'add overtime',
'edit overtime',
'delete overtime',
'request overtime',
'approve overtime',
'view leaves',
'add leaves',
'edit leaves',
'delete leaves',
'request leaves',
'approve leaves',
'view announcements',
'add announcements',
'edit announcements',
'delete announcements',
'view rewards',
'add rewards',
'edit rewards',
'delete rewards',
'view slider',
'add slider',
'edit slider',
'delete slider',
'view statistics',
'add statistics',
'edit statistics',
'delete statistics'
]);
// assign peromission to admin
$role = Role::create(['name' => 'team-lead'])
->givePermissionTo([
'view projects',
'add projects',
'edit projects',
'delete projects',
'view tasks',
'add tasks',
'edit tasks',
'delete tasks',
'view teams',
'add teams',
'edit teams',
'delete teams',
'view employees',
'view attendance',
'view benefits',
'view deductions',
'view holidays',
'view bonus',
'view loans',
'request loans',
'view cash advances',
'request cash advances',
'view allowances',
'view overtime',
'request overtime',
'approve overtime',
'view leaves',
'request leaves',
'view announcements',
'view rewards'
]);
// assign peromission to admin
$role = Role::create(['name' => 'employee'])
->givePermissionTo([
'view projects',
'view tasks',
'add tasks',
'edit tasks',
'delete tasks',
'view teams',
'view employees',
'view attendance',
'view benefits',
'view deductions',
'view holidays',
'view bonus',
'view loans',
'request loans',
'view cash advances',
'request cash advances',
'view allowances',
'view overtime',
'request overtime',
'view leaves',
'request leaves',
'view announcements',
'view rewards'
]);
$role = Role::create(['name' => 'super-admin']);
$role->givePermissionTo(Permission::all());
}
}
<file_sep>/app/Http/Controllers/ProjectController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Project;
use User;
use Team;
use ProjectTransformer;
use UserTransformer;
use TeamTransformer;
use Cache;
use UserService;
use TeamService;
class ProjectController extends Controller
{
protected $projectTransformer;
protected $userTransformer;
protected $teamTransformer;
protected $userService;
/**
* Construct the controller
* @param App\Transformers\Project\ProjectTransformer $projectTransformer
* @param App\Transformers\User\UserTransformer $userTransformer
* @param App\Transformers\Team\TeamTransformer $teamTransformer
* @param App\Services\UserService $userTransformer
* @param App\Services\TeamService $teamTransformer
* @return void
*/
public function __construct(ProjectTransformer $projectTransformer, UserTransformer $userTransformer, TeamTransformer $teamTransformer, UserService $userService, TeamService $teamService)
{
$this->projectTransformer = $projectTransformer;
$this->userTransformer = $userTransformer;
$this->teamTransformer = $teamTransformer;
$this->userService = $userService;
$this->teamService = $teamService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
if ($projects = Cache::get('projects')) {
return $projects;
}
$projects = new Project;
// Sort
$sortBy = request('sortBy', 'title');
$sort = request('sort', 'DESC');
$projects = $projects->orderBy($sortBy, $sort)->get();
$projects = response()->json($this->projectTransformer->transformCollection($projects->all()));
Cache::forever('projects', $projects);
return $projects;
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$users = $this->userService->allUsers();
$teams = $this->teamService->allTeams();
return response()->json([
'users' => $this->userTransformer->transformCollection($users),
'teams' => $this->teamTransformer->transformCollection($teams)
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Cache::forget('projects');
$this->validate(request(), [
'title' => 'required',
'description' => 'required'
]);
$project = Project::create($request->all());
$project->users()->sync(request('users'));
$project->teams()->sync(request('teams'));
return response()->json();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
$users = $this->userService->allUsers()->whereNotIn('id', $project->users->pluck('id'))->values()->all();
$teams = $this->teamService->allTeams()->whereNotIn('id', $project->teams->pluck('id'))->values()->all();
return response()->json([
'project' => $this->projectTransformer->transform($project),
'users' => $this->userTransformer->transformCollection($users),
'assignedUsers' => $this->userTransformer->transformCollection($project->users),
'teams' => $this->teamTransformer->transformCollection($teams),
'assignedTeams' => $this->teamTransformer->transformCollection($project->teams)
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
Cache::forget('projects');
$this->validate(request(), [
'title' => 'required',
'description' => 'required'
]);
$project->update($request->all());
$project->users()->sync(request('users'));
$project->teams()->sync(request('teams'));
return response()->json();
}
/**
* Remove the specified resource from storage.
*
* @param App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
Cache::forget('projects');
$project->delete();
return response()->json();
}
}
<file_sep>/app/Transformers/Project/ProjectTransformer.php
<?php
namespace App\Transformers\Project;
use App\Transformers\Transformer;
class ProjectTransformer extends Transformer
{
/**
* Transform project
*
* @param Collection $item
* @return array
*/
public function transform($item)
{
return [
'id' => $item->id,
'title' => $item->title,
'description' => $item->description
];
}
}
<file_sep>/resources/js/routes.js
import Home from './components/Home';
import Projects from './components/Projects';
import ProjectsCreate from './components/ProjectsCreate';
import ProjectsShow from './components/ProjectsShow';
import ProjectsEdit from './components/ProjectsEdit';
import Tasks from './components/Tasks';
import Teams from './components/Teams';
import TeamsCreate from './components/TeamsCreate';
import TeamsEdit from './components/TeamsEdit';
import Users from './components/Users';
import UsersShow from './components/UsersShow';
import UsersEdit from './components/UsersEdit';
import UsersCreate from './components/UsersCreate';
import Attendance from './components/Attendance';
import Payroll from './components/Payroll';
import Benefits from './components/Benefits';
import Deductions from './components/Deductions';
import Holidays from './components/Holidays';
import Bonus from './components/Bonus';
import CashAdvances from './components/CashAdvances';
import Allowances from './components/Allowances';
import Overtime from './components/Overtime';
import Leaves from './components/Leaves';
import Slider from './components/Slider';
import NotFound from './components/NotFound';
export default {
mode: 'history',
routes: [
{
path: '*',
component: NotFound,
name: 'notfound'
},
{
path: '/',
component: Home,
name: ''
},
{
path: '/projects',
component: Projects,
name: 'projects'
},
{
path: '/projects/create',
component: ProjectsCreate,
name: 'projects.create'
},
{
path: '/projects/:id',
component: ProjectsShow,
name: 'projects.show'
},
{
path: '/projects/:id/edit',
component: ProjectsEdit,
name: 'projects.edit'
},
{
path: '/tasks',
component: Tasks,
name: 'tasks'
},
{
path: '/users',
component: Users,
name: 'users'
},
{
path: '/users/create',
component: UsersCreate,
name: 'users.create'
},
{
path: '/users/:id',
component: UsersShow,
name: 'users.show'
},
{
path: '/users/:id/edit',
component: UsersEdit,
name: 'users.edit'
},
{
path: '/teams',
component: Teams,
name: 'teams'
},
{
path: '/teams/create',
component: TeamsCreate,
name: 'teams.create'
},
{
path: '/teams/:id/edit',
component: TeamsEdit,
name: 'teams.edit'
},
{
path: '/attendance',
component: Attendance,
name: 'attendance'
},
{
path: '/payroll',
component: Payroll,
name: 'payroll'
},
{
path: '/benefits',
component: Benefits,
name: 'benefits'
},
{
path: '/deductions',
component: Deductions,
name: 'deductions'
},
{
path: '/holidays',
component: Holidays,
name: 'holidays'
},
{
path: '/bonus',
component: Bonus,
name: 'bonus'
},
{
path: '/cash-advances',
component: CashAdvances,
name: 'cash-advances'
},
{
path: '/allowances',
component: Allowances,
name: 'allowances'
},
{
path: '/overtime',
component: Overtime,
name: 'overtime'
},
{
path: '/leaves',
component: Leaves,
name: 'leaves'
},
{
path: '/slider',
component: Slider,
name: 'slider'
}
]
}
<file_sep>/app/Transformers/Team/TeamTransformer.php
<?php
namespace App\Transformers\Team;
use App\Transformers\Transformer;
class TeamTransformer extends Transformer
{
/**
* Transform team list
*
* @param Collection $item
* @return array
*/
public function transform($item)
{
return [
'id' => $item->id,
'title' => $item->title,
'description' => $item->description,
'users_count' => $item->users_count
];
}
}
|
0463c766782b01ea0359ad70a7d2d7c059d4109f
|
[
"JavaScript",
"PHP"
] | 25
|
PHP
|
ediboy/track
|
00c9ed810255ae3294c687ce856d062ceb3f8018
|
9efa84027283d956f9ff35381d44946c2776325f
|
refs/heads/master
|
<file_sep>#include "Mesh.h"
#include "Renderer/Helpers.h"
std::unordered_map<std::string, std::shared_ptr<Mesh>> Mesh::Load(const std::string &filename, const std::string &root)
{
std::unordered_map<std::string, std::shared_ptr<Mesh>> meshes;
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err;
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, filename.c_str(), (root + "models/").c_str());
for (size_t i = 0; i < shapes.size(); ++i) {
std::shared_ptr<Mesh> tempMesh = std::make_shared<Mesh>();
tempMesh->_BoxMax = glm::vec3(-1024.0f, -1024.0f, -1024.0f);
tempMesh->_BoxMin = glm::vec3(1024.0f, 1024.0f,10240.0f);
for (const auto& index : shapes[i].mesh.indices) {
Vertex vertex = {};
vertex.position = {
attrib.vertices[3 * index.vertex_index + 0],
attrib.vertices[3 * index.vertex_index + 1],
attrib.vertices[3 * index.vertex_index + 2]
};
// Compute bounding box max point
tempMesh->_BoxMax.x = std::max(tempMesh->_BoxMax.x, vertex.position.x);
tempMesh->_BoxMax.y = std::max(tempMesh->_BoxMax.y, vertex.position.y);
tempMesh->_BoxMax.z = std::max(tempMesh->_BoxMax.z, vertex.position.z);
// Compute bounding box min point
tempMesh->_BoxMin.x = std::min(tempMesh->_BoxMin.x, vertex.position.x);
tempMesh->_BoxMin.y = std::min(tempMesh->_BoxMin.y, vertex.position.y);
tempMesh->_BoxMin.z = std::min(tempMesh->_BoxMin.z, vertex.position.z);
if (attrib.normals.size() > 0) {
vertex.normal = {
attrib.normals[3 * index.normal_index + 0],
attrib.normals[3 * index.normal_index + 1],
attrib.normals[3 * index.normal_index + 2]
};
}
if (attrib.texcoords.size() > 0) {
vertex.texCoord = {
attrib.texcoords[2 * index.texcoord_index + 0],
1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
};
}
for (const auto &v : tempMesh->_Vertices) {
if (vertex != v) {
tempMesh->_Vertices.push_back(vertex);
tempMesh->_Indices.push_back(tempMesh->_Indices.size());
break;
}
}
if (tempMesh->_Vertices.size() == 0) {
tempMesh->_Vertices.push_back(vertex);
tempMesh->_Indices.push_back(tempMesh->_Indices.size());
}
}
tempMesh->GenerateTangents();
// Generate the AABB mesh
tempMesh->GenerateDebugMesh();
meshes.insert(std::pair<std::string, std::shared_ptr<Mesh>>(shapes[i].name, tempMesh));
}
return meshes;
}
void Mesh::Upload(Device *device, const vk::CommandPool &cmdPool)
{
_Device = device;
// Upload the vertex buffer
{
size_t dataSize = sizeof(Vertex) * _Vertices.size();
Buffer stagingBuffer = Buffer(_Device, vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eTransferSrc, dataSize);
stagingBuffer.Copy(_Vertices.data(), dataSize);
_VertexBuffer = Buffer(_Device, vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eTransferDst, dataSize, vk::SharingMode::eExclusive, vk::MemoryPropertyFlagBits::eDeviceLocal);
stagingBuffer.Transfer(_VertexBuffer, cmdPool);
stagingBuffer.Clean();
}
// Upload the index buffer
{
size_t dataSize = sizeof(Index) * _Indices.size();
Buffer stagingBuffer = Buffer(_Device, vk::BufferUsageFlagBits::eIndexBuffer | vk::BufferUsageFlagBits::eTransferSrc, dataSize);
stagingBuffer.Copy(_Indices.data(), dataSize);
_IndexBuffer = Buffer(_Device, vk::BufferUsageFlagBits::eIndexBuffer | vk::BufferUsageFlagBits::eTransferDst, dataSize, vk::SharingMode::eExclusive, vk::MemoryPropertyFlagBits::eDeviceLocal);
stagingBuffer.Transfer(_IndexBuffer, cmdPool);
stagingBuffer.Clean();
}
// Upload the debug mesh
if (!_DebugVertices.empty()) {
Buffer stagingBuffer2 = Buffer(_Device, vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eTransferSrc, sizeof(Vertex) * _DebugVertices.size());
stagingBuffer2.Copy(_DebugVertices.data(), sizeof(Vertex) * _DebugVertices.size());
_DebugVertexBuffer = Buffer(_Device, vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eTransferDst, sizeof(Vertex) * _DebugVertices.size(), vk::SharingMode::eExclusive, vk::MemoryPropertyFlagBits::eDeviceLocal);
stagingBuffer2.Transfer(_DebugVertexBuffer, cmdPool);
stagingBuffer2.Clean();
}
}
void Mesh::Clean()
{
//_VertexBuffer.Clean();
}
void Mesh::GenerateTangents()
{
for (int i = 0; i < _Vertices.size(); i += 3) {
glm::vec3 & v0 = _Vertices[i + 0].position;
glm::vec3 & v1 = _Vertices[i + 1].position;
glm::vec3 & v2 = _Vertices[i + 2].position;
// Shortcuts for UVs
glm::vec2 & uv0 = _Vertices[i + 0].texCoord;
glm::vec2 & uv1 = _Vertices[i + 1].texCoord;
glm::vec2 & uv2 = _Vertices[i + 2].texCoord;
// Edges of the triangle : position delta
glm::vec3 deltaPos1 = v1 - v0;
glm::vec3 deltaPos2 = v2 - v0;
// UV delta
glm::vec2 deltaUV1 = uv1 - uv0;
glm::vec2 deltaUV2 = uv2 - uv0;
float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x);
_Vertices[i + 0].tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y)*r;
_Vertices[i + 0].bitangent = (deltaPos2 * deltaUV1.x - deltaPos1 * deltaUV2.x)*r;
_Vertices[i + 1].tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y)*r;
_Vertices[i + 1].bitangent = (deltaPos2 * deltaUV1.x - deltaPos1 * deltaUV2.x)*r;
_Vertices[i + 2].tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y)*r;
_Vertices[i + 2].bitangent = (deltaPos2 * deltaUV1.x - deltaPos1 * deltaUV2.x)*r;
}
}
void Mesh::GenerateDebugMesh()
{
vertices[0] = _BoxMax;
vertices[1] = glm::vec3(_BoxMax.x, _BoxMin.y, _BoxMax.z);
vertices[2] = glm::vec3(_BoxMin.x, _BoxMin.y, _BoxMax.z);
vertices[3] = glm::vec3(_BoxMin.x, _BoxMax.y, _BoxMax.z);
vertices[4] = glm::vec3(_BoxMax.x, _BoxMax.y, _BoxMin.z);
vertices[5] = glm::vec3(_BoxMax.x, _BoxMin.y, _BoxMin.z);
vertices[6] = _BoxMin;
vertices[7] = glm::vec3(_BoxMin.x, _BoxMax.y, _BoxMin.z);
_DebugVertices.assign({
Vertex{ vertices[0] }, Vertex{ vertices[1] }, Vertex{ vertices[2] }, Vertex{ vertices[0] }, Vertex{ vertices[2] }, Vertex{ vertices[3] },
Vertex{ vertices[0] }, Vertex{ vertices[1] }, Vertex{ vertices[5] }, Vertex{ vertices[0] }, Vertex{ vertices[5] }, Vertex{ vertices[4] },
Vertex{ vertices[0] }, Vertex{ vertices[4] }, Vertex{ vertices[7] }, Vertex{ vertices[0] }, Vertex{ vertices[7] }, Vertex{ vertices[3] },
Vertex{ vertices[2] }, Vertex{ vertices[1] }, Vertex{ vertices[5] }, Vertex{ vertices[2] }, Vertex{ vertices[5] }, Vertex{ vertices[6] },
Vertex{ vertices[2] }, Vertex{ vertices[3] }, Vertex{ vertices[7] }, Vertex{ vertices[2] }, Vertex{ vertices[6] }, Vertex{ vertices[7] },
Vertex{ vertices[4] }, Vertex{ vertices[5] }, Vertex{ vertices[6] }, Vertex{ vertices[4] }, Vertex{ vertices[6] }, Vertex{ vertices[7] },
});
}
<file_sep>#pragma once
#include <string>
#include <vector>
#include <unordered_map>
#include "Shader.h"
#include "GlobalDescriptor.h"
class Scene;
class Material {
public:
Material() {}
Material(const std::string &name) : _Name(name) {}
void Load(Device *device, const GlobalDescriptor &globalDescriptor, const uint16_t width, const uint16_t height, const uint32_t poolSize);
void ReloadPipeline(const vk::RenderPass &renderPass, const uint16_t width, const uint16_t height);
void BindShader(std::shared_ptr<Shader> shader);
void ClearShaders();
std::vector<Shader*> GetShaderList();
void CreatePipeline(const vk::RenderPass &renderPass);
const vk::DescriptorPool &GetDescriptorPool() const {
return _DescriptorPool;
}
const vk::DescriptorSetLayout &GetDescriptorSetLayout() const {
return _DesciptorSetLayout;
}
const vk::Pipeline &GetPipeline() const {
return _Pipeline;
}
const vk::PipelineLayout &GetPipelineLayout() const {
return _PipelineLayout;
}
const size_t NumberPushConstants() const {
return _PushConstantRange.size();
}
bool _CastShadow = false;
const std::string _Name = "";
protected:
Device *_Device;
void PopulateInfo(const uint32_t width, const uint32_t height);
void CreateInputAssemblyInfo();
vk::PipelineInputAssemblyStateCreateInfo _InputAssemblyInfo;
void CreateViewportInfo(const uint32_t width, const uint32_t height);
vk::Viewport _Viewport;
vk::Rect2D _Scissor;
vk::PipelineViewportStateCreateInfo _ViewportInfo;
virtual void CreateRasterizationInfo();
vk::PipelineRasterizationStateCreateInfo _RasterizationInfo;
virtual void CreateMultisampleInfo();
vk::PipelineMultisampleStateCreateInfo _MultisampleInfo;
virtual void CreateDepthStencilInfo();
vk::PipelineDepthStencilStateCreateInfo _DepthStencilInfo;
virtual void CreateColorBlendInfo();
vk::PipelineColorBlendAttachmentState _ColorBlendAttachement;
vk::PipelineColorBlendStateCreateInfo _ColorBlendInfo;
virtual void CreateDescriptorSetLayout();
std::vector<vk::DescriptorSetLayoutBinding> _LayoutBindings;
vk::DescriptorSetLayout _DesciptorSetLayout;
virtual void CreatePushConstantRange();
std::vector<vk::PushConstantRange> _PushConstantRange;
virtual void CreateDescriptorPool(const uint32_t poolSize);
vk::DescriptorPool _DescriptorPool;
vk::PipelineLayout _PipelineLayout;
// Return the bound shaders in a list
std::vector<vk::PipelineShaderStageCreateInfo> GetShaderInfoList();
std::unordered_map<vk::ShaderStageFlagBits, std::shared_ptr<Shader>> _ShaderMap;
vk::Pipeline _Pipeline;
vk::PipelineVertexInputStateCreateInfo _VertexInputInfo;
};
class Wireframe : public Material {
public:
Wireframe() {}
Wireframe(const std::string &name) : Material(name) {}
protected:
virtual void CreateRasterizationInfo() override
{
_RasterizationInfo = vk::PipelineRasterizationStateCreateInfo(
{},
false,
false,
vk::PolygonMode::eLine,
vk::CullModeFlagBits::eNone,
vk::FrontFace::eCounterClockwise,
false,
0,
0,
0,
1.0
);
}
};<file_sep>#pragma once
template <class C>
class Singleton {
public:
template <typename... Args>
static C* GetInstance( Args ... pArgs ) {
if ( !m_instance )
m_instance = new C ( std::forward<Args> ( pArgs )... );
return m_instance;
}
static void DestroyInstance () {
if ( m_instance ) {
delete m_instance;
m_instance = nullptr;
}
}
private:
static C* m_instance;
};
template <class T> T* Singleton<T>::m_instance = nullptr;<file_sep>#pragma once
#include <array>
#include "Texture.h"
class CubeTexture: public Texture {
public:
explicit CubeTexture(const std::array<std::string, 6> &filenames);
CubeTexture() = delete;
CubeTexture(CubeTexture const&) = delete;
CubeTexture& operator=(CubeTexture const&) = delete;
~CubeTexture() = default;
virtual const char *GetFilename() const noexcept override { return ""; }
virtual void CreateAndUpload(Device *device, const vk::CommandPool &cmdPool) override;
private:
std::array<std::string, 6> _Filenames = { "" };
// These are temporary buffers that will be deleted as soon as the image is in GPU memory
std::array<unsigned char*, 6> _ImageBuffers;
};
<file_sep>#include "Package.h"
#include "Engine/Texture.h"
#include "Engine/CubeTexture.h"
#include "Renderer/Mesh.h"
#include "Renderer/Material.h"
#include "Renderer/Cubemap.h"
#include "Renderer/Shadow.h"
#include "Renderer/Unlit.h"
#include "Renderer/PBR.h"
#include "ResourceManager.h"
#include <iostream>
#include "Scene.h"
#include "Renderer/Renderer.h"
Package::Package(const std::string & name, const std::string &root) :
_Root("Shutter-Data/" + root + "/"),
_Name(name)
{
}
void Package::Load()
{
try {
LoadTexturesFromPackage();
LoadMeshesFromPackage();
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
LoadMaterialsFromPackage();
}
void Package::Initialize(Renderer &renderer, uint32_t poolSize)
{
Device *device = renderer.GetDevice();
uint16_t width, height;
renderer.GetRendererDimensions(width, height);
const vk::CommandPool& cmdPool = renderer.GetCommandPool();
// Upload textures to device
for (auto &texture : _Textures) {
texture.second->CreateAndUpload(device, cmdPool);
}
// Upload meshes to device
for (auto &mesh : _Meshes) {
mesh.second->Upload(device, cmdPool);
}
// Setup materials
for (auto &mat : _Materials) {
// Load the shaders
for (auto shader : mat.second->GetShaderList()) {
shader->Load(device);
}
mat.second->Load(device, renderer.GetGlobalDescriptor(), width, height, poolSize);
mat.second->CreatePipeline(renderer.GetMainRenderPass());
}
}
void Package::LoadTexturesFromPackage()
{
// Try to find the right file in the package
// Textures resources can be defined in the info.yaml under resources then textures
// or in textures.yaml under textures
YAML::Node fileNode;
YAML::Node textureNode;
try {
fileNode = YAML::LoadFile(_Root + "textures.yaml");
if (!fileNode["textures"].IsDefined()) {
throw std::runtime_error("Texture definition cannot be found");
}
textureNode = fileNode["textures"];
}
catch (YAML::BadFile) {
try {
// Info file presence guaranteed by previous step
fileNode = YAML::LoadFile(_Root + "info.yaml");
if (fileNode["resources"].IsDefined()) {
if (!fileNode["resources"]["textures"].IsDefined()) {
throw std::runtime_error("Texture definition cannot be found");
}
}
else {
throw std::runtime_error("Texture definition cannot be found");
}
textureNode = fileNode["resources"]["textures"];
}
catch (YAML::BadFile e) {
std::cout << e.what() << std::endl;
}
}
for (const auto &node : textureNode) {
try {
LoadTexture(node);
}
catch (const std::exception& e) {
std::cout << e.what() << std::endl;
}
}
}
void Package::LoadTexture(const YAML::Node & node)
{
// Check for the mandatory fields
if (
!node["name"].IsDefined() ||
!node["type"].IsDefined()
) {
throw std::runtime_error("Missing mandatory fields.");
}
std::string name = node["name"].as<std::string>();
std::string type = node["type"].as<std::string>();
bool mipmap = true;
if (node["mipmap"].IsDefined()) {
mipmap = node["mipmap"].as<bool>();
};
std::shared_ptr<Texture> tempTexture;
if (type == "normal") {
tempTexture = std::make_shared<Texture>(_Root + "textures/" + name, mipmap);
}
else if (type == "cube") {
tempTexture = std::make_shared<CubeTexture>(std::array<std::string, 6> {
_Root + "textures/" + name + "/posx.jpg",
_Root + "textures/" + name + "/negx.jpg",
_Root + "textures/" + name + "/posy.jpg",
_Root + "textures/" + name + "/negy.jpg",
_Root + "textures/" + name + "/posz.jpg",
_Root + "textures/" + name + "/negz.jpg"
});
}
else {
throw std::runtime_error("Unknown texture type");
}
_Textures.insert({ name, tempTexture });
ResourceManager::GetInstance()->_Textures.insert({ name, tempTexture });
}
void Package::LoadMeshesFromPackage()
{
YAML::Node fileNode;
YAML::Node meshNode;
try {
fileNode = YAML::LoadFile(_Root + "info.yaml");
if (fileNode["resources"].IsDefined()) {
if (!fileNode["resources"]["meshes"].IsDefined()) {
throw std::runtime_error("Meshes definition cannot be found");
}
}
else {
throw std::runtime_error("Meshes definition cannot be found");
}
meshNode = fileNode["resources"]["meshes"];
}
catch (YAML::BadFile e) {
std::cout << e.what() << std::endl;
}
for (const auto &node : meshNode) {
try {
// Check for the mandatory fields
if (!node["filename"].IsDefined()) {
throw std::runtime_error("Missing mandatory fields.");
}
std::string name = node["filename"].as<std::string>();
std::unordered_map<std::string, std::shared_ptr<Mesh>> temp = Mesh::Load(_Root + "models/" + name, _Root);
ResourceManager::GetInstance()->_Meshes.insert(temp.begin(), temp.end());
_Meshes.insert(temp.begin(), temp.end());
}
catch (const std::exception& e) {
std::cout << e.what() << std::endl;
}
}
}
void Package::LoadMaterialsFromPackage()
{
YAML::Node fileNode;
YAML::Node materialNode;
try {
fileNode = YAML::LoadFile(_Root + "info.yaml");
if (fileNode["resources"].IsDefined()) {
if (!fileNode["resources"]["materials"].IsDefined()) {
throw std::runtime_error("Materials definition cannot be found");
}
}
else {
throw std::runtime_error("Materials definition cannot be found");
}
materialNode = fileNode["resources"]["materials"];
}
catch (YAML::BadFile e) {
std::cout << e.what() << std::endl;
}
for (const auto &node : materialNode) {
// Load the vertex shader
std::string vertex = node["shaders"]["vertex"].as<std::string>();
std::shared_ptr<Shader> vertexShader;
auto vert = ResourceManager::GetInstance()->_Shaders.find(vertex);
if ( vert != ResourceManager::GetInstance()->_Shaders.end()) {
vertexShader = vert->second.lock();
}
else {
vertexShader = std::make_shared<Shader>(vertex, _Root + "shaders/" + vertex, vk::ShaderStageFlagBits::eVertex);
ResourceManager::GetInstance()->_Shaders.insert({ vertex, vertexShader });
}
// Load the fragment shader
std::string fragment = node["shaders"]["fragment"].as<std::string>();
std::shared_ptr<Shader> fragmentShader;
auto frag = ResourceManager::GetInstance()->_Shaders.find(fragment);
if (frag != ResourceManager::GetInstance()->_Shaders.end()) {
fragmentShader = frag->second.lock();
}
else {
fragmentShader = std::make_shared<Shader>(fragment, _Root + "shaders/" + fragment, vk::ShaderStageFlagBits::eFragment);
ResourceManager::GetInstance()->_Shaders.insert({ fragment, fragmentShader });
}
// Load the material
std::string name = node["name"].as<std::string>();
bool CastShadow = node["castShadow"].IsDefined();
// Find the type
std::string pipeline = node["pipeline"].as<std::string>();
std::shared_ptr<Material> mat;
if (pipeline == "basic") {
mat = std::make_shared<Material>(name);
}
else if (pipeline == "cubemap") {
mat = std::make_shared<Cubemap>();
}
else if (pipeline == "shadow") {
mat = std::make_shared<Shadow>();
}
else if (pipeline == "wireframe") {
mat = std::make_shared<Wireframe>(name);
}
else if (pipeline == "unlit") {
mat = std::make_shared<Unlit>(name);
}
else if (pipeline == "PBR") {
mat = std::make_shared<PBR>(name);
}
mat->BindShader(vertexShader);
mat->BindShader(fragmentShader);
mat->_CastShadow = CastShadow;
_Materials.insert({ name, mat });
ResourceManager::GetInstance()->_Materials.insert({ name, mat });
}
}
<file_sep>#include "CubeTexture.h"
#include "stb_image.h"
CubeTexture::CubeTexture(const std::array<std::string, 6>& filenames) :
_Filenames(filenames)
{
for (uint8_t i = 0; i < _ImageBuffers.size(); ++i)
{
int temp;
_ImageBuffers[i] = stbi_load(_Filenames[i].c_str(), &_Dimensions.x, &_Dimensions.y, &temp, STBI_rgb_alpha);
}
}
void CubeTexture::CreateAndUpload(Device * device, const vk::CommandPool & cmdPool)
{
// Copy the GPU resources
_Image = Image(
device,
_Dimensions,
6,
vk::Format::eR8G8B8A8Unorm,
vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
_MipMapping
);
_Sampler = SamplerCache::GetInstance()->Get(device, SamplerInfo{ REPEAT, REPEAT, REPEAT, _Image.GetMipLevel() });
// Upload to the GPU memory
for (uint8_t i = 0; i < _ImageBuffers.size(); ++i)
{
assert(_ImageBuffers[i] != nullptr);
_Image.Transfer(_ImageBuffers[i], cmdPool, i);
free(_ImageBuffers[i]);
_ImageBuffers[i] = nullptr;
}
}
<file_sep>#include "Unlit.h"
#include "glm/glm.hpp"
void Unlit::CreatePushConstantRange()
{
vk::PushConstantRange pushConstant(vk::ShaderStageFlagBits::eFragment, 0, sizeof(glm::vec3));
_PushConstantRange.push_back(pushConstant);
}<file_sep>#include "Surface.h"
Surface::Surface(Device * device, vk::Instance *instance, GLFWwindow *window) :
_Device(device),
_Window(window),
_Instance(instance)
{
// Platform specific code for handling the surface goes here
#ifdef WIN32
_Surface = _Instance->createWin32SurfaceKHR(vk::Win32SurfaceCreateInfoKHR(
{},
GetModuleHandle(nullptr),
glfwGetWin32Window(_Window)
));
#endif
}
void Surface::Clean()
{
CleanSwapChain();
_Instance->destroySurfaceKHR(_Surface);
}
const vk::Extent2D Surface::GetWindowDimensions() const
{
int width, height;
glfwGetWindowSize(_Window, &width, &height);
return vk::Extent2D(width, height);
}
void Surface::CreateSwapChain()
{
// Populate the info if they are empty
if (_NbImages == 0) {
GetSurfaceInfo();
}
// Create the swapchain
const auto&& queueIndexSet = _Device->GetQueueIndexSet();
std::vector<uint32_t> queueIndexList;
std::copy(queueIndexSet.begin(), queueIndexSet.end(), std::back_inserter(queueIndexList));
_Swapchain = _Device->GetDevice().createSwapchainKHR(vk::SwapchainCreateInfoKHR(
{},
_Surface,
_NbImages,
_SelectedSurfaceFormat.format,
_SelectedSurfaceFormat.colorSpace,
GetWindowDimensions(),
1,
vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferDst,
vk::SharingMode::eExclusive,
queueIndexList.size(),
queueIndexList.data(),
vk::SurfaceTransformFlagBitsKHR::eIdentity,
vk::CompositeAlphaFlagBitsKHR::eOpaque,
vk::PresentModeKHR::eFifo,
true,
{}
));
// Create the swapchain images
std::vector<vk::Image> swapchainImages(_Device->GetDevice().getSwapchainImagesKHR(_Swapchain));
_SwapchainImages.resize(swapchainImages.size());
size_t i = 0;
for (auto &image : _SwapchainImages) {
image.FromVkImage(_Device, swapchainImages[i], _SelectedSurfaceFormat.format);
++i;
}
}
void Surface::RecreateSwapChain()
{
CleanSwapChain();
_NbImages = 0;
CreateSwapChain();
}
void Surface::CleanSwapChain()
{
// Clean the images
for (auto &image : _SwapchainImages) {
image.Clean();
}
// Clean the swapchain
_Device->GetDevice().destroySwapchainKHR(_Swapchain);
}
void Surface::GetSurfaceInfo()
{
// Query the newly create surface capabilities
_SurfaceCapabilities = _Device->GetPhysicalDevice().getSurfaceCapabilitiesKHR(_Surface);
_SurfaceFormats = _Device->GetPhysicalDevice().getSurfaceFormatsKHR(_Surface);
_NbImages = _SurfaceCapabilities.minImageCount;
_SelectedSurfaceFormat = _SurfaceFormats.front();
}
<file_sep>#pragma once
#include "SceneObject.h"
#include <glm/glm.hpp>
#include "Frustrum.h"
struct CameraUniformData {
glm::mat4 _View;
glm::mat4 _Projection;
glm::vec4 _Position;
};
struct Direction {
bool Up;
bool Down;
bool Left;
bool Right;
};
class Camera : public SceneObject {
public:
Camera() {}
Camera(const std::string &name, float fov, const uint16_t width, const uint16_t height, const glm::vec3 &position, const glm::vec3 direction, const glm::vec3 up);
void Update(const double mouseX, const double mouseY, const Direction &dir);
CameraUniformData GetUniformData();
glm::mat4 GetProjection() const;
glm::mat4 GetView() const;
uint16_t _Width;
uint16_t _Height;
Frustrum _Frustrum;
public:
float _FOV;
glm::vec3 _Front;
glm::vec3 _Up;
glm::vec3 _Right;
float _Near = 0.01f, _Far = 100.0f;
float _TranslationSpeed;
float _RotationSpeed;
double _HorizontalAngle;
double _VerticalAngle;
};
class OrthographicCamera : public SceneObject {
public:
OrthographicCamera() {}
OrthographicCamera(const std::string &name, const glm::vec4 &ortho, const glm::vec3 &position, const glm::vec3 direction, const glm::vec3 up);
CameraUniformData GetUniformData();
glm::mat4 GetProjection() const;
glm::mat4 GetView() const;
uint16_t _Width;
uint16_t _Height;
private:
glm::vec4 _Ortho;
glm::vec3 _Front;
glm::vec3 _Up;
glm::vec3 _Right;
};<file_sep>#include "imgui.h"
#include <vulkan/vulkan.hpp>
#include "Renderer/vulkan/DeviceHandler.h"
#include "Engine/Scene.h"
#include "Widgets.h"
#include "Renderer/RenderPass.h"
class GUI : public RenderPass {
public:
GUI(Device *device, GLFWwindow *window, vk::Instance *instance);
void CreateVulkanTexture(LiveTexture *texture);
virtual void Init(const vk::CommandPool &commandPool) override;
virtual void CreateCommandBuffers(const uint8_t frame, GlobalDescriptor *globalDescriptor, Scene *scene) override;
virtual void Render(const size_t currentFrame, vk::Semaphore *semaphore, const uint32_t imageIndex) override;
virtual void Resize(const vk::Extent2D &dimension);
PerformanceWidget perf;
SceneTreeWidget tree;
ControlsWidget controls;
RenderWidget render;
Image_IN_ptr _IN_Color;
Image_OUT_ptr _OUT_Color;
vk::Semaphore _OUT_SEM_GUI;
private:
void CreateImage(const vk::CommandPool &commandPool);
void CreateRenderPass();
void CreateDescriptorPool();
void CreateFramebuffer();
std::vector<vk::CommandBuffer> _CommandBuffers;
vk::DescriptorPool _DescriptorPool;
vk::Framebuffer _Framebuffer;
vk::Instance *_Instance;
int selectIndex = 0;
};<file_sep>#pragma once
#include "App.h"
class DemoApplication : public Application {
public:
DemoApplication() : Application("Demo") {};
virtual void Init() override;
};<file_sep>#include "RenderPass.h"
#include "Renderer/Material.h"
#include "Engine/ResourceManager.h"
#include "Renderer/GlobalDescriptor.h"
#include "Engine/Scene.h"
void ColorPass::Init(const vk::CommandPool &commandPool) {
assert(!_IN_Depth.expired());
_CommandBuffers = _Device->GetDevice().allocateCommandBuffers(vk::CommandBufferAllocateInfo(commandPool, vk::CommandBufferLevel::ePrimary, 1));
CreateImage(commandPool);
CreateRenderPass();
CreateFramebuffer();
_OUT_SEM_Color = _Device->GetDevice().createSemaphore({});
}
void ColorPass::CreateCommandBuffers(const uint8_t frame, GlobalDescriptor *globalDescriptor, Scene *scene) {
_CommandBuffers[frame].begin({ vk::CommandBufferUsageFlagBits::eSimultaneousUse });
_Device->StartMarker(_CommandBuffers[frame], "Color Render");
_MultisampleColor.TransitionLayout(_CommandBuffers[frame], vk::ImageLayout::eColorAttachmentOptimal);
_OUT_Color->TransitionLayout(_CommandBuffers[frame], vk::ImageLayout::eColorAttachmentOptimal);
std::array<vk::ClearValue, 2> clearValues;
clearValues[0] = vk::ClearColorValue(std::array<float, 4>{ 0.0f, 0.0f, 0.0f, 1.0f });
clearValues[1] = vk::ClearDepthStencilValue(1.0f, 0);
_CommandBuffers[frame].beginRenderPass(
vk::RenderPassBeginInfo(
_RenderPass,
_Framebuffer,
{ {0, 0}, _Dimension },
clearValues.size(),
clearValues.data()
),
vk::SubpassContents::eInline
);
_CommandBuffers[frame].bindDescriptorSets(
vk::PipelineBindPoint::eGraphics,
ResourceManager::GetInstance()->_Materials.at("unlit").lock()->GetPipelineLayout(),
0,
{
globalDescriptor->_SceneDescriptorSets.at(frame)
},
{}
);
_Drawcalls = 0;
// Render all non transparent objects
for (const auto &mat : scene->_Objects) {
if (mat.second.size() > 0) {
_Device->StartMarker(_CommandBuffers[frame], mat.first->_Name);
_CommandBuffers[frame].bindPipeline(vk::PipelineBindPoint::eGraphics, mat.first->GetPipeline());
for (const auto &object : mat.second) {
if (scene->_Camera._Frustrum.TestFrustrum(object->GetBoundingBox()) || mat.first->_Name == "unlit-wireframe") {
if (mat.first->NumberPushConstants() != 0) {
// Update all the push constants
for (size_t i = 0; i < mat.first->NumberPushConstants(); ++i) {
if (object->_PushConstants.size() <= i) {
_CommandBuffers[frame].pushConstants(mat.first->GetPipelineLayout(), vk::ShaderStageFlagBits::eFragment, 0, sizeof(glm::vec3), glm::vec3(1.0,0,0).data.data);
}
else {
_CommandBuffers[frame].pushConstants(mat.first->GetPipelineLayout(), vk::ShaderStageFlagBits::eFragment, 0, sizeof(glm::vec3), object->_PushConstants[i].data.data);
}
}
}
_CommandBuffers[frame].bindVertexBuffers(0, { object->_Mesh._VertexBuffer.GetBuffer() }, { 0 });
_CommandBuffers[frame].bindIndexBuffer(object->_Mesh._IndexBuffer.GetBuffer(), 0, vk::IndexType::eUint16);
_CommandBuffers[frame].bindDescriptorSets(
vk::PipelineBindPoint::eGraphics,
mat.first->GetPipelineLayout(),
0,
{
globalDescriptor->_SceneDescriptorSets.at(frame),
object->GetDescriptorSet(frame)
},
{ object->_DynamicIndex * static_cast<uint32_t>(Object::dynamicAlignement) }
);
_Drawcalls++;
_CommandBuffers[frame].drawIndexed(object->_Mesh._Vertices.size(), 1, 0, 0, 0);
}
}
_Device->EndMarker(_CommandBuffers[frame]);
}
}
// Render all transparent objects
for (const auto &mat : scene->_ObjectsTransparent) {
if (mat.second.size() > 0) {
_Device->StartMarker(_CommandBuffers[frame], mat.first->_Name);
_CommandBuffers[frame].bindPipeline(vk::PipelineBindPoint::eGraphics, mat.first->GetPipeline());
for (const auto &object : mat.second) {
_CommandBuffers[frame].bindVertexBuffers(0, { object._Mesh._VertexBuffer.GetBuffer() }, { 0 });
_CommandBuffers[frame].bindDescriptorSets(
vk::PipelineBindPoint::eGraphics,
mat.first->GetPipelineLayout(),
0,
{
globalDescriptor->_SceneDescriptorSets.at(frame),
object.GetDescriptorSet(frame)
},
{ object._DynamicIndex * static_cast<uint32_t>(Object::dynamicAlignement) }
);
_CommandBuffers[frame].draw(object._Mesh._Vertices.size(), 1, 0, 0);
}
_Device->EndMarker(_CommandBuffers[frame]);
}
}
_CommandBuffers[frame].endRenderPass();
_Device->EndMarker(_CommandBuffers[frame]);
_CommandBuffers[frame].end();
}
void ColorPass::Render(const size_t currentFrame, vk::Semaphore *semaphore, const uint32_t imageIndex) {
_Device->GetQueue(E_QUEUE_TYPE::GRAPHICS).VulkanQueue.submit(
{
vk::SubmitInfo(
1,
semaphore,
&vk::PipelineStageFlags(vk::PipelineStageFlagBits::eColorAttachmentOutput),
1,
&_CommandBuffers[currentFrame],
1,
&_OUT_SEM_Color
)
},
{}
);
}
void ColorPass::Resize(const vk::Extent2D & dimension)
{
_Dimension = dimension;
_MultisampleColor.Resize(_Dimension);
_OUT_Color->Resize(_Dimension);
_OUT_ColorTexture->_Image = *_OUT_Color.get();
_Device->GetDevice().destroyFramebuffer(_Framebuffer);
CreateFramebuffer();
}
void ColorPass::CreateRenderPass()
{
// Color Image
vk::AttachmentDescription colorAttachement(
{},
_MultisampleColor.GetFormat(),
vk::SampleCountFlagBits::e4,
vk::AttachmentLoadOp::eClear,
vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eColorAttachmentOptimal,
vk::ImageLayout::eColorAttachmentOptimal
);
vk::AttachmentReference colorAttachementReference(
0,
vk::ImageLayout::eColorAttachmentOptimal
);
// Depth Image
vk::AttachmentDescription depthAttachement(
{},
_IN_Depth.lock()->GetFormat(),
vk::SampleCountFlagBits::e4,
vk::AttachmentLoadOp::eLoad,
vk::AttachmentStoreOp::eDontCare,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eDepthStencilReadOnlyOptimal,
vk::ImageLayout::eDepthStencilReadOnlyOptimal
);
vk::AttachmentReference depthAttachementReference(
1,
vk::ImageLayout::eDepthStencilReadOnlyOptimal
);
// Multisample Resolved Image
vk::AttachmentDescription resolveAttachement(
{},
_OUT_Color->GetFormat(),
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eColorAttachmentOptimal,
vk::ImageLayout::eColorAttachmentOptimal
);
vk::AttachmentReference resolveAttachementReference(
2,
vk::ImageLayout::eColorAttachmentOptimal
);
vk::SubpassDescription subpass(
{},
vk::PipelineBindPoint::eGraphics,
0,
nullptr,
1,
&colorAttachementReference,
&resolveAttachementReference,
&depthAttachementReference
);
std::array<vk::AttachmentDescription, 3> attachements{
colorAttachement,
depthAttachement,
resolveAttachement
};
_RenderPass = _Device->GetDevice().createRenderPass(vk::RenderPassCreateInfo(
{},
attachements.size(),
attachements.data(),
1,
&subpass,
1,
&vk::SubpassDependency(
VK_SUBPASS_EXTERNAL,
0,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
{},
vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite
)
));
}
void ColorPass::CreateFramebuffer()
{
std::array<vk::ImageView, 3> attachments = {
_MultisampleColor.GetImageView(),
_IN_Depth.lock()->GetImageView(),
_OUT_Color->GetImageView()
};
_Framebuffer = _Device->GetDevice().createFramebuffer(vk::FramebufferCreateInfo(
{},
_RenderPass,
attachments.size(),
attachments.data(),
_Dimension.width,
_Dimension.height,
1
));
}
void ColorPass::CreateImage(const vk::CommandPool &commandPool) {
_MultisampleColor = Image(
_Device,
VkExtent3D{ _Dimension.width, _Dimension.height, 1 },
1,
vk::Format::eB8G8R8A8Unorm,
vk::ImageUsageFlagBits::eTransientAttachment | vk::ImageUsageFlagBits::eColorAttachment,
false,
vk::SampleCountFlagBits::e4
);
_MultisampleColor.TransitionLayout(commandPool, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
_OUT_Color = std::make_shared<Image>(
_Device,
VkExtent3D{ _Dimension.width, _Dimension.height, 1 },
1,
vk::Format::eB8G8R8A8Unorm,
vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eSampled,
false,
vk::SampleCountFlagBits::e1
);
_OUT_Color->TransitionLayout(commandPool, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
_OUT_ColorTexture = std::make_shared<LiveTexture>(_Device, *_OUT_Color);
}
<file_sep>#include "Widgets.h"
#include "Engine/Object.h"
#include "Engine/Light.h"
void ControlsWidget::Draw()
{
ImGui::Begin("Controls", nullptr);
if (_SceneTree->_SelectedObject != nullptr) {
ImGui::DragFloat3("Position", &_SceneTree->_SelectedObject->Position()[0], 0.1f);
if (Light* light = dynamic_cast<Light*>(_SceneTree->_SelectedObject)) {
ImGui::ColorEdit3("color", &light->_Colour[0]);
ImGui::DragFloat("Strength", &light->_Strength, 0.1f);
ImGui::DragFloat("Range", &range, 0.1f);
ImGui::SameLine();
if (ImGui::Button("Apply!")) {
light->SetRange(range);
}
}
if (Object* object = dynamic_cast<Object*>(_SceneTree->_SelectedObject)) {
ImGui::DragFloat3("Rotation", &object->Rotation()[0], 0.1f);
ImGui::DragFloat3("Scale", &object->Scale()[0], 0.1f);
if (object->_PushConstants.size() != 0) {
ImGui::DragFloat3("Push constants", &object->_PushConstants[0][0], 0.1f, 0.0f, 1.0f);
}
}
}
ImGui::End();
}<file_sep>#pragma once
#include <array>
#include <string>
#include <functional>
#include "imgui.h"
#include "examples/imgui_impl_glfw.h"
#include "examples/imgui_impl_vulkan.h"
class Widget {
public:
virtual void Draw() = 0;
bool IsVisible = true;
int _ViewportWidth, _ViewportHeight;
protected:
const float _Margin = 15.0f;
};
class PerformanceWidget : public Widget {
public:
void Draw() override;
void AddValue(const float frameTime);
float _LastFrameTime = .0f;
std::array<float, 40> _Buffer = { .0f };
int _BufferOffset = 0;
uint16_t _Drawcalls = 0;
};
class Scene;
class Object;
class SceneObject;
class SceneTreeWidget : public Widget {
public:
void Draw() override;
Scene *_Scene;
std::string _Selected;
SceneObject *_SelectedObject = nullptr;
private:
void DrawNode(Object *node, size_t depth = 0);
};
class ControlsWidget : public Widget {
public:
void Draw() override;
float range;
SceneTreeWidget *_SceneTree;
};
class LiveTexture;
class RenderWidget : public Widget {
public:
void BindTexture(LiveTexture * texture);
void ClearTexture();
void Draw() override;
std::vector<std::function<void(double width, double height)>> onResizeCallbacks;
private:
ImVec2 _SizeBuffer = {100, 100};
void* _ImguiImage = nullptr;
};<file_sep>#include "Light.h"
Light::Light(const std::string & name, const glm::vec3 & position) :
SceneObject(name, position),
_Colour(glm::vec3(0.0, 0.0, 0.0)),
_Constant(1.0),
_Linear(0.22),
_Quadratic(0.20),
_Strength(1.0)
{
}
void Light::SetRange(const double range)
{
// https://wiki.ogre3d.org/Light+Attenuation+Shortcut
_Constant = 1.0;
_Linear = 4.5 / range;
_Quadratic = 75.0f / (range * range);
}
LightUniformData Light::GetUniformData()
{
LightUniformData data;
data._Position = glm::vec4(_Position, 0.0);
data._Colour = glm::vec4(_Colour, 0.0);
data._Parameters = glm::vec4(_Constant, _Linear, _Quadratic, _Strength);
return data;
}
<file_sep>#pragma once
#define PLATFORM WIN32
#define VK_USE_PLATFORM_WIN32_KHR
#define GLFW_EXPOSE_NATIVE_WGL
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#include <vulkan/vulkan.hpp>
#include <Renderer/vulkan/Image.h>
#include <Renderer/vulkan/DeviceHandler.h>
class Surface {
public:
Surface() {}
Surface(Device *device, vk::Instance *instance, GLFWwindow *window);
void Clean();
const vk::Extent2D GetWindowDimensions() const;
void CreateSwapChain();
void RecreateSwapChain();
private:
void CleanSwapChain();
void GetSurfaceInfo();
public:
vk::SurfaceKHR _Surface;
vk::SwapchainKHR _Swapchain;
std::vector<Image> _SwapchainImages;
uint32_t _NbImages = 0;
vk::SurfaceFormatKHR _SelectedSurfaceFormat;
private:
Device *_Device;
GLFWwindow *_Window;
vk::Instance *_Instance;
vk::SurfaceCapabilitiesKHR _SurfaceCapabilities;
std::vector<vk::SurfaceFormatKHR> _SurfaceFormats;
};<file_sep>#include "Widgets.h"
#include "Engine/Scene.h"
#include "Engine/Object.h"
void SceneTreeWidget::Draw()
{
//ImGui::SetNextWindowSize(ImVec2(200, 300));
//ImGui::SetNextWindowPos(ImVec2(_ViewportWidth - 200 - _Margin, _Margin));
ImGui::Begin("Scene Tree", nullptr);
if (ImGui::Selectable(_Scene->_Camera._Name.c_str(), _Scene->_Camera._Name == _Selected)) {
if (_SelectedObject == &_Scene->_Camera) {
_Selected = "";
_SelectedObject = nullptr;
}
else {
_Selected = _Scene->_Camera._Name;
_SelectedObject = &_Scene->_Camera;
}
}
for (auto &light : _Scene->_Lights) {
if (ImGui::Selectable(light._Name.c_str(), light._Name == _Selected)) {
if (_SelectedObject == &light) {
_Selected = "";
_SelectedObject = nullptr;
}
else {
_Selected = light._Name;
_SelectedObject = &light;
}
}
}
// Root of the scene
DrawNode(_Scene->_RootObject.lock().get());
ImGui::End();
}
void SceneTreeWidget::DrawNode(Object *node, size_t depth)
{
if (ImGui::Selectable((std::string(depth, ' ') + node->_Name).c_str(), node->_Name == _Selected)) {
if (_SelectedObject == node) {
_Selected = "";
_SelectedObject = nullptr;
node->isSelected = false;
}
else {
_Selected = node->_Name;
_SelectedObject = node;
node->isSelected = true;
}
}
size_t newDepth = depth + 1;
for (auto &child : node->_Children) {
DrawNode(dynamic_cast<Object*>(child.get()), newDepth);
}
}
<file_sep>#pragma once
#include <vulkan/vulkan.hpp>
#include <glm/glm.hpp>
#include <array>
#include <vector>
#include <unordered_map>
#include "tiny_obj_loader.h"
#include "Renderer/vulkan/DeviceHandler.h"
#include "Renderer/vulkan/Buffer.h"
struct BoundingBox {
glm::vec3 _Max;
glm::vec3 _Min;
};
using Index = uint16_t;
struct Vertex {
glm::vec3 position;
glm::vec3 normal;
glm::vec2 texCoord;
glm::vec3 tangent;
glm::vec3 bitangent;
bool operator !=(const Vertex &v) {
if (position == v.position && normal == v.normal && texCoord == v.texCoord) {
return false;
}
return true;
}
static vk::VertexInputBindingDescription GetBindingDescription() {
return vk::VertexInputBindingDescription(0, sizeof(Vertex), vk::VertexInputRate::eVertex);
}
static std::array<vk::VertexInputAttributeDescription, 5> GetAttributeDescriptions() {
std::array<vk::VertexInputAttributeDescription, 5> attributeDescriptions;
attributeDescriptions[0] = vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, position));
attributeDescriptions[1] = vk::VertexInputAttributeDescription(1, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, normal));
attributeDescriptions[2] = vk::VertexInputAttributeDescription(2, 0, vk::Format::eR32G32Sfloat, offsetof(Vertex, texCoord));
attributeDescriptions[3] = vk::VertexInputAttributeDescription(3, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, tangent));
attributeDescriptions[4] = vk::VertexInputAttributeDescription(4, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, bitangent));
return attributeDescriptions;
}
};
class Mesh {
public:
Mesh(){}
static std::unordered_map<std::string, std::shared_ptr<Mesh>> Load(const std::string &filename, const std::string &root);
void Upload(Device *device, const vk::CommandPool &cmdPool);
void Clean();
public:
std::vector<Vertex> _Vertices;
std::vector<Index> _Indices;
// BBOX verticies?
glm::vec3 vertices[8];
std::vector<Vertex> _DebugVertices;
glm::vec3 _BoxMax, _BoxMin;
Buffer _VertexBuffer;
Buffer _IndexBuffer;
Buffer _DebugVertexBuffer;
private:
Device *_Device;
void GenerateTangents();
void GenerateDebugMesh();
};<file_sep>//#include "examples/imgui_impl_vulkan.h"
#include "Widgets.h"
#include "Engine/LiveTexture.h"
void RenderWidget::BindTexture(LiveTexture * texture)
{
_ImguiImage = ImGui_ImplVulkanH_AddTexture(VkSampler(texture->GetSampler()._Sampler), VkImageView(texture->GetImage().GetImageView()));
}
void RenderWidget::ClearTexture()
{
if (_ImguiImage != nullptr) {
ImGui_ImplVulkanH_ClearTexture(_ImguiImage);
}
}
void RenderWidget::Draw()
{
ImGui::Begin("Main View", nullptr);
//ImGui::FindWindowByName
ImVec2 pos = ImGui::GetCursorScreenPos();
ImVec2 size = ImGui::GetContentRegionAvail();
// Flag the resize event
if (size.x != _SizeBuffer.x || size.y != _SizeBuffer.y) {
for (auto callback : onResizeCallbacks) {
callback(size.x, size.y);
}
_SizeBuffer = size;
}
ImGui::GetWindowDrawList()->AddImage(
_ImguiImage,
pos,
ImVec2(pos.x + size.x, pos.y + size.y),
ImVec2(0, 0),
ImVec2(1, 1)
);
ImGui::End();
}
<file_sep>#pragma once
#include "Buffer.h"
#include "../Helpers.h"
Buffer::Buffer(
Device *device,
const vk::BufferUsageFlags usage,
const size_t size,
const vk::SharingMode sharingMode,
vk::MemoryPropertyFlags memoryFlags
):
_Device(device),
_Size(size)
{
_Buffer = _Device->GetDevice().createBuffer(vk::BufferCreateInfo( {}, size, usage, sharingMode ));
vk::MemoryRequirements memoryRequirements = _Device->GetDevice().getBufferMemoryRequirements(_Buffer);
vk::MemoryAllocateInfo memoryInfo;
memoryInfo.allocationSize = memoryRequirements.size;
memoryInfo.memoryTypeIndex = findMemoryType(*_Device, memoryRequirements.memoryTypeBits, memoryFlags);
_Memory = _Device->GetDevice().allocateMemory(memoryInfo);
_Device->GetDevice().bindBufferMemory(_Buffer, _Memory, 0);
}
void Buffer::Copy(void * data, const size_t size) const
{
void *deviceData;
deviceData = _Device->GetDevice().mapMemory(_Memory, 0, size, {});
std::memcpy(deviceData, data, size);
std::array<vk::MappedMemoryRange, 1> memoryRanges;
memoryRanges[0] = vk::MappedMemoryRange(_Memory, 0, VK_WHOLE_SIZE);
_Device->GetDevice().flushMappedMemoryRanges(memoryRanges);
_Device->GetDevice().unmapMemory(_Memory);
}
void Buffer::Transfer(const Buffer & dstBuffer, const vk::CommandPool &cmdPool)
{
vk::CommandBuffer cmd = BeginSingleUseCommandBuffer(*_Device, cmdPool);
vk::BufferCopy region(0, 0, _Size);
cmd.copyBuffer(_Buffer, dstBuffer._Buffer, 1, ®ion);
EndSingleUseCommandBuffer(cmd, *_Device, cmdPool);
}
void Buffer::Clean()
{
if (_Memory) {
_Device->GetDevice().freeMemory(_Memory);
}
if (_Buffer) {
_Device->GetDevice().destroyBuffer(_Buffer);
}
}
<file_sep>#pragma once
#include <vector>
#include <set>
#include <map>
#include <optional>
#include <vulkan/vulkan.hpp>
typedef std::optional<std::reference_wrapper<vk::SurfaceKHR>> optional_surface;
struct DeviceRequestInfo {
std::vector<const char*> RequiredExtensions;
bool SupportPresentation = false;
bool SupportGraphics = false;
};
enum E_QUEUE_TYPE
{
GRAPHICS,
PRESENT
};
struct Queue {
uint32_t Index;
vk::Queue VulkanQueue;
};
class Device {
public:
Device() {}
explicit Device(const vk::PhysicalDevice &physicalDevice);
// Return a device with the first suitable Vulkan physical device
static Device GetDevice(const vk::Instance &instance, const DeviceRequestInfo& info, optional_surface surface);
void Init(DeviceRequestInfo& info, optional_surface surface);
void Clean();
std::set<uint32_t> GetQueueIndexSet();
const bool IsSuitable(const DeviceRequestInfo& info, optional_surface surface) const;
void StartMarker(const vk::CommandBuffer &cmdBuffer, const std::string &name);
void EndMarker(const vk::CommandBuffer &cmdBuffer);
const vk::Device& GetDevice() const {
return _Device;
}
const vk::Device& operator()() const {
return _Device;
}
const vk::PhysicalDevice& GetPhysicalDevice() const {
return _PhysicalDevice;
}
const Queue& GetQueue(const E_QUEUE_TYPE queueType) const {
return _Queues.at(queueType);
}
const vk::PhysicalDeviceProperties &GetProperties() const {
return _PhysicalDeviceProperties;
}
private:
void PickQueueFamilyIndex(const DeviceRequestInfo& info, optional_surface surface);
private:
// Physical device (graphics card)
vk::PhysicalDevice _PhysicalDevice;
vk::PhysicalDeviceProperties _PhysicalDeviceProperties;
vk::PhysicalDeviceFeatures _PhysicalDeviceFeatures;
// Logical device (vulkan handle)
vk::Device _Device;
std::vector<vk::ExtensionProperties> _DeviceExtensions;
// Queues currently on the device
std::vector<vk::QueueFamilyProperties> _QueueFamilyProperties;
std::map<E_QUEUE_TYPE, Queue> _Queues;
bool _SupportDebugMarkers = false;
PFN_vkCmdDebugMarkerBeginEXT pfnCmdDebugMarkerBegin;
PFN_vkCmdDebugMarkerEndEXT pfnCmdDebugMarkerEnd;
};<file_sep>#pragma once
#include <vector>
#include <vulkan/vulkan.hpp>
typedef const char* tLayerName;
typedef std::vector<tLayerName> tLayerNameList;
struct LayerRequestInfo {
tLayerNameList RequiredLayers;
tLayerNameList OptionalLayers;
};
class Layer {
public:
Layer() {}
void Init(const LayerRequestInfo& info);
void Clean(const vk::Instance &instance);
const tLayerNameList& GetEnabledLayers() const {
return _EnabledLayers;
}
const tLayerNameList& GetDisabledLayers() const {
return _DisabledLayers;
}
void AttachDebugCallback(const vk::Instance &instance);
private:
bool CheckLayer(const tLayerName& layerName);
private:
std::vector<vk::LayerProperties> _AvailableLayers;
tLayerNameList _EnabledLayers;
tLayerNameList _DisabledLayers;
vk::DebugReportCallbackEXT _CallbackWarning;
vk::DebugReportCallbackEXT _CallbackError;
};<file_sep>#include "DemoApplication.h"
#include <iostream>
int main() {
DemoApplication app;
app.Init();
app.Run();
app.Clean();
return 0;
}<file_sep>#include "Shader.h"
#include <fstream>
Shader::Shader(
const std::string &shaderName,
const std::string &filename,
const vk::ShaderStageFlagBits stage,
const std::string &entrypoint
) :
_Stage(stage),
_Name(shaderName),
_Filename(filename),
_EntryPoint(entrypoint)
{
LoadFile(filename);
}
void Shader::Load(Device * device)
{
_Device = device;
if (!_Module) {
CreateShaderModule();
}
}
void Shader::Reload() {
// Reload the file
LoadFile(_Filename);
// Destroy the existing module
_Device->GetDevice().destroyShaderModule(_Module);
// Recreate a new module inplace
CreateShaderModule();
// ... Enjoy!!!
}
void Shader::Clean()
{
_Device->GetDevice().destroyShaderModule(_Module);
}
vk::PipelineShaderStageCreateInfo Shader::GetShaderPipelineInfo() const
{
return vk::PipelineShaderStageCreateInfo({}, _Stage, _Module, _EntryPoint.c_str());
}
void Shader::LoadFile(const std::string &filename)
{
std::ifstream file(filename, std::ios::ate | std::ios::binary);
if (!file.is_open()) {
throw std::runtime_error("File " + filename + " not found.");
}
size_t fileSize = (size_t)file.tellg();
_Code.resize(fileSize);
file.seekg(0);
file.read(_Code.data(), fileSize);
file.close();
}
void Shader::CreateShaderModule()
{
_Module = _Device->GetDevice().createShaderModule(vk::ShaderModuleCreateInfo({}, _Code.size(), reinterpret_cast<const uint32_t*>(_Code.data())));
}
<file_sep>#pragma once
#include <vector>
#include <vulkan/vulkan.h>
typedef const char* tExtensionName;
typedef std::vector<tExtensionName> tExtensionNameList;
struct ExtensionRequestInfo {
tExtensionNameList RequiredExtensions;
tExtensionNameList OptionalExtensions;
};
class Extension {
public:
Extension() {}
void Init(const ExtensionRequestInfo& info);
const tExtensionNameList& GetEnabledExtensions() const;
const tExtensionNameList& GetDisabledExtensions() const;
private:
bool CheckExtension(const tExtensionName& extensionName);
private:
std::vector<VkExtensionProperties> AvailableExtensions;
tExtensionNameList EnabledExtensions;
tExtensionNameList DisabledExtensions;
};<file_sep>#pragma once
#include <string>
#include "Shader.h"
#include "Material.h"
class Cubemap: public Material {
public:
Cubemap(){}
Cubemap(const std::string &name) : Material(name) {}
protected:
void CreateRasterizationInfo() override;
};<file_sep>#pragma once
#include "Material.h"
class PBR : public Material {
public:
PBR() {}
PBR(const std::string &name) : Material(name) {}
protected:
virtual void CreatePushConstantRange() override;
};<file_sep>#pragma once
#include <vector>
#include <unordered_map>
#include <memory>
#include <vulkan/vulkan.hpp>
#include <glm/glm.hpp>
#include "Camera.h"
#include "Renderer/vulkan/DeviceHandler.h"
#include "Renderer/vulkan/Buffer.h"
#include "Light.h"
#include "Renderer/Material.h"
#include "Renderer/Cubemap.h"
#include "Renderer/Mesh.h"
#include "Object.h"
#include "Texture.h"
#include "CubeTexture.h"
#include "Renderer/Shadow.h"
#include "yaml-cpp/yaml.h"
#include "Engine/Lib.h"
#define MAX_NUM_DYNAMIC_LIGHTS 5u
#define DATA_BUFFER_SIZE 4
struct SceneDataObject {
union alignas(256) Data{
CameraUniformData _CameraData;
CameraUniformData _ShadowCameraData;
LightUniformData _LightData[MAX_NUM_DYNAMIC_LIGHTS];
uint32_t _NumLights;
} _Data[DATA_BUFFER_SIZE];
};
class Renderer;
class EXPORT Scene {
public:
// Load a scene from a set of yaml files
void Load(const std::string &name, Renderer &renderer);
void Resize(const vk::Extent2D &dimension);
std::vector<Light> _Lights;
std::unordered_map<std::shared_ptr<Material>, std::vector<std::shared_ptr<Object>>> _Objects;
std::unordered_map<std::shared_ptr<Material>, std::vector<Object>> _ObjectsTransparent;
void CreateDynamic(Device *device);
uint32_t AddToDynamic(Object &object);
void UploadDynamic();
void Update(const uint32_t image, const Buffer &sceneBuffer);
private:
public:
Camera _Camera;
OrthographicCamera _ShadowCamera;
std::weak_ptr<Object> _RootObject;
std::string _Name;
private:
Device *_Device;
size_t dynamicIndex = 0;
std::vector<SceneDataObject> _SceneDataObjects;
void ParseObject(const YAML::Node &node, std::shared_ptr<Object> parent, std::shared_ptr<Texture> shadow);
};<file_sep>#pragma once
#include <vector>
#include "Renderer/vulkan/Image.h"
#include <vulkan/vulkan.hpp>
#include "DepthOnly.h"
#include "Shadow.h"
#include "vulkan/Surface.h"
#include "Engine/LiveTexture.h"
class GlobalDescriptor;
class Scene;
#define NB_IMAGE 2
using Image_IN_ptr = std::weak_ptr<Image>;
using Image_OUT_ptr = std::shared_ptr<Image>;
class RenderPass {
public:
RenderPass(Device *device) : _Device(device) {}
virtual void Init(const vk::CommandPool &commandPool) = 0;
virtual void CreateCommandBuffers(const uint8_t frame, GlobalDescriptor *globalDescriptor, Scene *scene) = 0;
virtual void Render(const size_t currentFrame, vk::Semaphore *semaphore, const uint32_t imageIndex) = 0;
virtual void Resize(const vk::Extent2D &dimension) = 0;
vk::Extent2D _Dimension;
vk::RenderPass _RenderPass;
uint16_t _Drawcalls;
protected:
Device *_Device;
std::vector<vk::CommandBuffer> _CommandBuffers;
std::vector<vk::Framebuffer> _Framebuffers;
};
// This render pass renders a shadow map to a texture
class ShadowPass : public RenderPass {
public:
ShadowPass(Device *device) : RenderPass(device) {}
virtual void Init(const vk::CommandPool &commandPool) override;
virtual void InitShader(const GlobalDescriptor &globalDescriptor);
virtual void CreateCommandBuffers(const uint8_t frame, GlobalDescriptor *globalDescriptor, Scene *scene) override;
virtual void Render(const size_t currentFrame, vk::Semaphore *semaphore, const uint32_t imageIndex) override;
virtual void Resize(const vk::Extent2D &dimension) override;
Image_OUT_ptr _OUT_Shadow;
std::shared_ptr<LiveTexture> _OUT_ShadowTexture;
vk::Semaphore _OUT_SEM_Shadow;
private:
void CreateImage(const vk::CommandPool &commandPool);
void CreateRenderPass();
void CreateFramebuffer();
vk::Framebuffer _Framebuffer;
Shadow _ShadowMaterial;
};
// This render pass takes the main scene and render a depth image to be used in subsequent render
class DepthPrePass : public RenderPass {
public:
DepthPrePass(Device *device) : RenderPass(device) {}
virtual void Init(const vk::CommandPool &commandPool) override;
virtual void InitShader(const GlobalDescriptor &globalDescriptor);
virtual void CreateCommandBuffers(const uint8_t frame, GlobalDescriptor *globalDescriptor, Scene *scene) override;
virtual void Render(const size_t currentFrame, vk::Semaphore *semaphore, const uint32_t imageIndex) override;
virtual void Resize(const vk::Extent2D &dimension) override;
Image_OUT_ptr _OUT_Depth;
vk::Semaphore _OUT_SEM_Depth;
private:
void CreateImage(const vk::CommandPool &commandPool);
void CreateRenderPass();
void CreateFramebuffer();
vk::Framebuffer _Framebuffer;
DepthOnly _DepthOnlyMaterial;
};
// This render pass takes the output of a depth prepass and uses it to render a color image, this output is no longer multisampled
class ColorPass : public RenderPass {
public:
ColorPass(Device *device) : RenderPass(device) {}
virtual void Init(const vk::CommandPool &commandPool) override;
virtual void CreateCommandBuffers(const uint8_t frame, GlobalDescriptor *globalDescriptor, Scene *scene) override;
virtual void Render(const size_t currentFrame, vk::Semaphore *semaphore, const uint32_t imageIndex) override;
virtual void Resize(const vk::Extent2D &dimension) override;
Image_IN_ptr _IN_Depth;
Image_OUT_ptr _OUT_Color;
std::shared_ptr<LiveTexture> _OUT_ColorTexture;
vk::Semaphore _OUT_SEM_Color;
private:
void CreateImage(const vk::CommandPool &commandPool);
void CreateRenderPass();
void CreateFramebuffer();
Image _MultisampleColor;
vk::Framebuffer _Framebuffer;
};
// This render pass takes a color image as an input and copies it to the current frame's swapchain image
// The two images must have the same type and settings
class PresentPass : public RenderPass {
public:
PresentPass(Device *device, std::shared_ptr<Surface> surface) : RenderPass(device), _Surface(std::move(surface)) {}
virtual void Init(const vk::CommandPool &commandPool) override;
virtual void CreateCommandBuffers(const uint8_t frame, GlobalDescriptor *globalDescriptor, Scene *scene) override;
virtual void Render(const size_t currentFrame, vk::Semaphore *semaphore, const uint32_t imageIndex) override;
virtual void Resize(const vk::Extent2D &dimension) override;
Image_IN_ptr _IN_Color;
// Flag the CPU if the requested frame has been transfered back to the present image
std::vector<vk::Fence> _OUT_InFlight;
private:
std::shared_ptr<Surface> _Surface;
std::vector<vk::Semaphore> _TransferSemaphores;
};<file_sep>#pragma once
#include <array>
#include <vulkan/vulkan.h>
#include <glm/glm.hpp>
#include "vulkan/Buffer.h"
#define vk_expect_success(func, message) { \
if (func != VK_SUCCESS) { \
throw std::runtime_error(message); \
} \
}
static uint32_t findMemoryType(const Device& device, uint32_t typeFilter, vk::MemoryPropertyFlags properties)
{
vk::PhysicalDeviceMemoryProperties memoryProperties = device.GetPhysicalDevice().getMemoryProperties();
for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++) {
if ((typeFilter & (1 << i)) && (memoryProperties.memoryTypes[i].propertyFlags & properties) == properties) {
return i;
}
}
throw std::runtime_error("failed to find suitable memory type!");
}
// Create a one shot command buffer
static vk::CommandBuffer BeginSingleUseCommandBuffer(const Device &device, const vk::CommandPool &cmdPool)
{
std::vector<vk::CommandBuffer> cmdBuffer = device().allocateCommandBuffers({ cmdPool, vk::CommandBufferLevel::ePrimary, 1 });
cmdBuffer.front().begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
return cmdBuffer.front();
}
static void EndSingleUseCommandBuffer(const vk::CommandBuffer &cmdBuffer, const Device &device, const vk::CommandPool &cmdPool)
{
cmdBuffer.end();
std::array<vk::SubmitInfo, 1> submitInfo;
submitInfo[0] = {};
submitInfo[0].commandBufferCount = 1;
submitInfo[0].pCommandBuffers = &cmdBuffer;
device.GetQueue(E_QUEUE_TYPE::GRAPHICS).VulkanQueue.submit(submitInfo, {});
device.GetQueue(E_QUEUE_TYPE::GRAPHICS).VulkanQueue.waitIdle();
device().freeCommandBuffers(cmdPool, { cmdBuffer });
}
<file_sep>#include "Image.h"
#include <algorithm>
#include "Buffer.h"
Image::Image(
Device *device,
const vk::Extent3D &dimensions,
const uint8_t layers,
const vk::Format &format,
const vk::ImageUsageFlags usage,
const bool generateMips,
const vk::SampleCountFlagBits numSamples
) :
_Device(device),
_Format(format),
_Usage(usage),
_NbLayers(layers),
_Dimensions(dimensions),
_NumSamples(numSamples)
{
if (generateMips) {
_MipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(_Dimensions.width, _Dimensions.height))) + 1);
_Usage |= vk::ImageUsageFlagBits::eTransferSrc;
}
else {
_MipLevels = 1;
}
Init();
}
Image::Image(
Device * device,
const glm::ivec3 & dimensions,
const uint8_t layers,
const vk::Format & format,
const vk::ImageUsageFlags usage,
const bool generateMips,
const vk::SampleCountFlagBits numSamples
) :Image(device, vk::Extent3D(dimensions.x, dimensions.y, dimensions.z), layers, format, usage, generateMips, numSamples)
{
}
void Image::FromVkImage(
Device *device,
const vk::Image &image,
const vk::Format &format
) {
_Device = device;
_Image = image;
_Format = format;
_Dimensions = VkExtent3D{ 0, 0, 1 };
_NbLayers = 1;
_MipLevels = 1;
CreateImageView();
_FromSwapchain = true;
}
void Image::Init()
{
CreateImage();
AllocateMemory();
CreateImageView();
}
void Image::Clean()
{
_CurrentLayout = vk::ImageLayout::eUndefined;
if (_View) {
_Device->GetDevice().destroyImageView(_View);
}
// In case we obtained the image through the sawpchain, do not clear it
if (!_FromSwapchain) {
if (_Image) {
_Device->GetDevice().destroyImage(_Image);
}
if (_Memory) {
_Device->GetDevice().freeMemory(_Memory);
}
}
}
void Image::Resize(const vk::Extent2D & dimension)
{
Clean();
_Dimensions = vk::Extent3D(dimension, 1);
Init();
}
void Image::GenerateMipmaps(const vk::CommandPool& cmdPool)
{
vk::CommandBuffer cmdBuffer = BeginSingleUseCommandBuffer(*_Device, cmdPool);
std::array<vk::ImageMemoryBarrier, 1> barriers;
barriers[0].image = _Image;
barriers[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barriers[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barriers[0].subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
barriers[0].subresourceRange.baseArrayLayer = 0;
barriers[0].subresourceRange.layerCount = 1;
barriers[0].subresourceRange.levelCount = 1;
int32_t mipWidth = _Dimensions.width;
int32_t mipHeight = _Dimensions.height;
for (uint32_t i = 1; i < _MipLevels; ++i) {
barriers[0].subresourceRange.baseMipLevel = i - 1;
barriers[0].oldLayout = vk::ImageLayout::eTransferDstOptimal;
barriers[0].newLayout = vk::ImageLayout::eTransferSrcOptimal;
barriers[0].srcAccessMask = vk::AccessFlagBits::eTransferWrite;
barriers[0].dstAccessMask = vk::AccessFlagBits::eTransferRead;
cmdBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eTransfer,
vk::DependencyFlags(),
nullptr,
nullptr,
barriers[0]
);
vk::ImageBlit blit(
vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor,i-1, 0, 1),
{
vk::Offset3D{0,0,0},
vk::Offset3D{ mipWidth, mipHeight, 1}
},
vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, i, 0, 1),
{
vk::Offset3D{ 0,0,0},
vk::Offset3D{ mipWidth > 1 ? mipWidth / 2 : 1, mipHeight > 1 ? mipHeight / 2 : 1, 1 }
}
);
cmdBuffer.blitImage(
_Image, vk::ImageLayout::eTransferSrcOptimal,
_Image, vk::ImageLayout::eTransferDstOptimal,
{ blit },
vk::Filter::eLinear
);
barriers[0].oldLayout = vk::ImageLayout::eTransferSrcOptimal;
barriers[0].newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
barriers[0].srcAccessMask = vk::AccessFlagBits::eTransferRead;
barriers[0].dstAccessMask = vk::AccessFlagBits::eShaderRead;
cmdBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eFragmentShader,
vk::DependencyFlags(),
nullptr,
nullptr,
barriers[0]
);
if (mipWidth > 1) mipWidth /= 2;
if (mipHeight > 1) mipHeight /= 2;
}
barriers[0].subresourceRange.baseMipLevel = _MipLevels - 1;
barriers[0].oldLayout = vk::ImageLayout::eTransferDstOptimal;
barriers[0].newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
barriers[0].srcAccessMask = vk::AccessFlagBits::eTransferRead;
barriers[0].dstAccessMask = vk::AccessFlagBits::eShaderRead;
cmdBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eFragmentShader,
vk::DependencyFlags(),
nullptr,
nullptr,
barriers[0]
);
EndSingleUseCommandBuffer(cmdBuffer, *_Device, cmdPool);
}
void Image::TransitionLayout(const vk::CommandPool &cmdPool, const vk::ImageLayout oldLayout, const vk::ImageLayout newLayout)
{
vk::CommandBuffer cmdBuffer = BeginSingleUseCommandBuffer(*_Device, cmdPool);
TransitionLayout(cmdBuffer, oldLayout, newLayout);
EndSingleUseCommandBuffer(cmdBuffer, *_Device, cmdPool);
}
void Image::TransitionLayout(const vk::CommandBuffer & cmdBuffer, const vk::ImageLayout oldLayout, const vk::ImageLayout newLayout)
{
std::array<vk::ImageMemoryBarrier, 1> barriers;
barriers[0].image = _Image;
barriers[0].oldLayout = oldLayout;
barriers[0].newLayout = newLayout;
barriers[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barriers[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barriers[0].subresourceRange.aspectMask = _Format == vk::Format::eD32Sfloat ? vk::ImageAspectFlagBits::eDepth : vk::ImageAspectFlagBits::eColor;
barriers[0].subresourceRange.baseArrayLayer = 0;
barriers[0].subresourceRange.layerCount = _NbLayers;
barriers[0].subresourceRange.levelCount = _MipLevels;
vk::PipelineStageFlagBits srcStage, dstStage;
barriers[0].srcAccessMask = GetAccess(oldLayout);
barriers[0].dstAccessMask = GetAccess(newLayout);
srcStage = GetStage(oldLayout);
dstStage = GetStage(newLayout);
cmdBuffer.pipelineBarrier(
srcStage,
dstStage,
vk::DependencyFlags(),
nullptr,
nullptr,
barriers[0]
);
_CurrentLayout = newLayout;
}
void Image::TransitionLayout(const vk::CommandBuffer & cmdBuffer, const vk::ImageLayout newLayout)
{
if (newLayout != _CurrentLayout) {
TransitionLayout(cmdBuffer, _CurrentLayout, newLayout);
}
}
void Image::Transfer(unsigned char * buffer, const vk::CommandPool & cmdPool, const uint8_t layer)
{
// Create the staging buffer
size_t size = _Dimensions.width * _Dimensions.height * 4;
Buffer staging(_Device, vk::BufferUsageFlagBits::eTransferSrc, size);
staging.Copy(buffer, size);
// Copy the staging buffer to image memory
std::array<vk::BufferImageCopy, 1> regions = {};
regions[0].bufferOffset = 0;
regions[0].bufferRowLength = 0;
regions[0].bufferImageHeight = 0;
regions[0].imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
regions[0].imageSubresource.mipLevel = 0;
regions[0].imageSubresource.baseArrayLayer = layer;
regions[0].imageSubresource.layerCount = 1;
regions[0].imageOffset = { 0,0,0 };
regions[0].imageExtent = _Dimensions;
TransitionLayout(cmdPool, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal);
vk::CommandBuffer cmdBuffer = BeginSingleUseCommandBuffer(*_Device, cmdPool);
cmdBuffer.copyBufferToImage(
staging.GetBuffer(),
_Image,
vk::ImageLayout::eTransferDstOptimal,
regions
);
EndSingleUseCommandBuffer(cmdBuffer, *_Device, cmdPool);
if (_MipLevels > 1u) {
GenerateMipmaps(cmdPool);
}
else
{
TransitionLayout(cmdPool, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
}
// Clean the staging buffer
staging.Clean();
}
void Image::Transfer(Image &image, const vk::CommandBuffer &cmdBuffer, const glm::vec2 &offset)
{
auto previousLayout = _CurrentLayout;
TransitionLayout(cmdBuffer, vk::ImageLayout::eTransferSrcOptimal);
image.TransitionLayout(cmdBuffer, vk::ImageLayout::eTransferDstOptimal);
std::array<vk::ImageCopy, 1> regions = {};
regions[0].extent.width = _Dimensions.width;
regions[0].extent.height = _Dimensions.height;
regions[0].extent.depth = 1;
regions[0].dstOffset = { static_cast<int>(offset.x), static_cast<int>(offset.y), 0 };
regions[0].srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
regions[0].srcSubresource.layerCount = 1;
regions[0].dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
regions[0].dstSubresource.layerCount = 1;
cmdBuffer.copyImage(
_Image,
vk::ImageLayout::eTransferSrcOptimal,
image.GetImage(),
vk::ImageLayout::eTransferDstOptimal,
regions
);
TransitionLayout(cmdBuffer, previousLayout);
}
void Image::CreateImage()
{
vk::ImageCreateFlagBits flags = {};
if (_NbLayers > 1) {
flags = vk::ImageCreateFlagBits::eCubeCompatible;
}
_Image = _Device->GetDevice().createImage(vk::ImageCreateInfo(
flags,
_Dimensions.depth > 1 ? vk::ImageType::e3D : vk::ImageType::e2D,
_Format,
_Dimensions,
_MipLevels,
_NbLayers,
_NumSamples,
vk::ImageTiling::eOptimal,
_Usage,
vk::SharingMode::eExclusive
));
}
void Image::AllocateMemory()
{
vk::MemoryRequirements imageMemReq = _Device->GetDevice().getImageMemoryRequirements(_Image);
_Memory = _Device->GetDevice().allocateMemory(
vk::MemoryAllocateInfo(
imageMemReq.size,
findMemoryType(*_Device, imageMemReq.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal)
)
);
_Device->GetDevice().bindImageMemory(_Image, _Memory, 0);
}
void Image::CreateImageView()
{
// Get the right image type
vk::ImageViewType imageType;
if (_Dimensions.depth > 1) {
imageType = vk::ImageViewType::e3D;
}
else if (_NbLayers > 1) {
imageType = vk::ImageViewType::eCube;
}
else {
imageType = vk::ImageViewType::e2D;
}
_View = _Device->GetDevice().createImageView(vk::ImageViewCreateInfo(
vk::ImageViewCreateFlags(),
_Image,
imageType,
_Format,
vk::ComponentMapping(),
vk::ImageSubresourceRange(
_Format == vk::Format::eD32Sfloat ? vk::ImageAspectFlagBits::eDepth : vk::ImageAspectFlagBits::eColor,
0,
_MipLevels,
0,
_NbLayers
)
));
}
vk::AccessFlags Image::GetAccess(const vk::ImageLayout layout)
{
switch (layout)
{
case vk::ImageLayout::eUndefined:
return {};
case vk::ImageLayout::eColorAttachmentOptimal:
return vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite;
case vk::ImageLayout::ePresentSrcKHR:
return {};
case vk::ImageLayout::eDepthStencilAttachmentOptimal:
return vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite;
case vk::ImageLayout::eDepthStencilReadOnlyOptimal:
return vk::AccessFlagBits::eDepthStencilAttachmentRead;
case vk::ImageLayout::eTransferSrcOptimal:
return vk::AccessFlagBits::eTransferRead;
case vk::ImageLayout::eTransferDstOptimal:
return vk::AccessFlagBits::eTransferWrite;
case vk::ImageLayout::eShaderReadOnlyOptimal:
return vk::AccessFlagBits::eShaderRead;
default:
throw std::runtime_error("Access not implemented.");
}
}
vk::PipelineStageFlagBits Image::GetStage(const vk::ImageLayout layout)
{
switch (layout)
{
case vk::ImageLayout::eUndefined:
return vk::PipelineStageFlagBits::eTopOfPipe;
case vk::ImageLayout::eColorAttachmentOptimal:
return vk::PipelineStageFlagBits::eColorAttachmentOutput;
case vk::ImageLayout::ePresentSrcKHR:
return vk::PipelineStageFlagBits::eColorAttachmentOutput;
case vk::ImageLayout::eDepthStencilAttachmentOptimal:
return vk::PipelineStageFlagBits::eEarlyFragmentTests;
case vk::ImageLayout::eDepthStencilReadOnlyOptimal:
return vk::PipelineStageFlagBits::eEarlyFragmentTests;
case vk::ImageLayout::eTransferSrcOptimal:
return vk::PipelineStageFlagBits::eTransfer;
case vk::ImageLayout::eTransferDstOptimal:
return vk::PipelineStageFlagBits::eTransfer;
case vk::ImageLayout::eShaderReadOnlyOptimal:
return vk::PipelineStageFlagBits::eFragmentShader;
default:
throw std::runtime_error("Stage not implemented.");
}
}
<file_sep>#include "Texture.h"
#include "stb_image.h"
Texture::Texture(const std::string & filename, const bool generateMips) :
_Filename(filename.c_str()),
_MipMapping(generateMips)
{
// Load the image from disk
int temp;
_ImageBuffer = stbi_load(_Filename.c_str(), &_Dimensions.x, &_Dimensions.y, &temp, STBI_rgb_alpha);
}
Texture::~Texture()
{
_Image.Clean();
}
void Texture::CreateAndUpload(Device *device, const vk::CommandPool &cmdPool)
{
// Copy the GPU resources
_Image = Image(
device,
_Dimensions,
1,
vk::Format::eR8G8B8A8Unorm,
vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
_MipMapping
);
_Sampler = SamplerCache::GetInstance()->Get(device, SamplerInfo{ REPEAT, REPEAT, REPEAT, _Image.GetMipLevel() });
// Upload to the GPU memory
assert(_ImageBuffer != nullptr);
_Image.Transfer(_ImageBuffer, cmdPool);
free(_ImageBuffer);
_ImageBuffer = nullptr;
}<file_sep>#include "Widgets.h"
void PerformanceWidget::Draw()
{
ImGui::SetNextWindowSize(ImVec2(150, 90));
ImGui::SetNextWindowPos(ImVec2(_Margin + 25, _Margin + 25));
ImGui::Begin("Performance", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar);
ImGui::Text("%u FPS", static_cast<unsigned int>(1000.f / _LastFrameTime));
ImGui::Text("%.2f ms", _LastFrameTime);
ImGui::Text("Draw calls: %u", _Drawcalls);
ImGui::PushItemWidth(-1);
ImGui::PlotLines("", _Buffer.data(), _Buffer.size(), 0, nullptr, 16.0f, 30.0f);
ImGui::End();
}
void PerformanceWidget::AddValue(const float frameTime)
{
_LastFrameTime = frameTime;
_Buffer[_BufferOffset] = frameTime;
_BufferOffset = (_BufferOffset + 1) % _Buffer.size();
}
<file_sep>#include "DemoApplication.h"
#include "Engine/Package.h"
void DemoApplication::Init()
{
Application::Init();
// Load the resource package
Package levelPackage = Package("sponza", "sponza");
levelPackage.Load();
levelPackage.Initialize(render, 1024);
_Packages.push_back(levelPackage);
// Load the scene
_Scene.Load("sponza",render);
_Scene.UploadDynamic();
}
<file_sep>#pragma once
#include <string>
#include "Shader.h"
#include "Material.h"
class Shadow: public Material {
public:
Shadow(){}
Shadow(const std::string &name) : Material(name) {}
protected:
virtual void CreateDepthStencilInfo() override;
virtual void CreateMultisampleInfo() override {
_MultisampleInfo = vk::PipelineMultisampleStateCreateInfo({}, vk::SampleCountFlagBits::e1, false);
}
virtual void CreateColorBlendInfo() override {
_ColorBlendAttachement = vk::PipelineColorBlendAttachmentState(
false
);
}
virtual void CreateRasterizationInfo() override
{
_RasterizationInfo = vk::PipelineRasterizationStateCreateInfo(
{},
false,
false,
vk::PolygonMode::eFill,
vk::CullModeFlagBits::eFront,
vk::FrontFace::eCounterClockwise,
false,
0,
0,
0,
1.0
);
}
};<file_sep>#ifdef EXPORT_LIBRARY
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif<file_sep>#pragma once
#include <string>
#include <unordered_map>
#include "yaml-cpp/yaml.h"
#include "Renderer/vulkan/DeviceHandler.h"
#include <vulkan/vulkan.hpp>
#include "Renderer/GlobalDescriptor.h"
#include "Engine/Lib.h"
class Texture;
class Mesh;
class Shader;
class Material;
class Scene;
class Renderer;
class EXPORT Package {
public:
Package() {};
Package(const std::string &root, const std::string &name);
void Load();
void Initialize(Renderer &renderer, uint32_t poolSize);
const std::string _Name;
private:
void LoadTexturesFromPackage();
void LoadTexture(const YAML::Node &node);
void LoadMeshesFromPackage();
void LoadMaterialsFromPackage();
private:
const std::string _Root;
std::unordered_map<std::string, std::shared_ptr<Texture>> _Textures;
std::unordered_map<std::string, std::shared_ptr<Mesh>> _Meshes;
std::unordered_map<std::string, std::shared_ptr<Material>> _Materials;
};<file_sep>#include "RenderPass.h"
void PresentPass::Init(const vk::CommandPool &commandPool){
assert(!_IN_Color.expired());
_CommandBuffers = _Device->GetDevice().allocateCommandBuffers(vk::CommandBufferAllocateInfo(commandPool, vk::CommandBufferLevel::ePrimary, NB_IMAGE));
_TransferSemaphores.resize(NB_IMAGE);
_OUT_InFlight.resize(NB_IMAGE);
for (size_t i = 0; i < NB_IMAGE; ++i) {
_TransferSemaphores[i] = _Device->GetDevice().createSemaphore({});
_OUT_InFlight[i] = _Device->GetDevice().createFence({ vk::FenceCreateFlagBits::eSignaled });
}
}
void PresentPass::CreateCommandBuffers(const uint8_t frame, GlobalDescriptor *globalDescriptor, Scene *scene) {
assert(!_IN_Color.expired());
_CommandBuffers[frame].begin({ vk::CommandBufferUsageFlagBits::eSimultaneousUse });
_Device->StartMarker(_CommandBuffers[frame], "Present pass");
_IN_Color.lock()->TransitionLayout(_CommandBuffers[frame], vk::ImageLayout::eTransferSrcOptimal);
_Surface->_SwapchainImages[frame].TransitionLayout(_CommandBuffers[frame], vk::ImageLayout::eTransferDstOptimal);
_IN_Color.lock()->Transfer(_Surface->_SwapchainImages[frame], _CommandBuffers[frame]);
_Surface->_SwapchainImages[frame].TransitionLayout(_CommandBuffers[frame], vk::ImageLayout::ePresentSrcKHR);
_Device->EndMarker(_CommandBuffers[frame]);
_CommandBuffers[frame].end();
}
void PresentPass::Render(const size_t currentFrame, vk::Semaphore *semaphore, const uint32_t imageIndex) {
// Submit the transfer job
_Device->GetQueue(E_QUEUE_TYPE::GRAPHICS).VulkanQueue.submit(
{
vk::SubmitInfo(
1,
semaphore,
&vk::PipelineStageFlags(vk::PipelineStageFlagBits::eAllCommands),
1,
&_CommandBuffers[currentFrame],
1,
&_TransferSemaphores[currentFrame]
)
},
_OUT_InFlight[0]
);
// And then present
_Device->GetQueue(E_QUEUE_TYPE::PRESENT).VulkanQueue.presentKHR(vk::PresentInfoKHR(
1,
&_TransferSemaphores[currentFrame],
1,
&_Surface->_Swapchain,
&imageIndex
));
}
void PresentPass::Resize(const vk::Extent2D & dimension)
{
}
<file_sep>#include "DeviceHandler.h"
#include <algorithm>
#include "../Helpers.h"
Device::Device(const vk::PhysicalDevice & physicalDevice):
_PhysicalDevice(physicalDevice)
{
_PhysicalDeviceProperties = _PhysicalDevice.getProperties();
_PhysicalDeviceFeatures = _PhysicalDevice.getFeatures();
_DeviceExtensions = _PhysicalDevice.enumerateDeviceExtensionProperties();
_QueueFamilyProperties = _PhysicalDevice.getQueueFamilyProperties();
}
void Device::Init(DeviceRequestInfo& info, optional_surface surface)
{
// Activate the debug markers if we can
auto it = std::find_if(
_DeviceExtensions.begin(),
_DeviceExtensions.end(),
[](const vk::ExtensionProperties& availableExtenion) {
return std::strcmp(availableExtenion.extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME) == 0;
}
);
if (it != _DeviceExtensions.end()) {
_SupportDebugMarkers = true;
info.RequiredExtensions.push_back(VK_EXT_DEBUG_MARKER_EXTENSION_NAME);
}
PickQueueFamilyIndex(info, surface);
std::vector<vk::DeviceQueueCreateInfo> deviceQueuesInfo;
for (const auto& id : GetQueueIndexSet()) {
float queuePrio = 1.0f;
deviceQueuesInfo.push_back(vk::DeviceQueueCreateInfo{ {}, id, 1, &queuePrio });
}
vk::PhysicalDeviceFeatures deviceFeatures = {};
deviceFeatures.fillModeNonSolid = true;
vk::DeviceCreateInfo deviceInfo = {};
deviceInfo.pQueueCreateInfos = deviceQueuesInfo.data();
deviceInfo.queueCreateInfoCount = deviceQueuesInfo.size();
deviceInfo.pEnabledFeatures = &deviceFeatures;
deviceInfo.enabledExtensionCount = info.RequiredExtensions.size();
deviceInfo.ppEnabledExtensionNames = info.RequiredExtensions.data();
_Device = _PhysicalDevice.createDevice(deviceInfo);
for (auto &queue : _Queues)
{
queue.second.VulkanQueue = _Device.getQueue(queue.second.Index, 0);
}
if (_SupportDebugMarkers) {
pfnCmdDebugMarkerBegin = (PFN_vkCmdDebugMarkerBeginEXT)_Device.getProcAddr("vkCmdDebugMarkerBeginEXT");
pfnCmdDebugMarkerEnd = (PFN_vkCmdDebugMarkerEndEXT)_Device.getProcAddr("vkCmdDebugMarkerEndEXT");
}
}
void Device::Clean()
{
//_Device.destroy();
}
std::set<uint32_t> Device::GetQueueIndexSet()
{
std::set<uint32_t> uniqueQueueId;
for (const auto &queue : _Queues)
{
uniqueQueueId.insert(queue.second.Index);
}
return uniqueQueueId;
}
const bool Device::IsSuitable(const DeviceRequestInfo& info, optional_surface surface) const
{
// Check that we got all the required extensions
for (const auto& extensionName : info.RequiredExtensions) {
auto it = std::find_if(
_DeviceExtensions.begin(),
_DeviceExtensions.end(),
[&extensionName](const vk::ExtensionProperties& availableExtenion) {
return std::strcmp(availableExtenion.extensionName, extensionName) == 0;
}
);
if (it == _DeviceExtensions.end()) {
return false;
}
}
// Check that we have at least a queue
if (_QueueFamilyProperties.size() == 0) {
return false;
}
// Check the queues for the required setup
bool havePresentation = !info.SupportPresentation;
bool haveGraphics = !info.SupportGraphics;
uint32_t i = 0;
for (const auto &queueFamily : _QueueFamilyProperties) {
if (info.SupportPresentation && surface.has_value()) {
vk::Bool32 presentSupport = _PhysicalDevice.getSurfaceSupportKHR(i, surface.value());
if (presentSupport) {
havePresentation = true;
}
}
if (info.SupportGraphics) {
if (queueFamily.queueFlags & vk::QueueFlagBits::eGraphics) {
haveGraphics = true;
}
}
++i;
}
return havePresentation && haveGraphics;
}
void Device::StartMarker(const vk::CommandBuffer & cmdBuffer, const std::string & name)
{
if (_SupportDebugMarkers) {
VkDebugMarkerMarkerInfoEXT markerInfo = {};
markerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT;
float color[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
memcpy(markerInfo.color, &color[0], sizeof(float) * 4);
markerInfo.pMarkerName = name.c_str();
pfnCmdDebugMarkerBegin(VkCommandBuffer(cmdBuffer), &markerInfo);
}
}
void Device::EndMarker(const vk::CommandBuffer & cmdBuffer)
{
if (_SupportDebugMarkers) {
pfnCmdDebugMarkerEnd(VkCommandBuffer(cmdBuffer));
}
}
void Device::PickQueueFamilyIndex(const DeviceRequestInfo& info, optional_surface surface)
{
// Look for a queue with present if we need one
uint32_t i = 0;
if (info.SupportPresentation && surface.has_value()) {
for (const auto &queueFamily : _QueueFamilyProperties) {
vk::Bool32 presentSupport = _PhysicalDevice.getSurfaceSupportKHR(i, surface.value());
if (presentSupport) {
Queue present = { i };
_Queues.emplace(PRESENT, present);
break;
}
}
}
// Look for a queue sith graphics if we need one
i = 0;
if (info.SupportGraphics) {
for (const auto &queueFamily : _QueueFamilyProperties) {
if (queueFamily.queueFlags & vk::QueueFlagBits::eGraphics) {
Queue present = { i };
_Queues.emplace(GRAPHICS, present);
break;
}
}
++i;
}
}
Device Device::GetDevice(const vk::Instance &instance, const DeviceRequestInfo& info, optional_surface surface)
{
uint32_t deviceCount = 0;
std::vector<vk::PhysicalDevice> physicalDeviceList;
physicalDeviceList = instance.enumeratePhysicalDevices();
std::vector<Device> deviceList;
for (const auto& physicalDevice : physicalDeviceList) {
Device device(physicalDevice);
if (device.IsSuitable(info, surface)) {
deviceList.push_back(device);
}
}
if (deviceList.size() == 0) {
throw std::runtime_error("No suitable GPU detected");
}
return deviceList.front();
}
<file_sep>#pragma once
#include <string>
#include <memory>
#include <GLFW\glfw3.h>
#include "Engine/Camera.h"
#include "Engine/Scene.h"
#include "Renderer/Renderer.h"
#include "Engine/Lib.h"
#include "Engine/Package.h"
class EXPORT Application {
public:
Application(const std::string &appName);
virtual void Init();
void Run();
void Clean();
void TriggerShaderReload();
void TriggerResize(const int width, const int height);
static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
static void MouseCallback(GLFWwindow* window, int button, int action, int mods);
static void ResizeCallback(GLFWwindow* window, int width, int height);
static void MinimizeCallback(GLFWwindow* window, int iconified);
bool broadcastCursor = true;
protected:
void DrawFrame();
const uint16_t _Width = 1024;
const uint16_t _Height = 768;
std::string _ApplicationName;
GLFWwindow* Window;
Renderer render;
enum KEY_BINDINGS {
UP = GLFW_KEY_W,
LEFT = GLFW_KEY_A,
DOWN = GLFW_KEY_S,
RIGHT = GLFW_KEY_D,
RELOAD = GLFW_KEY_R
};
Camera *_Camera;
Scene _Scene;
double horizontalAngle;
double verticalAngle;
bool shaderReaload;
bool _PauseRender = false;
std::vector<Package> _Packages;
};<file_sep># Shutter
Toy 3D renderer in Vulkan
# Current limitations
Only runs on windows.
<file_sep>#include "Shadow.h"
#include "Mesh.h"
#include "Helpers.h"
void Shadow::CreateDepthStencilInfo()
{
_DepthStencilInfo = vk::PipelineDepthStencilStateCreateInfo(
{},
true,
true,
vk::CompareOp::eLess,
false,
false
);
}<file_sep>#pragma once
#include <map>
#include <memory>
#include <vector>
#include <vulkan/vulkan.hpp>
#include "Renderer/Mesh.h"
#include "Texture.h"
#include "Renderer/Material.h"
#include "Engine/SceneObject.h"
class Object : public SceneObject {
public:
Object(){}
explicit Object(Device *device, const Mesh &mesh, Material *material, const uint32_t nbImages);
void AddTexture(const uint32_t binding, std::shared_ptr<Texture> texture);
void CreateDescriptorSet();
Material *GetMaterial() {
return _Material;
}
const vk::DescriptorSet &GetDescriptorSet(const uint32_t id) const {
return _DescriptorSets.at(id);
}
virtual const glm::mat4 &GetModelMatrix() override;
const BoundingBox GetBoundingBox();
glm::vec3 &Rotation();
glm::vec3 &Scale();
private:
Material *_Material;
public:
Mesh _Mesh;
uint32_t _DynamicIndex;
// Used to store push constants, only vec3 is available
std::vector<glm::vec3> _PushConstants;
static Buffer DynamicBuffer;
static uint32_t dynamicAlignement;
static struct UboDynamic {
glm::mat4 *model = nullptr;
} uboDynamic;
bool isSelected = false;
private:
BoundingBox _CachedBoundingBox;
glm::vec3 _Rotation;
glm::vec3 _Scale;
Device *_Device;
uint32_t _NbImages;
// Map containing the relation between a texture and its binding
std::map<uint32_t, std::shared_ptr<Texture>> _Textures;
std::vector<vk::DescriptorSet> _DescriptorSets;
};<file_sep>#pragma once
#include "vulkan/DeviceHandler.h"
#include "vulkan/Buffer.h"
class GlobalDescriptor {
public:
GlobalDescriptor(Device *device, const uint32_t nbImages) : _Device(device)
{
CreateDescriptorSets(nbImages);
CreateDescriptorSetLayout(nbImages);
}
void CreateDescriptorSets(const uint32_t nbImages);
void CreateDescriptorSetLayout(const uint32_t nbImages);
const Buffer &GetDataBuffer(const uint32_t image) const {
return _SceneDataBuffers[image];
}
vk::DescriptorSetLayout _DescriptorSetLayout;
std::vector<vk::DescriptorSet> _SceneDescriptorSets;
private:
Device *_Device;
vk::DescriptorPool _DescriptorPool;
std::vector<Buffer> _SceneDataBuffers;
};<file_sep>#include "Object.h"
#include <glm/gtc/matrix_transform.hpp>
#include "Renderer/Helpers.h"
Object::Object(Device *device, const Mesh &mesh, Material *material, const uint32_t nbImages) :
SceneObject("object"),
_Device(device),
_Mesh(mesh),
_Material(material),
_NbImages(nbImages)
{
}
void Object::AddTexture(const uint32_t binding, std::shared_ptr<Texture> texture)
{
_Textures.emplace(binding, texture);
}
void Object::CreateDescriptorSet()
{
std::vector<vk::DescriptorSetLayout> layouts(_NbImages, _Material->GetDescriptorSetLayout());
_DescriptorSets = _Device->GetDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(
_Material->GetDescriptorPool(),
_NbImages,
layouts.data()
));
size_t i = 0;
for (const auto &descSet : _DescriptorSets) {
std::vector<vk::WriteDescriptorSet> descriptorWrites;
// Model Matrix
descriptorWrites.push_back(vk::WriteDescriptorSet(
descSet,
0,
0,
1,
vk::DescriptorType::eUniformBufferDynamic,
nullptr,
&vk::DescriptorBufferInfo(
DynamicBuffer.GetBuffer(),
0,
sizeof(uboDynamic)
),
nullptr
));
std::vector<vk::DescriptorImageInfo> textureDescriptors;
textureDescriptors.resize(_Textures.size());
size_t j = 0;
for (const auto &texture : _Textures) {
textureDescriptors.at(j) = vk::DescriptorImageInfo(
texture.second->GetSampler()._Sampler,
texture.second->GetImage().GetImageView(),
vk::ImageLayout::eShaderReadOnlyOptimal
);
descriptorWrites.push_back(vk::WriteDescriptorSet(
descSet,
texture.first,
0,
1,
vk::DescriptorType::eCombinedImageSampler,
&textureDescriptors.at(j),
nullptr,
nullptr
));
++j;
}
_Device->GetDevice().updateDescriptorSets(descriptorWrites, {});
i++;
}
}
const glm::mat4 &Object::GetModelMatrix()
{
if (_IsModelDirty) {
glm::mat4 temp = glm::mat4(1.0f);
// If we haver a prant get its model matrix
if (auto parent = _Parent.lock()) {
temp = parent->GetModelMatrix();
}
_CachedModelMatrix = glm::translate(temp, _Position);
//_CachedModelMatrix = glm::rotate(_CachedModelMatrix, glm::radians(_Rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
//_CachedModelMatrix = glm::rotate(_CachedModelMatrix, glm::radians(_Rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
//_CachedModelMatrix = glm::rotate(_CachedModelMatrix, glm::radians(_Rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
_CachedModelMatrix = glm::scale(_CachedModelMatrix, _Scale);
// Apply the translation
_CachedBoundingBox._Min = glm::vec3(_CachedModelMatrix[3].x, _CachedModelMatrix[3].y, _CachedModelMatrix[3].z);
_CachedBoundingBox._Max = glm::vec3(_CachedModelMatrix[3].x, _CachedModelMatrix[3].y, _CachedModelMatrix[3].z);
for (size_t i = 0; i < 8; ++i)
{
glm::vec4 temp = _CachedModelMatrix * glm::vec4(_Mesh.vertices[i], 1.0);
// Compute bounding box max point
_CachedBoundingBox._Max.x = std::max(_CachedBoundingBox._Max.x, temp.x);
_CachedBoundingBox._Max.y = std::max(_CachedBoundingBox._Max.y, temp.y);
_CachedBoundingBox._Max.z = std::max(_CachedBoundingBox._Max.z, temp.z);
// Compute bounding box min point
_CachedBoundingBox._Min.x = std::min(_CachedBoundingBox._Min.x, temp.x);
_CachedBoundingBox._Min.y = std::min(_CachedBoundingBox._Min.y, temp.y);
_CachedBoundingBox._Min.z = std::min(_CachedBoundingBox._Min.z, temp.z);
}
_IsModelDirty = false;
}
return _CachedModelMatrix;
}
const BoundingBox Object::GetBoundingBox()
{
return _CachedBoundingBox;
}
glm::vec3 &Object::Rotation()
{
SetModelDirty();
return _Rotation;
}
glm::vec3 &Object::Scale()
{
SetModelDirty();
return _Scale;
}
Buffer Object::DynamicBuffer = Buffer();
uint32_t Object::dynamicAlignement = 0;
Object::UboDynamic Object::uboDynamic = {};<file_sep>#include "Cubemap.h"
#include "Mesh.h"
#include "Helpers.h"
void Cubemap::CreateRasterizationInfo()
{
_RasterizationInfo = vk::PipelineRasterizationStateCreateInfo(
{},
false,
false,
vk::PolygonMode::eFill,
vk::CullModeFlagBits::eFront,
vk::FrontFace::eCounterClockwise,
false,
0,
0,
0,
1.0
);
}
<file_sep>#pragma once
#include <string>
#include <memory>
#include <assert.h>
#include "Renderer/vulkan/Image.h"
#include "Renderer/vulkan/Buffer.h"
#include "Renderer/vulkan/Sampler.h"
class Texture {
public:
explicit Texture(const std::string &filename, const bool generateMips = false);
Texture(Texture const&) = delete;
Texture& operator=(Texture const&) = delete;
~Texture();
// Create the GPU object and upload to it
virtual void CreateAndUpload(Device *device, const vk::CommandPool &cmdPool);
virtual const char *GetFilename() const noexcept { return _Filename.c_str(); }
const glm::ivec3 &GetDimensions() const noexcept { return _Dimensions; }
const Image &GetImage() const noexcept { return _Image; }
const Sampler &GetSampler() const noexcept { return *_Sampler; }
const bool _MipMapping = false;
protected:
Texture() = default;
glm::ivec3 _Dimensions = glm::vec3(0, 0, 1);
public:
Image _Image;
std::shared_ptr<Sampler> _Sampler;
private:
std::string _Filename = "";
// This is a temporary buffer that will be deleted as soon as the image is in GPU memory
unsigned char *_ImageBuffer;
};
<file_sep>#include "Sampler.h"
Sampler::Sampler(Device * device, const SamplerInfo &info) :
_Device(device),
_SamplerInfo(info)
{
vk::SamplerCreateInfo samplerInfo = {};
samplerInfo.magFilter = vk::Filter::eLinear;
samplerInfo.minFilter = vk::Filter::eLinear;
samplerInfo.addressModeU = static_cast<vk::SamplerAddressMode>(info._SamplerU);
samplerInfo.addressModeV = static_cast<vk::SamplerAddressMode>(info._SamplerV);
samplerInfo.addressModeW = static_cast<vk::SamplerAddressMode>(info._SamplerW);
samplerInfo.anisotropyEnable = false;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = vk::BorderColor::eFloatOpaqueBlack;
samplerInfo.unnormalizedCoordinates = false;
samplerInfo.compareEnable = false;
samplerInfo.compareOp = vk::CompareOp::eAlways;
samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = static_cast<float>(info._LOD);
_Sampler = _Device->GetDevice().createSampler(samplerInfo);
}
Sampler::~Sampler()
{
_Device->GetDevice().destroySampler(_Sampler);
}
std::shared_ptr<Sampler> SamplerCache::Get(Device *device, const SamplerInfo &info)
{
// Scan the cache for a matching sampler candidate
for (const auto &s : _Cache) {
if (s.lock()->_SamplerInfo == info) {
return s.lock();
}
}
// If none found we just create a new one
std::shared_ptr<Sampler> temp = std::make_shared<Sampler>(device, info);
_Cache.push_back(temp);
return temp;
}
const bool SamplerInfo::operator==(const SamplerInfo & si) const
{
return _SamplerU == si._SamplerU &&
_SamplerV == si._SamplerV &&
_SamplerW == si._SamplerW &&
_LOD == si._LOD;
}
<file_sep>#include "Camera.h"
#include <glm/gtc/matrix_transform.hpp>
Camera::Camera(const std::string &name, const float fov, const uint16_t width, const uint16_t height, const glm::vec3 & position, const glm::vec3 direction, const glm::vec3 up) :
SceneObject(name, position),
_FOV(fov),
_Width(width),
_Height(height),
_Front(direction),
_Up(up)
{
_Right = glm::cross(_Front, _Up);
_TranslationSpeed = 0.13f;
_RotationSpeed = 0.01f;
_HorizontalAngle = 0.f;
_VerticalAngle = 0.f;
_Frustrum.GenerateFrustrum(*this);
}
void Camera::Update(const double mouseX, const double mouseY, const Direction &dir)
{
_HorizontalAngle += _RotationSpeed * mouseX;
_VerticalAngle += _RotationSpeed * mouseY;
glm::vec3 direction(
cos(_VerticalAngle) * cos(_HorizontalAngle),
sin(_VerticalAngle),
cos(_VerticalAngle) * sin(_HorizontalAngle)
);
_Right = glm::vec3(
cos(_HorizontalAngle - 3.14f / 2.0f),
0,
sin(_HorizontalAngle - 3.14f / 2.0f)
);
_Up = glm::cross(_Right, direction);
_Front = glm::normalize(direction);
glm::vec3 movement = { 0.0f, 0.0f, 0.0f };
if (dir.Up) {
movement = _Front * _TranslationSpeed;
}
else if (dir.Down) {
movement = _Front * -_TranslationSpeed;
}
if (dir.Left) {
movement += _Right * -_TranslationSpeed;
}
else if (dir.Right) {
movement += _Right * _TranslationSpeed;
}
_Position += movement;
_Frustrum.GenerateFrustrum(*this);
}
CameraUniformData Camera::GetUniformData()
{
CameraUniformData data;
data._Position = glm::vec4(_Position, 0.0);
data._Projection = GetProjection();
data._View = GetView();
return data;
}
glm::mat4 Camera::GetProjection() const
{
glm::mat4 proj = glm::perspective(glm::radians(_FOV), float(_Width) / float(_Height), _Near, _Far);
proj[1][1] *= -1;
return proj;
}
glm::mat4 Camera::GetView() const
{
return glm::lookAt(_Position, _Position + _Front, _Up);
}
OrthographicCamera::OrthographicCamera(const std::string & name, const glm::vec4 & ortho, const glm::vec3 & position, const glm::vec3 direction, const glm::vec3 up) :
SceneObject(name, position),
_Ortho(ortho),
_Front(direction),
_Up(up)
{
}
CameraUniformData OrthographicCamera::GetUniformData()
{
CameraUniformData data;
data._Position = glm::vec4(_Position, 0.0);
data._Projection = GetProjection();
data._View = GetView();
return data;
}
glm::mat4 OrthographicCamera::GetProjection() const
{
glm::mat4 proj = glm::ortho(_Ortho.x, _Ortho.y, _Ortho.z, _Ortho.w, 0.01f, 85.0f);
//proj[1][1] *= -1;
return proj;
}
glm::mat4 OrthographicCamera::GetView() const
{
return glm::lookAt(_Position, _Position + _Front, _Up);
}
<file_sep>#include "GlobalDescriptor.h"
#include "Engine/Scene.h"
void GlobalDescriptor::CreateDescriptorSets(const uint32_t nbImages)
{
CreateDescriptorSetLayout(nbImages);
std::vector<vk::DescriptorSetLayout> layouts(nbImages, _DescriptorSetLayout);
_SceneDescriptorSets = _Device->GetDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(
_DescriptorPool,
nbImages,
layouts.data()
));
_SceneDescriptorSets.resize(nbImages);
_SceneDataBuffers.resize(nbImages);
for (size_t i = 0; i < nbImages; ++i)
{
_SceneDataBuffers.at(i) = Buffer(_Device, vk::BufferUsageFlagBits::eUniformBuffer, sizeof(SceneDataObject::Data) * DATA_BUFFER_SIZE);
vk::WriteDescriptorSet cameraDescriptor(
_SceneDescriptorSets.at(i),
0, 0, 1,
vk::DescriptorType::eUniformBuffer,
nullptr,
&vk::DescriptorBufferInfo(
_SceneDataBuffers[i].GetBuffer(),
0,
sizeof(CameraUniformData)
)
);
vk::WriteDescriptorSet shadowCameraDescriptor(
_SceneDescriptorSets.at(i),
1, 0, 1,
vk::DescriptorType::eUniformBuffer,
nullptr,
&vk::DescriptorBufferInfo(
_SceneDataBuffers[i].GetBuffer(),
alignof(SceneDataObject::Data),
sizeof(CameraUniformData)
)
);
vk::WriteDescriptorSet lightDescriptor(
_SceneDescriptorSets.at(i),
2, 0, 1,
vk::DescriptorType::eUniformBuffer,
nullptr,
&vk::DescriptorBufferInfo{
_SceneDataBuffers.at(i).GetBuffer(),
alignof(SceneDataObject::Data) * 2,
sizeof(LightUniformData)
}
);
vk::WriteDescriptorSet lightNumDescriptor(
_SceneDescriptorSets.at(i),
3, 0, 1,
vk::DescriptorType::eUniformBuffer,
nullptr,
&vk::DescriptorBufferInfo(
_SceneDataBuffers[i].GetBuffer(),
alignof(SceneDataObject::Data) * 3,
sizeof(uint32_t)
)
);
_Device->GetDevice().updateDescriptorSets({ cameraDescriptor, shadowCameraDescriptor, lightDescriptor, lightNumDescriptor }, nullptr);
}
}
void GlobalDescriptor::CreateDescriptorSetLayout(const uint32_t nbImages)
{
vk::DescriptorSetLayoutBinding cameraInfo(0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutBinding shadowCameraInfo(1, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutBinding lightInfo(2, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutBinding lightNumInfo(3, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment);
std::vector<vk::DescriptorSetLayoutBinding> bindings{ cameraInfo, shadowCameraInfo, lightInfo, lightNumInfo };
_DescriptorSetLayout = _Device->GetDevice().createDescriptorSetLayout(
vk::DescriptorSetLayoutCreateInfo(
{},
bindings.size(),
bindings.data()
)
);
std::vector<vk::DescriptorPoolSize> poolSizes;
poolSizes.resize(bindings.size());
for (size_t i = 0; i < bindings.size(); ++i) {
poolSizes[i].type = bindings[i].descriptorType;
poolSizes[i].descriptorCount = nbImages;
}
_DescriptorPool = _Device->GetDevice().createDescriptorPool(vk::DescriptorPoolCreateInfo({}, nbImages, poolSizes.size(), poolSizes.data()));
}
<file_sep>#pragma once
#include <vector>
#include <memory>
#include <vulkan/vulkan.hpp>
#include "DeviceHandler.h"
#include "Engine/Singleton.h"
enum SamplerAddressMode
{
REPEAT = vk::SamplerAddressMode::eRepeat,
MIRRORED_REPEAT = vk::SamplerAddressMode::eMirroredRepeat,
CLAMP_TO_EDGE = vk::SamplerAddressMode::eClampToEdge,
CLAMP_TO_BORDER = vk::SamplerAddressMode::eClampToBorder,
MIRROR_CLAMP_TO_EDGE = vk::SamplerAddressMode::eMirrorClampToEdge
};
class SamplerInfo {
public:
const bool operator==(const SamplerInfo& si) const;
SamplerAddressMode _SamplerU;
SamplerAddressMode _SamplerV;
SamplerAddressMode _SamplerW;
uint32_t _LOD;
};
class Sampler {
public:
Sampler() = delete;
Sampler(const Sampler&) = delete;
Sampler& operator= (const Sampler&) = delete;
explicit Sampler(Device *device, const SamplerInfo &info);
~Sampler();
vk::Sampler _Sampler;
const SamplerInfo _SamplerInfo;
private:
Device *_Device = nullptr;
};
class SamplerCache : public Singleton<SamplerCache> {
public:
std::shared_ptr<Sampler> Get(Device *device, const SamplerInfo &info);
private:
std::vector<std::weak_ptr<Sampler>> _Cache;
};
<file_sep>#pragma once
#include <array>
#include "Texture.h"
#include "Renderer/vulkan/Sampler.h"
class LiveTexture : public Texture {
public:
explicit LiveTexture(Device *device, Image image){
_Image = image;
_Sampler = SamplerCache::GetInstance()->Get(device, SamplerInfo{ REPEAT, REPEAT, REPEAT, _Image.GetMipLevel() });
}
LiveTexture() = delete;
LiveTexture(LiveTexture const&) = delete;
LiveTexture& operator=(LiveTexture const&) = delete;
~LiveTexture() = default;
virtual const char *GetFilename() const noexcept override { return "live"; }
virtual void CreateAndUpload(Device *device, const vk::CommandPool &cmdPool) override {}
};
<file_sep>#include "Extensions.h"
#include <vulkan/vulkan.h>
#include <algorithm>
void Extension::Init(const ExtensionRequestInfo& info)
{
uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
AvailableExtensions.resize(extensionCount);
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, AvailableExtensions.data());
// Check the required, missing one will throw an exception
for (const auto& extensionName : info.RequiredExtensions) {
if (!CheckExtension(extensionName)) {
throw std::runtime_error("Required extension " + std::string(extensionName) + " is unavailable.");
}
EnabledExtensions.push_back(extensionName);
}
// Check the optional, missing one will add it to the disabled
for (const auto& extensionName : info.OptionalExtensions) {
if (!CheckExtension(extensionName)) {
DisabledExtensions.push_back(extensionName);
}
EnabledExtensions.push_back(extensionName);
}
}
const tExtensionNameList& Extension::GetEnabledExtensions() const
{
return EnabledExtensions;
}
const tExtensionNameList& Extension::GetDisabledExtensions() const
{
return DisabledExtensions;
}
bool Extension::CheckExtension(const tExtensionName & extensionName)
{
auto it = std::find_if(
AvailableExtensions.begin(),
AvailableExtensions.end(),
[&extensionName](const VkExtensionProperties& availableExtenion) {
return std::strcmp(availableExtenion.extensionName, extensionName) == 0;
}
);
return it != AvailableExtensions.end();
}
<file_sep>#include "RenderPass.h"
<file_sep>#include "DepthOnly.h"
void DepthOnly::CreateColorBlendInfo()
{
_ColorBlendAttachement = vk::PipelineColorBlendAttachmentState(
false
);
}
void DepthOnly::CreateDepthStencilInfo()
{
_DepthStencilInfo = vk::PipelineDepthStencilStateCreateInfo(
{},
true,
true,
vk::CompareOp::eLess,
false,
false
);
}<file_sep>#include "Frustrum.h"
#include "Camera.h"
#include "ResourceManager.h"
#include "Object.h"
#include "Scene.h"
#include <iostream>
void Frustrum::GenerateFrustrum(const Camera &camera)
{
/*
Far plane: Near plane:
f1 ---- f2 n1 ---- n2
| | | |
| | | |
f4 ---- f3 n4 ---- n3
*/
glm::vec3 nearCenter = camera.Position() + (camera._Front * camera._Near);
glm::vec3 farCenter = camera.Position() + (camera._Front * camera._Far);
float nearHalfWidth = std::atanf(camera._FOV / 2.0f) * camera._Near;
glm::vec3 nearHalfWidthVector = nearHalfWidth * camera._Right;
float farHalfWidth = std::atanf(camera._FOV / 2.0f) * camera._Far;
glm::vec3 farHalfWidthVector = farHalfWidth * camera._Right;
float ratio = static_cast<float>(camera._Height) / static_cast<float>(camera._Width);
float nearHalfHeight = nearHalfWidth * ratio;
glm::vec3 nearHalfHeightVector = nearHalfHeight * camera._Up;
float farHalfHeight = farHalfWidth * ratio;
glm::vec3 farHalfHeightVector = farHalfHeight * camera._Up;
glm::vec3 f1, f2, f3, f4, n1, n2, n3, n4;
n1 = nearCenter + nearHalfHeightVector - nearHalfWidthVector;
n2 = nearCenter + nearHalfHeightVector + nearHalfWidthVector;
n3 = nearCenter - nearHalfHeightVector + nearHalfWidthVector;
n4 = nearCenter - nearHalfHeightVector - nearHalfWidthVector;
f1 = farCenter + farHalfHeightVector - farHalfWidthVector;
f2 = farCenter + farHalfHeightVector + farHalfWidthVector;
f3 = farCenter - farHalfHeightVector + farHalfWidthVector;
f4 = farCenter - farHalfHeightVector - farHalfWidthVector;
Plane front{ n4, n3, n2, n1 };
Plane left{ n1, f1, f4, n4 };
Plane top{ n1, n2, f2, f1 };
Plane right{ n3, f3, f2, n2 };
Plane bottom{ n4, f4, f3, n3 };
Plane back{ f1, f2, f3, f4 };
_FrustrumPlanes = { front, left, top, right, bottom, back };
for (uint8_t i = 0; i < 6; ++i) {
_FrustrumPlaneNormals[i] = glm::cross((_FrustrumPlanes[i][0] - _FrustrumPlanes[i][1]), (_FrustrumPlanes[i][2] - _FrustrumPlanes[i][1]));
_FrustrumPlaneNormals[i] = glm::normalize(_FrustrumPlaneNormals[i]);
_FrustrumPlanesD[i] = -(_FrustrumPlaneNormals[i].x * _FrustrumPlanes[i][1].x + _FrustrumPlaneNormals[i].y * _FrustrumPlanes[i][1].y + _FrustrumPlaneNormals[i].z * _FrustrumPlanes[i][1].z);
}
}
bool Frustrum::TestFrustrum(const BoundingBox bbox)
{
uint8_t isIn = 0;
for (uint8_t i = 0; i < 6; ++i) {
bool isOut = false;
glm::vec3 &normal = _FrustrumPlaneNormals[i];
float d = _FrustrumPlanesD[i];
glm::vec3 p = bbox._Min;
if (normal.x >= 0) {
p.x = bbox._Max.x;
}
if (normal.y >= 0) {
p.y = bbox._Max.y;
}
if (normal.z >= 0) {
p.z = bbox._Max.z;
}
if (d + (normal.x * p.x + normal.y * p.y + normal.z * p.z) < 0) {
return false;
}
}
return true;
}
void Frustrum::CreateMesh(Device *device, Scene &scene, const vk::CommandPool &cmdPool)
{
// Frustrum object
Mesh debug;
for (const auto &plane : _FrustrumPlanes) {
debug._Vertices.push_back(Vertex{ plane[0] });
debug._Vertices.push_back(Vertex{ plane[1] });
debug._Vertices.push_back(Vertex{ plane[2] });
debug._Vertices.push_back(Vertex{ plane[0] });
debug._Vertices.push_back(Vertex{ plane[2] });
debug._Vertices.push_back(Vertex{ plane[3] });
}
debug.Upload(device, cmdPool);
_DebugObject = std::make_shared<Object>(device, debug, ResourceManager::GetInstance()->_Materials.at("unlit-wireframe").lock().get(), 2);
_DebugObject->Position() = glm::vec3(0.0, 0.0, 0.0);
_DebugObject->Rotation() = glm::vec3(0.0, 0.0, 0.0);
_DebugObject->Scale() = glm::vec3(1.0, 1.0, 1.0);
_DebugObject->_DynamicIndex = scene.AddToDynamic(*_DebugObject);
_DebugObject->CreateDescriptorSet();
_DebugObject->_Name = "Frustrum";
scene._Objects[ResourceManager::GetInstance()->_Materials.at("unlit-wireframe").lock()].push_back(_DebugObject);
}
<file_sep>#pragma once
#include <unordered_map>
#include <string>
#include "Singleton.h"
class Texture;
class Mesh;
class Material;
class Shader;
// Central holding place for resources, spanning over multiple packages
class ResourceManager : public Singleton<ResourceManager> {
public:
std::unordered_map<std::string, std::weak_ptr<Texture>> _Textures;
std::unordered_map<std::string, std::weak_ptr<Mesh>> _Meshes;
std::unordered_map<std::string, std::weak_ptr<Shader>> _Shaders;
std::unordered_map<std::string, std::weak_ptr<Material>> _Materials;
};<file_sep>#include "RenderPass.h"
#include "Renderer/GlobalDescriptor.h"
#include "Engine/ResourceManager.h"
#include "Engine/Scene.h"
void ShadowPass::Init(const vk::CommandPool &commandPool) {
_CommandBuffers = _Device->GetDevice().allocateCommandBuffers(vk::CommandBufferAllocateInfo(commandPool, vk::CommandBufferLevel::ePrimary, 1));
CreateImage(commandPool);
CreateRenderPass();
CreateFramebuffer();
_OUT_SEM_Shadow = _Device->GetDevice().createSemaphore({});
}
void ShadowPass::InitShader(const GlobalDescriptor & globalDescriptor)
{
// Create the depth only pipeline
std::shared_ptr<Shader> vertexShader = std::make_shared<Shader>("shadow.vert.spv", "Shutter-Data/engine/shaders/shadow.vert.spv", vk::ShaderStageFlagBits::eVertex);
std::shared_ptr<Shader> fragmentShader = std::make_shared<Shader>("empty.frag.spv", "Shutter-Data/engine/shaders/empty.frag.spv", vk::ShaderStageFlagBits::eFragment);
_ShadowMaterial.BindShader(vertexShader);
_ShadowMaterial.BindShader(fragmentShader);
vertexShader->Load(_Device);
fragmentShader->Load(_Device);
_ShadowMaterial.Load(_Device, globalDescriptor, _Dimension.width, _Dimension.height, 2048);
_ShadowMaterial.CreatePipeline(_RenderPass);
}
void ShadowPass::CreateCommandBuffers(const uint8_t frame, GlobalDescriptor *globalDescriptor, Scene *scene) {
_CommandBuffers[frame].begin({ vk::CommandBufferUsageFlagBits::eSimultaneousUse });
_Device->StartMarker(_CommandBuffers[frame], "Shadow Pass");
_OUT_Shadow->TransitionLayout(_CommandBuffers[0], vk::ImageLayout::eDepthStencilAttachmentOptimal);
std::array<vk::ClearValue, 1> clearValues;
clearValues[0] = vk::ClearDepthStencilValue(1.0f, 0);
_CommandBuffers[0].beginRenderPass(
vk::RenderPassBeginInfo(
_RenderPass,
_Framebuffer,
{ {0, 0}, _Dimension },
clearValues.size(),
clearValues.data()
),
vk::SubpassContents::eInline
);
_CommandBuffers[0].bindDescriptorSets(
vk::PipelineBindPoint::eGraphics,
_ShadowMaterial.GetPipelineLayout(),
0,
{
globalDescriptor->_SceneDescriptorSets.at(frame)
},
{}
);
_Drawcalls = 0;
_CommandBuffers[0].bindPipeline(vk::PipelineBindPoint::eGraphics, _ShadowMaterial.GetPipeline());
// Render all non transparent objects
for (const auto &mat : scene->_Objects) {
if (mat.first->_CastShadow && mat.second.size() > 0) {
_Device->StartMarker(_CommandBuffers[0], mat.first->_Name);
for (const auto &object : mat.second) {
_CommandBuffers[0].bindVertexBuffers(0, { object->_Mesh._VertexBuffer.GetBuffer() }, { 0 });
_CommandBuffers[0].bindDescriptorSets(
vk::PipelineBindPoint::eGraphics,
mat.first->GetPipelineLayout(),
0,
{
globalDescriptor->_SceneDescriptorSets.at(0),
object->GetDescriptorSet(0)
},
{ object->_DynamicIndex * static_cast<uint32_t>(Object::dynamicAlignement) }
);
_Drawcalls++;
_CommandBuffers[0].draw(object->_Mesh._Vertices.size(), 1, 0, 0);
}
_Device->EndMarker(_CommandBuffers[0]);
}
}
_CommandBuffers[frame].endRenderPass();
_OUT_Shadow->TransitionLayout(_CommandBuffers[0], vk::ImageLayout::eDepthStencilReadOnlyOptimal);
_Device->EndMarker(_CommandBuffers[frame]);
_CommandBuffers[frame].end();
}
void ShadowPass::Render(const size_t currentFrame, vk::Semaphore *semaphore, const uint32_t imageIndex) {
_Device->GetQueue(E_QUEUE_TYPE::GRAPHICS).VulkanQueue.submit(
{
vk::SubmitInfo(
1,
semaphore,
&vk::PipelineStageFlags(vk::PipelineStageFlagBits::eAllCommands),
1,
&_CommandBuffers[0],
1,
&_OUT_SEM_Shadow
)
},
{}
);
}
void ShadowPass::Resize(const vk::Extent2D & dimension)
{
_Dimension = dimension;
_OUT_Shadow->Resize(_Dimension);
_Device->GetDevice().destroyFramebuffer(_Framebuffer);
CreateFramebuffer();
_ShadowMaterial.ReloadPipeline(_RenderPass, _Dimension.width, _Dimension.height);
}
void ShadowPass::CreateImage(const vk::CommandPool &commandPool) {
_OUT_Shadow = std::make_shared<Image>(
_Device,
VkExtent3D{ _Dimension.width, _Dimension.height, 1 },
1,
vk::Format::eD32Sfloat,
vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eSampled,
false,
vk::SampleCountFlagBits::e1
);
_OUT_Shadow->TransitionLayout(commandPool, vk::ImageLayout::eUndefined, vk::ImageLayout::eDepthStencilAttachmentOptimal);
_OUT_ShadowTexture = std::make_shared<LiveTexture>(_Device, *_OUT_Shadow);
}
void ShadowPass::CreateRenderPass()
{
vk::AttachmentDescription depthAttachement(
{},
_OUT_Shadow->GetFormat(),
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eClear,
vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eDepthStencilAttachmentOptimal
);
vk::AttachmentReference depthAttachementReference(
0,
vk::ImageLayout::eDepthStencilAttachmentOptimal
);
std::array<vk::AttachmentDescription, 1> attachements{
depthAttachement
};
vk::SubpassDescription subpass(
{},
vk::PipelineBindPoint::eGraphics,
0,
{},
0,
nullptr,
nullptr,
&depthAttachementReference
);
_RenderPass = _Device->GetDevice().createRenderPass(vk::RenderPassCreateInfo(
{},
attachements.size(),
attachements.data(),
1,
&subpass,
1,
&vk::SubpassDependency(
VK_SUBPASS_EXTERNAL,
0,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
{},
vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite
)
));
}
void ShadowPass::CreateFramebuffer()
{
std::array<vk::ImageView, 1> attachments = {
_OUT_Shadow->GetImageView(),
};
_Framebuffer = _Device->GetDevice().createFramebuffer(vk::FramebufferCreateInfo(
{},
_RenderPass,
attachments.size(),
attachments.data(),
_Dimension.width,
_Dimension.height,
1
));
}
<file_sep>#include "Renderer.h"
#include <array>
#include <limits>
#include <algorithm>
#include <iterator>
#include <glm/glm.hpp>
#include "Helpers.h"
#include "Engine/ResourceManager.h"
void Renderer::Init(const std::string &name, GLFWwindow* window, Scene *scene)
{
_Window = window;
_Scene = scene;
CreateInstance(name);
_Surface = std::make_shared<Surface>(&_Device, &_Instance, window);
CreateDevice();
_Surface->CreateSwapChain();
_GlobalDescriptor = std::make_unique<GlobalDescriptor>(&_Device, _Surface->_NbImages);
CreateCommandPool();
_ShadowPass = std::make_shared<ShadowPass>(&_Device);
_ShadowPass->_Dimension = vk::Extent2D(2048, 2048);
_ShadowPass->Init(_CommandPool);
_ShadowPass->InitShader(*_GlobalDescriptor);
_DepthPrePass = std::make_shared<DepthPrePass>(&_Device);
_DepthPrePass->_Dimension = _Surface->GetWindowDimensions();
_DepthPrePass->Init(_CommandPool);
_DepthPrePass->InitShader(*_GlobalDescriptor);
_ColorPass = std::make_shared<ColorPass>(&_Device);
_ColorPass->_IN_Depth = _DepthPrePass->_OUT_Depth;
_ColorPass->_Dimension = _Surface->GetWindowDimensions();
_ColorPass->Init(_CommandPool);
_GUIPass = std::make_shared<GUI>(&_Device, _Window, &_Instance);
_GUIPass->_IN_Color = _ColorPass->_OUT_Color;
_GUIPass->_Dimension = _Surface->GetWindowDimensions();
_GUIPass->Init(_CommandPool);
_GUIPass->tree._Scene = _Scene;
_GUIPass->render.BindTexture(_ColorPass->_OUT_ColorTexture.get());
_GUIPass->render.onResizeCallbacks.push_back([this](double width, double height) {
this->_IsResize = true;
this->_Width = width;
this->_Height = height;
});
_PresentPass = std::make_shared<PresentPass>(&_Device, _Surface);
_PresentPass->_Dimension = _Surface->GetWindowDimensions();
_PresentPass->_IN_Color = _GUIPass->_OUT_Color;
_PresentPass->Init(_CommandPool);
CreateSemaphores();
}
void Renderer::Draw()
{
_Device().waitForFences(_PresentPass->_OUT_InFlight[0], VK_TRUE, std::numeric_limits<uint64_t>::max());
_Device().resetFences(_PresentPass->_OUT_InFlight[0]);
_FrameDuration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
_GUIPass->perf.AddValue(static_cast<float>(_FrameDuration));
_GUIPass->perf._Drawcalls = _ColorPass->_Drawcalls;
start = std::chrono::steady_clock::now();
uint32_t imageIndex = _Device().acquireNextImageKHR(_Surface->_Swapchain, std::numeric_limits<uint64_t>::max(), _ImageAvailableSemaphore[_CurrentFrame], {}).value;
_Scene->Update(_CurrentFrame, _GlobalDescriptor->GetDataBuffer(_CurrentFrame));
_ShadowPass->CreateCommandBuffers(0, _GlobalDescriptor.get(), _Scene);
_DepthPrePass->CreateCommandBuffers(0, _GlobalDescriptor.get(), _Scene);
_ColorPass->CreateCommandBuffers(0, _GlobalDescriptor.get(), _Scene);
_GUIPass->CreateCommandBuffers(0, _GlobalDescriptor.get(), _Scene);
_PresentPass->CreateCommandBuffers(_CurrentFrame, nullptr, nullptr);
_ShadowPass->Render(0, &_ImageAvailableSemaphore[_CurrentFrame], imageIndex);
_DepthPrePass->Render(0, &_ShadowPass->_OUT_SEM_Shadow, imageIndex);
_ColorPass->Render(0, &_DepthPrePass->_OUT_SEM_Depth, imageIndex);
_GUIPass->Render(0, &_ColorPass->_OUT_SEM_Color, imageIndex);
_PresentPass->Render(_CurrentFrame, &_GUIPass->_OUT_SEM_GUI, imageIndex);
_CurrentFrame = (_CurrentFrame + 1) % 2;
if (_IsResize) {
_IsResize = false;
if (_Width < 5000 && _Width > 0 && _Height < 5000 && _Height > 0) {
this->WaitIdle();
this->_GUIPass->render.ClearTexture();
this->onResize(_Width, _Height);
this->_GUIPass->render.BindTexture(_ColorPass->_OUT_ColorTexture.get());
}
}
}
void Renderer::Clean()
{
//DepthImage.Clean(DeviceRef);
//for (auto &frame : FrameBuffers) {
// vkDestroyFramebuffer(DeviceRef.GetLogicalDevice(), frame, nullptr);
//}
//vkFreeCommandBuffers(DeviceRef.GetLogicalDevice(), CommandPool, CommandBuffers.size(), CommandBuffers.data());
//vkDestroyRenderPass(DeviceRef.GetLogicalDevice(), RenderPass, nullptr);
//for (auto &image : SwapChainImageViews) {
// image.Clean(DeviceRef);
//}
//vkDestroySwapchainKHR(DeviceRef.GetLogicalDevice(), SwapChain, nullptr);
//for (auto &semaphore : ImageAvailableSemaphore) {
// vkDestroySemaphore(DeviceRef.GetLogicalDevice(), semaphore, nullptr);
//}
//for (auto &semaphore : RenderFinishedSemaphore) {
// vkDestroySemaphore(DeviceRef.GetLogicalDevice(), semaphore, nullptr);
//}
//for (auto &fence : InFlightFences) {
// vkDestroyFence(DeviceRef.GetLogicalDevice(), fence, nullptr);
//}
//vkDestroyCommandPool(DeviceRef.GetLogicalDevice(), CommandPool, nullptr);
//VertexShader.Clean(DeviceRef);
//FragmentShader.Clean(DeviceRef);
//DeviceRef.Clean();
//layerManager.Clean(Instance);
//vkDestroySurfaceKHR(Instance, Surface, nullptr);
//vkDestroyInstance(Instance, nullptr);
}
void Renderer::WaitIdle()
{
_Device().waitIdle();
}
void Renderer::ReloadShaders()
{
WaitIdle();
// Reload the shader modules
for (auto &shader : ResourceManager::GetInstance()->_Shaders) {
shader.second.lock()->Reload();
}
// And reload the vulkan pipelines
auto dimensions = _Surface->GetWindowDimensions();
for (auto &mat : ResourceManager::GetInstance()->_Materials) {
if (mat.first == "shadow") {
//mat.second.lock()->ReloadPipeline(_ShadowRenderPass, 4096, 4096);
}
else {
mat.second.lock()->ReloadPipeline(_ColorPass->_RenderPass, _Width, _Height);
}
}
}
void Renderer::Resize()
{
WaitIdle();
_Surface->RecreateSwapChain();
auto dimension = _Surface->GetWindowDimensions();
_GUIPass->Resize(dimension);
//onResize(dimension.width, dimension.height);
//_GUI.windowSize = _Surface->GetWindowDimensions();
}
void Renderer::onResize(double width, double height)
{
_DepthPrePass->Resize(vk::Extent2D(width, height));
_ColorPass->Resize(vk::Extent2D(width, height));
vk::Extent2D dimensions = vk::Extent2D(width, height);
for (auto &mat : ResourceManager::GetInstance()->_Materials) {
mat.second.lock()->ReloadPipeline(_ColorPass->_RenderPass, dimensions.width, dimensions.height);
}
_Scene->Resize(dimensions);
}
void Renderer::GetRendererDimensions(uint16_t & width, uint16_t & height)
{
auto dimensions = _Surface->GetWindowDimensions();
width = dimensions.width;
height = dimensions.height;
}
void Renderer::CreateInstance(const std::string &name)
{
vk::ApplicationInfo applicationInfo(name.c_str(), VK_MAKE_VERSION(1, 0, 0), "Shutter", VK_MAKE_VERSION(1, 0, 0), VULKAN_VERSION);
uint32_t glfwExtensionCount = 0;
const char **glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
ExtensionRequestInfo extensionInfo = {};
extensionInfo.RequiredExtensions = {
VK_EXT_DEBUG_REPORT_EXTENSION_NAME
};
extensionInfo.RequiredExtensions.insert(extensionInfo.RequiredExtensions.end(), extensions.begin(), extensions.end());
LayerRequestInfo layerInfo = {};
layerInfo.RequiredLayers = {
"VK_LAYER_LUNARG_standard_validation"
};
// Query extension and layer capabilities
_ExtensionManager.Init(extensionInfo);
_LayerManager.Init(layerInfo);
_Instance = vk::createInstance(vk::InstanceCreateInfo(
{},
&applicationInfo,
_LayerManager.GetEnabledLayers().size(),
_LayerManager.GetEnabledLayers().data(),
_ExtensionManager.GetEnabledExtensions().size(),
_ExtensionManager.GetEnabledExtensions().data()
));
_LayerManager.AttachDebugCallback(_Instance);
}
void Renderer::CreateDevice() {
DeviceRequestInfo deviceRequestInfo = {};
deviceRequestInfo.RequiredExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
deviceRequestInfo.SupportPresentation = true;
deviceRequestInfo.SupportGraphics = true;
_Device = Device::GetDevice(_Instance, deviceRequestInfo, _Surface->_Surface);
_Device.Init(deviceRequestInfo, _Surface->_Surface);
}
void Renderer::CreateCommandPool()
{
_CommandPool = _Device().createCommandPool(vk::CommandPoolCreateInfo(vk::CommandPoolCreateFlagBits::eResetCommandBuffer, _Device.GetQueue(E_QUEUE_TYPE::GRAPHICS).Index));
}
void Renderer::CreateSemaphores()
{
_ImageAvailableSemaphore.resize(2);
for (uint8_t i = 0; i < 2; ++i)
{
_ImageAvailableSemaphore[i] = _Device().createSemaphore({});
}
}<file_sep>#include "GUI.h"
#include "Renderer/Helpers.h"
#include "Engine/Object.h"
GUI::GUI(Device * device, GLFWwindow * window, vk::Instance *instance) : RenderPass(device), _Instance(instance)
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
ImGui_ImplGlfw_InitForVulkan(window, true);
}
void GUI::CreateVulkanTexture(LiveTexture * texture)
{
//_ImguiImage = ImGui_ImplVulkanH_AddTexture(VkSampler(texture->GetSampler()._Sampler), VkImageView(texture->GetImage().GetImageView()));
}
void GUI::Init(const vk::CommandPool & commandPool)
{
CreateImage(commandPool);
CreateDescriptorPool();
CreateRenderPass();
CreateFramebuffer();
_CommandBuffers = _Device->GetDevice().allocateCommandBuffers(vk::CommandBufferAllocateInfo(commandPool, vk::CommandBufferLevel::ePrimary, 2));
_OUT_SEM_GUI = _Device->GetDevice().createSemaphore({});
ImGui_ImplVulkan_InitInfo init_info = {};
init_info.Instance = VkInstance(*_Instance);
init_info.PhysicalDevice = VkPhysicalDevice(_Device->GetPhysicalDevice());
init_info.Device = VkDevice(_Device->GetDevice());
init_info.QueueFamily = _Device->GetQueue(E_QUEUE_TYPE::GRAPHICS).Index;
init_info.Queue = VkQueue(_Device->GetQueue(E_QUEUE_TYPE::GRAPHICS).VulkanQueue);
init_info.DescriptorPool = VkDescriptorPool(_DescriptorPool);
ImGui_ImplVulkan_Init(&init_info, VkRenderPass(_RenderPass));
// Upload Fonts
{
// Use any command queue
vk::CommandBuffer cmdBuffer = BeginSingleUseCommandBuffer(*_Device, commandPool);
VkCommandBuffer command_buffer = VkCommandBuffer(cmdBuffer);
ImGui_ImplVulkan_CreateFontsTexture(command_buffer);
EndSingleUseCommandBuffer(cmdBuffer, *_Device, commandPool);
command_buffer = VK_NULL_HANDLE;
ImGui_ImplVulkan_InvalidateFontUploadObjects();
}
controls._SceneTree = &tree;
}
void GUI::CreateCommandBuffers(const uint8_t frame, GlobalDescriptor * globalDescriptor, Scene * scene)
{
ImGui_ImplVulkan_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("File"))
{
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Edit"))
{
if (ImGui::MenuItem("Undo", "CTRL+Z")) {}
if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item
ImGui::Separator();
if (ImGui::MenuItem("Cut", "CTRL+X")) {}
if (ImGui::MenuItem("Copy", "CTRL+C")) {}
if (ImGui::MenuItem("Paste", "CTRL+V")) {}
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->Pos);
ImGui::SetNextWindowSize(viewport->Size);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::SetNextWindowBgAlpha(0.0f);
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace Demo", nullptr, window_flags);
ImGui::PopStyleVar(3);
ImGuiID dockspace_id = ImGui::GetID("MyDockspace");
ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_PassthruDockspace;
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f));
ImGui::End();
//ImGui::ShowDemoWindow(nullptr);
perf.Draw();
tree.Draw();
tree._ViewportWidth = _Dimension.width;
controls.Draw();
controls._ViewportHeight = _Dimension.height;
render.Draw();
ImGui::Render();
std::array<vk::ClearValue, 1> clearValues;
clearValues[0] = vk::ClearColorValue(std::array<float, 4>{ 0.0f, 0.0f, 0.0f, 1.0f });
_CommandBuffers[frame].begin({ vk::CommandBufferUsageFlagBits::eSimultaneousUse });
_Device->StartMarker(_CommandBuffers[frame], "GUI");
_IN_Color.lock()->TransitionLayout(_CommandBuffers[frame], vk::ImageLayout::eColorAttachmentOptimal);
_OUT_Color->TransitionLayout(_CommandBuffers[frame], vk::ImageLayout::eColorAttachmentOptimal);
_CommandBuffers[frame].beginRenderPass(
vk::RenderPassBeginInfo(
_RenderPass,
_Framebuffer,
{ {0,0}, {_Dimension.width, _Dimension.height} },
1,
clearValues.data()
),
vk::SubpassContents::eInline
);
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), VkCommandBuffer(_CommandBuffers[frame]));
_CommandBuffers[frame].endRenderPass();
_Device->EndMarker(_CommandBuffers[frame]);
_CommandBuffers[frame].end();
}
void GUI::Render(const size_t currentFrame, vk::Semaphore * semaphore, const uint32_t imageIndex)
{
_Device->GetQueue(E_QUEUE_TYPE::GRAPHICS).VulkanQueue.submit(
{
vk::SubmitInfo(
1,
semaphore,
&vk::PipelineStageFlags(vk::PipelineStageFlagBits::eColorAttachmentOutput),
1,
&_CommandBuffers[currentFrame],
1,
&_OUT_SEM_GUI
)
},
{}
);
}
void GUI::Resize(const vk::Extent2D & dimension)
{
_Dimension = dimension;
_OUT_Color->Resize(_Dimension);
_Device->GetDevice().destroyFramebuffer(_Framebuffer);
CreateFramebuffer();
}
void GUI::CreateImage(const vk::CommandPool & commandPool)
{
_OUT_Color = std::make_shared<Image>(
_Device,
VkExtent3D{ _Dimension.width, _Dimension.height, 1 },
1,
vk::Format::eB8G8R8A8Unorm,
vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc,
false,
vk::SampleCountFlagBits::e1
);
_OUT_Color->TransitionLayout(commandPool, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
}
void GUI::CreateRenderPass()
{
vk::AttachmentDescription colorAttachement(
{},
vk::Format::eB8G8R8A8Unorm,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eClear,
vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eColorAttachmentOptimal,
vk::ImageLayout::eColorAttachmentOptimal
);
vk::AttachmentReference colorAttachementReference(
0,
vk::ImageLayout::eColorAttachmentOptimal
);
vk::SubpassDescription subpass(
{},
vk::PipelineBindPoint::eGraphics,
0,
{},
1,
&colorAttachementReference
);
std::array<vk::AttachmentDescription, 1> attachements{
colorAttachement
};
_RenderPass = _Device->GetDevice().createRenderPass(vk::RenderPassCreateInfo(
{},
attachements.size(),
attachements.data(),
1,
&subpass,
1,
&vk::SubpassDependency(
VK_SUBPASS_EXTERNAL,
0,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
{},
vk::AccessFlagBits::eColorAttachmentWrite
)
));
}
void GUI::CreateDescriptorPool()
{
std::array<vk::DescriptorPoolSize, 11> poolSize;
poolSize[0] = { vk::DescriptorType::eSampler, 1000 };
poolSize[1] = { vk::DescriptorType::eCombinedImageSampler, 1000 };
poolSize[2] = { vk::DescriptorType::eSampledImage, 1000 };
poolSize[3] = { vk::DescriptorType::eStorageImage, 1000 };
poolSize[4] = { vk::DescriptorType::eUniformTexelBuffer, 1000 };
poolSize[5] = { vk::DescriptorType::eStorageTexelBuffer, 1000 };
poolSize[6] = { vk::DescriptorType::eUniformBuffer, 1000 };
poolSize[7] = { vk::DescriptorType::eStorageBuffer, 1000 };
poolSize[8] = { vk::DescriptorType::eUniformBufferDynamic, 1000 };
poolSize[9] = { vk::DescriptorType::eStorageBufferDynamic, 1000 };
poolSize[10] = { vk::DescriptorType::eInputAttachment, 1000 };
_DescriptorPool = _Device->GetDevice().createDescriptorPool(vk::DescriptorPoolCreateInfo(vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, 2, poolSize.size(), poolSize.data()));
}
void GUI::CreateFramebuffer()
{
std::array<vk::ImageView, 1> attachments = {
_OUT_Color->GetImageView()
};
_Framebuffer = _Device->GetDevice().createFramebuffer(vk::FramebufferCreateInfo(
{},
_RenderPass,
attachments.size(),
attachments.data(),
_Dimension.width,
_Dimension.height,
1
));
}<file_sep>#pragma once
#include <glm/glm.hpp>
#include <vulkan/vulkan.h>
#include "DeviceHandler.h"
#include "../Helpers.h"
class Image {
public:
Image(){}
explicit Image(
Device *device,
const vk::Extent3D &dimensions,
const uint8_t layers,
const vk::Format &format,
const vk::ImageUsageFlags usage,
const bool generateMips = false,
const vk::SampleCountFlagBits numSamples = vk::SampleCountFlagBits::e1
);
explicit Image(
Device *device,
const glm::ivec3 &dimensions,
const uint8_t layers,
const vk::Format &format,
const vk::ImageUsageFlags usage,
const bool generateMips = false,
const vk::SampleCountFlagBits numSamples = vk::SampleCountFlagBits::e1
);
// Only create the image view, based on the provided image
void FromVkImage(
Device *device,
const vk::Image &image,
const vk::Format &format
);
void Init();
void Clean();
void Resize(const vk::Extent2D &dimension);
void GenerateMipmaps(const vk::CommandPool &cmdPool);
void TransitionLayout(const vk::CommandPool &cmdPool, const vk::ImageLayout oldLayout, const vk::ImageLayout newLayout);
void TransitionLayout(const vk::CommandBuffer &cmdBuffer, const vk::ImageLayout oldLayout, const vk::ImageLayout newLayout);
void TransitionLayout(const vk::CommandBuffer &cmdBuffer, const vk::ImageLayout newLayout);
void Transfer(unsigned char *buffer, const vk::CommandPool &cmdPool, const uint8_t layer = 0);
void Transfer(Image &image, const vk::CommandBuffer &cmdBuffer, const glm::vec2 &offset = glm::vec3(0));
vk::Image &GetImage() {
return _Image;
}
const vk::ImageView &GetImageView() const {
return _View;
}
const vk::Format &GetFormat() const {
return _Format;
}
const uint32_t GetMipLevel() const {
return _MipLevels;
}
vk::ImageLayout _CurrentLayout = vk::ImageLayout::eUndefined;
private:
void CreateImage();
void AllocateMemory();
void CreateImageView();
vk::AccessFlags GetAccess(const vk::ImageLayout layout);
vk::PipelineStageFlagBits GetStage(const vk::ImageLayout layout);
private:
Device *_Device;
vk::Format _Format;
vk::ImageUsageFlags _Usage;
vk::SampleCountFlagBits _NumSamples;
vk::Extent3D _Dimensions;
uint32_t _MipLevels;
uint32_t _NbLayers;
vk::Image _Image;
vk::ImageView _View;
vk::DeviceMemory _Memory;
bool _FromSwapchain = false;
};<file_sep>#include "Layers.h"
#include <algorithm>
#include <iostream>
#if WIN32
#include <Windows.h>
#endif // WIN32
#include <Windows.h>
static HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
static VKAPI_ATTR vk::Bool32 VKAPI_CALL debugCallbackError(
vk::DebugUtilsMessengerCallbackDataFlagsEXT flags,
vk::DebugReportObjectTypeEXT objType,
uint64_t obj,
size_t location,
int32_t code,
const char* layerPrefix,
const char* msg,
void* userData) {
#ifdef WIN32
SetConsoleTextAttribute(hConsole, 12);
#endif
std::cerr << "[ERROR] - " << msg << std::endl;
#ifdef WIN32
SetConsoleTextAttribute(hConsole, 15);
#endif
return VK_FALSE;
}
static VKAPI_ATTR vk::Bool32 VKAPI_CALL debugCallbackWarning(
vk::DebugUtilsMessengerCallbackDataFlagsEXT flags,
vk::DebugReportObjectTypeEXT objType,
uint64_t obj,
size_t location,
int32_t code,
const char* layerPrefix,
const char* msg,
void* userData) {
#ifdef WIN32
SetConsoleTextAttribute(hConsole, 14);
#endif
std::cerr << "[WARNING] - " << msg << std::endl;
#ifdef WIN32
SetConsoleTextAttribute(hConsole, 15);
#endif
return VK_FALSE;
}
void Layer::Init(const LayerRequestInfo& info)
{
_AvailableLayers = vk::enumerateInstanceLayerProperties();
// Check the required, missing one will throw an exception
for (const auto& layerName : info.RequiredLayers) {
if (!CheckLayer(layerName)) {
throw std::runtime_error("Required layer " + std::string(layerName) + " is unavailable.");
}
_EnabledLayers.push_back(layerName);
}
// Check the optional, missing one will add it to the disabled
for (const auto& layerName : info.OptionalLayers) {
if (!CheckLayer(layerName)) {
_DisabledLayers.push_back(layerName);
}
_EnabledLayers.push_back(layerName);
}
}
void Layer::Clean(const vk::Instance &instance)
{
//instance.destroyDebugReportCallbackEXT(_Callback);
}
void Layer::AttachDebugCallback(const vk::Instance &instance)
{
vk::DispatchLoaderDynamic dldi(instance);
vk::DebugReportCallbackCreateInfoEXT callbackInfoError(vk::DebugReportFlagBitsEXT::eError, (PFN_vkDebugReportCallbackEXT)&debugCallbackError);
instance.createDebugReportCallbackEXT(&callbackInfoError, nullptr, &_CallbackError, dldi);
vk::DebugReportCallbackCreateInfoEXT callbackInfoWarning(vk::DebugReportFlagBitsEXT::eWarning, (PFN_vkDebugReportCallbackEXT)&debugCallbackWarning);
instance.createDebugReportCallbackEXT(&callbackInfoWarning, nullptr, &_CallbackWarning, dldi);
}
bool Layer::CheckLayer(const tLayerName & layerName)
{
auto it = std::find_if(
_AvailableLayers.begin(),
_AvailableLayers.end(),
[&layerName](const vk::LayerProperties& availableExtenion) {
return std::strcmp(availableExtenion.layerName, layerName) == 0;
}
);
return it != _AvailableLayers.end();
}
<file_sep>#pragma once
#include <vector>
#include <memory>
#define NOMINMAX
#include "Shader.h"
#include "vulkan/Extensions.h"
#include "vulkan/Layers.h"
#include "vulkan/DeviceHandler.h"
#include "Renderer/Mesh.h"
#include "Engine/Object.h"
#include "Material.h"
#define VULKAN_VERSION VK_API_VERSION_1_0
#define GLM_FORCE_RADIANS
#define GLM_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <chrono>
#include "vulkan/Image.h"
#include "Engine/Texture.h"
#include "Engine/Camera.h"
#include "Engine/Scene.h"
#include "Renderer/Cubemap.h"
#include "Engine/CubeTexture.h"
#include "Engine/LiveTexture.h"
#include "vulkan/vulkan.hpp"
#include "GUI/GUI.h"
#include <chrono>
#include "vulkan/Surface.h"
#include "GlobalDescriptor.h"
#include "RenderPass.h"
#include "Engine/Lib.h"
class EXPORT Renderer {
public:
Renderer(){
}
void Init(const std::string &name, GLFWwindow* window, Scene *scene);
void Draw();
void Clean();
void WaitIdle();
void ReloadShaders();
void Resize();
void onResize(double width, double height);
void GetRendererDimensions(uint16_t &width, uint16_t &height);
Device *GetDevice() {
return &_Device;
}
const vk::CommandPool &GetCommandPool() const {
return _CommandPool;
}
const vk::RenderPass &GetMainRenderPass() const {
return _ColorPass->_RenderPass;
}
const GlobalDescriptor &GetGlobalDescriptor() const {
return *_GlobalDescriptor.get();
}
private:
void CreateInstance(const std::string &name);
void CreateDevice();
void CreateCommandPool();
void CreateSemaphores();
private:
// Screen/window related
GLFWwindow *_Window;
vk::Extent2D _ScreenSize;
std::shared_ptr<Surface> _Surface;
// Rendering related
Extension _ExtensionManager;
Layer _LayerManager;
Device _Device;
vk::Instance _Instance;
vk::CommandPool _CommandPool;
size_t _CurrentFrame = 0;
// Sync related
std::vector<vk::Semaphore> _ImageAvailableSemaphore;
std::unique_ptr<GlobalDescriptor> _GlobalDescriptor;
// Scene/Objects related
Scene *_Scene;
long long _FrameDuration;
std::chrono::steady_clock::time_point start;
bool _IsResize = false;
double _Width, _Height;
public:
std::shared_ptr<ColorPass> _ColorPass;
std::shared_ptr<ShadowPass> _ShadowPass;
std::shared_ptr<DepthPrePass> _DepthPrePass;
std::shared_ptr<PresentPass> _PresentPass;
std::shared_ptr<GUI> _GUIPass;
};<file_sep>#include "Material.h"
#include "Mesh.h"
#include "Helpers.h"
#include "Engine/Scene.h"
void Material::Load(Device *device, const GlobalDescriptor &globalDescriptor, const uint16_t width, const uint16_t height, const uint32_t poolSize)
{
_Device = device;
CreateDescriptorSetLayout();
CreatePushConstantRange();
CreateDescriptorPool(poolSize);
PopulateInfo(width, height);
std::array<vk::DescriptorSetLayout, 2> descriptorSetLayouts = { globalDescriptor._DescriptorSetLayout, _DesciptorSetLayout };
_PipelineLayout = _Device->GetDevice().createPipelineLayout(
vk::PipelineLayoutCreateInfo(
{},
descriptorSetLayouts.size(), descriptorSetLayouts.data(),
_PushConstantRange.size(), _PushConstantRange.data()
)
);
}
void Material::ReloadPipeline(const vk::RenderPass &renderPass, const uint16_t width, const uint16_t height)
{
_Device->GetDevice().destroyPipeline(_Pipeline);
PopulateInfo(width, height);
CreatePipeline(renderPass);
}
void Material::BindShader(std::shared_ptr<Shader> shader)
{
if (!_ShaderMap.insert(std::make_pair(shader->_Stage, shader)).second) {
throw std::runtime_error("Shader already bound for this stage.");
}
}
void Material::ClearShaders()
{
_ShaderMap.clear();
}
void Material::CreatePipeline(const vk::RenderPass &renderPass)
{
/// TODO: Clean, moved here to keep pointer context
_VertexInputInfo = vk::PipelineVertexInputStateCreateInfo(
{},
static_cast<uint32_t>(1),
&Vertex::GetBindingDescription(),
static_cast<uint32_t>(Vertex::GetAttributeDescriptions().size()),
Vertex::GetAttributeDescriptions().data()
);
auto stages = GetShaderInfoList();
vk::GraphicsPipelineCreateInfo pipelineInfo(
{},
static_cast<uint32_t>(_ShaderMap.size()),
stages.data(),
&_VertexInputInfo,
&_InputAssemblyInfo,
nullptr,
&_ViewportInfo,
&_RasterizationInfo,
&_MultisampleInfo,
&_DepthStencilInfo,
&_ColorBlendInfo,
nullptr,
_PipelineLayout,
renderPass,
0
);
_Pipeline = _Device->GetDevice().createGraphicsPipeline(nullptr, pipelineInfo);
}
void Material::PopulateInfo(const uint32_t width, const uint32_t height)
{
CreateInputAssemblyInfo();
CreateViewportInfo(width, height);
CreateRasterizationInfo();
CreateMultisampleInfo();
CreateDepthStencilInfo();
CreateColorBlendInfo();
}
void Material::CreateInputAssemblyInfo()
{
_InputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo({}, vk::PrimitiveTopology::eTriangleList, false);
}
void Material::CreateViewportInfo(const uint32_t width, const uint32_t height)
{
_Viewport = vk::Viewport(0.0f, 0.0f, width, height, 0.0f, 1.0f);
_Scissor = vk::Rect2D({ 0, 0 }, { width, height });
_ViewportInfo = vk::PipelineViewportStateCreateInfo({}, 1, &_Viewport, 1, &_Scissor);
}
void Material::CreateRasterizationInfo()
{
_RasterizationInfo = vk::PipelineRasterizationStateCreateInfo(
{},
false,
false,
vk::PolygonMode::eFill,
vk::CullModeFlagBits::eBack,
vk::FrontFace::eCounterClockwise,
false,
0,
0,
0,
1.0
);
}
void Material::CreateMultisampleInfo()
{
_MultisampleInfo = vk::PipelineMultisampleStateCreateInfo({}, vk::SampleCountFlagBits::e4, false);
}
void Material::CreateDepthStencilInfo()
{
_DepthStencilInfo = vk::PipelineDepthStencilStateCreateInfo(
{},
true,
false,
vk::CompareOp::eLessOrEqual,
false,
false
);
}
void Material::CreateColorBlendInfo()
{
_ColorBlendAttachement = vk::PipelineColorBlendAttachmentState(
true,
vk::BlendFactor::eSrcAlpha,
vk::BlendFactor::eOneMinusSrcAlpha,
vk::BlendOp::eAdd,
vk::BlendFactor::eOne,
vk::BlendFactor::eZero,
vk::BlendOp::eAdd,
vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA
);
_ColorBlendInfo = vk::PipelineColorBlendStateCreateInfo(
{},
false,
{},
1,
&_ColorBlendAttachement
);
}
void Material::CreatePushConstantRange()
{
}
void Material::CreateDescriptorSetLayout()
{
_LayoutBindings.push_back(vk::DescriptorSetLayoutBinding(
0,
vk::DescriptorType::eUniformBufferDynamic,
1,
vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment
));
_LayoutBindings.push_back(vk::DescriptorSetLayoutBinding(
1,
vk::DescriptorType::eCombinedImageSampler,
1,
vk::ShaderStageFlagBits::eFragment
));
_LayoutBindings.push_back(vk::DescriptorSetLayoutBinding(
2,
vk::DescriptorType::eCombinedImageSampler,
1,
vk::ShaderStageFlagBits::eFragment
));
_LayoutBindings.push_back(vk::DescriptorSetLayoutBinding(
3,
vk::DescriptorType::eCombinedImageSampler,
1,
vk::ShaderStageFlagBits::eFragment
));
_LayoutBindings.push_back(vk::DescriptorSetLayoutBinding(
4,
vk::DescriptorType::eCombinedImageSampler,
1,
vk::ShaderStageFlagBits::eFragment
));
_LayoutBindings.push_back(vk::DescriptorSetLayoutBinding(
5,
vk::DescriptorType::eCombinedImageSampler,
1,
vk::ShaderStageFlagBits::eFragment
));
_DesciptorSetLayout = _Device->GetDevice().createDescriptorSetLayout(vk::DescriptorSetLayoutCreateInfo({}, _LayoutBindings.size(), _LayoutBindings.data()));
}
void Material::CreateDescriptorPool(const uint32_t poolSize)
{
std::vector<vk::DescriptorPoolSize> poolSizes;
poolSizes.resize(_LayoutBindings.size());
for (size_t i = 0; i < _LayoutBindings.size(); ++i) {
poolSizes[i].type = _LayoutBindings[i].descriptorType;
poolSizes[i].descriptorCount = poolSize;
}
_DescriptorPool = _Device->GetDevice().createDescriptorPool(vk::DescriptorPoolCreateInfo({}, poolSize, poolSizes.size(), poolSizes.data()));
}
std::vector<Shader*> Material::GetShaderList()
{
std::vector<Shader*> shaderList;
for (auto &shader : _ShaderMap) {
shaderList.push_back(shader.second.get());
}
return shaderList;
}
std::vector<vk::PipelineShaderStageCreateInfo> Material::GetShaderInfoList()
{
std::vector<vk::PipelineShaderStageCreateInfo> shaderList;
for (auto &shader : _ShaderMap) {
shaderList.push_back(shader.second->GetShaderPipelineInfo());
}
return shaderList;
}
<file_sep>#pragma once
#include "Material.h"
class DepthOnly : public Material {
public:
DepthOnly(){}
DepthOnly(const std::string &name) : Material(name) {}
protected:
virtual void CreateColorBlendInfo() override;
virtual void CreateDepthStencilInfo() override;
};<file_sep>#include <string>
#include <iostream>
#include <assert.h>
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
#include <fstream>
int main(int argc, char **argv) {
// Generate a scene file from the given obj
assert(argc > 1);
std::cout << "Generating scene file for: " << argv[1] << std::endl;
std::ofstream file("scene.yaml");
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err;
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, argv[1], std::string(std::string(argv[2]) + "\\").c_str());
file << " - name: object-root\n";
file << " position: [0.0,0.0,0.0]\n";
file << " rotation: [90.0,90.0,0.0]\n";
file << " scale: [0.01,0.01,0.01]\n";
file << " childrens:\n";
for (size_t i = 0; i < shapes.size(); ++i) {
file << " - name: " << shapes[i].name << "\n";
file << " model: " << shapes[i].name << "\n";
if (materials.at(shapes.at(i).mesh.material_ids.front()).ambient_texname != "") {
bool isUsingBump = false;
bool isUsingSpec = false;
bool isUsingAlpha = false;
file << " textures:\n";
// Add the diffuse texture if there are some provided
if (materials.at(shapes.at(i).mesh.material_ids.front()).ambient_texname != "") {
file << " - slot: 1\n";
std::string ambient = materials.at(shapes.at(i).mesh.material_ids.front()).ambient_texname;
file << " texture: " << ambient.erase(0, 9) << "\n";
}
if (materials.at(shapes.at(i).mesh.material_ids.front()).alpha_texname != "") {
file << " - slot: 3\n";
isUsingAlpha = true;
std::string alpha = materials.at(shapes.at(i).mesh.material_ids.front()).alpha_texname;
file << " texture: " << alpha.erase(0, 9) << "\n";
}
if (materials.at(shapes.at(i).mesh.material_ids.front()).bump_texname != "") {
isUsingBump = true;
file << " - slot: 4\n";
std::string bump = materials.at(shapes.at(i).mesh.material_ids.front()).bump_texname;
file << " texture: " << bump.erase(0, 9) << "\n";
}
if (materials.at(shapes.at(i).mesh.material_ids.front()).specular_texname != "") {
isUsingSpec = true;
file << " - slot: 5\n";
std::string bump = materials.at(shapes.at(i).mesh.material_ids.front()).specular_texname;
file << " texture: " << bump.erase(0, 9) << "\n";
}
if (isUsingAlpha) {
file << " material: transparent\n";
}
else if (isUsingSpec) {
if (isUsingBump) {
file << " material: bumpSpec\n";
}
else {
file << " material: spec\n";
}
}
else if (isUsingBump) {
file << " material: bump\n";
}
else {
file << " material: textured\n";
}
}
else {
file << " material: shaded\n";
}
}
file.close();
system("PAUSE");
}<file_sep>#include "App.h"
#include <iostream>
#define TINYOBJLOADER_IMPLEMENTATION
#include "Ext/tiny_obj_loader.h"
#define STB_IMAGE_IMPLEMENTATION
#include "Ext/stb_image.h"
Application::Application(const std::string &appName):
_ApplicationName(appName)
{
horizontalAngle = 3.14f;
verticalAngle = 0.0f;
shaderReaload = false;
}
void Application::Init()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
Window = glfwCreateWindow(_Width, _Height, _ApplicationName.c_str() , nullptr, nullptr);
//glfwSetInputMode(Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetWindowUserPointer(Window, this);
glfwSetFramebufferSizeCallback(Window, ResizeCallback);
//glfwSetMouseButtonCallback(Window, Application::MouseCallback);
_Scene = Scene();
render.Init(_ApplicationName, Window, &_Scene);
glfwSetWindowTitle(Window, _Scene._Name.c_str());
_Camera = &_Scene._Camera;
glfwSetKeyCallback(Window, Application::KeyCallback);
glfwSetWindowIconifyCallback(Window, Application::MinimizeCallback);
Package engine = Package("engine", "engine");
engine.Load();
engine.Initialize(render, 1024);
_Packages.push_back(engine);
}
void Application::Run()
{
double prevMouseX = 0, prevMouseY =0;
while (!glfwWindowShouldClose(Window)) {
glfwPollEvents();
if (!_PauseRender) {
if (glfwJoystickPresent(GLFW_JOYSTICK_1) == GLFW_TRUE) {
int count;
const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &count);
_Camera->Update(
abs(axes[2]) > 0.1 ? axes[2] * 5 : 0,
abs(axes[3]) > 0.1 ? axes[3] * 5 : 0,
Direction{
axes[1] < -0.15,
axes[1] > 0.15,
axes[0] < -0.15,
axes[0] > 0.15
}
);
}
double mouseX, mouseY;
glfwGetCursorPos(Window, &mouseX, &mouseY);
if (broadcastCursor) {
_Camera->Update(
mouseX - prevMouseX,
mouseY - prevMouseY,
Direction{
glfwGetKey(Window, UP) == GLFW_PRESS,
glfwGetKey(Window, DOWN) == GLFW_PRESS,
glfwGetKey(Window, LEFT) == GLFW_PRESS,
glfwGetKey(Window, RIGHT) == GLFW_PRESS
}
);
}
prevMouseX = mouseX;
prevMouseY = mouseY;
DrawFrame();
if (shaderReaload) {
render.WaitIdle();
render.ReloadShaders();
shaderReaload = false;
}
}
}
render.WaitIdle();
}
void Application::Clean()
{
render.Clean();
glfwDestroyWindow(Window);
glfwTerminate();
}
void Application::TriggerShaderReload()
{
std::cout << "Reloading shaders" << std::endl;
shaderReaload = true;
}
void Application::TriggerResize(const int width, const int height)
{
if (!_PauseRender) {
if (width != 0 && height != 0) {
render.Resize();
}
}
}
void Application::KeyCallback(GLFWwindow * window, int key, int scancode, int action, int mods)
{
// Reload the shaders
if (key == KEY_BINDINGS::RELOAD && action == GLFW_PRESS)
{
static_cast<Application*>(glfwGetWindowUserPointer(window))->TriggerShaderReload();
}
else if(key == GLFW_KEY_SPACE && action == GLFW_PRESS)
{
static_cast<Application*>(glfwGetWindowUserPointer(window))->broadcastCursor = !static_cast<Application*>(glfwGetWindowUserPointer(window))->broadcastCursor;
}
}
void Application::MouseCallback(GLFWwindow * window, int button, int action, int mods)
{
}
void Application::ResizeCallback(GLFWwindow * window, int width, int height)
{
static_cast<Application*>(glfwGetWindowUserPointer(window))->TriggerResize(width, height);
}
void Application::MinimizeCallback(GLFWwindow * window, int iconified)
{
static_cast<Application*>(glfwGetWindowUserPointer(window))->_PauseRender = iconified;
}
void Application::DrawFrame()
{
render.Draw();
}
<file_sep>#pragma once
#include <array>
#include <glm/glm.hpp>
#include "Renderer/Mesh.h"
typedef std::array<glm::vec3, 4> Plane;
class Camera;
class Scene;
class Device;
class Object;
class Frustrum {
public:
Frustrum() {}
void GenerateFrustrum(const Camera &camera);
bool TestFrustrum(const BoundingBox bbox);
void CreateMesh(Device *device, Scene &scene, const vk::CommandPool &cmdPool);
private:
std::array<Plane, 6> _FrustrumPlanes;
std::array<glm::vec3, 6> _FrustrumPlaneNormals;
std::array<float, 6> _FrustrumPlanesD;
std::shared_ptr<Object> _DebugObject;
};<file_sep>#pragma once
#include "SceneObject.h"
#include "Object.h"
#include <memory>
struct LightUniformData {
glm::vec4 _Position;
glm::vec4 _Colour;
glm::vec4 _Parameters;
};
class Light : public SceneObject {
public:
Light() {}
Light(const std::string &name, const glm::vec3 &position = glm::vec3(0.0f, 0.0f, 0.0f));
void SetRange(const double range);
void Update() {
DebugObject->Position() = Position();
DebugObject->_PushConstants[0] = _Colour;
}
LightUniformData GetUniformData();
glm::vec3 _Colour;
float _Strength;
Object* DebugObject;
private:
// Parameters used to set the range of a point light
double _Constant;
double _Linear;
double _Quadratic;
};<file_sep>set(SRC_FOLDERS
Engine
Renderer
GUI
)
foreach(loop_var ${SRC_FOLDERS})
file(GLOB_RECURSE SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}/*.cc)
file(GLOB_RECURSE HEADER ${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}/*.hpp ${CMAKE_CURRENT_SOURCE_DIR}/${loop_var}/*.h)
source_group("${loop_var}" FILES ${SOURCE} ${HEADER})
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} ${SOURCE} ${HEADER} ${CMAKE_CURRENT_SOURCE_DIR}/App.h CACHE INTERNAL "")
endforeach()
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} "${CMAKE_CURRENT_SOURCE_DIR}/App.cpp" CACHE INTERNAL "")
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} "${CMAKE_CURRENT_SOURCE_DIR}/Ext/stb_image.h" CACHE INTERNAL "")
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} "${CMAKE_CURRENT_SOURCE_DIR}/Ext/tiny_obj_loader.h" CACHE INTERNAL "")
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} "${CMAKE_CURRENT_SOURCE_DIR}/Ext/tiny_obj_loader.h" CACHE INTERNAL "")
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} "${CMAKE_CURRENT_SOURCE_DIR}/Ext/imgui/examples/imgui_impl_glfw.cpp" CACHE INTERNAL "")
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} "${CMAKE_CURRENT_SOURCE_DIR}/Ext/imgui/examples/imgui_impl_vulkan.cpp" CACHE INTERNAL "")
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} "${CMAKE_CURRENT_SOURCE_DIR}/Ext/imgui/imgui.cpp" CACHE INTERNAL "")
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} "${CMAKE_CURRENT_SOURCE_DIR}/Ext/imgui/imgui_draw.cpp" CACHE INTERNAL "")
set(SOURCE_GLOBAL ${SOURCE_GLOBAL} "${CMAKE_CURRENT_SOURCE_DIR}/Ext/imgui/imgui_demo.cpp" CACHE INTERNAL "")<file_sep>#pragma once
#include <vulkan/vulkan.hpp>
#include "DeviceHandler.h"
#include <algorithm>
class Buffer {
public:
Buffer(){}
explicit Buffer(
Device *device,
const vk::BufferUsageFlags usage,
const size_t size,
const vk::SharingMode sharingMode = vk::SharingMode::eExclusive,
vk::MemoryPropertyFlags memoryFlags = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
~Buffer() = default;
void Copy(void *data, const size_t size) const;
void Transfer(const Buffer &dstBuffer, const vk::CommandPool &cmdPool);
void Clean();
const vk::Buffer &GetBuffer() const {
return _Buffer;
}
const vk::DeviceMemory &GetMemory() const {
return _Memory;
}
protected:
Device *_Device;
vk::Buffer _Buffer;
vk::DeviceMemory _Memory;
size_t _Size;
};<file_sep>#include "PBR.h"
#include "glm/glm.hpp"
void PBR::CreatePushConstantRange()
{
// metallic, roughness, ao
vk::PushConstantRange pushConstant(vk::ShaderStageFlagBits::eFragment, 0, sizeof(glm::vec3));
_PushConstantRange.push_back(pushConstant);
}
<file_sep>#pragma once
#include <string>
#include <vector>
#include <glm/glm.hpp>
class SceneObject {
public:
SceneObject(){}
SceneObject(const std::string &name, const glm::vec3 &position = glm::vec3(0.0f, 0.0f, 0.0f)):
_Name(name),
_Position(position)
{}
virtual ~SceneObject() {};
const bool IsModelDirty() const;
virtual const glm::mat4 &GetModelMatrix();
// Get a reference to the position vector and flag the model matrix as dirty
glm::vec3 &Position();
const glm::vec3 &Position() const;
std::string _Name;
// Do no show in scene tree
bool _IgnoreInTree = false;
// Flag the model matrix as dirty and propagate the children
void SetModelDirty();
// Scene tree
std::weak_ptr<SceneObject> _Parent;
std::vector<std::shared_ptr<SceneObject>> _Children;
protected:
// Cached model matrix
bool _IsModelDirty = false;
glm::mat4 _CachedModelMatrix;
glm::vec3 _Position;
};<file_sep>#include "SceneObject.h"
#include <glm/gtc/matrix_transform.hpp>
const bool SceneObject::IsModelDirty() const
{
if (!_IsModelDirty) {
return _Parent.lock()->IsModelDirty();
}
return _IsModelDirty;
}
const glm::mat4 &SceneObject::GetModelMatrix()
{
if (_IsModelDirty) {
glm::mat4 temp = glm::mat4(1.0f);
// If we have a parent get its model matrix
if (auto parent = _Parent.lock()) {
temp = parent->GetModelMatrix();
}
_CachedModelMatrix = glm::translate(temp, _Position);
_IsModelDirty = false;
}
return _CachedModelMatrix;
}
glm::vec3 &SceneObject::Position()
{
SetModelDirty();
return _Position;
}
const glm::vec3 & SceneObject::Position() const
{
return _Position;
}
void SceneObject::SetModelDirty()
{
_IsModelDirty = true;
// Propagate to children
for (auto &child : _Children) {
child->SetModelDirty();
}
}
<file_sep>#include "Scene.h"
#include "ResourceManager.h"
#include "Renderer/Renderer.h"
namespace YAML {
template<>
struct convert<glm::vec3> {
static Node encode(const glm::vec3& rhs) {
Node node;
node.push_back(rhs.x);
node.push_back(rhs.y);
node.push_back(rhs.z);
return node;
}
static bool decode(const Node& node, glm::vec3& rhs) {
if (!node.IsSequence() || node.size() != 3) {
return false;
}
rhs.x = node[0].as<double>();
rhs.y = node[1].as<double>();
rhs.z = node[2].as<double>();
return true;
}
};
}
void Scene::Load(const std::string &name, Renderer &renderer) {
_Device = renderer.GetDevice();
CreateDynamic(_Device);
std::string root = "Shutter-Data/" + name + "/";
YAML::Node config = YAML::LoadFile(root + "info.yaml");
// Set the scene name
_Name = config["name"].as<std::string>();
// Load the lights
_Lights.resize(config["lights"].size());
for (int i = 0; i < _Lights.size() ; ++i) {
std::string name = config["lights"][i]["name"].as<std::string>();
glm::vec3 position = config["lights"][i]["position"].as<glm::vec3>();
_Lights[i] = Light(name, position);
_Lights[i]._Colour = config["lights"][i]["colour"].as<glm::vec3>();
_Lights[i].SetRange(config["lights"][i]["range"].as<double>());
auto unlit = ResourceManager::GetInstance()->_Materials.at("unlit").lock();
auto debug = std::make_unique<Object>(_Device, *ResourceManager::GetInstance()->_Meshes.at("Sphere").lock(), unlit.get(), 2);
debug->Position() = _Lights[i].Position();
debug->Rotation() = glm::vec3(0,0,0);
debug->Scale() = glm::vec3(0.2,0.2,0.2);
debug->_DynamicIndex = AddToDynamic(*debug.get());
debug->CreateDescriptorSet();
debug->_Name = name + "-debug";
debug->_IgnoreInTree = true;
debug->_PushConstants.resize(1);
_Lights[i].DebugObject = debug.get();
_Objects[unlit].push_back(std::move(debug));
}
// Load the camera
{
std::string name = config["cameras"][0]["name"].as<std::string>();
glm::vec3 position = config["cameras"][0]["position"].as<glm::vec3>();
float fov = config["cameras"][0]["fov"].as<float>();
_Camera = Camera(name, fov, 1024, 768, position, glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0));
}
// Create the camera for the light source
_ShadowCamera = OrthographicCamera(name, glm::vec4(-20, 20,20,-20), glm::vec3(25, 25, 65), glm::vec3(-25, -25, -65), glm::vec3(0.0, 0.0, 1.0));
// Create the scene root object
auto unlit = ResourceManager::GetInstance()->_Materials.at("unlit").lock();
auto rootObject = std::make_shared<Object>(_Device, *ResourceManager::GetInstance()->_Meshes.at("Sphere").lock(), unlit.get(), 2);
rootObject->Position() = glm::vec3(0, 0, 0);
rootObject->Rotation() = glm::vec3(0, 0, 0);
rootObject->Scale() = glm::vec3(1.0, 1.0, 1.0);
rootObject->_DynamicIndex = AddToDynamic(*rootObject.get());
rootObject->CreateDescriptorSet();
rootObject->SetModelDirty();
rootObject->_Name = "scene-root";
_Objects[unlit].push_back(rootObject);
_RootObject = rootObject;
YAML::Node scene = YAML::LoadFile(root + "scene.yaml");
// Load the objects
//_Objects.resize(scene["scene"].size());
for (int i = 0; i < scene["scene"].size(); ++i) {
ParseObject(scene["scene"][i], rootObject, renderer._ShadowPass->_OUT_ShadowTexture);
}
_SceneDataObjects.resize(2);
}
void Scene::Resize(const vk::Extent2D & dimension)
{
_Camera._Width = dimension.width;
_Camera._Height = dimension.height;
}
void Scene::CreateDynamic(Device *device)
{
uint32_t minAlignement = device->GetProperties().limits.minUniformBufferOffsetAlignment;
Object::dynamicAlignement = sizeof(glm::mat4);
if (minAlignement > 0) {
Object::dynamicAlignement = (Object::dynamicAlignement + minAlignement - 1) & ~(minAlignement - 1);
}
uint32_t bufferSize = 1024 * Object::dynamicAlignement;
Object::uboDynamic.model = (glm::mat4*)_aligned_malloc(bufferSize, Object::dynamicAlignement);
Object::DynamicBuffer = Buffer(device, vk::BufferUsageFlagBits::eUniformBuffer, bufferSize);
}
uint32_t Scene::AddToDynamic(Object & object)
{
uint32_t oldIndex = dynamicIndex;
glm::mat4* modelPtr = (glm::mat4*)(((uint64_t)Object::uboDynamic.model + (oldIndex * Object::dynamicAlignement)));
*modelPtr = object.GetModelMatrix();
dynamicIndex++;
return oldIndex;
}
void Scene::UploadDynamic()
{
uint32_t bufferSize = 1024 * Object::dynamicAlignement;
Object::DynamicBuffer.Copy(Object::uboDynamic.model, bufferSize);
}
void Scene::Update(const uint32_t image, const Buffer &sceneBuffer)
{
// Prepare the camera
_SceneDataObjects.at(image)._Data[0]._CameraData = _Camera.GetUniformData();
_SceneDataObjects.at(image)._Data[1]._CameraData = _ShadowCamera.GetUniformData();
// The lights
for (size_t i = 0; i < _Lights.size() && i < MAX_NUM_DYNAMIC_LIGHTS; ++i) {
_SceneDataObjects.at(image)._Data[2]._LightData[i] = _Lights[i].GetUniformData();
}
_SceneDataObjects.at(image)._Data[3]._NumLights = _Lights.size() <= MAX_NUM_DYNAMIC_LIGHTS ? _Lights.size() : MAX_NUM_DYNAMIC_LIGHTS;
sceneBuffer.Copy(&_SceneDataObjects.at(image)._Data, sizeof(SceneDataObject::Data) * DATA_BUFFER_SIZE);
for (auto &mat : _Objects) {
for (auto &obj : mat.second) {
glm::mat4* modelPtr = (glm::mat4*)(((uint64_t)Object::uboDynamic.model + (obj->_DynamicIndex * Object::dynamicAlignement)));
*modelPtr = obj->GetModelMatrix();
}
}
for (auto &light : _Lights) {
light.Update();
}
UploadDynamic();
}
void Scene::ParseObject(const YAML::Node &node, std::shared_ptr<Object> parent, std::shared_ptr<Texture> shadow)
{
std::string name = node["name"].as<std::string>();
std::string model = node["model"].as<std::string>();
std::string material = node["material"].as<std::string>();
std::shared_ptr<Material> materialM = ResourceManager::GetInstance()->_Materials.at(material).lock();
glm::vec3 position = node["position"].IsDefined() ? node["position"].as<glm::vec3>() : glm::vec3(0 ,0 ,0);
glm::vec3 rotation = node["rotation"].IsDefined() ? node["rotation"].as<glm::vec3>() : glm::vec3(0, 0, 0);
glm::vec3 scale = node["scale"].IsDefined() ? node["scale"].as<glm::vec3>() : glm::vec3(1.0, 1.0, 1.0);
auto object = std::make_shared<Object>(_Device, *ResourceManager::GetInstance()->_Meshes.at(model).lock(), materialM.get(), 2);
if (material != "transparent") {
object->Position() = position;
object->Rotation() = rotation;
object->Scale() = scale;
if (node["textures"].IsDefined()) {
for (int j = 0; j < node["textures"].size(); ++j) {
if (node["textures"]) {
int slot = node["textures"][j]["slot"].as<int>();
std::string name = node["textures"][j]["texture"].as<std::string>();
//Texture texture = _Textures.at(name);
object->AddTexture(slot, ResourceManager::GetInstance()->_Textures.at(name).lock());
}
}
}
if (material == "shaded" || material == "bump" || material == "bumpSpec" || material == "transparent" || material == "textured" || material == "normal" || material == "PBR") {
object->AddTexture(2, shadow);
}
object->_DynamicIndex = AddToDynamic(*object.get());
object->CreateDescriptorSet();
object->_Name = name;
object->SetModelDirty();
// Complete scene tree
object->_Parent = parent;
parent->_Children.push_back(object);
if (node["childrens"].IsDefined()) {
for (int i = 0; i < node["childrens"].size(); ++i) {
ParseObject(node["childrens"][i], object, shadow);
}
}
if (node["data"].IsDefined()) {
glm::vec3 data = node["data"].as<glm::vec3>();
object->_PushConstants.push_back(data);
}
_Objects[materialM].push_back(std::move(object));
}
else {
_ObjectsTransparent[materialM].push_back(Object(_Device, *ResourceManager::GetInstance()->_Meshes.at(model).lock(), materialM.get(), 2));
_ObjectsTransparent[materialM].back().Position() = position;
_ObjectsTransparent[materialM].back().Rotation() = rotation;
_ObjectsTransparent[materialM].back().Scale() = scale;
for (int j = 0; j < node["textures"].size(); ++j) {
if (node["textures"]) {
int slot = node["textures"][j]["slot"].as<int>();
std::string name = node["textures"][j]["texture"].as<std::string>();
//Texture texture = _Textures.at(name);
_ObjectsTransparent[materialM].back().AddTexture(slot, ResourceManager::GetInstance()->_Textures.at(name).lock());
}
}
if (material == "basic" || material == "bump" || material == "bumpSpec" || material == "transparent" || material == "flat") {
_ObjectsTransparent[materialM].back().AddTexture(2, shadow);
}
// Complete scene tree
_ObjectsTransparent[materialM].back()._Parent = parent;
_ObjectsTransparent[materialM].back()._Children.push_back(object);
_ObjectsTransparent[materialM].back()._DynamicIndex = AddToDynamic(_ObjectsTransparent[materialM].back());
_ObjectsTransparent[materialM].back().CreateDescriptorSet();
_ObjectsTransparent[materialM].back()._Name = name;
}
}
<file_sep>#pragma once
#include "Material.h"
class Unlit : public Material {
public:
Unlit() {}
Unlit(const std::string &name) : Material(name) {}
protected:
virtual void CreatePushConstantRange() override;
};<file_sep>#pragma once
#include <string>
#include <vector>
#include "vulkan/DeviceHandler.h"
#include <vulkan/vulkan.hpp>
class Shader {
public:
Shader(){}
explicit Shader(
const std::string &shaderName,
const std::string &filename,
const vk::ShaderStageFlagBits stage,
const std::string &entrypoint = "main"
);
void Load(Device *device);
void Reload();
void Clean();
const vk::ShaderModule& GetShaderModule() const {
return _Module;
}
vk::PipelineShaderStageCreateInfo GetShaderPipelineInfo() const;
private:
void LoadFile(const std::string &filename);
void CreateShaderModule();
public:
vk::ShaderStageFlagBits _Stage;
std::string _Name;
std::string _Filename;
std::string _EntryPoint;
private:
Device *_Device;
std::vector<char> _Code;
vk::ShaderModule _Module;
};
|
2e33847535e88952c13bc0b832131f5d76930795
|
[
"Markdown",
"C",
"CMake",
"C++"
] | 77
|
C++
|
Lord-Nazdar/Shutter
|
bf63c3e98d478f2507b2df7f6bfe571679456faa
|
c407090938dadbf71b7e119ff52e2ef3cb42687c
|
refs/heads/main
|
<repo_name>jonnattanChoque/crmclientes<file_sep>/components/pedidos/AsignarCliente.js
import React, { useContext, useEffect, useState } from 'react';
import Select from 'react-select';
import { gql, useQuery } from '@apollo/client';
import PedidoContext from '../../context/pedidos/PedidoContext';
const OBTENER_CLIENTES_USUARIOS = gql`
query obteneClientesVendedor {
obteneClientesVendedor {
id
nombre
apellido
empresa
email
}
}
`;
export default function AsignarCliente () {
const [cliente, setcliente] = useState([]);
const pedidoContext = useContext(PedidoContext);
const {agregarCliente} = pedidoContext;
const {data, loading, error} = useQuery(OBTENER_CLIENTES_USUARIOS);
useEffect(() => {
agregarCliente(cliente);//Esta funcion es del pedidoState
}, [cliente])
const seleccionCliente = cliente => {
setcliente(cliente);
}
if(loading) return null;
const {obteneClientesVendedor} = data;
return(
<>
<p className="mt-10 my-2 bg-white border-l-4 border-gray-800 text-gray-700 p-2 text-sm font-bold">1. Asigna un cliente</p>
<Select
placeholder="Seleccione uno"
noOptionsMessage={() => "No hay resultados"}
options={obteneClientesVendedor}
isMulti={false}
onChange={(opcion) => seleccionCliente(opcion)}
getOptionValue={(opciones) => opciones.id }
getOptionLabel={(opciones) => opciones.nombre}
/>
</>
)
}<file_sep>/pages/editarcliente/[pid].js
import React from 'react';
import {useRouter} from 'next/router';
import Layout from '../../components/Layout';
import {useQuery, gql, useMutation} from '@apollo/client';
import { Formik } from 'formik';
import * as Yup from 'yup';
import Swal from 'sweetalert2';
const OBTENER_CLIENTE = gql`
query obtenerCliente($id:ID!) {
obtenerCliente(id:$id) {
nombre
apellido
email
telefono
empresa
}
}
`;
const ACTUALIZAR_CLIENTE = gql`
mutation actualizarClienter($id: ID!, $input: ClienteInput){
actualizarCliente(id: $id, input: $input) {
nombre
email
}
}
`;
const OBTENER_CLIENTES_USUARIOS = gql`
query obteneClientesVendedor {
obteneClientesVendedor {
id
nombre
apellido
empresa
email
}
}
`;
export default function EditarCliente() {
const router = useRouter();
const { query: {id} } = router;
const {data, loading, error} = useQuery(OBTENER_CLIENTE, {
variables: {
id
}
});
const [actualizarCliente] = useMutation(ACTUALIZAR_CLIENTE, {
update(cache, {data: {actualizarCliente}}){
//obtener el objeto del cache
const { obteneClientesVendedor } = cache.readQuery({ query: OBTENER_CLIENTES_USUARIOS });
//reescribir el cache
cache.writeQuery({
query: OBTENER_CLIENTES_USUARIOS,
data: {
obteneClientesVendedor: [...obteneClientesVendedor, actualizarCliente]
}
})
}
});
//Validaciones
const schemaValidation = Yup.object({
nombre: Yup.string().required('El nombre es obligatorio'),
apellido: Yup.string().required('El apellido es obligatorio'),
email: Yup.string().required('El correo es obligatorio').email('El correo no es válido'),
empresa: Yup.string().required('La empresa es obligatoria'),
})
if(loading) return <h1>Cargando...</h1>
const {obtenerCliente} = data;
const actualizarInfoCliente = async (valores) => {
const { nombre, apellido, empresa, email, telefono } = valores;
try {
const { data } = await actualizarCliente({
variables: {
id,
input: {
nombre,
apellido,
empresa,
email,
telefono
}
}
})
Swal.fire({
title: 'Actualizado',
text: "El cliente se actualizó correctamente",
icon: 'success'
}).then((result) => {
router.push('/');
})
} catch (error) {
console.log(error);
}
}
return (
<Layout>
<h1 className="text-2xl text-gray-800 font-light">Editar cliente</h1>
<div className="flex justify-center mt-5">
<div className="w-full max-w-lg">
<Formik validationSchema={schemaValidation} enableReinitialize initialValues={obtenerCliente} onSubmit={(valores) => {
actualizarInfoCliente(valores)
}}>
{props => {
return (
<form className="bg-white shadow-md px-8 pt-6 pb-8 mb-4" onSubmit={props.handleSubmit}>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="nombre">Nombre</label>
<input
className="shadow appearance-none border border-gray-400 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:border-transparent"
type="text" id="nombre" placeholder="Escribe el nombre del cliente" value={props.values.nombre} onChange={props.handleChange} onBlur={props.handleBlur}
/>
{props.touched.nombre && props.errors.nombre ? (<div className="my-2 bg-red-100 border-l-4 border-red-500 text-red-700 p-4"><p className="font-bold">Error</p><p>{props.errors.nombre}</p></div>) : null}
</div>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="apellido">Apellido</label>
<input
className="shadow appearance-none border border-gray-400 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:border-transparent"
type="text" id="apellido" placeholder="Escribe el apellido del cliente" value={props.values.apellido} onChange={props.handleChange} onBlur={props.handleBlur}
/>
{props.touched.apellido && props.errors.apellido ? (<div className="my-2 bg-red-100 border-l-4 border-red-500 text-red-700 p-4"><p className="font-bold">Error</p><p>{props.errors.apellido}</p></div>) : null}
</div>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="email">Correo</label>
<input
className="shadow appearance-none border border-gray-400 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:border-transparent"
type="email" id="email" placeholder="Escribe el correo del cliente" value={props.values.email} onChange={props.handleChange} onBlur={props.handleBlur}
/>
{props.touched.email && props.errors.email ? (<div className="my-2 bg-red-100 border-l-4 border-red-500 text-red-700 p-4"><p className="font-bold">Error</p><p>{props.errors.email}</p></div>) : null}
</div>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="empresa">Empresa</label>
<input
className="shadow appearance-none border border-gray-400 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:border-transparent"
type="text" id="empresa" placeholder="Escribe la empresa del cliente" value={props.values.empresa} onChange={props.handleChange} onBlur={props.handleBlur}
/>
{props.touched.empresa && props.errors.empresa ? (<div className="my-2 bg-red-100 border-l-4 border-red-500 text-red-700 p-4"><p className="font-bold">Error</p><p>{props.errors.empresa}</p></div>) : null}
</div>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="telefono">Teléfono</label>
<input
className="shadow appearance-none border border-gray-400 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:border-transparent"
type="tel" id="telefono" placeholder="Escribe el teléfono del cliente" value={props.values.telefono} onChange={props.handleChange} onBlur={props.handleBlur}
/>
{props.touched.telefono && props.errors.telefono ? (<div className="my-2 bg-red-100 border-l-4 border-red-500 text-red-700 p-4"><p className="font-bold">Error</p><p>{props.errors.telefono}</p></div>) : null}
</div>
<input className="bg-gray-800 w-full mt-5 p-2 text-white uppercase font-bold hover:bg-gray-900" type="submit" value="Guardar"/>
</form>
)
}}
</Formik>
</div>
</div>
</Layout>
);
}<file_sep>/pages/mejoresclientes.js
import React, { useEffect } from 'react';
import Layout from '../components/Layout';
import {BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend} from 'recharts';
import {gql, useQuery} from '@apollo/client';
const MEJORES_CLIENTES = gql`
query mejoresClientes {
mejoresClientes {
cliente {
nombre
empresa
}
total
}
}
`;
const MejoresClientes = () => {
const {data, loading, error, startPolling, stopPolling} = useQuery(MEJORES_CLIENTES);
const clienteGrafica = [];
if(loading) return(<h1>Cargando</h1>)
const { mejoresClientes } = data;
mejoresClientes.map((cliente, index) => {
clienteGrafica[index] = {
...cliente.cliente[0],
total: cliente.total
}
})
return (
<Layout>
<h1 className="text-2xl text-gray-800 font-light">Mejores CLientes</h1>
<BarChart className="mt-10" width={500} height={300} data={clienteGrafica} margin={{top: 5, right: 30, left: 20, bottom: 5}}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="nombre" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="total" fill="#3182ba" />
</BarChart>
</Layout>
);
}
export default MejoresClientes;<file_sep>/components/Cliente.js
import React from 'react';
import Swal from 'sweetalert2';
import { gql, useMutation } from '@apollo/client';
import Router from 'next/router';
const ELIMINAR_CLIENTE = gql`
mutation eliminarCliente($id: ID!) {
eliminarCliente(id:$id)
}
`;
const OBTENER_CLIENTES_USUARIOS = gql`
query obteneClientesVendedor {
obteneClientesVendedor {
id
nombre
apellido
empresa
email
}
}
`;
export default function Cliente({cliente}){
const [eliminarCliente] = useMutation(ELIMINAR_CLIENTE, {
update(cache) {
const { obteneClientesVendedor } = cache.readQuery({query: OBTENER_CLIENTES_USUARIOS});
cache.writeQuery({
query: OBTENER_CLIENTES_USUARIOS,
data: {
obteneClientesVendedor: obteneClientesVendedor.filter(clienteActual => clienteActual.id !== id)
}
})
}
});
const { id, nombre, apellido, email, empresa} = cliente;
const confirmEliminar = id => {
Swal.fire({
title: '¿Estas seguro de eliminar el cliente?',
text: "Esta acción no se puede deshacer",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar',
cancelButtonText: 'No, cancelar'
}).then(async (result) => {
if (result.isConfirmed) {
try {
const {data} = await eliminarCliente({
variables: {
id
}
});
Swal.fire(
'Eliminado!',
data.eliminarCliente,
'success'
)
} catch (error) {
console.log(error);
}
}
})
}
const confirmEditar = () => {
Router.push({
pathname: '/editarcliente/[id]',
query: {id}
})
}
return (
<tr>
<td className="border px-4 py-2">{nombre} {apellido}</td>
<td className="border px-4 py-2">{empresa}</td>
<td className="border px-4 py-2">{email}</td>
<td className="border px-4 py-2 flex">
<button type="button" className="flex justify-center items-center bg-blue-800 rounded py-2 mx-5 px-4 w-full text-white text-xs uppercase font-bold" onClick={() => confirmEditar()}>
Actualizar<svg className="w-4 h-4 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>
</button>
<button type="button" className="flex justify-center items-center bg-red-800 rounded py-2 mx-5 px-4 w-full text-white text-xs uppercase font-bold" onClick={() => confirmEliminar(id)}>
Eliminar<svg className="w-4 h-4 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
</button>
</td>
</tr>
);
}<file_sep>/pages/nuevoproducto.js
import React, { useState } from 'react';
import Layout from '../components/Layout';
import { useRouter } from 'next/router';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import { useMutation, gql } from '@apollo/client';
const NUEVO_PRODUCTO = gql`
mutation nuevoProducto($input: ProductoInput) {
nuevoProducto(input: $input){
id
nombre
existencia
precio
}
}
`;
const OBTENER_PRODUCTOS = gql`
query obtenerProductos {
obtenerProductos {
id
nombre
precio
existencia
}
}
`;
const NuevoProducto = () => {
const [ nuevoProducto ] = useMutation(NUEVO_PRODUCTO, {
update(cache, {data: {nuevoProducto}}){
//obtener el objeto del cache
const { obtenerProductos } = cache.readQuery({ query: OBTENER_PRODUCTOS });
//reescribir el cache
cache.writeQuery({
query: OBTENER_PRODUCTOS,
data: {
obtenerProductos: [...obtenerProductos, nuevoProducto]
}
})
}
});
const [mensaje, guardarMensaje] = useState(null);
const router = useRouter();
const formik = useFormik({
initialValues: {
nombre: '',
existencia: '',
precio: ''
},
validationSchema: Yup.object({
nombre: Yup.string().required('El nombre es obligatorio'),
existencia: Yup.number().required('La cantidad es obligatoria').positive('No se aceptan negativos').integer("Solo se aceptan números enteros"),
precio: Yup.number().required('El precio es obligatorio').positive('No se aceptan negativos')
}),
onSubmit: async valores => {
const { nombre, existencia, precio } = valores;
try {
const {data} = await nuevoProducto({
variables: {
input: {
"nombre": nombre,
"existencia": existencia,
"precio": precio
}
}
});
guardarMensaje(`Se creó el producto ${data.nuevoProducto.nombre}`);
setTimeout(() => {
guardarMensaje(null);
router.push("/productos");
}, 2000);
} catch (error) {
guardarMensaje(error.message);
}
}
});
const mostrarMensaje = () => {
return (
<div className="bg-red-400 py-2 px-3 w-full my-3 max-w-sm text-center mx-auto">
<p>{mensaje}</p>
</div>
)
}
return (
<Layout>
{mensaje && mostrarMensaje()}
<h1 className="text-2xl text-gray-800 font-light">Nuevo producto</h1>
<div className="flex justify-center mt-5">
<div className="w-full max-w-lg">
<form className="bg-white shadow-md px-8 pt-6 pb-8 mb-4" onSubmit={formik.handleSubmit}>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="nombre">Nombre</label>
<input
className="shadow appearance-none border border-gray-400 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:border-transparent"
type="text" id="nombre" placeholder="Escribe el nombre del producto" value={formik.values.nombre} onChange={formik.handleChange}
/>
{formik.touched.nombre && formik.errors.nombre ? (<div className="my-2 bg-red-100 border-l-4 border-red-500 text-red-700 p-4"><p className="font-bold">Error</p><p>{formik.errors.nombre}</p></div>) : null}
</div>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="existencia">Cantidad disponible</label>
<input
className="shadow appearance-none border border-gray-400 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:border-transparent"
type="number" id="existencia" min="0" placeholder="Escribe la cantidad disponible" value={formik.values.existencia} onChange={formik.handleChange}
/>
{formik.touched.existencia && formik.errors.existencia ? (<div className="my-2 bg-red-100 border-l-4 border-red-500 text-red-700 p-4"><p className="font-bold">Error</p><p>{formik.errors.existencia}</p></div>) : null}
</div>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="precio">Precio</label>
<input
className="shadow appearance-none border border-gray-400 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:border-transparent"
type="number" id="precio" placeholder="Escribe el precio" value={formik.values.precio} onChange={formik.handleChange} onBlur={formik.handleBlur}
/>
{formik.touched.precio && formik.errors.precio ? (<div className="my-2 bg-red-100 border-l-4 border-red-500 text-red-700 p-4"><p className="font-bold">Error</p><p>{formik.errors.precio}</p></div>) : null}
</div>
<input className="bg-gray-800 w-full mt-5 p-2 text-white uppercase font-bold hover:bg-gray-900" type="submit" value="Guardar"/>
</form>
</div>
</div>
</Layout>
);
}
export default NuevoProducto;<file_sep>/pages/clientes.js
import Layout from '../components/Layout';
import { gql, useQuery } from '@apollo/client';
import Link from 'next/link';
import Cliente from '../components/Cliente';
const OBTENER_CLIENTES_USUARIOS = gql`
query obteneClientesVendedor {
obteneClientesVendedor {
id
nombre
apellido
empresa
email
}
}
`;
export default function Clientes() {
const { data, loading, error } = useQuery(OBTENER_CLIENTES_USUARIOS);
console.log(data);
if(loading) return <div>Cargando...</div>
return (
<div>
<Layout>
<h1 className="text-2xl text-gray-800 font-light">Clientes</h1>
<Link href="/nuevocliente">
<a className="w-full lg:w-auto bg-green-800 py-3 px-5 mt-3 inline-block text-white rounded text-sm hover:bg-green-500 mb-3 uppercase font-bold">Nuevo cliente</a>
</Link>
<div className="overflow-x-scroll">
<table className="table-auto shadow-md mt-10 w-full w-lg">
<thead className="bg-gray-800">
<tr className="text-white">
<th className="w-1/5 py-2">Nombre</th>
<th className="w-1/5 py-2">Empresa</th>
<th className="w-1/5 py-2">Correo</th>
<th className="w-1/5 py-2">Acciones</th>
</tr>
</thead>
<tbody className="bg-white">
{data.obteneClientesVendedor.map( cliente => (
<Cliente key={cliente.id} cliente={cliente} />
))}
</tbody>
</table>
</div>
</Layout>
</div>
)
}
|
9dc3bf68c54c80026ddc12e0652d2ebc3ca9cf04
|
[
"JavaScript"
] | 6
|
JavaScript
|
jonnattanChoque/crmclientes
|
91123822546671b46190e057f062ae5121c50d2d
|
00cb9aea7af155f2f74860dddd33f6508d359ce2
|
refs/heads/master
|
<repo_name>jakubwieczorek/wrapper-client<file_sep>/src/app/tool/tool.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {FormsModule} from "@angular/forms";
import {ToolComponent} from "./tool.component";
import {ToolRoutingModule} from "./tool-routing.module";
import {ToolService} from "./service/tool.service";
import {GenericService} from "../common/generic.service";
@NgModule({
imports: [
CommonModule,
FormsModule,
ToolRoutingModule
],
providers: [
ToolService,
GenericService
],
declarations: [ToolComponent]
})
export class ToolModule { }
<file_sep>/src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import {ToolService} from "../tool/service/tool.service";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private _toolService: ToolService) { }
ngOnInit() {
}
upload($event)
{
console.log('siema1');
this._toolService.getFile($event).subscribe
(
data => console.log('success'),
error => console.log(error)
);
}
}
<file_sep>/src/app/tool/tool.component.ts
import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {ToolService} from "./service/tool.service";
@Component({
selector: 'app-tool',
templateUrl: './tool.component.html',
styleUrls: ['./tool.component.css'],
encapsulation: ViewEncapsulation.None
})
export class ToolComponent implements OnInit {
constructor(private _toolService: ToolService) { }
ngOnInit()
{
}
upload($event)
{
console.log('siema1');
this._toolService.getFile($event).subscribe
(
data => console.log('success'),
error => console.log(error)
);
}
}
<file_sep>/src/app/tool/tool-routing.module.ts
import { NgModule } from '@angular/core';
import {RouterModule, Routes} from "@angular/router";
import {ToolComponent} from "./tool.component";
const toolRoutes: Routes = [
{
path: 'tool',
component: ToolComponent
}
];
@NgModule({
imports: [
RouterModule.forChild(toolRoutes)
],
exports: [
RouterModule
]
})
export class ToolRoutingModule { }
<file_sep>/src/app/common/generic.service.ts
import {Http} from "@angular/http";
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
@Injectable()
export class GenericService
{
constructor(private http: Http)
{
}
protected get(url: string)
{
return this.http.get(url).map((res) =>
{
return res;
});
}
protected post(url:string, formData, options)
{
return this.http.post("http://localhost:8080/wrapper/file/upload/", formData, options)
.map(res => GenericService.extractData(res))
.catch(error => Observable.throw(error))
}
private static extractData(res)
{
return res.text() ? res.json() : {};
}
}
<file_sep>/src/app/tool/service/tool.service.ts
import {Injectable, Input} from '@angular/core';
import {GenericService} from "../../common/generic.service";
import {Http, RequestOptions, ResponseContentType} from "@angular/http";
import {Observable} from "rxjs/Observable";
@Injectable()
export class ToolService extends GenericService
{
constructor(private httpT: Http)
{
super(httpT);
}
public getFile(event)
{
let fileList: FileList = event.target.files;
if(fileList.length > 0)
{
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
/** No need to include Content-Type in Angular 4 */
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions(headers);
return super.post("http://localhost:8080/wrapper/file/upload/", formData, options);
}
}
}
<file_sep>/e2e/app.e2e-spec.ts
import { WrapperPage } from './app.po';
describe('wrapper App', () => {
let page: WrapperPage;
beforeEach(() => {
page = new WrapperPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('Welcome to app!');
});
});
|
0e45ee3ee4a8df1af33550614607db3a617796fe
|
[
"TypeScript"
] | 7
|
TypeScript
|
jakubwieczorek/wrapper-client
|
9537de76782ea195e73fe12dcebe01da89718f5d
|
871139104b60870d4d08577be9ff9f858eea1840
|
refs/heads/main
|
<file_sep>const { User, Book } = require("../models");
const { signToken } = require("../utils/auth");
const resolvers = {
Query: {
// Use JWT auth to find and return the appropriate user
// GraphQL will automatically attach the user to the context
me: async () => {
console.log(user);
console.log(req.user);
},
},
Mutation: {
login: async (parent, { email, password }, token) => {
const user = await User.findOne({ email });
if (!user) {
throw new Error("User does not exist");
}
const valid = await user.isCorrectPassword(password);
if (!valid) {
throw new Error("Invalid password");
}
const signedToken = signToken(user);
return {
token: signedToken,
user,
};
},
addUser: async (parent, { username, email, password }, token) => {
const user = await User.create({
username,
email,
password,
});
const signedToken = signToken(user);
return { token: signedToken, user };
},
saveBook: async (
parent,
{ bookAuthors, description, title, bookId, image, link },
token
) => {
const user = await User.findOne({ id: token.userId });
if (!user) {
throw new Error("User does not exist");
}
const book = await Book.create({
bookAuthors,
description,
title,
bookId,
image,
link,
});
user.addBook(book);
return user;
},
removeBook: async (parent, { bookId }, token) => {
const user = await User.findOne({ id: token.userId });
if (!user) {
throw new Error("User does not exist");
}
const book = await Book.findOne({ id: bookId });
if (!book) {
throw new Error("Book does not exist");
}
user.removeBook(book);
return user;
},
},
};
module.exports = resolvers;
|
6810b405d0b54305391936c8c8d918cf088243a2
|
[
"JavaScript"
] | 1
|
JavaScript
|
HavoxPrime/bookSearchEngineHW
|
e93439c41936dfe503340f3068d7162d2af53fe4
|
d9ba7f676efbe83d4e63e9025bb1a50144c8992c
|
refs/heads/master
|
<repo_name>kreodont/fg<file_sep>/builder.py
from Monster import Monster
import os
import shutil
from FgXml import FgXml
import zipfile
dist_folder = 'dist'
module_name = 'RussianBestiary'
module_file_name = 'RussianBestiary.mod'
fantasy_grounds_folder = 'C:/Users/Dima/Dropbox/Fantasy Grounds/modules'
# fantasy_grounds_folder = '/Users/dima/Dropbox/Fantasy Grounds/modules'
only_assemble_files = False
if dist_folder == 'backup': # To avoid rewriting backup folder
only_assemble_files = True
def create_definition_xml(name, author='KY'):
xml_text = '''<?xml version="1.0" encoding="iso-8859-1"?>
<root version="3.3" release="8|CoreRPG:3">
<name>%s</name>
<category>Rus</category>
<author>%s</author>
<ruleset>5E</ruleset>
</root>''' % (name, author)
with open('%s/definition.xml' % dist_folder, 'w') as f:
f.write(xml_text)
def purge_dist_folder():
if not os.path.isdir(dist_folder):
os.makedirs(dist_folder)
for the_file in os.listdir(dist_folder):
file_path = os.path.join(dist_folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(e)
def zipdir(path, ziph, exceptions=()):
for root, dirs, files in os.walk(path):
for f in files:
full_path = os.path.join(root, f).replace('\\', '/')
if full_path in exceptions:
continue
full_path_without_folder_name = '/'.join(full_path.split('/')[1:])
if full_path_without_folder_name in exceptions:
continue
ziph.write(full_path, full_path_without_folder_name)
def build_xml():
root = FgXml(module_name)
root.append_under('root', 'library')
root.append_under('library', 'russian_bestiary')
root.append_under('russian_bestiary', 'categoryname', {'type': 'string'}, value='Rus')
root.append_under('russian_bestiary', 'name', {'type': 'string'}, value='russian_bestiary')
root.append_under('russian_bestiary', 'entries')
root.append_under('entries', 'imagewindow')
root.append_under('imagewindow', 'librarylink', {'type': "windowreference"})
root.append_under('imagewindow', 'name', {'type': "string"}, value='Images & Maps')
root.append_under('librarylink', 'class', value='referenceindexsorted')
root.append_under('librarylink', 'recordname', value='lists.imagewindow@%s' % module_name)
root.append_under('entries', 'npc')
root.append_under('npc', 'name', {'type': "string"}, value='NPCs')
root.append_under('npc', 'librarylink', {'type': "windowreference"})
root.append_under('npc -> librarylink', 'class', value='referenceindexsorted')
root.append_under('npc -> librarylink', 'recordname', value='lists.npc@%s' % module_name)
root.append_under('root', 'lists')
root.append_under('lists', 'imagewindow')
root.append_under('lists -> imagewindow', 'name', {'type': "string"}, value='Images & Maps')
root.append_under('lists -> imagewindow', 'index')
root.append_under('lists', 'npc')
root.append_under('lists -> npc', 'name', {'type': "string"}, value='NPCs')
root.append_under('lists -> npc', 'index')
# root.append_under('root', 'reference', {'static': "true"})
root.append_under('root', 'reference')
root.append_under('reference', 'imagedata')
root.append_under('imagedata', 'category', {"name": "RUNPC", "baseicon": "0", "decalicon": "0"})
root.append_under('reference', 'npcdata')
root.append_under('npcdata', 'category', {"name": "Ru", "baseicon": "0", "decalicon": "0"})
return root
if __name__ == '__main__':
if only_assemble_files:
zip_file = zipfile.ZipFile(module_file_name, 'w', zipfile.ZIP_DEFLATED)
zipdir(dist_folder, zip_file)
zip_file.close()
shutil.copy(module_file_name, fantasy_grounds_folder)
exit(0)
xml = build_xml()
all_monsters = Monster.load_from_file('updated_monsters.obj')
purge_dist_folder() # Deleting everything from dist folder
create_definition_xml(module_name)
shutil.copy('thumbnail.png', dist_folder + '/thumbnail.png')
os.mkdir('%s/tokens' % dist_folder)
os.mkdir('%s/images' % dist_folder)
# monsters_dict = Monster.filter(all_monsters, {'name': 'Adult Red Dragon'})
monsters_dict = all_monsters
for monster_name in sorted(monsters_dict):
monster = monsters_dict[monster_name]
print(monster.get('name', both=True, encode=False))
image_file, token_file = monster.append_to_xml(xml)
if image_file:
shutil.copy(image_file, '%s/%s' % (dist_folder, image_file))
shutil.copy(token_file, '%s/%s' % (dist_folder, token_file))
common_xml_text = str(xml)
with open('%s/common.xml' % dist_folder, 'w+') as common_xml:
common_xml.write(common_xml_text)
common_xml.close()
zip_file = zipfile.ZipFile(module_file_name, 'w', zipfile.ZIP_DEFLATED)
zipdir(dist_folder, zip_file)
zip_file.close()
shutil.copy(module_file_name, fantasy_grounds_folder)
# print(xml)
<file_sep>/temp_module_builder.py
# -*- coding: utf8 -*-
from story_builder import purge_dist_folder, create_definition_xml, build_xml, zipdir
from fg_translations import translate_to_iso_codes
import shutil
import zipfile
import random
fantasy_grounds_folder = 'C:/Users/Dima/Dropbox/Fantasy Grounds/modules' # win
# fantasy_grounds_folder = '/Users/dima/Dropbox/Fantasy Grounds/modules' # mac
text = '''
Логово клаугийлиаматара находится в семидесяти милях от Лейлона. На пути к логову дракона, персонажи имеют следующую встречу в Криптгарденском лесу.
<NAME>
Установите сцену, прочитав вслух следующий текст в рамке:
Сквозь густые лианы и листву впереди можно увидеть танцующее пламя, окружающее плавающий череп. Тени движутся в зелени поблизости, указывая на то, что огненное существо путешествует не в одиночку.
Каранор, а
огненный череп, созданный Улараном мортусом, приводит упырей в логово Клаугийлиаматара. Количество присутствующих упырей равно количеству персонажей в партии, не считая закадычных друзей. Когда нежить замечает персонажей, они нападают. Каранор не раскрывает подробностей своей миссии, если только это не вызвано магией. Тем не менее, огненный череп не знает большей цели своей миссии, только то, что у него есть приказ от Вианты Круэлхекс атаковать логово.Столкновение
Логово Характеристики
Логово клаугийлиаматара-это естественная пещерная система, усиленная магической связью дракона с природой. Пещера имеет землистый запах и является теплой и влажной. Следующие особенности являются общими во всем.
Потолки.
Потолки по всей пещере достигают 40 футов в высоту.Свет.
Фосфоресцирующий мох, растущий на стенах, наполняет пещеры тусклым зеленым светом, накладывая недостаток на проверки мудрости (восприятия), которые полагаются на зрение.Сталактиты.
Сталагмиты среднего размера встречаются по всей пещере. При использовании этих сталагмитов для защиты, среднее или маленькое существо получает половину покрытия.Статуи.
Клаугийлиаматар собрал статуи могущественных гуманоидов женского пола со всего Фаэруна и поместил их в свое логово. Каждая статуя имеет высоту 10 футов и весит 1000 фунтов. Персонаж знает фигуру, изображенную статуей, с успешной проверкой интеллекта DC 15 (История).Деревья.
Деревья за пределами логова 1d6 + 10 футов высотой и не требуют проверки способности подняться.Стены.
На стенах пещеры растут дикие виноградные лозы. Восхождение на стены без оборудования требует успешной проверки силы DC 11 (Легкая атлетика).
'''
if __name__ == '__main__':
dist_folder = 'temp_dist'
module_name = 'TempModule'
only_assemble_files = False
module_file_name = '%s.mod' % module_name
index = random.randint(10, 7000)
print(index)
story_index = 'id-%s' % str(index).zfill(5)
purge_dist_folder()
create_definition_xml(module_name, dist_folder)
xml = build_xml(module_name)
xml.append_under('npc -> index', '%s' % story_index)
xml.append_under('npc -> index -> %s' % story_index, 'listlink', {"type": "windowreference"})
xml.append_under('npc -> index -> %s -> listlink' % story_index, 'class', value='encounter')
xml.append_under('npc -> index -> %s -> listlink' % story_index, 'recordname', value='reference.npcdata.%s@%s' % (story_index, xml.module_name))
xml.append_under('npc -> index -> %s' % story_index, 'name', {"type": "string"}, value=str(index).zfill(5) + ' ' + translate_to_iso_codes(module_name))
xml.append_under('npcdata -> category', '%s' % story_index)
story_path = 'npcdata -> category -> %s' % story_index
xml.append_under(story_path, 'name', {'type': "string"}, value=translate_to_iso_codes(module_name))
xml.append_under(story_path, 'text', {'type': "formattedtext"}, value=translate_to_iso_codes(text))
with open('%s/common.xml' % dist_folder, 'w+') as common_xml:
common_xml.write(str(xml))
common_xml.close()
zip_file = zipfile.ZipFile(module_file_name, 'w', zipfile.ZIP_DEFLATED)
zipdir(dist_folder, zip_file)
zip_file.close()
print(text)
print(f'Copying {module_file_name} to {fantasy_grounds_folder}')
shutil.copy(module_file_name, fantasy_grounds_folder)
print('Done')
<file_sep>/fg_translations.py
import unicodedata
import re
def only_roman_chars(unistr: str) -> bool:
latin_letters = {}
def is_latin(uchr):
try:
return latin_letters[uchr]
except KeyError:
return latin_letters.setdefault(
uchr,
'LATIN' in unicodedata.name(uchr),
)
return all(is_latin(uchr) for uchr in unistr if uchr.isalpha())
special_symbols_dict = {'ё': '¸', 'Ё': '¸', '&': '&',
'•': ' -- ', '—': '-', '−': '-',
'’': '’', '–': '-', '*': '
'}
code_to_special_symbols_dict = {v: k for k, v in special_symbols_dict.items()}
def translate_to_iso_codes(text: str) -> str:
first_letter_code = 192
all_letters = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' \
'абвгдежзийклмнопрстуфхцчшщъыьэюя'
result_text = ''
for char in text:
if char in special_symbols_dict:
result_text += special_symbols_dict[char]
# elif char == 'Ё':
# result_text += '¨'
# elif char == '&':
# result_text += '&'
elif char in all_letters:
char_position = all_letters.index(char)
code = first_letter_code + char_position
result_text += '&#%s;' % code
else:
result_text += char
return result_text
def translate_from_iso_codes(text):
if isinstance(text, int):
return text
russian_letters = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' \
'абвгдежзийклмнопрстуфхцчшщъыьэюя'
for letter in text:
try:
letter_code = int.from_bytes(letter.encode('latin-1'), 'big')
except UnicodeEncodeError:
# print('Error: %s' % e)
continue
if 192 <= letter_code <= 256:
text = text.replace(letter, russian_letters[letter_code - 192])
elif letter_code == 184:
text = text.replace(letter, 'ё')
elif letter_code == 168:
text = text.replace(letter, 'Ё')
output_text = text
letters = re.findall('&#.+?;', text)
for letter in letters:
if letter in code_to_special_symbols_dict:
ru_letter = code_to_special_symbols_dict[letter]
else:
letter_number = int(letter[2:-1]) - 192
ru_letter = russian_letters[letter_number]
output_text = output_text.replace(letter, ru_letter)
return output_text
<file_sep>/parse_pdf.py
from bs4 import BeautifulSoup
import re
import pickle
'''
OBSOLETE
USE parse_html.py instead
This module is intended for converting HTML file resulted from pdfminer into
Fantasy Ground module structure
python C:\\Users\\Dima\\pdfminer.six\\tools\\pdf2txt.py -o Tomb.html "C:\YandexDisk\DnD\Гробница Аннигиляции.pdf"
'''
def paragraph_code_and_size_to_text_definition(*, paragraph_code, text_size):
pair = (paragraph_code, text_size)
styles_dict = {('LOEWBH', '11'): 'Normal text',
('EOQGHV', '11'): 'Normal text',
('VQHELN', '11'): 'Normal text',
('LOEWBH', '13'): 'Normal text',
('QYRATX', '9'): 'Page footer',
('MSTCPF', '10'): 'Page number',
('QYRATX', '15'): 'Header 1',
('UEUYXP', '14'): 'Gray note bold header',
('WCPFZL', '12'): 'Bold text',
('SWRHVT', '12'): 'Bold text',
('UMSYXP', '10'): 'Bold text',
('QYRATX', '13'): 'Header 2',
('QYRATX', '28'): 'Header 3',
('UMSYXP', '12'): 'Header 4',
('WCPFZL', '15'): 'Header 5',
('UEUYXP', '10'): 'Gray note bold header',
('PHFUFZ', '10'): 'Gray note normal text',
('KXSQNJ', '10'): 'Gray note normal text',
('IUTELN', '10'): 'Green note italic text',
('XEYGNJ', '13'): 'Bold italic text',
('RSCBHV', '11'): 'Italic text',
('NMEDDD', '11'): 'Italic text',
('WCPFZL', '25'): 'Other',
('LOEWBH', '18'): 'Other',
('LOEWBH', '9'): 'Other',
('LOEWBH', '4'): 'Other',
('LOEWBH', '2'): 'Other',
('LOEWBH', '5'): 'Other',
('LOEWBH', '3'): 'Other',
('WCPFZL', '11'): 'Other',
('WHTKZL', '55'): 'Other',
('UEUYXP', '24'): 'Other',
('UEUYXP', '17'): 'Other',
('WHTKZL', '48'): 'Other',
('MUMUVP', '61'): 'Other',
('DEWSZH', '24'): 'Other',
('DEWSZH', '17'): 'Other',
('JAWCFV', '11'): 'Bold text',
('PJYMLJ', '10'): 'Normal text',
('DRUSZH', '10'): 'Bold text',
('BBXGXL', '28'): 'Header 6',
('BBXGXL', '19'): 'Header 6',
('ACIAJN', '11'): 'Normal text',
('TPWKPB', '15'): 'Header 7',
('UTLQDZ', '11'): 'Italic',
('KZLITT', '10'): 'Normal',
('UBJLDZ', '11'): 'Italic text',
('OSHBXL', '11'): 'Italic',
('KMJDTT', '9'): 'Small italic',
('GBGFPB', '9'): 'Normal',
('DRUSZH', '12'): 'Bold text',
('AKGAJN', '11'): 'Normal text',
('PJYMLJ', '7'): 'Small text',
('OSHBXL', '7'): 'Small italic',
('PJYMLJ', '13'): 'Normal text',
('FCWZBD', '30'): 'Header 8',
('FCWZBD', '21'): 'Header 8',
('EYHTNF', '13'): 'Header 9',
('EYHTNF', '13'): 'Header 10',
('ACIAJN', '12'): 'Header 11',
('TPWKPB', '28'): 'Header 12',
('PJYMLJ', '12'): 'Page number',
('TPWKPB', '12'): 'Page footer',
('TPWKPB', '20'): 'Header 13',
('DEWSZH', '16'): 'Header 14',
('OSHBXL', '10'): 'Italic text',
('XQVDTT', '13'): 'Bold text',
('XQVDTT', '9'): 'Bold text',
('TPWKPB', '13'): 'Other',
('EYHTNF', '12'): 'Normal text',
('DEWSZH', '14'): 'Note header',
('DEWSZH', '10'): 'Note header',
('UJHLDZ', '10'): 'Bold text',
('QGUWOM', '12'): 'Normal text',
('AKGAJN', '10'): 'Normal text',
('CPHQVO', '10'): 'Normal text',
('LLTJHR', '10'): 'Normal text',
('MTVAVU', '13'): 'Bold italic text',
('KMJDTT', '10'): 'Italic text',
('TPWKPB', '7'): 'Normal text',
('PJYMLJ', '9'): 'Other',
('PJYMLJ', '15'): 'UnderscoNormal text',
('VATRRX', '10'): 'Normal text',
('DRUSZH', '16'): 'Normal text',
('GBGFPB', '10'): 'Normal text',
('ACIAJN', '6'): 'Normal text',
('NWVVJN', '12'): 'Normal text',
('OSHBXL', '9'): 'Other',
('KZLITT', '9'): 'Normal text',
('VNWRRX', '13'): 'Other',
('RCTTNF', '10'): 'Normal',
('XQVDTT', '11'): 'Normal text',
('XQVDTT', '8'): 'Normal text',
('MUMUVP', '36'): 'Other',
('ACIAJN', '15'): 'Other',
('UTLQDZ', '15'): 'Other',
('ACIAJN', '14'): 'Other',
('UBJLDZ', '14'): 'Other',
('VNWRRX', '11'): 'Other',
('DEWSZH', '11'): 'Header 14',
('ZEDXPF', '9'): 'Small italic',
('IUTELN', '7'): 'Small italic',
('PHFUFZ', '7'): 'Small normal',
('KXSQNJ', '7'): 'Small normal',
('PHFUFZ', '13'): 'Normal text',
('QYRATX', '20'): 'Other',
('PHFUFZ', '11'): 'Other',
('LJFRBH', '11'): 'Other',
('LJFRBH', '8'): 'Other',
('WHTKZL', '12'): 'Other',
('UMSYXP', '6'): 'Other',
('RSCBHV', '13'): 'Italic text',
('PHFUFZ', '6'): 'Unknown',
('QGUATX', '6'): 'Unknown',
('UMSYXP', '3'): 'Unknown',
('UMSYXP', '2'): 'Unknown',
('UMSYXP', '4'): 'Unknown',
('VQHELN', '6'): 'Unknown',
('JGBFZL', '12'): 'Unknown',
('UEUYXP', '16'): 'Unknown',
('UEUYXP', '11'): 'Unknown',
('LZBMBH', '10'): 'Unknown',
('WCPFZL', '14'): 'Unknown',
('WCPFZL', '35'): 'Unknown',
('WCPFZL', '17'): 'Unknown',
('LOEWBH', '7'): 'Unknown',
('WCPFZL', '24'): 'Unknown',
('EOQGHV', '10'): 'Unknown',
('ZEDXPF', '10'): 'Unknown',
('WCPFZL', '8'): 'Unknown',
('LOEWBH', '6'): 'Unknown',
('LOEWBH', '10'): 'Unknown',
('UEUYXP', '9'): 'Unknown',
('QGUATX', '8'): 'Unknown',
('RCGGHV', '9'): 'Unknown',
('UMSYXP', '8'): 'Unknown',
('WCPFZL', '41'): 'Unknown',
('LOEWBH', '8'): 'Unknown',
('RCGGHV', '12'): 'Unknown',
('LOEWBH', '15'): 'Unknown',
('WCPFZL', '32'): 'Unknown',
('UEUYXP', '12'): 'Unknown',
('UEUYXP', '7'): 'Unknown',
('UEUYXP', '8'): 'Unknown',
('QYRATX', '24'): 'Unknown',
('QYRATX', '22'): 'Unknown',
('QYRATX', '21'): 'Unknown',
('QYRATX', '18'): 'Unknown',
('QYRATX', '14'): 'Unknown',
('QYRATX', '11'): 'Unknown',
('QYRATX', '25'): 'Unknown',
('QYRATX', '19'): 'Unknown',
('QYRATX', '17'): 'Unknown',
('QYRATX', '16'): 'Unknown',
('QYRATX', '10'): 'Unknown',
('QYRATX', '7'): 'Unknown',
('QYRATX', '12'): 'Unknown',
('QYRATX', '8'): 'Unknown',
('QYRATX', '5'): 'Unknown',
('QYRATX', '3'): 'Unknown',
('QYRATX', '0'): 'Unknown',
('QYRATX', '2'): 'Unknown',
('QYRATX', '6'): 'Unknown',
('QGUATX', '10'): 'Unknown',
('LOEWBH', '1'): 'Unknown',
('LOEWBH', '0'): 'Unknown',
('LOEWBH', '19'): 'Unknown',
('LOEWBH', '17'): 'Unknown',
('FNFMVT', '10'): 'Unknown',
('WCPFZL', '34'): 'Unknown',
('LOEWBH', '14'): 'Unknown',
('OYTILB', '10'): 'Unknown',
('UMSYXP', '16'): 'Unknown',
('WHTKZL', '36'): 'Unknown',
('RSCBHV', '14'): 'Unknown',
('HNDKZK', '55'): 'Other',
('JQCWBG', '55'): 'Header',
('GOOELM', '39'): 'Header',
('FKZYXO', '24'): 'Other',
('FKZYXO', '17'): 'Image',
('DHAMVS', '28'): 'Header',
('ASSZND', '11'): 'Normal',
('UROKHP', '11'): 'Normal',
('QLQMDX', '11'): 'Italic text',
('TSEETR', '11'): 'Italic text',
('LWZDLH', '10'): 'Bold text',
('DKYHDX', '10'): 'Normal',
('JTARJL', '10'): 'Normal',
('LWZDLH', '12'): 'Header',
('VVZLNI', '11'): 'Normal',
('RPBNJQ', '11'): 'Normal',
('QLMHVS', '9'): 'Small italic',
('JTARJL', '7'): 'Small text',
('HHYJCP', '7'): 'Small italic',
('DKYHDX', '7'): 'Normal',
('JTARJL', '13'): 'Normal text',
('HHYJCP', '10'): 'Italic text',
('QNMSYX', '15'): 'Header',
('ASSZND', '13'): 'Normal',
('DHAMVS', '20'): 'Header',
('FKZYXO', '14'): 'Header part',
('FKZYXO', '10'): 'Header part',
('ZBCJRA', '10'): 'Page number',
('DHAMVS', '9'): 'Header',
('OQLVTW', '15'): 'Comment italic',
('DHAMVS', '15'): 'Header',
('DHAMVS', '13'): 'Header',
('FKZYXO', '16'): 'Header part',
('FKZYXO', '11'): 'Header part',
('SJMOXO', '13'): 'Bold text',
('DHAMVS', '10'): 'Page number',
('OQLVTW', '16'): 'Comment italic',
('LXEEMC', '10'): 'Other',
('OQLVTW', '14'): 'Comment italic',
('OQLVTW', '18'): 'Other',
('OQLVTW', '17'): 'Other',
('TIWULM', '9'): 'Other',
('DKYHDX', '9'): 'Other',
('JTARJL', '9'): 'Comment',
('YZPACC', '10'): 'Other',
('QNMSYX', '12'): 'Header',
('JQCWBG', '36'): 'Header',
('ASSZND', '14'): 'Normal text',
('TSEETR', '14'): 'Italic text'
}
return styles_dict[pair] if pair in styles_dict else 'Unknown'
known_styles = {'normal': {'open': '', 'close': '', 'name': 'normal', 'opens_paragraph': True, 'closes_paragraph': False},
'bold': {'open': '<p>', 'close': '</p>', 'name': 'bold', 'opens_paragraph': True, 'closes_paragraph': False},
'italic': {'open': '<p>', 'close': '</p>', 'name': 'italic', 'opens_paragraph': True, 'closes_paragraph': False},
'header': {'open': '<h>', 'close': '</h>\r\n', 'name': 'header', 'opens_paragraph': False, 'closes_paragraph': True},
'bold italic': {'open': '<p>', 'close': '</p>', 'name': 'bold italic', 'opens_paragraph': True, 'closes_paragraph': False},
'small': {'open': '', 'close': '', 'name': 'small', 'opens_paragraph': True, 'closes_paragraph': True},
'context': {'open': '', 'close': '', 'name': 'context', 'opens_paragraph': True, 'closes_paragraph': False}}
texts_examples = {}
def fetch_style_code_from_string(style_string: str) -> str:
tokens = re.findall("font-family: b'(.+)\+.+font-size:(\d+)px",
style_string)
if not tokens or len(tokens) != 2:
return 'Error'
return tokens[0]
def fetch_style_font_size_from_string(style_string: str) -> str:
tokens = re.findall("font-family: b'(.+)\+.+font-size:(\d+)px",
style_string)
if not tokens or len(tokens) != 2:
return 'Error'
return tokens[1]
def parse_style(style_string, this_paragraph_text, page_number=0):
tokens = re.findall("font-family: b'(.+)\+.+font-size:(\d+)px", style_string)
if not tokens or len(tokens[0]) < 2:
return ''
else:
tokens = tokens[0]
paragraph_code, text_size = tokens
if tokens not in texts_examples:
texts_examples[tokens] = ''
if len(texts_examples[tokens]) < 10000:
texts_examples[tokens] += '\n' + this_paragraph_text + ' (page %s)' % page_number
print(f"({paragraph_code}, {text_size}): 'replace_me'")
return paragraph_code_and_size_to_text_definition(paragraph_code=paragraph_code, text_size=text_size)
text = open('tomb.html', encoding="utf-8").read()
soup = BeautifulSoup(text, "html.parser")
paragraphs = soup.find_all('div')
articles_list = []
current_page_number = 1
current_article_header = ''
current_article_text = ''
paragraph_text = ''
full_text = ''
previous_style = {}
current_style = {}
paragraph_opened = False
header_opened = False
paragraph_count = 0
for paragraph_count, p in enumerate(paragraphs):
if not p.text.strip(): # empty paragraph
continue
spans = p.find_all('span')
# print(f'There are {len(spans)} spans found in paragraph {paragraph_count}')
if 'page' in p.text.lower() and ',' not in p.text:
current_page_number = int(p.text.lower().replace('page ', ''))
# print(f'Paragraph {paragraph_count} is a page number {current_page_number}')
continue
if not paragraph_opened and not header_opened:
full_text += '<p>'
paragraph_opened = True
for span_number, span in enumerate(spans):
if not span:
print(f'Span {span_number} in paragraph {paragraph_count} is empty, continuing')
continue
style = parse_style(span['style'], span.text, current_page_number)
if not style:
print(span)
print(f'Span {span_number} in paragraph {paragraph_count} '
f'style not found, continuing')
continue
if not span.text:
print(f'Span {span_number} in paragraph {paragraph_count} '
f'text is empty, continuing')
continue
if 'other' in style.lower() or 'unknown' in style.lower() or 'page' in style.lower():
print(f'Style in paragraph {paragraph_count} span {span_number} is {style}: {span["style"]}')
print(f'Span text: {span.text}')
print()
exit(1)
continue
print('here')
current_style = ''
for style_name in known_styles:
if style_name.lower() in style.lower():
current_style = known_styles[style_name]
if not current_style:
print(style)
exit(1)
if previous_style != current_style:
if previous_style:
full_text += previous_style['close']
if previous_style['name'] == 'header':
header_opened = False
if previous_style and previous_style['closes_paragraph'] and paragraph_opened:
full_text += '</p>\r\n'
paragraph_opened = False
if current_style['closes_paragraph'] and paragraph_opened:
full_text += '</p>\r\n'
paragraph_opened = False
if current_style['opens_paragraph'] and not paragraph_opened and not header_opened:
full_text += '<p>'
paragraph_opened = True
full_text += current_style['open']
if current_style['name'] == 'header':
header_opened = True
span_text = span.text.replace('-\n', '').replace('\n', ' ')
if span_text.strip() == '-':
span_text = span_text.replace('-', '')
if not header_opened:
span_text = re.sub('\.([^<\\. >\d,])', r'.</p>\n<p>\1', span_text)
full_text += span_text
previous_style = current_style
if paragraph_opened and (full_text.strip().endswith('.') or full_text.strip().endswith('»')) and current_style['name'] == 'normal':
full_text += current_style['close']
full_text += '</p>\r\n'
paragraph_opened = False
full_text += '</p>\r\n'
full_text = full_text.replace('<p></p>\r\n', '')
full_text = full_text.replace(' ', ' - ')
full_text = full_text.replace(' ', ' ')
# print(full_text[150000:350000])
for style in texts_examples:
font_code, font_size = style
if paragraph_code_and_size_to_text_definition(
paragraph_code=font_code,
text_size=font_size) == 'Unknown':
print(style)
print(texts_examples[style])
print('-' * 80)
with open('stories.obj', 'wb') as f:
f.write(pickle.dumps(full_text))
<file_sep>/create_xml.py
def translate_to_iso_codes(text):
first_letter_code = 192
all_letters = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯабвгдежзийклмнопрстуфхцчшщьыъэюя'
result_text = ''
for char in text:
if char in all_letters:
char_position = all_letters.index(char)
code = first_letter_code + char_position
result_text += '&#%s' % code
else:
result_text += char
return result_text
print(translate_to_iso_codes('Заклинатель This is rule'))<file_sep>/Monster.py
import unicodedata
import xml.etree.ElementTree as Et
import re
import pickle
import glob
import os
from FgXml import FgXml
def only_roman_chars(unistr):
latin_letters = {}
def is_latin(uchr):
try:
return latin_letters[uchr]
except KeyError:
return latin_letters.setdefault(uchr, 'LATIN' in unicodedata.name(uchr))
return all(is_latin(uchr) for uchr in unistr if uchr.isalpha()) # isalpha suggested by <NAME>
def translate_to_iso_codes(text):
first_letter_code = 192
all_letters = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя'
result_text = ''
for char in text:
if char == 'ё':
result_text += '¸'
elif char == 'Ё':
result_text += '¨'
elif char in all_letters:
char_position = all_letters.index(char)
code = first_letter_code + char_position
result_text += '&#%s;' % code
else:
result_text += char
return result_text
def translate_from_iso_codes(text):
if isinstance(text, int):
return text
russian_letters = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя'
for letter in text:
try:
letter_code = int.from_bytes(letter.encode('latin-1'), 'big') # this is decoding from FG format
except UnicodeEncodeError:
# print('Error: %s' % e)
continue
if 192 <= letter_code <= 256:
text = text.replace(letter, russian_letters[letter_code - 192])
elif letter_code == 184:
text = text.replace(letter, 'ё')
elif letter_code == 168:
text = text.replace(letter, 'Ё')
output_text = text
letters = re.findall('&#.+?;', text)
for letter in letters:
if letter == '•':
ru_letter = '•'
elif letter == '—':
ru_letter = '—'
elif letter == '−':
ru_letter = '−'
elif letter == '’':
ru_letter = '’'
elif letter == '–':
ru_letter = '–'
elif letter == '¸':
ru_letter = 'ё'
elif letter == '¸':
ru_letter = 'Ё'
else:
letter_number = int(letter[2:-1]) - 192
ru_letter = russian_letters[letter_number]
output_text = output_text.replace(letter, ru_letter)
return output_text
class Monster:
attribute_names_translation = {'name': 'имя', 'charisma': 'хар', 'constitution': 'тел', 'dexterity': 'лов', 'intelligence': 'инт', 'strength': 'сил', 'wisdom': 'мдр', 'ac': 'класс доспеха', 'actions': 'действия', 'alignment': 'мировоззрение',
'cr': 'опасность', 'hd': 'кубики хитов',
'hp': 'хиты', 'innatespells': 'врожденные заклинания', 'lairactions': 'действия логова', 'languages': 'языки', 'legendaryactions': 'легендарные действия', 'reactions': 'реакции', 'senses': 'чувства',
'size': 'размер', 'skills': 'умения', 'speed': 'скорость', 'spells': 'заклинания', 'text': 'дополнительный текст', 'traits': 'свойства', 'type': 'тип', 'xp': 'опыт', 'damageresistances': 'сопротивляемость урону',
'conditionimmunities': 'иммунитет к состояниям', 'damagevulnerabilities': 'уязвимость к урону', 'damageimmunities': 'уязвимость к урону', 'savingthrows': 'спасброски'}
mandatory_attributes_list = ['name', 'charisma', 'constitution', 'dexterity', 'intelligence', 'strength', 'wisdom', 'ac', 'hp']
path_in_xml = {'name': 'name', 'charisma': 'abilities/charisma/score', 'constitution': 'abilities/constitution/score', 'dexterity': 'abilities/dexterity/score', 'intelligence': 'abilities/intelligence/score',
'strength': 'abilities/strength/score',
'wisdom': 'abilities/wisdom/score', 'ac': 'ac', 'alignment': 'alignment', 'cr': 'cr', 'hp': 'hp', 'hd': 'hd', 'languages': 'languages', 'senses': 'senses', 'size': 'size', 'skills': 'skills', 'speed': 'speed', 'text': 'text',
'xp': 'xp', 'damageresistances': 'damageresistances', 'conditionimmunities': 'conditionimmunities', 'damagevulnerabilities': 'damagevulnerabilities', 'innatespells': 'innatespells', 'actions': 'actions', 'reactions': 'reactions',
'traits': 'traits', 'spells': 'spells', 'savingthrows': 'savingthrows', 'damageimmunities': 'damageimmunities', 'lairactions': 'lairactions', 'legendaryactions': 'legendaryactions', 'type': 'type'}
cr_to_xp = {'0': 10, '1/8': 25, '1/4': 50, '1/2': 100, '1': 200, '2': 450, '3': 700, '4': 1100, '5': 1800, '6': 2300, '7': 2900, '8': 3900, '9': 5000, '10': 5900, '11': 7200, '12': 8400, '13': 10000,
'14': 11500, '15': 13000, '16': 15000, '17': 18000, '18': 20000, '19': 22000, '20': 25000, '21': 33000, '22': 41000, '23': 50000, '24': 62000, '25': 75000, '26': 90000, '27': 105000, '28': 120000, '29': 135000, '30': 155000}
sizes_dict = {'Large': 'Большой', 'Medium': 'Средний', 'Small': 'Маленький', 'Tiny': 'Крошечный', 'Huge': 'Огромный', 'Gargantuan': 'Громадный'}
def __init__(self, number=0):
self.name = None
self.charisma = None
self.constitution = None
self.dexterity = None
self.intelligence = None
self.strength = None
self.wisdom = None
self.ac = None
self.actions = None
self.alignment = None
self.cr = None
self.hd = None
self.hp = None
self.innatespells = None
self.lairactions = None
self.languages = None
self.legendaryactions = None
self.reactions = None
self.senses = None
self.size = None
self.skills = None
self.speed = None
self.spells = None
self.text = None
self.traits = None
self.type = None
self.xp = None
self.damageresistances = None
self.conditionimmunities = None
self.damagevulnerabilities = None
self.damageimmunities = None
self.savingthrows = None
self.number = number
# if register_number:
# if register_number in Monster.registered_monsters.keys():
# Monster.registered_monsters[max(Monster.registered_monsters.keys()) + 1] = self
# else:
# Monster.registered_monsters[register_number] = self
# else:
# if not Monster.registered_monsters:
# Monster.registered_monsters[1] = self
# else:
# last_number = max(Monster.registered_monsters.keys())
# Monster.registered_monsters[last_number + 1] = self
def __repr__(self):
text_to_return = '\n'
for attribute_name in sorted(self.__dict__.keys()):
if attribute_name == 'number':
continue
value = self.__dict__[attribute_name]
if not value:
text_to_return += '%s: %s\n' % (attribute_name, value)
else:
if value['en_value'] == value['ru_value']:
text_to_return += '%s: %s\n' % (attribute_name, value['en_value'])
else:
text_to_return += '%s: %s (%s)\n' % (attribute_name, value['en_value'], value['ru_value'])
return text_to_return + '\n'
def __setattr__(self, key, value):
if key == 'number':
self.__dict__[key] = value
return
if value is None:
self.__dict__[key] = {'ru_name': Monster.attribute_names_translation[key], 'ru_value': None, 'en_value': None}
return
elif isinstance(value, list):
self.__dict__[key] = value
return
else:
try:
value_int = int(value)
self.__dict__[key]['ru_value'] = value_int
self.__dict__[key]['en_value'] = value_int
return
except (TypeError, ValueError):
translated = translate_from_iso_codes(value)
if only_roman_chars(translated):
self.__dict__[key]['en_value'] = translated
else:
self.__dict__[key]['ru_value'] = translated
def find_attribute_by_ru_name(self, ru_name):
ru_to_en_translation = {v: k for k, v in Monster.attribute_names_translation.items()}
if ru_name.lower() not in ru_to_en_translation.keys():
raise Exception('Russian name "%s" is not found. Possible Russian names: %s' % (ru_name, ', '.join(ru_to_en_translation.keys())))
else:
return self.__getattribute__(ru_to_en_translation[ru_name.lower()])
def not_complete(self):
result = {}
for attribute_name in Monster.mandatory_attributes_list:
if not self.__getattribute__(attribute_name)['ru_value']:
if 'reason' not in result.keys():
result['reason'] = ''
result['reason'] += 'Russian attribute "%s" value is not set\n' % attribute_name
if not self.__getattribute__(attribute_name)['en_value']:
if 'reason' not in result.keys():
result['reason'] = ''
result['reason'] += 'English attribute "%s" value is not set\n' % attribute_name
return result
def find_image(self):
if self.name['en_value'].replace('/', ' ') in [os.path.basename(f).replace('.jpg', '') for f in glob.glob('images/*.jpg')]:
return 'images/%s.jpg' % self.name['en_value'].replace('/', ' ')
def find_token(self):
name = self.name['en_value'].replace(' ', '').replace('-', '_').replace("'", '_').replace('/', '').lower()
tokens_filenames = glob.glob('tokens/*.png')
matched_filename = None
for token_filename in tokens_filenames:
if name == token_filename.replace('tokens\\', '').replace('tokens/', '').replace('.png', '').replace(' ', '').replace('-', '_').lower():
matched_filename = token_filename
break
return matched_filename
def get(self, attribute_name, ru=True, both=False, encode=True):
if attribute_name not in self.__dict__:
return ''
value_dict = self.__getattribute__(attribute_name)
ru_value = str(value_dict['ru_value'])
en_value = str(value_dict['en_value'])
if ru_value == 'None':
ru_value = ''
if en_value == 'None':
en_value = ''
if encode:
ru_value = translate_to_iso_codes(ru_value)
if both:
if not ru_value and not en_value:
return ''
if not ru_value:
return en_value
if not en_value:
return ru_value
else:
return '%s (%s)' % (ru_value, en_value)
if ru:
return ru_value
else:
return en_value
@staticmethod
def parse_xml(xml_text):
if not xml_text:
raise Exception('Empty XML provided')
monsters_dict = {}
root_element = Et.fromstring(xml_text)
npc_element = root_element.find('npc')
if not npc_element:
npc_element = root_element.find('reference').find('npcdata')
if not npc_element:
npc_element = root_element.find('reference').find('category').find('npcdata')
if not npc_element:
raise Exception('Tag npc not found')
category_element = npc_element.find('category')
if not category_element:
raise Exception('There should be tag category under npc tag')
xml_monsters = category_element.findall('*')
for xml_monster in xml_monsters:
monster = Monster(number=int(xml_monster.tag.replace('id-', '')))
for attribute in monster.__dict__.keys():
if attribute in Monster.path_in_xml.keys():
xml_path = Monster.path_in_xml[attribute]
tag = xml_monster.find(xml_path)
if tag is None:
monster.__setattr__(attribute, '')
else:
text = tag.text
if text is None:
text = ''
if attribute == 'name':
if ') (' in text:
ru_name, english_name = text.split(') (')
ru_name += ')'
english_name = english_name.replace('))', ')')
else:
ru_name = text.split(' (')[0]
english_name = text.replace(ru_name, '').replace('(', '').replace(')', '').strip()
monster.name['en_value'] = english_name
monster.name['ru_value'] = translate_from_iso_codes(ru_name)
inner_tags = tag.findall('*')
for itag in inner_tags:
text += Et.tostring(itag).decode('utf-8')
if attribute != 'name':
monster.__setattr__(attribute, text)
monsters_dict[monster.name['en_value'].lower()] = monster
return monsters_dict
@staticmethod
def save_to_file(dictionary_to_save, filename):
with open(filename, 'wb') as f:
f.write(pickle.dumps(dictionary_to_save))
@staticmethod
def load_from_file(filename='monsters.obj'):
with open(filename, 'rb') as f:
loaded_monsters = pickle.loads(f.read())
return loaded_monsters
@staticmethod
def find_several_elements_by_value(monsters_dict, attribute_name, value, strict=False):
elements_to_return = []
for element in monsters_dict.values():
if attribute_name not in element.__dict__.keys():
continue
else:
values_dict = element.__dict__[attribute_name]
if strict:
if value.lower() in (values_dict['ru_value'].lower(), values_dict['en_value'].lower()):
elements_to_return.append(element)
else:
if value.lower() in values_dict['ru_value'].lower() or value.lower() in values_dict['en_value'].lower():
elements_to_return.append(element)
return elements_to_return
@staticmethod
def filter(monsters_dict, filters_parameters_dict):
result_dict = {}
for monster in monsters_dict.values():
match = False
for attribute in filters_parameters_dict:
if attribute not in monster.__dict__:
continue
attribute_value = filters_parameters_dict[attribute]
monster_value_ru = monster.__dict__[attribute]['ru_value']
monster_value_en = monster.__dict__[attribute]['en_value']
if monster_value_ru is None:
monster_value_ru = ''
if monster_value_en is None:
monster_value_en = ''
monster_value_en = str(monster_value_en)
monster_value_ru = str(monster_value_ru)
if str(attribute_value) in monster_value_ru or str(attribute_value) in monster_value_en:
match = True
else:
match = False
continue
if match:
result_dict[len(result_dict) + 1] = monster
return result_dict
def append_to_xml(self, root):
if not isinstance(root, FgXml):
return
FgXml.last_monster_number += 1
# monster_nubmer = FgXml.last_monster_number
monster_index = 'id-%s' % str(FgXml.last_monster_number).zfill(5)
image_file_name = self.find_image()
token_file_name = self.find_token()
additional_text = ''
if not token_file_name:
token_file_name = 'tokens/%s.png' % self.get('name', ru=False)[0].upper()
if image_file_name:
FgXml.last_picture_number += 1
monster_picture_number = FgXml.last_picture_number
monster_picture_index = 'id-%s' % str(monster_picture_number).zfill(5)
if 'imagewindow' in self.get('text'):
old_picture_id = re.findall('reference\.imagedata\.(.+)"', self.get('text'))[0]
self.text['ru_value'] = self.text['ru_value'].replace(old_picture_id, monster_picture_index)
else:
additional_text = '<linklist>\n<link class="imagewindow" recordname="reference.imagedata.%s">%s</link>\n</linklist>\n' % (monster_picture_index, self.get('name', both=True))
root.append_under('imagewindow -> index', '%s' % monster_picture_index)
root.append_under('imagewindow -> index -> %s' % monster_picture_index, 'listlink', {"type": "windowreference"})
root.append_under('imagewindow -> index -> %s -> listlink' % monster_picture_index, 'class', value='imagewindow')
root.append_under('imagewindow -> index -> %s -> listlink' % monster_picture_index, 'recordname', value='reference.imagedata.%s@%s' % (monster_picture_index, root.module_name))
root.append_under('imagewindow -> index -> %s' % monster_picture_index, 'name', {"type": "string"}, value=self.get('name', both=True))
root.append_under('reference -> imagedata -> category', '%s' % monster_picture_index)
root.append_under('reference -> imagedata -> category -> %s' % monster_picture_index, 'image', {'type': "image"})
root.append_under('reference -> imagedata -> category -> %s -> image' % monster_picture_index, 'bitmap', value='%s' % image_file_name)
root.append_under('reference -> imagedata -> category -> %s' % monster_picture_index, 'isidentified', {'type': "number"}, value='0')
root.append_under('reference -> imagedata -> category -> %s' % monster_picture_index, 'name', {'type': "string"}, value=self.get('name', both=True))
root.append_under('npc -> index', '%s' % monster_index)
root.append_under('npc -> index -> %s' % monster_index, 'listlink', {"type": "windowreference"})
root.append_under('npc -> index -> %s -> listlink' % monster_index, 'class', value='npc')
root.append_under('npc -> index -> %s -> listlink' % monster_index, 'recordname', value='reference.npcdata.%s@%s' % (monster_index, root.module_name))
root.append_under('npc -> index -> %s' % monster_index, 'name', {"type": "string"}, value=self.get('name', both=True))
root.append_under('npcdata -> category', '%s' % monster_index)
monster_path = 'npcdata -> category -> %s' % monster_index
root.append_under(monster_path, 'abilities')
root.append_under('%s -> abilities' % monster_path, 'charisma')
root.append_under('%s -> abilities -> charisma' % monster_path, 'bonus', {'type': "number"}, value=str((self.charisma['en_value'] - 10) // 2))
root.append_under('%s -> abilities -> charisma' % monster_path, 'score', {'type': "number"}, value=str(self.charisma['en_value']))
root.append_under('%s -> abilities' % monster_path, 'constitution')
root.append_under('%s -> abilities -> constitution' % monster_path, 'bonus', {'type': "number"}, value=str((self.constitution['en_value'] - 10) // 2))
root.append_under('%s -> abilities -> constitution' % monster_path, 'score', {'type': "number"}, value=str(self.constitution['en_value']))
root.append_under('%s -> abilities' % monster_path, 'dexterity')
root.append_under('%s -> abilities -> dexterity' % monster_path, 'bonus', {'type': "number"}, value=str((self.dexterity['en_value'] - 10) // 2))
root.append_under('%s -> abilities -> dexterity' % monster_path, 'score', {'type': "number"}, value=str(self.dexterity['en_value']))
root.append_under('%s -> abilities' % monster_path, 'intelligence')
root.append_under('%s -> abilities -> intelligence' % monster_path, 'bonus', {'type': "number"}, value=str((self.intelligence['en_value'] - 10) // 2))
root.append_under('%s -> abilities -> intelligence' % monster_path, 'score', {'type': "number"}, value=str(self.intelligence['en_value']))
root.append_under('%s -> abilities' % monster_path, 'strength')
root.append_under('%s -> abilities -> strength' % monster_path, 'bonus', {'type': "number"}, value=str((self.strength['en_value'] - 10) // 2))
root.append_under('%s -> abilities -> strength' % monster_path, 'score', {'type': "number"}, value=str(self.strength['en_value']))
root.append_under('%s -> abilities' % monster_path, 'wisdom')
root.append_under('%s -> abilities -> wisdom' % monster_path, 'bonus', {'type': "number"}, value=str((self.wisdom['en_value'] - 10) // 2))
root.append_under('%s -> abilities -> wisdom' % monster_path, 'score', {'type': "number"}, value=str(self.wisdom['en_value']))
root.append_under('%s' % monster_path, 'ac', {'type': "number"}, value=self.get('ac'))
root.append_under('%s' % monster_path, 'actions', value=''.join(str(t) for t in self.actions['ru_value']))
root.append_under('%s' % monster_path, 'alignment', {'type': "string"}, value=self.get('alignment'))
root.append_under('%s' % monster_path, 'cr', {'type': "string"}, value=str(self.cr['en_value']))
root.append_under('%s' % monster_path, 'hd', {'type': "string"}, value=str(self.hd['en_value']))
root.append_under('%s' % monster_path, 'hp', {'type': "number"}, value=str(self.hp['en_value']))
root.append_under('%s' % monster_path, 'innatespells', value=str(self.get('innatespells')))
root.append_under('%s' % monster_path, 'lairactions', value=str(self.get('lairactions')))
root.append_under('%s' % monster_path, 'legendaryactions', value=''.join(str(t) for t in self.legendaryactions['ru_value']))
root.append_under('%s' % monster_path, 'reactions', value=str(self.get('reactions')))
root.append_under('%s' % monster_path, 'languages', {'type': "string"}, value=self.get('languages', ru=False))
root.append_under('%s' % monster_path, 'locked', {'type': "number"}, value='1')
root.append_under('%s' % monster_path, 'name', {'type': "string"}, value=self.get('name', both=True))
root.append_under('%s' % monster_path, 'senses', {'type': "string"}, value=self.get('senses', ru=False))
root.append_under('%s' % monster_path, 'size', {'type': "string"}, value=self.get('size', ru=False))
root.append_under('%s' % monster_path, 'skills', {'type': "string"}, value=self.get('skills', ru=False))
root.append_under('%s' % monster_path, 'speed', {'type': "string"}, value=self.get('speed', ru=False))
root.append_under('%s' % monster_path, 'spells', value=self.get('spells'))
root.append_under('%s' % monster_path, 'conditionimmunities', {'type': "string"}, value=self.get('conditionimmunities', ru=False))
root.append_under('%s' % monster_path, 'damageresistances', {'type': "string"}, value=self.get('damageresistances', ru=False))
root.append_under('%s' % monster_path, 'damagevulnerabilities', {'type': "string"}, value=self.get('damagevulnerabilities', ru=False))
root.append_under('%s' % monster_path, 'damageimmunities', {'type': "string"}, value=self.get('damageimmunities', ru=False))
root.append_under('%s' % monster_path, 'savingthrows', {'type': "string"}, value=self.get('savingthrows', ru=False))
additional_text += self.get('text')
root.append_under('%s' % monster_path, 'text', {'type': "formattedtext"}, value=additional_text)
root.append_under('%s' % monster_path, 'token', {'type': "token"}, value='%s@%s' % (token_file_name, root.module_name))
root.append_under('%s' % monster_path, 'traits', value=''.join(str(t) for t in self.traits['ru_value']))
root.append_under('%s' % monster_path, 'type', {'type': "string"}, value=self.get('type', ru=False))
root.append_under('%s' % monster_path, 'xp', {'type': "number"}, value=self.get('xp'))
return image_file_name, token_file_name
@staticmethod
def load_patch_from_xml(xml_text):
if not xml_text:
raise Exception('Empty XML provided')
monsters_list = []
root_element = Et.fromstring(xml_text)
npc_element = root_element.find('reference').find('category').find('npcdata')
if not npc_element:
raise Exception('Tag npc not found')
category_element = npc_element.find('category')
if not category_element:
raise Exception('There should be tag category under npc tag')
xml_monsters = category_element.findall('*')
for xml_monster in xml_monsters:
monster = Monster(number=int(xml_monster.tag.replace('id-', '')))
for attribute in monster.__dict__.keys():
if attribute in Monster.path_in_xml.keys():
xml_path = Monster.path_in_xml[attribute]
tag = xml_monster.find(xml_path)
if tag is None:
monster.__setattr__(attribute, '')
else:
text = tag.text
if text is None:
text = ''
if attribute == 'name':
if ') (' in text:
ru_name, english_name = text.split(') (')
ru_name += ')'
english_name = english_name.replace('))', ')')
else:
ru_name = text.split(' (')[0]
english_name = text.replace(ru_name, '').replace('(', '').replace(')', '').strip()
monster.name['en_value'] = english_name
monster.name['ru_value'] = translate_from_iso_codes(ru_name)
inner_tags = tag.findall('*')
for itag in inner_tags:
text += Et.tostring(itag).decode('utf-8')
if attribute != 'name':
monster.__setattr__(attribute, text)
monsters_list.append(monster)
return monsters_list
if __name__ == '__main__':
pass
<file_sep>/mod_file_assembler.py
"""
Input: list of XML formatted strings
Output: Module file that can be imported to Fantasy Grounds
"""
import shutil
import os
import zipfile
from typing import List, Tuple
from FgXml import FgXml
from fg_translations import translate_to_iso_codes
from parse_html import get_stories
def define_fg_folder(os_type: str) -> str:
if os_type.strip().lower() == 'win':
return 'C:/Users/Dima/Dropbox/Fantasy Grounds/modules'
elif os_type.strip().lower() == 'mac':
return '/Users/dima/Dropbox/Fantasy Grounds/modules'
def copy_mod_file_to_fg_folder(filename: str, destination_folder: str):
shutil.copy(filename, destination_folder)
def create_dist_folder(folder_name: str):
if not os.path.isdir(folder_name):
os.makedirs(folder_name)
for the_file in os.listdir(folder_name):
file_path = os.path.join(folder_name, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(e)
def zipdir(
module_name: str,
dist_folder_name: str,
exclude_files: List[str] = (),
) -> str:
zip_file = zipfile.ZipFile(f'{module_name}.mod', 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(dist_folder_name):
for f in files:
full_path = os.path.join(root, f).replace('\\', '/')
if full_path in exclude_files:
continue
full_path_without_folder_name = '/'.join(full_path.split('/')[1:])
if full_path_without_folder_name in exclude_files:
continue
zip_file.write(full_path, full_path_without_folder_name)
return zip_file.filename
def create_definition_xml(
module_name: str,
dist_folder: str,
author: str = 'Kreodont',
ruleset: str = '5E',
) -> str:
xml_text = '''<?xml version="1.0" encoding="iso-8859-1"?>
<root version="3.3" release="8|CoreRPG:3">
<name>%s</name>
<category>Rus</category>
<author>%s</author>
<ruleset>%s</ruleset>
</root>''' % (module_name, author, ruleset)
with open('%s/definition.xml' % dist_folder, 'w') as output_file:
output_file.write(xml_text)
return f'{dist_folder}/definition.xml'
def create_common_xml(
*,
module_name: str,
dist_folder: str,
stories_list: List[Tuple[str, str]],
) -> str:
def build_xml_template(mod_name) -> FgXml:
root = FgXml(mod_name)
library_name = mod_name
root.append_under('root', 'library')
root.append_under('library', library_name)
root.append_under(library_name, 'categoryname',
{'type': 'string'}, value='Rus')
root.append_under(library_name, 'name', {'type': 'string'},
value=library_name)
root.append_under(library_name, 'entries')
root.append_under('entries', 'imagewindow')
root.append_under('imagewindow', 'librarylink',
{'type': "windowreference"})
root.append_under('imagewindow', 'name', {'type': "string"},
value='Images & Maps')
root.append_under('librarylink', 'class', value='referenceindexsorted')
root.append_under('librarylink', 'recordname',
value='lists.imagewindow@%s' % mod_name)
root.append_under('entries', 'npc')
root.append_under('npc', 'name', {'type': "string"}, value='Story')
root.append_under('npc', 'librarylink', {'type': "windowreference"})
root.append_under('npc -> librarylink', 'class',
value='referenceindexsorted')
root.append_under('npc -> librarylink', 'recordname',
value='lists.npc@%s' % mod_name)
root.append_under('root', 'lists')
root.append_under('lists', 'imagewindow')
root.append_under('lists -> imagewindow', 'name', {'type': "string"},
value='Images & Maps')
root.append_under('lists -> imagewindow', 'index')
root.append_under('lists', 'npc')
root.append_under('lists -> npc', 'name', {'type': "string"},
value='Story')
root.append_under('lists -> npc', 'index')
root.append_under('root', 'reference')
root.append_under('reference', 'imagedata')
root.append_under('imagedata', 'category',
{"name": "RUNPC", "baseicon": "0", "decalicon": "0"})
root.append_under('reference', 'npcdata')
root.append_under('npcdata', 'category',
{"name": "Ru", "baseicon": "0", "decalicon": "0"})
return root
xml_template = build_xml_template(module_name)
for story_number, story in enumerate(stories_list, 1):
story_index = 'id-%s' % str(story_number).zfill(5)
xml_template.append_under('npc -> index', '%s' % story_index)
xml_template.append_under(
'npc -> index -> %s' % story_index,
'listlink',
{"type": "windowreference"},
)
xml_template.append_under(
'npc -> index -> %s -> listlink' % story_index,
'class',
value='encounter',
)
xml_template.append_under(
'npc -> index -> %s -> listlink' % story_index,
'recordname', value='reference.npcdata.%s@%s' % (
story_index,
module_name,
),
)
story_name, story_formatted_text = story
xml_template.append_under(
'npc -> index -> %s' % story_index,
'name',
{"type": "string"},
value=translate_to_iso_codes(story_name)
)
xml_template.append_under('npcdata -> category', '%s' % story_index)
story_path = 'npcdata -> category -> %s' % story_index
xml_template.append_under(
story_path,
'name',
{'type': "string"},
value=translate_to_iso_codes(story_name),
)
xml_template.append_under(
story_path,
'text',
{'type': "formattedtext"},
value=translate_to_iso_codes(story_formatted_text),
)
print(f'\n\n{story}\n\n')
with open('%s/common.xml' % dist_folder, 'w') as output_file:
output_file.write(str(xml_template))
return f'{dist_folder}/common.xml'
if __name__ == '__main__':
module_name_ = 'dragon_rus'
print(f'Module name: "{module_name_}"')
dist_folder_name_ = f'{module_name_}_dist'
print(f'Creating folder "{dist_folder_name_}"')
create_dist_folder(dist_folder_name_)
print('Creating definition.xml')
create_definition_xml(module_name_, dist_folder_name_)
print('Creating common.xml')
create_common_xml(
module_name=module_name_,
dist_folder=dist_folder_name_,
# stories_list=['xexexe'],
stories_list=get_stories(
module_name_,
(0, 200),
several_blocks=False,
),
)
module_file_name = zipdir(module_name_, dist_folder_name_)
print(f'Packed {dist_folder_name_} to {module_file_name}')
destination_folder_ = define_fg_folder("win")
print(f'Copying {module_file_name} '
f'to {destination_folder_}/{module_file_name}')
copy_mod_file_to_fg_folder(module_file_name, destination_folder_)
print('Done')
<file_sep>/2functions.py
import re
def translate_to_iso_codes(text):
first_letter_code = 192
all_letters = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя'
result_text = ''
for char in text:
if char == 'ё':
result_text += '¸'
elif char == 'Ё':
result_text += '¨'
elif char in all_letters:
char_position = all_letters.index(char)
code = first_letter_code + char_position
result_text += '&#%s;' % code
else:
result_text += char
return result_text
def translate_from_iso_codes(text):
if isinstance(text, int):
return text
russian_letters = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя'
for letter in text:
try:
# this is decoding from FG format
letter_code = int.from_bytes(letter.encode('latin-1'), 'big')
except UnicodeEncodeError:
# print('Error: %s' % e)
continue
if 192 <= letter_code <= 256:
text = text.replace(letter, russian_letters[letter_code - 192])
elif letter_code == 184:
text = text.replace(letter, 'ё')
elif letter_code == 168:
text = text.replace(letter, 'Ё')
output_text = text
letters = re.findall('&#.+?;', text)
for letter in letters:
if letter == '•':
ru_letter = '•'
elif letter == '—':
ru_letter = '—'
elif letter == '−':
ru_letter = '−'
elif letter == '’':
ru_letter = '’'
elif letter == '–':
ru_letter = '–'
elif letter == '¸':
ru_letter = 'ё'
elif letter == '¸':
ru_letter = 'Ё'
else:
letter_number = int(letter[2:-1]) - 192
ru_letter = russian_letters[letter_number]
output_text = output_text.replace(letter, ru_letter)
return output_text
if __name__ == '__main__':
result = translate_to_iso_codes('Что-нибудь ещё')
print(result)
<file_sep>/FgXml.py
from xml.etree.ElementTree import Element, tostring, SubElement
import xml.dom.minidom
class FgXml(object):
last_monster_number = 0
last_picture_number = 0
def __init__(self, module_name, name='root', attributes=None):
if attributes is None:
attributes = {'version': "3.3", 'release': "8|CoreRPG:3"}
self.full_paths = {}
self.module_name = module_name
self.root = Element(name)
for attribute_name, attribute_value in attributes.items():
self.root.set(attribute_name, attribute_value)
self.full_paths[name] = self.root
def __repr__(self):
xmlstr = xml.dom.minidom.parseString(tostring(self.root)).toprettyxml(indent=" ", encoding='iso-8859-1')
return xmlstr.decode('utf-8', 'ignore').replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"')
def find_in_full_path(self, path_part):
matched_paths = []
for full_path in self.full_paths:
if full_path.endswith(path_part):
matched_paths.append(full_path)
return matched_paths
def append_under(self, name_under, name_to_append, attributes=None, under_each=False, value=None):
if not name_under:
raise Exception('You should specify the tag name to append under')
parents_full_paths = self.find_in_full_path(name_under)
if not parents_full_paths:
raise Exception('Cannot find element named "%s" to append "%s" under' % (name_under, name_to_append))
if len(parents_full_paths) > 1 and not under_each:
raise Exception('There are %s tags with name "%s": %s. To add under each, specify under_each=True' % (len(parents_full_paths), name_under, ', '.join(parents_full_paths)))
if attributes is None:
attributes = {}
for parent_full_path in parents_full_paths:
parent = self.full_paths[parent_full_path]
element = SubElement(parent, name_to_append, attrib=attributes)
if value is not None:
element.text = value
element_full_path = parent_full_path + ' -> ' + name_to_append
if element_full_path in self.full_paths:
raise Exception('Element %s already exists' % element_full_path)
self.full_paths[element_full_path] = element
if __name__ == '__main__':
test = FgXml('TestModule')
test.append_under('root', 'library')
test.append_under('library', 'rudnd5e2', {'static': 'true'})
test.append_under('rudnd5e2', 'categoryname', {'type': 'string'}, value='Rus')
test.append_under('rudnd5e2', 'entries')
test.append_under('entries', 'imagewindow')
print(test)
<file_sep>/story_builder.py
import os
import shutil
from FgXml import FgXml
import zipfile
import pickle
from fg_translations import translate_to_iso_codes
dist_folder = 'story_dist'
# module_name = 'Tomb'
only_assemble_files = False
# module_file_name = '%s.mod' % module_name
# fantasy_grounds_folder = 'C:/Users/Dima/Dropbox/Fantasy Grounds/modules' # win
fantasy_grounds_folder = '/Users/dima/Dropbox/Fantasy Grounds/modules' # mac
def create_definition_xml(name, distribution_folder, author='Kreodont'):
xml_text = '''<?xml version="1.0" encoding="iso-8859-1"?>
<root version="3.3" release="8|CoreRPG:3">
<name>%s</name>
<category>Rus</category>
<author>%s</author>
<ruleset>5E</ruleset>
</root>''' % (name, author)
with open('%s/definition.xml' % distribution_folder, 'w') as output_file:
output_file.write(xml_text)
def purge_dist_folder():
if not os.path.isdir(dist_folder):
os.makedirs(dist_folder)
for the_file in os.listdir(dist_folder):
file_path = os.path.join(dist_folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(e)
def zipdir(path, ziph, exceptions=()):
for root, dirs, files in os.walk(path):
for f in files:
full_path = os.path.join(root, f).replace('\\', '/')
if full_path in exceptions:
continue
full_path_without_folder_name = '/'.join(full_path.split('/')[1:])
if full_path_without_folder_name in exceptions:
continue
ziph.write(full_path, full_path_without_folder_name)
def build_xml(module_name):
root = FgXml(module_name)
root.append_under('root', 'library')
root.append_under('library', 'russian_bestiary')
root.append_under('russian_bestiary', 'categoryname', {'type': 'string'}, value='Rus')
root.append_under('russian_bestiary', 'name', {'type': 'string'}, value='russian_bestiary')
root.append_under('russian_bestiary', 'entries')
root.append_under('entries', 'imagewindow')
root.append_under('imagewindow', 'librarylink', {'type': "windowreference"})
root.append_under('imagewindow', 'name', {'type': "string"}, value='Images & Maps')
root.append_under('librarylink', 'class', value='referenceindexsorted')
root.append_under('librarylink', 'recordname', value='lists.imagewindow@%s' % module_name)
root.append_under('entries', 'npc')
root.append_under('npc', 'name', {'type': "string"}, value='Story')
root.append_under('npc', 'librarylink', {'type': "windowreference"})
root.append_under('npc -> librarylink', 'class', value='referenceindexsorted')
root.append_under('npc -> librarylink', 'recordname', value='lists.npc@%s' % module_name)
root.append_under('root', 'lists')
root.append_under('lists', 'imagewindow')
root.append_under('lists -> imagewindow', 'name', {'type': "string"}, value='Images & Maps')
root.append_under('lists -> imagewindow', 'index')
root.append_under('lists', 'npc')
root.append_under('lists -> npc', 'name', {'type': "string"}, value='Story')
root.append_under('lists -> npc', 'index')
root.append_under('root', 'reference')
root.append_under('reference', 'imagedata')
root.append_under('imagedata', 'category', {"name": "RUNPC", "baseicon": "0", "decalicon": "0"})
root.append_under('reference', 'npcdata')
root.append_under('npcdata', 'category', {"name": "Ru", "baseicon": "0", "decalicon": "0"})
return root
if __name__ == '__main__':
module_name = 'Tomb'
module_file_name = '%s.mod' % module_name
if only_assemble_files:
zip_file = zipfile.ZipFile(module_file_name, 'w', zipfile.ZIP_DEFLATED)
zipdir(dist_folder, zip_file)
zip_file.close()
shutil.copy(module_file_name, fantasy_grounds_folder)
exit(0)
purge_dist_folder()
create_definition_xml(module_name, dist_folder)
xml = build_xml(module_name)
index = 14
total_text = ''
total_name = module_name
with open('stories.obj', 'rb') as stories_file:
stories = [pickle.loads(stories_file.read()), ]
print(stories)
for story in stories:
print(f'Story length: {len(story)}')
story_name = module_name
story_text = story
total_text += story_text
# if len(story_text) < 150:
# continue
story_index = 'id-%s' % str(index).zfill(5)
xml.append_under('npc -> index', '%s' % story_index)
xml.append_under('npc -> index -> %s' % story_index, 'listlink', {"type": "windowreference"})
xml.append_under('npc -> index -> %s -> listlink' % story_index, 'class', value='encounter')
xml.append_under('npc -> index -> %s -> listlink' % story_index, 'recordname', value='reference.npcdata.%s@%s' % (story_index, xml.module_name))
xml.append_under('npc -> index -> %s' % story_index, 'name', {"type": "string"}, value=str(index).zfill(5) + ' ' + translate_to_iso_codes(total_name))
xml.append_under('npcdata -> category', '%s' % story_index)
story_path = 'npcdata -> category -> %s' % story_index
xml.append_under(story_path, 'name', {'type': "string"}, value=translate_to_iso_codes(total_name))
xml.append_under(story_path, 'text', {'type': "formattedtext"}, value=translate_to_iso_codes(total_text))
index += 1
with open('%s/common.xml' % dist_folder, 'w+') as common_xml:
common_xml.write(str(xml))
common_xml.close()
zip_file = zipfile.ZipFile(module_file_name, 'w', zipfile.ZIP_DEFLATED)
zipdir(dist_folder, zip_file)
zip_file.close()
print(f'Copying {module_file_name} to {fantasy_grounds_folder}')
shutil.copy(module_file_name, fantasy_grounds_folder)
print('Done')
<file_sep>/parse_docx.py
from docx import Document
import pickle
document = Document('bestiary.docx')
monsters_names_to_text = {}
exceptions = ('Действия', 'Легендарные действия')
current_paragraph = None
current_paragraph_style = 'Normal'
previous_paragraph_style = 'Normal'
current_text = ''
current_monster_name = ''
for paragraph in document.paragraphs:
paragraph_style = paragraph.paragraph_format.element.xpath('w:pPr/w:shd')
if paragraph_style and paragraph_style[0].values()[2] == 'FDE9D9': # Citation
continue
if paragraph_style and paragraph_style[0].values()[2] == 'DDD9C3': # Stats block background
current_paragraph_style = 'Stats'
continue
# if previous_paragraph_style == 'Normal' and current_text.strip(): # Switching to stats block, need to print all we collected before
# monsters_names_to_text[current_monster_name] = current_text
# current_text = ''
# else: # White background or any other colors
# current_paragraph_style = 'Normal'
# if paragraph.style.name == 'Heading 1':
# if current_text.strip():
# monsters_names_to_text[current_monster_name] = current_text
# current_text = ''
if paragraph.style.name in ('Heading 1', ): # New monster starting
monsters_names_to_text[current_monster_name] = current_text
current_monster_name = paragraph.text.strip()
current_text = '<h>%s</h>' % current_monster_name
elif paragraph.style.name == 'Заголовок2Подч':
current_text += '<h>%s</h>' % current_monster_name
else:
if paragraph.text.strip():
current_text += '\n<p>'
for run in paragraph.runs:
text = run.text
if run.bold:
text = '<b>%s</b>' % text
if not text.strip():
continue
current_text += text
if paragraph.text.strip():
current_text += '</p>'
monsters_names_to_text[current_monster_name] = current_text
for monster_name in monsters_names_to_text.keys():
print(monsters_names_to_text[monster_name])
print('\n\n\n')
with open('docxsave.obj', 'wb') as f:
f.write(pickle.dumps(monsters_names_to_text))
# paragraph_color = paragraph.paragraph_format.element.xpath('w:pPr/w:shd')[0].values()
# print(paragraph_color)
# for run in paragraph.runs:
# print(run.text)
# print(run.font.color.element.xpath())
# if paragraph.style.name != 'Normal':
# print('%s: %s' % (paragraph.style.name, paragraph.text))
# else:
# for run in paragraph.runs:
# if not run.text.strip():
# continue
# if run.bold:
# print('<b>%s</b>' % run.text)
# else:
# print('"%s"' % run.text)
# print('\n\n')
<file_sep>/parse_html.py
"""
This module is intended for converting HTML file resulted from pdfminer into
Fantasy Ground module structure
python C:\\Users\\Dima\\pdfminer.six\\tools\\pdf2txt.py -o tomb_exported.html
"C:\\YandexDisk\\DnD\\Гробница Аннигиляции.pdf"
Result - object file with list of Fantasy Grounds formatted text
Tags:
p - Indicates paragraph using normal formatting.
h - Indicates a paragraph using header formatting.
frame - Indicates a paragraph using chat frame formatting.
frameid - Used within the frame tag, immediately following the frame open tag.
Indicates the speaker for chat text.
list - Indicates a list.
li - Used within the list tag. Supports a numerical indent attribute.
Indicates an entry in the list, and contains the text to display for
this list item.
linklist - Indicates a list of shortcut links.
(similar to windowreferencecontrols)
link - Used within the linklist tag. Supports a numerical indent attribute.
Indicates an entry in the link text, and contains the text to display next
to the link.
b - Used within p, li or link tags. Indicates that the text within
the tags should be bold.
i - Used within p, li or link tags. Indicates that the text within
the tags should be italicized.
u - Used within p, li or link tags. Indicates that the text within the
tags should be underlined.
table - Indicates a table. Tables can not be created or edited, only
accessed via modules created outside of FG.
tr - Used within the table tag. Indicates a table row.
td - Used within the tr tag. Supports a colspan attribute, similar to HTML
formatting. Indicates a table cell, and the text to display within the cell.
"""
from dataclasses import dataclass, field
from typing import Union, List, Tuple
import bs4
import os
import pickle
import functools
import re
@dataclass
class Error:
text: str
def __repr__(self):
return f'Error: {self.text}'
def get_font_family(style_string: str) -> str:
tokens = re.findall("font-family: b\\'(.+)\\'",
style_string)
if not tokens or len(tokens) < 1:
return style_string
return tokens[0]
def get_font_size(style_string: str) -> int:
tokens = re.findall("font-family: b'(.+)\+.+font-size:(\d+)px",
style_string)
if not tokens or len(tokens) != 1 or len(tokens[0]) != 2:
return 0
return int(tokens[0][1])
@dataclass
class TextBlock:
text: str
style: str
is_starting_block: bool = False
def __repr__(self):
font_family = get_font_family(self.style)
font_size = get_font_size(self.style)
return f'("{font_family}", {font_size}),\nText:\n{self.text}'
@dataclass
class Accumulator:
articles: List[str]
current_page: int = 0
previous_block: TextBlock = TextBlock('', '')
preprevious_block: TextBlock = TextBlock('', '')
start_next_paragraph_when_font_changes: bool = False
# book_started: bool = False
current_article_text: str = ''
current_text_block_number: int = 0
temporary_article: str = ''
debug: bool = False
currently_open_tags: list = field(default_factory=list)
def is_page_block_a_page_number(
page_block: TextBlock,
expected_font_family: str,
expected_font_size: int,
) -> int:
if (get_font_family(page_block.style) == expected_font_family and
get_font_size(page_block.style) == expected_font_size and
page_block.text.strip().isdigit()):
return int(page_block.text)
return 0
def maybe(func):
def runner(*args, **kwargs):
for positional_parameter in args:
if isinstance(positional_parameter, Error):
return positional_parameter
for parameter_name in kwargs:
parameter = kwargs[parameter_name]
if isinstance(parameter, Error):
return parameter
try:
return func(*args, **kwargs)
except Exception as e:
return Error(f'{type(e)}: {e}')
return runner
@maybe
def get_file_text(filename: str) -> Union[str, Error]:
with open(filename, encoding="utf-8") as input_file:
return input_file.read()
@maybe
def parse_into_beautiful_soup_html(
text: Union[str, Error],
) -> Union[Error, bs4.BeautifulSoup]:
return bs4.BeautifulSoup(text, "html.parser")
def get_paragraph_spans(paragraph: bs4.element.Tag) -> List[TextBlock]:
# if not paragraph.text.strip():
# return [TextBlock('', paragraph['style'])]
spans = [TextBlock(span.text, span['style']) for
span in paragraph.find_all('span')]
if not spans:
return [TextBlock(paragraph.text, paragraph['style']), ]
return spans
# return [TextBlock(span.text, span['style'])
# for span in paragraph.find_all('span')]
@maybe
def get_page_blocks(
name: str,
force_reread: bool = False,
) -> Union[List[TextBlock], Error]:
cache_file_name = f'{name}_pickle.obj'
if os.path.isfile(cache_file_name) and not force_reread:
try:
return pickle.loads(open(cache_file_name, 'rb').read())
except (TypeError, EOFError):
pass
initial_html_file_name = f"./{name}.html"
file_text = get_file_text(initial_html_file_name)
# I found no way to pickle soup object due to high level of recursion
print('Starting parsing html')
soup = parse_into_beautiful_soup_html(file_text)
print('Parsing html done')
paragraphs: list = soup.find_all('div')
spans_lists = map(get_paragraph_spans, paragraphs)
page_blocks = list((item for t in spans_lists for item in t))
open(cache_file_name, 'wb').write(pickle.dumps(page_blocks))
return page_blocks
def get_text_from_block(
previous_block: TextBlock,
current_block: TextBlock,
) -> str:
if current_block.text.strip() == '-' and \
not previous_block.text.endswith(' '):
return ''
if current_block.text == '\n' and not previous_block.text.endswith(' '):
return ' '
return current_block.text
def is_block_should_be_completely_ignored(
text_block: TextBlock,
previous_block: TextBlock):
if isinstance(text_block, Error):
return False
font_family = get_font_family(text_block.style)
font_size = get_font_size(text_block.style)
previous_font_size = get_font_size(previous_block.style)
# if font_size == 0:
# return True
if isinstance(font_family, Error) or isinstance(font_size, Error):
return True
if font_family in (
"GARIGC+Mookmania-Italic",
"TANMCH+OpenSans",
"UISOUA+OpenSans-Bold",
"LKERYS+Mookmania",
"IQTUIY+OpenSansLight-Italic",
) and text_block.text.strip() == '-':
return True
if font_family == "TWFNGC+Mr.NigaSmallCaps" and font_size == 10: # new page
return True
if (font_family, font_size) in (
# ("YGSRYS+Mr.NigaSmallCaps", 28),
("YGSRYS+Mr.NigaSmallCaps", 9),
):
return True
if (font_family, font_size) in (
("YGSRYS+Mr.NigaSmallCaps", 28),
) and previous_font_size == 0:
return True
return False
def close_opened_tags(tags_list: List[str]) -> str:
return ''.join([f'</{t}>' for t in tags_list[::-1]])
def normalize_word(word: str) -> str:
stripped_word = word.strip()
if len(stripped_word) < 3:
return word
first_letter = word.lstrip()[0]
last_part = word.split(first_letter)[1].lower()
before_first_letter = word.split(first_letter)[0]
return f'{before_first_letter}{first_letter}{last_part}'
def transform_text(
current_text: str,
previous_text: str,
# currently_opened_tags: List[str]
) -> str:
if isinstance(current_text, Error):
return ''
text_to_return = current_text
# text_to_return = text_to_return.strip()
if delete_leading_and_ending_tags(previous_text).endswith('.\n'):
text_to_return = '.' + text_to_return
text_to_return = text_to_return.replace('\n', '')
# if 'frame' not in currently_opened_tags:
text_to_return = text_to_return.replace('•', '*•')
text_to_return = restich_string(text_to_return)
if delete_leading_and_ending_tags(previous_text).endswith('.\n') and \
text_to_return.startswith('.'):
text_to_return = text_to_return[1:]
# Put new line before every number which is single paragraph
if text_to_return.strip().isdecimal():
text_to_return = f'*{text_to_return}'
if len(delete_leading_and_ending_tags(current_text)) > 0 \
and delete_leading_and_ending_tags(current_text)[0].isdecimal():
text_to_return = f'*{text_to_return}'
# if len(text_to_return.strip()) > 0 and
# text_to_return.strip()[0].isdecimal():
# text_to_return = f'*{text_to_return}'
return text_to_return
def delete_leading_and_ending_tags(string):
return re.sub(r'(</?.+?>)+', '', string)
def restich_string(input_string: str) -> str:
return re.sub(r'(\.)([А-Я])+', r'\g<1>*\g<2>', input_string)
def get_block_tag(
*,
current_block: TextBlock,
# previous_block: TextBlock,
) -> str:
current_font_family = get_font_family(current_block.style)
current_font_size = get_font_size(current_block.style)
if (current_font_family, current_font_size) in \
(
("FTEHSE+NodestoCyrillic", 55),
("YGSRYS+Mr.NigaSmallCaps", 28),
("FTEHSE+NodestoCyrillic", 54),
("YGSRYS+Mr.NigaSmallCaps", 15),
("YGSRYS+Mr.NigaSmallCaps", 20),
("YGSRYS+Mr.NigaSmallCaps", 13),
("EPUBEG+OpenSans-Bold-SC700", 11),
("EPUBEG+OpenSans-Bold-SC700", 16),
# ("VDMYED+OpenSans-Bold", 12),
):
return 'h'
if 'italic' in current_font_family.lower():
return 'i'
if 'bold' in current_font_family.lower():
return 'b'
# previous_font_family = get_font_family(previous_block.style)
# frame_styles = ('SXQHSE+Mookmania', 'EPUBEG+OpenSans-Bold-SC700',
# 'FBHCSE+OpenSans', )
#
# if previous_font_family in frame_styles + ('', ) and \
# current_font_family in frame_styles:
# return 'frame'
return 'p' # normal text paragraph
def blocks_font_the_same(block1: TextBlock, block2: TextBlock):
block1_font_family = get_font_family(block1.style)
block2_font_family = get_font_family(block2.style)
block1_font_size = get_font_size(block1.style)
block2_font_size = get_font_size(block2.style)
if block1_font_family != block2_font_family:
return False
if block1_font_size != block2_font_size:
return False
return True
def tags_should_be_closed(
*,
currently_openning_tag: str,
current_block: TextBlock,
previous_block: TextBlock,
previously_opened_tags: List[str],
) -> List[str]:
current_font_family = get_font_family(current_block.style)
previous_font_family = get_font_family(previous_block.style)
previous_block_tag = get_block_tag(current_block=previous_block)
if currently_openning_tag == previous_block_tag and \
current_font_family == previous_font_family:
return []
if currently_openning_tag == 'b':
return ['b']
if currently_openning_tag == 'i':
if previously_opened_tags and previously_opened_tags[-1] == 'b':
return ['b', 'i']
return ['i']
if currently_openning_tag in ('p', 'h'):
return ['b', 'i']
# if currently_openning_tag == 'frame':
# return ['i', 'b', 'frame']
return []
def open_p_paragraph(currently_opened_tags: List[str]) -> List[str]:
return [f'</{tag}>' for tag in currently_opened_tags[::-1]] + ['<p>', ]
def open_header(currently_opened_tags: List[str]):
return [f'</{tag}>' for tag in currently_opened_tags[::-1]] + ['<h>', ]
def tags_should_be_opened(
*,
current_tag: str,
previously_opened_tags: List[str],
current_block: TextBlock,
previous_block: TextBlock,
acc: Accumulator,
) -> List[str]:
current_font_family = get_font_family(current_block.style)
current_font_size = get_font_size(current_block.style)
previous_font_family = get_font_family(previous_block.style)
previous_font_size = get_font_size(previous_block.style)
previous_block_tag = get_block_tag(current_block=previous_block)
if current_tag == previous_block_tag and \
current_font_family == previous_font_family:
return []
if (current_font_family, current_font_size) == \
("FBHCSE+OpenSans", 10) and \
(previous_font_family, previous_font_size) not in \
(
("FBHCSE+OpenSans", 10),
("VDMYED+OpenSans-Bold", 10),
("OXHEKR+OpenSans-Italic", 10),
("TANMCH+OpenSans", 10),
):
acc.start_next_paragraph_when_font_changes = True
return ['frame', ]
if current_tag in ('b', 'i'):
if current_tag in previously_opened_tags:
return []
elif 'p' not in previously_opened_tags:
return ['p', current_tag]
else:
return [current_tag, ]
return []
def new_header_should_be_started(current_block, previous_block) -> bool:
if previous_block.is_starting_block and \
get_block_tag(current_block=current_block) == 'h':
return True
if get_block_tag(current_block=current_block) == 'h' and \
get_block_tag(current_block=previous_block) != 'h':
return True
return False
def new_paragraph_should_be_started(current_block, previous_block, acc) -> bool:
current_tag = get_block_tag(current_block=current_block)
previous_tag = get_block_tag(current_block=previous_block)
previous_font_family = get_font_family(previous_block.style)
previous_font_size = get_font_size(previous_block.style)
current_font_family = get_font_family(current_block.style)
current_font_size = get_font_size(current_block.style)
if previous_block.is_starting_block and current_tag != 'h':
return True
if previous_tag == 'h' and current_tag != 'h':
return True
if (current_font_family, current_font_size) == \
("EFQWEG+VictorianGothicThree", 105):
return True
if (current_font_family, current_font_size) == \
("VDMYED+OpenSans-Bold", 10) and \
(previous_font_family, previous_font_size) != \
("VDMYED+OpenSans-Bold", 10):
return True
if (current_font_family, current_font_size) == \
("WCDQSB+Mookmania-Bold", 12):
text = current_block.text.strip()
if len(text) > 0 and text[0].isdecimal():
return True
if (current_font_family, current_font_size) == \
("MWRSMQ+OpenSansLight-Italic", 9) and \
(previous_font_family, previous_font_size) != \
("MWRSMQ+OpenSansLight-Italic", 9):
acc.start_next_paragraph_when_font_changes = True
return True
return False
def reduce_text_blocks2(acc: Accumulator, current_block: TextBlock):
acc.current_text_block_number += 1
current_tag = get_block_tag(
current_block=current_block,
# previous_block=acc.previous_block,
)
text_to_add = ''
if acc.debug:
print(current_block)
print(f'Block number: {acc.current_text_block_number}')
if is_block_should_be_completely_ignored(current_block, acc.previous_block):
return acc
if not blocks_font_the_same(current_block, acc.previous_block):
if new_header_should_be_started(current_block, acc.previous_block):
text_to_add = ''.join(open_header(acc.currently_open_tags))
acc.currently_open_tags = ['h', ]
elif new_paragraph_should_be_started(
current_block,
acc.previous_block,
acc):
text_to_add = ''.join(open_p_paragraph(acc.currently_open_tags))
acc.currently_open_tags = ['p', ]
elif acc.start_next_paragraph_when_font_changes:
text_to_add = ''.join(open_p_paragraph(acc.currently_open_tags))
acc.currently_open_tags = ['p', ]
acc.start_next_paragraph_when_font_changes = False
tags_to_be_closed = tags_should_be_closed(
currently_openning_tag=current_tag,
current_block=current_block,
previous_block=acc.previous_block,
previously_opened_tags=acc.currently_open_tags,
)
for currently_opened_tag in acc.currently_open_tags[::-1]:
if currently_opened_tag in tags_to_be_closed:
acc.currently_open_tags.remove(currently_opened_tag)
text_to_add += f'</{currently_opened_tag}>'
tags_to_be_opened = tags_should_be_opened(
current_tag=current_tag,
previously_opened_tags=acc.currently_open_tags,
current_block=current_block,
previous_block=acc.previous_block,
acc=acc,
)
for tag_to_be_opened in tags_to_be_opened:
acc.currently_open_tags.append(tag_to_be_opened)
text_to_add += f'<{tag_to_be_opened}>'
# tags_to_be_closed = tags_should_be_closed(
# current_tag,
# # acc.currently_open_tags,
# )
#
# for tag in acc.currently_open_tags[::-1]:
# if tag in tags_to_be_closed:
# acc.currently_open_tags.remove(tag)
# text_to_add += f'</{tag}>'
#
# if should_open_new_tag(
# previously_opened_tags=acc.currently_open_tags,
# previous_block=acc.previous_block,
# preprevious_block=acc.preprevious_block,
# current_block=current_block,
# ):
#
# if current_tag in ('b', 'i') and 'p' not in
# acc.currently_open_tags:
# acc.currently_open_tags.append('p')
# text_to_add += '<p>'
#
# acc.currently_open_tags.append(current_tag)
# text_to_add += f'<{current_tag}>'
# # print(f'New tag should be opened: {current_tag}')
text_to_add += get_text_from_block(acc.previous_block, current_block)
acc.current_article_text += transform_text(
text_to_add,
acc.previous_block.text,
)
if acc.debug:
print(f'Currently opened tags: {acc.currently_open_tags}')
print('\n\n')
acc.preprevious_block = acc.previous_block
acc.previous_block = current_block
return acc
def split_articles(incoming_text) -> List[Tuple[str, str]]:
output_list = []
articles = ['<h>' + a for a in incoming_text.split('<h>') if a]
for article_number, a in enumerate(articles):
output_list.append(
(str(article_number).zfill(5) + ' ' +
re.findall(r'<h>(.+)</h>', a)[0], a))
return output_list
@maybe
def get_stories(
mod_name: str,
blocks_from_to: tuple = (),
debug: bool = False,
several_blocks: bool = False,
) -> List[Tuple[str, str]]:
text_blocks = get_page_blocks(mod_name, force_reread=False)
print(text_blocks)
if blocks_from_to:
text_blocks = text_blocks[blocks_from_to[0]:blocks_from_to[1]]
articles = functools.reduce(
reduce_text_blocks2,
text_blocks,
Accumulator(
[],
debug=debug,
previous_block=TextBlock('', '', is_starting_block=True),
preprevious_block=TextBlock('', '', is_starting_block=True),
),
)
articles.current_article_text += close_opened_tags(
articles.currently_open_tags)
articles.articles.append(articles.current_article_text)
if several_blocks:
return split_articles(articles.articles[0])
return [('Full Text', articles.articles[0])]
if __name__ == '__main__':
print(get_stories(
"dragon_rus",
(0, 200),
debug=True,
several_blocks=False,
))
<file_sep>/fetch_images.py
import requests
import shutil
from bs4 import BeautifulSoup
for page_number in range(1, 42):
print('Page %s' % page_number)
url = 'https://www.dndbeyond.com/monsters?page=%s' % page_number
result = requests.get(url)
soup = BeautifulSoup(result.text, "html5lib")
monsters_list = soup.find_all('div', {'data-type': 'monsters'})
for monster in monsters_list:
name = monster.find('a', {'class': 'link'}).contents[0]
image_div = monster.find('div', {'class': 'row monster-icon'}).find('a')
if not image_div:
print('%s has no picture' % name)
continue
image_link = image_div['href']
print('%s %s' % (name, image_link))
try:
response = requests.get(image_link, stream=True)
with open('%s.jpg' % name, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
except Exception as e:
print(e)
|
9d4ff5e70147b82fa133bf00fe87b1f08ee76e1e
|
[
"Python"
] | 13
|
Python
|
kreodont/fg
|
39e52c403b62653b1be15d053d494e336231a850
|
6d35f865ee10bdd184ba0a2a5b902ca806b5f958
|
refs/heads/master
|
<file_sep>import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
/**
* Class BallDemo - a short demonstration showing animation with the
* Canvas class.
*
* @author <NAME> and <NAME>
* @version 2011.07.31
*/
public class BallDemo
{
private Canvas myCanvas;
/**
* Create a BallDemo object. Creates a fresh canvas and makes it visible.
*/
public BallDemo()
{
// 600 es la x y 500 es la y
myCanvas = new Canvas("Ball Demo", 600, 500);
}
/**
* Simulate two bouncing balls
*/
public void bounce1(int bola)
{
int ground = 400; // position of the ground line
myCanvas.setVisible(true);
// draw the ground
myCanvas.drawLine(50, ground, 550, ground);
ArrayList <BouncingBall> bolas = new ArrayList<>();
// caja y mostrar las bolas
for(int i=0; i<bola; i++){
Random aleatorio = new Random ();
int x = aleatorio.nextInt(300);
int y = aleatorio.nextInt(250);
int diametro = aleatorio.nextInt(50);
int colorRojo = aleatorio.nextInt(256);
int colorVerde = aleatorio.nextInt(256);
int colorAzul = aleatorio.nextInt(256);
BouncingBall ball = new BouncingBall(x, y, diametro, new Color(colorRojo, colorVerde, colorAzul), ground, myCanvas);
ball.draw();
bolas.add(ball);
}
// make them bounce
boolean finished = false;
while(!finished) {
myCanvas.wait(50); // small delay
for(BouncingBall cadaBola:bolas){
cadaBola.move();
// stop once ball has travelled a certain distance on x axis
if(cadaBola.getXPosition() >= 550) {
finished = true;
break;
}
}
}
}
public void boxBounce(int bola){
ArrayList <BoxBall> bolas = new ArrayList<>();
int techoDelRectangulo = 100;
int sueloDelRectangulo = 300;
int paredIzquierdaRectangulo = 100;
int paredDerechaRectangulo = 400;
myCanvas.fillRectangle(paredIzquierdaRectangulo,techoDelRectangulo,paredDerechaRectangulo - paredIzquierdaRectangulo,sueloDelRectangulo - techoDelRectangulo);
myCanvas.setVisible(true);
// caja y mostrar las bolas
for(int i=0; i<bola; i++){
Random aleatorio = new Random ();
int x = aleatorio.nextInt(300)+100;
int y = aleatorio.nextInt(200) +100;
int diametro = aleatorio.nextInt(50);
int colorRojo = aleatorio.nextInt(256);
int colorVerde = aleatorio.nextInt(256);
int colorAzul = aleatorio.nextInt(256);
int ySpeed = 1;
int xSpeed = 1;
// BouncingBall ball = new BouncingBall(x, y, diametro, new Color(colorRojo, colorVerde, colorAzul), ground, myCanvas);
BoxBall ball = new BoxBall(x, y, diametro, new Color(colorRojo, colorVerde, colorAzul), ySpeed, xSpeed, paredIzquierdaRectangulo, techoDelRectangulo, paredDerechaRectangulo, sueloDelRectangulo, myCanvas);
ball.draw();
bolas.add(ball);
}
// make them bounce
boolean finished = false;
while(!finished) {
myCanvas.wait(10); // Cambiado el parametro de 50 a 10 para que vaya mas rapido
for(BoxBall cadaBola:bolas){
cadaBola.move();
}
}
}
}
|
bc6acbba30fba2167a5cfb142fe4fd07e0a16d6d
|
[
"Java"
] | 1
|
Java
|
saragonzalez/0100
|
416e331d412a706d29343d828d9504c2d09dd3d9
|
bdd2e2ba4639fb2bc740752dec82301a63f50bdd
|
refs/heads/master
|
<repo_name>tidydee/Sintra_exercrise<file_sep>/app/models/message.rb
class Message < ActiveRecord::Base
validates :title,
presence: true,
length: { minimum:3 }
validates :author,
presence: true,
length: { minimum:3 }
validates :content,
presence: true,
length: { minimum:3 }
end
|
e541e42077a7dfcafc9a570bf62276a3b9057fc4
|
[
"Ruby"
] | 1
|
Ruby
|
tidydee/Sintra_exercrise
|
36fba5b6513dce76995b716a602357b78a48b3de
|
a1c3f56f91eaeeeedec06ffd88f7de788154741c
|
refs/heads/master
|
<repo_name>spawaskar-cora/cora-analytics-docker<file_sep>/analytics/admin.py
from django.contrib import admin
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_text
from django.utils.html import format_html
# Register your models here.
from .forms.helpers import FormSetWithParentAccess
from .models.toolkits import Toolkit
from .models.tools import Tool
from .models.tools_input import InputParameter, InputParameterStringValueOption, \
InputParameterNumericValueOption
from .models.tools_output import OutputFile
from .models.file_types import FileType
from .forms.custom_admin_forms import CustomToolkitAdminForm, CustomToolAdminForm,\
CustomInputParameterInlineForm, CustomInputParameterAdminForm, \
CustomInputParameterStringValueAdminForm, \
CustomInputParameterNumericValueAdminForm, CustomFileTypeAdminForm, \
CustomOutputFileAdmin
from .models.results import Result
class EditLinkToInlineObject(object):
def edit_link(self, obj=None):
if obj.pk:
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name),
args=[force_text(obj.id)])
return format_html("<a href= '{}'>{}</a>", url, self.url_text)
return _("(save and continue editing to create a link)")
edit_link.short_description = _("Edit link")
class ToolsInline(EditLinkToInlineObject, admin.StackedInline):
extra = 0
verbose_name_plural = "Current tool list"
url_text = "Add or edit tool input and output parameters"
model = Tool
form=CustomToolAdminForm
fields = ('tool_name', 'display_name', 'tool_type', 'short_description', 'long_description', 'toolkit', 'edit_link')
exclude = ('updated_at',)
readonly_fields = ('edit_link',)
classes = ['collapse']
def has_add_permission(self, request):
return False
class AddToolsInline(admin.StackedInline):
extra = 0
verbose_name_plural = "Add new tool"
model = Tool
form=CustomToolAdminForm
fields = ('tool_name', 'display_name', 'tool_type', 'short_description', 'long_description', 'toolkit')
exclude = ('updated_at',)
def has_change_permission(self, request, obj=None):
return False
class InputParametersInline(EditLinkToInlineObject, admin.StackedInline):
extra = 0
verbose_name_plural = "Current input parameter list"
url_text = "Add or edit input parameter value options"
model = InputParameter
formset = FormSetWithParentAccess
form = CustomInputParameterInlineForm
fields= ('parameter_name', 'display_name', 'short_description', 'tool', 'parameter_type',
'parameter_required', 'requires', 'excludes', 'edit_link')
exclude = ('updated_at',)
classes = ['collapse']
readonly_fields = ['edit_link', 'parameter_type']
def has_add_permission(self, request):
return False
class AddInputParametersInline(admin.StackedInline):
extra = 0
verbose_name_plural = "Add new input parameter"
model = InputParameter
formset = FormSetWithParentAccess
form = CustomInputParameterInlineForm
fields= ('parameter_name', 'display_name', 'short_description', 'tool', 'parameter_type',
'parameter_required', 'requires', 'excludes')
exclude = ('updated_at',)
def has_change_permission(self, request, obj=None):
return False
class InputParameterStringValueOptionInline(admin.StackedInline):
extra = 3
model = InputParameterStringValueOption
formset = FormSetWithParentAccess
form = CustomInputParameterStringValueAdminForm
fields = ('string_value', 'short_description', 'default_value',
'parameter', 'requires', 'excludes')
exclude = ('updated_at',)
class InputParameterNumericValueOptionInline(admin.StackedInline):
extra = 3
model = InputParameterNumericValueOption
form = CustomInputParameterNumericValueAdminForm
fields = ('numeric_value', 'short_description', 'default_value',
'parameter')
exclude = ('updated_at',)
class OutputFilesInline(EditLinkToInlineObject, admin.StackedInline):
extra=0
url_text = "Edit output file"
model = OutputFile
form = CustomOutputFileAdmin
fields=('parameter_name', 'file_base_name', 'file_type', 'short_description', 'tool')
exclude = ('updated_at',)
classes = ['collapse']
verbose_name_plural = "List of current output files"
def has_add_permission(self, request):
return False
class AddOutputFilesInline(admin.StackedInline):
extra=0
verbose_name_plural = "Add new output file"
model = OutputFile
form = CustomOutputFileAdmin
fields=('parameter_name', 'file_base_name', 'file_type', 'short_description', 'tool')
exclude = ('updated_at',)
def has_change_permission(self, request, obj=None):
return False
class InputParameterAdmin(admin.ModelAdmin):
inlines = (InputParameterStringValueOptionInline,
InputParameterNumericValueOptionInline,)
model = InputParameter
form = CustomInputParameterAdminForm
fields = ('parameter_name', 'short_description', 'tool', 'parameter_type',
'parameter_required', 'requires', 'excludes')
exclude = ('updated_at',)
def get_model_perms(self, request):
"""Return empty perms dict to hide model from admin index
"""
return {}
def get_readonly_fields(self, request, obj=None):
if obj: #This is the case when obj is already created. i.e on edit page.
return ['parameter_type']
else:
return []
def get_fields(self, request, obj=None):
if obj is not None:
if obj.parameter_type == "FILE" or obj.parameter_type == "FILE_SELECT":
return ('parameter_name', 'short_description', 'tool', 'parameter_type',
'parameter_required', 'file_type', 'requires', 'excludes')
return ('parameter_name', 'short_description', 'tool', 'parameter_type',
'parameter_required', 'requires', 'excludes')
def get_formsets_with_inlines(self, request, obj=None):
if obj is not None:
for inline in self.get_inline_instances(request, obj):
if isinstance(inline, InputParameterStringValueOptionInline
) and obj.parameter_type == "STR":
yield inline.get_formset(request, obj), inline
if isinstance(inline, InputParameterNumericValueOptionInline
) and obj.parameter_type == "NUMERIC":
yield inline.get_formset(request, obj), inline
class ToolAdmin(admin.ModelAdmin):
inlines = (AddInputParametersInline, InputParametersInline,
AddOutputFilesInline, OutputFilesInline,)
model = Tool
form = CustomToolAdminForm
fields = ('tool_name', 'display_name', 'tool_type', 'short_description', 'long_description', 'toolkit')
exclude = ('updated_at',)
list_filter = ('toolkit',)
class ToolkitAdmin(admin.ModelAdmin):
inlines = (AddToolsInline, ToolsInline,)
model = Toolkit
form = CustomToolkitAdminForm
fields = ('toolkit_name', 'display_name', 'short_description', 'long_description')
exclude = ('updated_at',)
class ResultAdmin(admin.ModelAdmin):
model = Result
fields = ('file_name', 'task_id', 'tool', 'file_type', 'created_at', 'status')
exclude = ('updated_at', 'user_id')
readonly_fields = ['file_name', 'task_id', 'tool', 'created_at']
class FileTypeAdmin(admin.ModelAdmin):
model = FileType
form = CustomFileTypeAdminForm
fields = ('file_type_name', 'display_name', 'short_description', 'file_extension')
exclude = ('updated_at',)
admin.site.register(FileType, FileTypeAdmin)
admin.site.register(Tool, ToolAdmin)
admin.site.register(Toolkit, ToolkitAdmin)
admin.site.register(InputParameter, InputParameterAdmin)
admin.site.register(Result, ResultAdmin)<file_sep>/analytics/models/tools_input.py
from django.db import models
from django.utils import timezone
from .tools import Tool
from .file_types import FileType
class InputParameter(models.Model):
parameter_name = models.CharField(max_length=200)
display_name = models.CharField(max_length=200)
short_description = models.CharField(max_length=200)
tool = models.ForeignKey(Tool, on_delete=models.CASCADE,)
boolean_param = 'BOOL'
string_param = 'STR'
numerical_param = 'NUMERIC'
file_param = 'FILE'
file_select_param = 'FILE_SELECT' # server side file
header_select_param = 'HEADER_SELECT' # select value based on uploaded csv, tsv, header files
parameter_type_choices = (
(boolean_param, 'Boolean'),
(string_param, 'String'),
(numerical_param, 'Numerical'),
(file_param, 'File'),
(file_select_param, 'File Select'),
(header_select_param, 'Header Select'),
)
parameter_type = models.CharField(max_length=30, choices=parameter_type_choices)
parameter_required = models.BooleanField()
file_type = models.ManyToManyField(FileType, blank=True)
#check for bugs - Can requires and excludes be set to self? Probably yes. ## FIXED
requires = models.ManyToManyField('self', blank=True, symmetrical=False,
related_name='requiring_parameters',
verbose_name='Requires input parameters')
excludes = models.ManyToManyField('self', blank=True, symmetrical=False,
related_name='excluded_parameters',
verbose_name='Excludes input parameters')
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def __unicode__(self):
return u"%s" % self.parameter_name
def __str__(self):
return self.parameter_name
def save(self, *args, **kwargs):
"""On save update timestamp"""
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(InputParameter, self).save(*args, **kwargs) # call the real save method
class InputParameterStringValueOption(models.Model):
string_value = models.CharField(max_length=200)
short_description = models.CharField(max_length=200)
default_value = models.BooleanField()
parameter = models.ForeignKey(InputParameter, on_delete=models.CASCADE)
requires = models.ManyToManyField('InputParameter', blank=True, symmetrical=False,
related_name='requiring_values',
verbose_name='Requires input parameters')
excludes = models.ManyToManyField('InputParameter', blank=True, symmetrical=False,
related_name='excluding_values',
verbose_name='Excludes input parameters')
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def __unicode__(self):
return u"%s" % self.string_value
def __str__(self):
return self.string_value
def save(self, *args, **kwargs):
"""On save update timestamp"""
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
if self.default_value:
if self.parameter.parameter_required:
raise ValueError("Parameter value required: can not have default.")
try:
temp = InputParameterStringValueOption.objects.get(parameter_id=self.parameter, default_value=True)
if self != temp:
temp.default_value = False
temp.save()
except InputParameterStringValueOption.DoesNotExist:
pass
super(InputParameterStringValueOption, self).save(*args, **kwargs)
class InputParameterNumericValueOption(models.Model):
numeric_value = models.FloatField(max_length=200)
short_description = models.CharField(max_length=200)
default_value = models.BooleanField()
parameter = models.ForeignKey(InputParameter, on_delete=models.CASCADE)
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def __unicode__(self):
return u"%s" % str(self.numeric_value)
def __str__(self):
return str(self.numeric_value)
def save(self, *args, **kwargs):
"""On save update timestamp"""
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
if self.default_value:
if self.parameter.parameter_required:
raise ValueError("Parameter value required: can not have default.")
try:
temp = InputParameterNumericValueOption.objects.get(parameter_id=self.parameter, default_value=True)
if self != temp:
temp.default_value = False
temp.save()
except InputParameterNumericValueOption.DoesNotExist:
pass
super(InputParameterNumericValueOption, self).save(*args, **kwargs)<file_sep>/bin/z-transform-method/src/CSVRow.cpp
/*
* CSVRow.cpp
*
* Created on: Jan 14, 2017
* Author: Julia
*/
#include <iterator>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
#include "CSVRow.h"
CSVRow::CSVRow() {
// TODO Auto-generated constructor stub
}
CSVRow::~CSVRow() {
// TODO Auto-generated destructor stub
}
string const & CSVRow::operator[](size_t index) const {
return m_data[index];
}
size_t CSVRow::size() const
{
return m_data.size();
}
void CSVRow::readNextRow(std::istream& str) {
std::string line;
std::getline(str, line);
std::stringstream lineStream(line);
std::string cell;
m_data.clear();
while(std::getline(lineStream, cell, '\t'))
{
m_data.push_back(cell);
}
// This checks for a trailing comma with no data after it.
if (!lineStream && cell.empty())
{
// If there was a trailing comma then add an empty element.
m_data.push_back(string(""));
}
}
istream& operator>>(istream& str, CSVRow& data)
{
data.readNextRow(str);
return str;
}
<file_sep>/bin/z-transform-method/src/Main.cpp
/*
* Main.cpp
*
* Created on: Jan 14, 2017
* Author: Julia
*/
#include<iostream>
#include<dirent.h>
#include <sys/stat.h>
#include <RInside.h>
#include <fstream>
#include<cstring>
#include<ctime>
using namespace std;
#include "SEinventory.h"
#include "CSVRow.h"
#include "CSVIterator.h"
#include "Summator.h"
#include "Mean.h"
#include "Variance.h"
#include "Correlation.h"
#include "tTest.h"
#include "LinearRegression.h"
#include "ZScoreMethod.h"
#define help 911
#define bufOverflow 999
#define notFound 404
#define parseError 123
#define paramError 500
void help_message(int err_message)
{
cerr<<endl;
cerr<<endl;
cerr<<endl;
cerr<<"SE_Compare: Written by <NAME>"<<endl;
cerr<<endl;
cerr<<"Usage: SE_Compare [Options]"<<endl;
cerr<<endl;
cerr<<"Options:"<<endl;
cerr<<"--rTrain: [Required]: right side skeletal elements ref. population"<<endl;
cerr<<"--lTrain: [Required]: left side skeletal elements ref. population"<<endl;
cerr<<"--rClass: right side skeletal elements population to be tested"<<endl;
cerr<<"--lClass: left side skeletal elements population to be tested"<<endl;
cerr<<"--uweightedZ: The unweighted Zscore method for generating p-values is used"<<endl;
cerr<<"--effectSizeZ: The weighted (effect size) Zscore method for generating p-values is used"<<endl;
cerr<<"--standardErrorZ: The weighted (standard error) Zscore method for generating p-values is used"<<endl;
cerr<<"--tTest: The t-test for summed measurements to generate p-values is used"<<endl;
cerr<<"--abs_tTest: The absolute value t-test for summed measurements to generate p-values is used"<<endl;
cerr<<"--tTest_wMean: The t-test (mean-centered) for summed measurements to generate p-values is used"<<endl;
cerr<<"--LOOCV: Leave one out cross validation (Performed on training data)"<<endl;
cerr<<"--descLen: Maximum skeletal element name length (default 50)"<<endl;
cerr<<"--header: The first line of the input files is the header line (default true)"<<endl;
cerr<<"--time: Print the start and end time for the program"<<endl;
cerr<<endl;
cerr<<endl;
cerr<<endl;
cerr<<"Example Usage:"<<endl;
cerr<<endl;
cerr<<"Perform Leave-One-Out Crossvalidation on Reference population set using unweighted Z method"<<endl;
cerr<<"./SE_Compare --rTrain fileR --lTrain fileL --uweightedZ TRUE"<<endl;
cerr<<endl;
cerr<<"Use t-test method to obtain p-values for test data using a reference population set"<<endl;
cerr<<"./SE_Compare --rTrain fileR --lTrain fileL --rClass file2R --lClass file2L --tTest TRUE"<<endl;
cerr<<endl;
cerr<<endl;
cerr<<endl;
cerr<<"Input file format (Tab delimited file):"<<endl;
cerr<<"ID "<<"[TAB]"<<" Size "<<"[TAB]"<<" Element "<<"[TAB]"<<" Measure 1 "<<"[TAB]"<<" Measure 2 "<<"[TAB]"<<" ... "<<"[TAB]"<<" Measure N"<<endl;
cerr<<endl;
cerr<<endl;
exit(911);
}
int main(int argc, char * argv[])
{
RInside R;
//Param options and defaults
string rightFileTrain = "noFile"; //right side skeletal elements ref. population
string leftFileTrain = "noFile"; //left side skeletal elements ref. population
string rightFileClass = "noFile"; //right side skeletal elements population to be tested
string leftFileClass = "noFile"; //left side skeletal elements population to be tested
bool unweightedZscore = false; //The unweighted Zscore method for generating p-values is used.
bool weightedEffectZscore = false; //The weighted (effect size) Zscore method for generating p-values is used.
bool weightedStdErrZscore = false; //The weighted (standard error) Zscore method for generating p-values is used.
bool sumtTest = false; //The t-test for summed measurements to generate p-values is used.
bool abstTest = false; //The absolute value t-test for summed measurements to generate p-values is used.
bool meanSumtTest = false; //The t-test (mean-centered) for summed measurements to generate p-values is used.
int minSig = 1;
bool LOOCV = false; //Leave one out cross validation
bool KFCV = false; //K-fold cross validation.If both the training and classification
//files are available than this parameter is disabled.
//Other Parameters
int seNameLen = 50; //Maximum skeletal element length
bool header = TRUE; //Are there headers on the input files: default true
bool timeT = FALSE;
//user options
string rightFileTrainS = "--rTrain";
string leftFileTrainS = "--lTrain";
string rightFileClassS = "--rClass";
string leftFileClassS = "--lClass";
string unweightedZscoreS = "--uweightedZ";
string weightedEffectZscoreS = "--effectSizeZ";
string weightedStdErrZscoreS = "--standardErrorZ";
string sumtTestS = "--tTest";
string abstTestS = "--abs_tTest";
string meanSumtTestS = "--tTest_wMean";
string LOOCVS = "--LOOCV";
string KFCVS = "--KFCV";
string seNameLenS = "--descLen";
string headerS = "--header";
string timeS = "--time";
for(int i = 1; i < argc; i+=2)
{
//The input files
if(argv[i] == rightFileTrainS)
{
rightFileTrain = argv[i+1];
}
if(argv[i] == leftFileTrainS)
{
leftFileTrain = argv[i+1];
}
if(argv[i] == rightFileClassS)
{
rightFileClass = argv[i+1];
}
if(argv[i] == leftFileClassS)
{
leftFileClass = argv[i+1];
}
//Methods
if(argv[i] == unweightedZscoreS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
unweightedZscore = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
unweightedZscore = true;
}
}
}
if(argv[i] == weightedEffectZscoreS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
weightedEffectZscore = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
weightedEffectZscore = true;
}
}
}
if(argv[i] == weightedStdErrZscoreS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
weightedStdErrZscore = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
weightedStdErrZscore = true;
}
}
}
if(argv[i] == sumtTestS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
sumtTest = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
sumtTest = true;
}
}
}
if(argv[i] == abstTestS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
abstTest = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
abstTest = true;
}
}
}
if(argv[i] == meanSumtTestS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
meanSumtTest = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
meanSumtTest = true;
}
}
}
//Cross-Validation methods
if(argv[i] == LOOCVS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
LOOCV = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
LOOCV = true;
}
}
}
if(argv[i] == KFCVS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
KFCV = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
KFCV = true;
}
}
}
//Other Parameters
if(argv[i] == seNameLenS)
{
seNameLen = atoi(argv[i+1]);
}
if(argv[i] == headerS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
header = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
header = true;
}
}
}
if(argv[i] == timeS)
{
string TorF = argv[i+1];
if(TorF.compare("FALSE") == 0 || TorF.compare("F") == 0)
{
timeT = false;
}else{
if(TorF.compare("TRUE") == 0 || TorF.compare("T") == 0)
{
timeT = true;
}
}
}
}
clock_t t1,t2;
t1=clock();
//PARAMETER CHECKING//
//User forgot a file, oops
if(argc == 1 || rightFileTrain.compare("noFile") == 0 || leftFileTrain.compare("noFile") == 0)
{
cerr<<"TRAINING FILES NOT FOUND"<<endl;
cerr<<endl;
help_message(notFound);
}
if(rightFileClass.compare("noFile") != 0 || leftFileClass.compare("noFile") != 0 )
{
LOOCV = false; KFCV = false;
}
if(argc == 1 || (rightFileClass.compare("noFile") != 0 && leftFileClass.compare("noFile") == 0))
{
cerr<<"MISSING THE LEFT CLASSIFICATION FILE"<<endl;
help_message(notFound);
}
if(argc == 1 || (rightFileClass.compare("noFile") == 0 && leftFileClass.compare("noFile") != 0))
{
cerr<<"MISSING THE RIGHT CLASSIFICATION FILE"<<endl;
help_message(notFound);
}
ifstream iFile (rightFileTrain.c_str());
if(header)
{
string line;
getline(iFile, line);
}
int numRecordsRT = 0; int numMeasurementsRT = 0;
string elementTypeRT = ""; string elementSideRT = "";
for(CSVIterator loop(iFile); loop != CSVIterator(); ++loop)
{
numMeasurementsRT = (*loop).size() - 3;
elementSideRT = (*loop)[1];
elementTypeRT = (*loop)[2];
numRecordsRT++;
}
iFile.close();
SEinventory rightTrain(numMeasurementsRT, numRecordsRT, seNameLen, elementSideRT, elementTypeRT);
float * measures = new float[numMeasurementsRT]; string id;
iFile.open(rightFileTrain.c_str());
if(header)
{
string line;
getline(iFile, line);
}
for(CSVIterator loop(iFile); loop != CSVIterator(); ++loop)
{
for(int i = 0; i < (*loop).size()-3; i++)
{
measures[i] = atof((*loop)[i+3].c_str());
}
id = (*loop)[0];
rightTrain.addMeasurements(id, measures);
}
iFile.close();
iFile.open(leftFileTrain.c_str());
if(header)
{
string line;
getline(iFile, line);
}
int numRecordsLT = 0; int numMeasurementsLT = 0;
string elementTypeLT = ""; string elementSideLT = "";
for(CSVIterator loop(iFile); loop != CSVIterator(); ++loop)
{
numMeasurementsLT = (*loop).size() - 3;
elementSideLT = (*loop)[1];
elementTypeLT = (*loop)[2];
numRecordsLT++;
}
iFile.close();
if(numMeasurementsLT != numMeasurementsRT)
{
delete [] measures;
cerr<<"Number of measurements in right and left ";
cerr<<"training files do not match"<<endl;
help_message(parseError);
}
if(numRecordsLT != numRecordsRT)
{
delete [] measures;
cerr<<"Number of records in right and left ";
cerr<<"training files do not match"<<endl;
help_message(parseError);
}
SEinventory leftTrain(numMeasurementsLT, numRecordsLT, seNameLen, elementSideLT, elementTypeLT);
iFile.open(leftFileTrain.c_str());
if(header)
{
string line;
getline(iFile, line);
}
for(CSVIterator loop(iFile); loop != CSVIterator(); ++loop)
{
for(int i = 0; i < (*loop).size()-3; i++)
{
measures[i] = atof((*loop)[i+3].c_str());
}
id = (*loop)[0];
leftTrain.addMeasurements(id, measures);
}
iFile.close();
int numRecordsTrain = (numRecordsRT+numRecordsLT)/2;
int numMeasurementsTrain = (numMeasurementsRT + numMeasurementsLT)/2;
double ** Dvals = new double * [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
Dvals[i] = new double[numRecordsTrain];
}
for(int i = 0; i < numMeasurementsTrain; i++)
{
for(int j = 0; j < numRecordsTrain; j++)
{
Dvals[i][j] = leftTrain.getRecordMeas(j,i) - rightTrain.getRecordMeas(j,i); //CHANGED
}
}
double means[numMeasurementsTrain]; Mean<double> mean;
for(int i = 0; i < numMeasurementsTrain; i++)
{
means[i] = mean.getMean(Dvals[i], numRecordsTrain);
}
double vars[numMeasurementsTrain]; Variance<double> var;
for(int i = 0; i < numMeasurementsTrain; i++)
{
vars[i] = var.getVar(Dvals[i], numRecordsTrain, means[i]);
}
double ** cors = new double * [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
cors[i] = new double[numMeasurementsTrain];
if(rightFileClass.compare("noFile") != 0 || leftFileClass.compare("noFile") != 0 )
{
iFile.open(rightFileClass.c_str());
if(header)
{
string line;
getline(iFile, line);
}
int numRecordsRC = 0; int numMeasurementsRC = 0;
string elementTypeRC = ""; string elementSideRC = "";
for(CSVIterator loop(iFile); loop != CSVIterator(); ++loop)
{
numMeasurementsRC = (*loop).size() - 3;
elementSideRC = (*loop)[1];
elementTypeRC = (*loop)[2];
numRecordsRC++;
}
iFile.close();
SEinventory rightClass(numMeasurementsRC, numRecordsRC, seNameLen, elementSideRC, elementTypeRC);
float * measures = new float[numMeasurementsRC]; string id;
iFile.open(rightFileClass.c_str());
if(header)
{
string line;
getline(iFile, line);
}
for(CSVIterator loop(iFile); loop != CSVIterator(); ++loop)
{
for(int i = 0; i < (*loop).size()-3; i++)
{
measures[i] = atof((*loop)[i+3].c_str());
}
id = (*loop)[0];
rightClass.addMeasurements(id, measures);
}
iFile.close();
iFile.open(leftFileClass.c_str());
if(header)
{
string line;
getline(iFile, line);
}
int numRecordsLC = 0; int numMeasurementsLC = 0;
string elementTypeLC = ""; string elementSideLC = "";
for(CSVIterator loop(iFile); loop != CSVIterator(); ++loop)
{
numMeasurementsLC = (*loop).size() - 3;
elementSideLC = (*loop)[1];
elementTypeLC = (*loop)[2];
numRecordsLC++;
}
iFile.close();
if(numMeasurementsLC != numMeasurementsRC)
{
delete [] measures;
cerr<<"Number of measurements in right and left ";
cerr<<"classification files do not match"<<endl;
help_message(parseError);
}
if(numRecordsLC != numRecordsRC)
{
delete [] measures;
cerr<<"Number of records in right and left ";
cerr<<"classification files do not match"<<endl;
help_message(parseError);
}
SEinventory leftClass(numMeasurementsLC, numRecordsLC, seNameLen, elementSideLC, elementTypeLC);
iFile.open(leftFileClass.c_str());
if(header)
{
string line;
getline(iFile, line);
}
for(CSVIterator loop(iFile); loop != CSVIterator(); ++loop)
{
for(int i = 0; i < (*loop).size()-3; i++)
{
measures[i] = atof((*loop)[i+3].c_str());
}
id = (*loop)[0];
leftClass.addMeasurements(id, measures);
}
iFile.close();
int numRecordsClass = (numRecordsRC+numRecordsLC)/2;
int numMeasurementsClass = (numMeasurementsRC + numMeasurementsLC)/2;
if(unweightedZscore && minSig == 1)
{
double zMean[numMeasurementsTrain];
double ** crossDvals = new double * [numMeasurementsClass];
double ** crossPvals = new double * [numMeasurementsClass];
double * result = new double [numRecordsTrain];
double ** Zscores = new double * [numMeasurementsTrain];
double ** pVals = new double * [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
crossDvals[i] = new double [numRecordsClass];
crossPvals[i] = new double [numRecordsClass];
Zscores[i] = new double [numRecordsTrain];
pVals[i] = new double [numRecordsTrain];
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
tTest<double> Tstats;
Tstats.getPvals(Dvals[k], pVals[k], means[k], vars[k], numRecordsTrain);
}
ZScoreMethod zScoreMethod;
zScoreMethod.OneTpValsToZ(pVals, Zscores, numRecordsTrain, numMeasurementsTrain);
for(int k = 0; k < numMeasurementsTrain; k++)
{
zMean[k] = mean.getMean(Zscores[k], numRecordsTrain);
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
for(int h = k+1; h < numMeasurementsTrain; h++)
{
Correlation<double> correlation;
cors[k][h] = correlation.getCor(Zscores[k], Zscores[h], numRecordsTrain, zMean[k], zMean[h]);
}
}
for(int i = 0; i < numRecordsClass; i++)
{
for(int j = 0; j < numRecordsClass; j++)
{
double crossZvals[numMeasurementsTrain]; double weights[numMeasurementsTrain];
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvals[k][i] = leftClass.getRecordMeas(i,k) - rightClass.getRecordMeas(j,k);
tTest<double> Tstats;
double tStat = Tstats.getTStatistic(crossDvals[k], i, means[k], vars[k]);
crossPvals[k][i] = Tstats.twoTailedPVal(tStat, numRecordsTrain);
crossZvals[k] = zScoreMethod.getZVal1T(crossPvals[k][i]); //zScoreMethod.getZVal2T(crossPvals[k][j]);
weights[k] = 1;
}
double finalP = zScoreMethod.combineZ(crossZvals, weights, cors, numMeasurementsTrain);
cout<<leftClass.getRecordId(i)<<"\t"<<rightClass.getRecordId(j)<<"\t"<<finalP<<endl;
}
}
}
if(weightedEffectZscore && minSig == 1)
{
double zMean[numMeasurementsTrain];
double ** crossDvals = new double * [numMeasurementsClass];
double ** crossPvals = new double * [numMeasurementsClass];
double * result = new double [numRecordsTrain];
double ** Zscores = new double * [numMeasurementsTrain];
double ** pVals = new double * [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
crossDvals[i] = new double [numRecordsClass];
crossPvals[i] = new double [numRecordsClass];
Zscores[i] = new double [numRecordsTrain];
pVals[i] = new double [numRecordsTrain];
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
tTest<double> Tstats;
Tstats.getPvals(Dvals[k], pVals[k], means[k], vars[k], numRecordsTrain);
}
ZScoreMethod zScoreMethod;
zScoreMethod.OneTpValsToZ(pVals, Zscores, numRecordsTrain, numMeasurementsTrain);
for(int k = 0; k < numMeasurementsTrain; k++)
{
zMean[k] = mean.getMean(Zscores[k], numRecordsTrain);
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
for(int h = k+1; h < numMeasurementsTrain; h++)
{
Correlation<double> correlation;
cors[k][h] = correlation.getCor(Zscores[k], Zscores[h], numRecordsTrain, zMean[k], zMean[h]);
}
}
for(int i = 0; i < numRecordsClass; i++)
{
for(int j = 0; j < numRecordsClass; j++)
{
double crossZvals[numMeasurementsTrain]; double weights[numMeasurementsTrain];
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvals[k][i] = leftClass.getRecordMeas(i,k) - rightClass.getRecordMeas(j,k);
tTest<double> Tstats;
double tStat = Tstats.getTStatistic(crossDvals[k], i, means[k], vars[k]);
crossPvals[k][i] = Tstats.twoTailedPVal(tStat, numRecordsTrain);
crossZvals[k] = zScoreMethod.getZVal1T(crossPvals[k][i]); //zScoreMethod.getZVal2T(crossPvals[k][j]);
weights[k] = abs(tStat);
}
double finalP = zScoreMethod.combineZ(crossZvals, weights, cors, numMeasurementsTrain);
cout<<leftClass.getRecordId(i)<<"\t"<<rightClass.getRecordId(j)<<"\t"<<finalP<<endl;
}
}
}
if(weightedStdErrZscore && minSig == 1)
{
double zMean[numMeasurementsTrain];
double ** crossDvals = new double * [numMeasurementsClass];
double ** crossPvals = new double * [numMeasurementsClass];
double * result = new double [numRecordsTrain];
double ** Zscores = new double * [numMeasurementsTrain];
double ** pVals = new double * [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
crossDvals[i] = new double [numRecordsClass];
crossPvals[i] = new double [numRecordsClass];
Zscores[i] = new double [numRecordsTrain];
pVals[i] = new double [numRecordsTrain];
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
tTest<double> Tstats;
Tstats.getPvals(Dvals[k], pVals[k], means[k], vars[k], numRecordsTrain);
}
ZScoreMethod zScoreMethod;
zScoreMethod.OneTpValsToZ(pVals, Zscores, numRecordsTrain, numMeasurementsTrain);
for(int k = 0; k < numMeasurementsTrain; k++)
{
zMean[k] = mean.getMean(Zscores[k], numRecordsTrain);
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
for(int h = k+1; h < numMeasurementsTrain; h++)
{
Correlation<double> correlation;
cors[k][h] = correlation.getCor(Zscores[k], Zscores[h], numRecordsTrain, zMean[k], zMean[h]);
}
}
for(int i = 0; i < numRecordsClass; i++)
{
for(int j = 0; j < numRecordsClass; j++)
{
double crossZvals[numMeasurementsTrain]; double weights[numMeasurementsTrain];
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvals[k][i] = leftClass.getRecordMeas(i,k) - rightClass.getRecordMeas(j,k);
tTest<double> Tstats;
double tStat = Tstats.getTStatistic(crossDvals[k], i, means[k], vars[k]);
crossPvals[k][i] = Tstats.twoTailedPVal(tStat, numRecordsTrain);
crossZvals[k] = zScoreMethod.getZVal1T(crossPvals[k][i]); //zScoreMethod.getZVal2T(crossPvals[k][j]);
weights[k] = sqrt(vars[k]);
}
double finalP = zScoreMethod.combineZ(crossZvals, weights, cors, numMeasurementsTrain);
cout<<leftClass.getRecordId(i)<<"\t"<<rightClass.getRecordId(j)<<"\t"<<finalP<<endl;
}
}
}
if(sumtTest)
{
double * DvalSums = new double [numRecordsTrain];
for(int i = 0; i < numRecordsTrain; i++)
{
DvalSums[i] = 0;
for(int j = 0; j < numMeasurementsTrain; j++)
{
DvalSums[i]+=Dvals[j][i];
}
}
double * crossDvalSums = new double [numRecordsTrain];
double SumMean = mean.getMean(DvalSums, numRecordsTrain);
double SumVar = var.getVar(DvalSums, numRecordsTrain, SumMean);
tTest<double> Tstats;
for(int i = 0; i < numRecordsClass; i++)
{
for(int j = 0; j < numRecordsClass; j++)
{
crossDvalSums[i] = 0;
for(int k = 0; k < numMeasurementsClass; k++)
{
crossDvalSums[i]+=rightClass.getRecordMeas(i,k)-leftClass.getRecordMeas(j,k);
}
double tStat = Tstats.getTStatistic(crossDvalSums, i, 0, SumVar);
double pVal = Tstats.twoTailedPVal(tStat, numRecordsTrain);
cout<<leftClass.getRecordId(i)<<"\t"<<rightClass.getRecordId(j)<<"\t"<<pVal<<endl;
}
}
}
if(meanSumtTest)
{
double * DvalSums = new double [numRecordsTrain];
for(int i = 0; i < numRecordsTrain; i++)
{
DvalSums[i] = 0;
for(int j = 0; j < numMeasurementsTrain; j++)
{
DvalSums[i]+=Dvals[j][i];
}
}
double * crossDvalSums = new double [numRecordsTrain];
double SumMean = mean.getMean(DvalSums, numRecordsTrain);
double SumVar = var.getVar(DvalSums, numRecordsTrain, SumMean);
tTest<double> Tstats;
for(int i = 0; i < numRecordsClass; i++)
{
for(int j = 0; j < numRecordsClass; j++)
{
crossDvalSums[i] = 0;
for(int k = 0; k < numMeasurementsClass; k++)
{
crossDvalSums[i]+=rightClass.getRecordMeas(i,k)-leftClass.getRecordMeas(j,k);
}
double tStat = Tstats.getTStatistic(crossDvalSums, i, SumMean, SumVar);
double pVal = Tstats.twoTailedPVal(tStat, numRecordsTrain);
cout<<leftClass.getRecordId(i)<<"\t"<<rightClass.getRecordId(j)<<"\t"<<pVal<<endl;
}
}
}
if(abstTest)
{
double * DvalSums = new double [numRecordsTrain];
for(int i = 0; i < numRecordsTrain; i++)
{
DvalSums[i] = 0;
for(int j = 0; j < numMeasurementsTrain; j++)
{
DvalSums[i]+=abs(Dvals[j][i]);
}
DvalSums[i] = pow(DvalSums[i] + 0.00005, 0.33);
}
double * crossDvalSums = new double [numRecordsTrain];
double SumMean = mean.getMean(DvalSums, numRecordsTrain);
double SumVar = var.getVar(DvalSums, numRecordsTrain, SumMean);
tTest<double> Tstats;
for(int i = 0; i < numRecordsClass; i++)
{
for(int j = 0; j < numRecordsClass; j++)
{
crossDvalSums[i] = 0;
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvalSums[i]+=abs(leftTrain.getRecordMeas(i,k)-rightTrain.getRecordMeas(j,k));
}
crossDvalSums[i] = pow(crossDvalSums[i] + 0.00005, 0.33);
double tStat = Tstats.getTStatistic(crossDvalSums, i, SumMean, SumVar);
double pVal = Tstats.twoTailedPVal(tStat, numRecordsTrain);
pVal=pVal/2;
cout<<leftClass.getRecordId(i)<<"\t"<<rightClass.getRecordId(j)<<"\t"<<pVal<<endl;
}
}
}
}
if(LOOCV && unweightedZscore && minSig == 1)
{
Summator<double> summator;
double sums[numMeasurementsTrain];
double sqSums[numMeasurementsTrain];
double adjMean[numMeasurementsTrain];
double adjVars[numMeasurementsTrain];
double zMean[numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
sums[i] = summator.sum(Dvals[i], numRecordsTrain);
sqSums[i] = summator.sumXY(Dvals[i], Dvals[i], numRecordsTrain);
}
double ** crossDvals = new double * [numMeasurementsTrain];
double ** crossPvals = new double * [numMeasurementsTrain];
double * result = new double [numRecordsTrain];
double ** Zscores = new double * [numMeasurementsTrain];
double ** pVals = new double * [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
crossDvals[i] = new double [numRecordsTrain];
crossPvals[i] = new double [numRecordsTrain];
Zscores[i] = new double [numRecordsTrain];
pVals[i] = new double [numRecordsTrain];
}
int LO[2] = {0};
for(int i = 0; i < numRecordsTrain; i++)
{
for(int j = 0; j < numRecordsTrain; j++)
{
LO[0] = i; LO[1] = j; int numLO = (i==j) ? 1:2;
for(int k = 0; k < numMeasurementsTrain; k++)
{
adjMean[k] = mean.getMeanLOO(Dvals[k], numRecordsTrain, LO, numLO, sums[k]);
adjVars[k] = var.getVarLOO(Dvals[k], numRecordsTrain, LO, numLO, sums[k], sqSums[k], adjMean[k]);
tTest<double> Tstats;
Tstats.getPvals(Dvals[k], pVals[k], adjMean[k], adjVars[k], numRecordsTrain);
}
ZScoreMethod zScoreMethod;
zScoreMethod.OneTpValsToZ(pVals, Zscores, numRecordsTrain, numMeasurementsTrain);
for(int k = 0; k < numMeasurementsTrain; k++)
{
double sum = summator.sum(Zscores[k], numRecordsTrain);
zMean[k] = mean.getMeanLOO(Zscores[k], numRecordsTrain, LO, numLO, sum);
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
for(int h = k+1; h < numMeasurementsTrain; h++)
{
Correlation<double> correlation;
cors[k][h] = correlation.getCorLO(Zscores[k], Zscores[h], numRecordsTrain, LO, numLO, zMean[k], zMean[h]);
}
}
double crossZvals[numMeasurementsTrain]; double weights[numMeasurementsTrain];
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvals[k][j] = leftTrain.getRecordMeas(j,k) - rightTrain.getRecordMeas(i,k);
tTest<double> Tstats;
double tStat = Tstats.getTStatistic(crossDvals[k], j, adjMean[k], adjVars[k]);
crossPvals[k][j] = Tstats.twoTailedPVal(tStat, numRecordsTrain-numLO);
crossZvals[k] = zScoreMethod.getZVal1T(crossPvals[k][j]); //zScoreMethod.getZVal2T(crossPvals[k][j]);
weights[k] = 1; //abs(tStat); //sqrt(adjVars[k]);
}
double finalP = zScoreMethod.combineZ(crossZvals, weights, cors, numMeasurementsTrain); //zScoreMethod.combineZ2T(crossZvals, weights, cors, numMeasurements);
cout<<leftTrain.getRecordId(j)<<"\t"<<rightTrain.getRecordId(i)<<"\t"<<finalP<<endl;
}
}
for(int i = 0; i < numMeasurementsTrain; i++)
{
delete [] crossDvals[i];
delete [] crossPvals[i];
delete [] Zscores [i];
delete [] pVals [i];
}
delete [] crossDvals;
delete [] crossPvals;
delete [] result;
delete [] Zscores;
delete [] pVals;
}
if(LOOCV && weightedEffectZscore && minSig == 1)
{
Summator<double> summator;
double sums[numMeasurementsTrain];
double sqSums[numMeasurementsTrain];
double adjMean[numMeasurementsTrain];
double adjVars[numMeasurementsTrain];
double zMean[numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
sums[i] = summator.sum(Dvals[i], numRecordsTrain);
sqSums[i] = summator.sumXY(Dvals[i], Dvals[i], numRecordsTrain);
}
double ** crossDvals = new double * [numMeasurementsTrain];
double ** crossPvals = new double * [numMeasurementsTrain];
double * result = new double [numRecordsTrain];
double ** Zscores = new double * [numMeasurementsTrain];
double ** pVals = new double * [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
crossDvals[i] = new double [numRecordsTrain];
crossPvals[i] = new double [numRecordsTrain];
Zscores[i] = new double [numRecordsTrain];
pVals[i] = new double [numRecordsTrain];
}
int LO[2] = {0};
for(int i = 0; i < numRecordsTrain; i++)
{
for(int j = 0; j < numRecordsTrain; j++)
{
LO[0] = i; LO[1] = j; int numLO = (i==j) ? 1:2;
for(int k = 0; k < numMeasurementsTrain; k++)
{
adjMean[k] = mean.getMeanLOO(Dvals[k], numRecordsTrain, LO, numLO, sums[k]);
adjVars[k] = var.getVarLOO(Dvals[k], numRecordsTrain, LO, numLO, sums[k], sqSums[k], adjMean[k]);
tTest<double> Tstats;
Tstats.getPvals(Dvals[k], pVals[k], adjMean[k], adjVars[k], numRecordsTrain);
}
ZScoreMethod zScoreMethod;
zScoreMethod.OneTpValsToZ(pVals, Zscores, numRecordsTrain, numMeasurementsTrain);
for(int k = 0; k < numMeasurementsTrain; k++)
{
double sum = summator.sum(Zscores[k], numRecordsTrain);
zMean[k] = mean.getMeanLOO(Zscores[k], numRecordsTrain, LO, numLO, sum);
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
for(int h = k+1; h < numMeasurementsTrain; h++)
{
Correlation<double> correlation;
cors[k][h] = correlation.getCorLO(Zscores[k], Zscores[h], numRecordsTrain, LO, numLO, zMean[k], zMean[h]);
}
}
double crossZvals[numMeasurementsTrain]; double weights[numMeasurementsTrain];
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvals[k][j] = leftTrain.getRecordMeas(j,k) - rightTrain.getRecordMeas(i,k);
tTest<double> Tstats;
double tStat = Tstats.getTStatistic(crossDvals[k], j, adjMean[k], adjVars[k]);
crossPvals[k][j] = Tstats.twoTailedPVal(tStat, numRecordsTrain-numLO);
crossZvals[k] = zScoreMethod.getZVal1T(crossPvals[k][j]); //zScoreMethod.getZVal2T(crossPvals[k][j]);
weights[k] = abs(tStat); //sqrt(adjVars[k]); //1;
}
double finalP = zScoreMethod.combineZ(crossZvals, weights, cors, numMeasurementsTrain); //zScoreMethod.combineZ2T(crossZvals, weights, cors, numMeasurements);
cout<<leftTrain.getRecordId(j)<<"\t"<<rightTrain.getRecordId(i)<<"\t"<<finalP<<endl;
}
}
for(int i = 0; i < numMeasurementsTrain; i++)
{
delete [] crossDvals[i];
delete [] crossPvals[i];
delete [] Zscores [i];
delete [] pVals [i];
}
delete [] crossDvals;
delete [] crossPvals;
delete [] result;
delete [] Zscores;
delete [] pVals;
}
if(LOOCV && weightedStdErrZscore && minSig == 1)
{
Summator<double> summator;
double sums[numMeasurementsTrain];
double sqSums[numMeasurementsTrain];
double adjMean[numMeasurementsTrain];
double adjVars[numMeasurementsTrain];
double zMean[numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
sums[i] = summator.sum(Dvals[i], numRecordsTrain);
sqSums[i] = summator.sumXY(Dvals[i], Dvals[i], numRecordsTrain);
}
double ** crossDvals = new double * [numMeasurementsTrain];
double ** crossPvals = new double * [numMeasurementsTrain];
double * result = new double [numRecordsTrain];
double ** Zscores = new double * [numMeasurementsTrain];
double ** pVals = new double * [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
crossDvals[i] = new double [numRecordsTrain];
crossPvals[i] = new double [numRecordsTrain];
Zscores[i] = new double [numRecordsTrain];
pVals[i] = new double [numRecordsTrain];
}
int LO[2] = {0};
for(int i = 0; i < numRecordsTrain; i++)
{
for(int j = 0; j < numRecordsTrain; j++)
{
LO[0] = i; LO[1] = j; int numLO = (i==j) ? 1:2;
for(int k = 0; k < numMeasurementsTrain; k++)
{
adjMean[k] = mean.getMeanLOO(Dvals[k], numRecordsTrain, LO, numLO, sums[k]);
adjVars[k] = var.getVarLOO(Dvals[k], numRecordsTrain, LO, numLO, sums[k], sqSums[k], adjMean[k]);
tTest<double> Tstats;
Tstats.getPvals(Dvals[k], pVals[k], adjMean[k], adjVars[k], numRecordsTrain);
}
ZScoreMethod zScoreMethod;
zScoreMethod.OneTpValsToZ(pVals, Zscores, numRecordsTrain, numMeasurementsTrain);
for(int k = 0; k < numMeasurementsTrain; k++)
{
double sum = summator.sum(Zscores[k], numRecordsTrain);
zMean[k] = mean.getMeanLOO(Zscores[k], numRecordsTrain, LO, numLO, sum);
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
for(int h = k+1; h < numMeasurementsTrain; h++)
{
Correlation<double> correlation;
cors[k][h] = correlation.getCorLO(Zscores[k], Zscores[h], numRecordsTrain, LO, numLO, zMean[k], zMean[h]);
}
}
double crossZvals[numMeasurementsTrain]; double weights[numMeasurementsTrain];
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvals[k][j] = leftTrain.getRecordMeas(j,k) - rightTrain.getRecordMeas(i,k);
tTest<double> Tstats;
double tStat = Tstats.getTStatistic(crossDvals[k], j, adjMean[k], adjVars[k]);
crossPvals[k][j] = Tstats.twoTailedPVal(tStat, numRecordsTrain-numLO);
crossZvals[k] = zScoreMethod.getZVal1T(crossPvals[k][j]); //zScoreMethod.getZVal2T(crossPvals[k][j]);
weights[k] = sqrt(adjVars[k]); //1; //abs(tStat);
}
double finalP = zScoreMethod.combineZ(crossZvals, weights, cors, numMeasurementsTrain); //zScoreMethod.combineZ2T(crossZvals, weights, cors, numMeasurements);
cout<<leftTrain.getRecordId(j)<<"\t"<<rightTrain.getRecordId(i)<<"\t"<<finalP<<endl;
}
}
for(int i = 0; i < numMeasurementsTrain; i++)
{
delete [] crossDvals[i];
delete [] crossPvals[i];
delete [] Zscores [i];
delete [] pVals [i];
}
delete [] crossDvals;
delete [] crossPvals;
delete [] result;
delete [] Zscores;
delete [] pVals;
}
if(LOOCV && minSig > 1) //at least U significant
{
Summator<double> summator;
double sums[numMeasurementsTrain];
double sqSums[numMeasurementsTrain];
double adjMean[numMeasurementsTrain];
double adjVars[numMeasurementsTrain];
double zMean[numMeasurementsTrain];
int orderZ [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
sums[i] = summator.sum(Dvals[i], numRecordsTrain);
sqSums[i] = summator.sumXY(Dvals[i], Dvals[i], numRecordsTrain);
}
double ** crossDvals = new double * [numMeasurementsTrain];
double ** crossPvals = new double * [numMeasurementsTrain];
double * result = new double [numRecordsTrain];
double ** Zscores = new double * [numMeasurementsTrain];
double ** pVals = new double * [numMeasurementsTrain];
for(int i = 0; i < numMeasurementsTrain; i++)
{
crossDvals[i] = new double [numRecordsTrain];
crossPvals[i] = new double [numRecordsTrain];
Zscores[i] = new double [numRecordsTrain];
pVals[i] = new double [numRecordsTrain];
}
int LO[2] = {0};
for(int i = 0; i < numRecordsTrain; i++)
{
for(int j = 0; j < numRecordsTrain; j++)
{
LO[0] = i; LO[1] = j; int numLO = (i==j) ? 1:2;
for(int k = 0; k < numMeasurementsTrain; k++)
{
adjMean[k] = mean.getMeanLOO(Dvals[k], numRecordsTrain, LO, numLO, sums[k]);
adjVars[k] = var.getVarLOO(Dvals[k], numRecordsTrain, LO, numLO, sums[k], sqSums[k], adjMean[k]);
tTest<double> Tstats;
Tstats.getPvals(Dvals[k], pVals[k], adjMean[k], adjVars[k], numRecordsTrain);
orderZ[k] = k;
}
ZScoreMethod zScoreMethod;
zScoreMethod.TwoTpValsToZ(pVals, Zscores, numRecordsTrain, numMeasurementsTrain);
for(int k = 0; k < numMeasurementsTrain; k++)
{
double sum = summator.sum(Zscores[k], numRecordsTrain);
zMean[k] = mean.getMeanLOO(Zscores[k], numRecordsTrain, LO, numLO, sum);
}
for(int k = 0; k < numMeasurementsTrain; k++)
{
for(int h = 0; h < numMeasurementsTrain; h++)
{
Correlation<double> correlation;
cors[k][h] = correlation.getCorLO(Zscores[k], Zscores[h], numRecordsTrain, LO, numLO, zMean[k], zMean[h]);
}
}
double crossZvals[numMeasurementsTrain]; double weights[numMeasurementsTrain];
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvals[k][j] = leftTrain.getRecordMeas(i,k)-rightTrain.getRecordMeas(j,k);
tTest<double> Tstats;
double tStat = Tstats.getTStatistic(crossDvals[k], j, adjMean[k], adjVars[k]);
crossPvals[k][j] = Tstats.twoTailedPVal(tStat, numRecordsTrain-numLO); //CHANGED
crossZvals[k] = zScoreMethod.getZVal2T(crossPvals[k][j]);
weights[k] = 1/sqrt(adjVars[k]);
}
int numTest = numMeasurementsTrain - minSig + 1;
double finalP = zScoreMethod.combineZ2TOrdered(crossZvals, weights, cors, orderZ, numTest, numMeasurementsTrain);
cout<<leftTrain.getRecordId(j)<<"\t"<<rightTrain.getRecordId(i)<<"\t"<<finalP<<endl;
}
}
for(int i = 0; i < numMeasurementsTrain; i++)
{
delete [] crossDvals[i];
delete [] crossPvals[i];
delete [] Zscores [i];
delete [] pVals [i];
}
delete [] crossDvals;
delete [] crossPvals;
delete [] result;
delete [] Zscores;
delete [] pVals;
}
if(LOOCV && sumtTest)
{
double * DvalSums = new double [numRecordsTrain];
for(int i = 0; i < numRecordsTrain; i++)
{
DvalSums[i] = 0;
for(int j = 0; j < numMeasurementsTrain; j++)
{
DvalSums[i]+=Dvals[j][i];
}
}
double * crossDvalSums = new double [numRecordsTrain];
Summator<double> summator;
double sum = summator.sum(DvalSums, numRecordsTrain);
double sqSum = summator.sumXY(DvalSums, DvalSums, numRecordsTrain);
tTest<double> Tstats;
int LO[2] = {0};
for(int i = 0; i < numRecordsTrain; i++)
{
for(int j = 0; j < numRecordsTrain; j++)
{
LO[0] = i; LO[1] = j; int numLO = (i==j) ? 1:2;
double adjMean = mean.getMeanLOO(DvalSums, numRecordsTrain, LO, numLO, sum);
double adjVar = var.getVarLOO(DvalSums, numRecordsTrain, LO, numLO, sum, sqSum, adjMean);
crossDvalSums[j] = 0;
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvalSums[j]+=(leftTrain.getRecordMeas(i,k)-rightTrain.getRecordMeas(j,k));
}
double tStat = Tstats.getTStatistic(crossDvalSums, j, 0, adjVar);
double pVal = Tstats.twoTailedPVal(tStat, numRecordsTrain-numLO);
cout<<leftTrain.getRecordId(j)<<"\t"<<rightTrain.getRecordId(i)<<"\t"<<pVal<<endl;
}
}
delete [] crossDvalSums;
}
if(LOOCV && meanSumtTest)
{
double * DvalSums = new double [numRecordsTrain];
for(int i = 0; i < numRecordsTrain; i++)
{
DvalSums[i] = 0;
for(int j = 0; j < numMeasurementsTrain; j++)
{
DvalSums[i]+=Dvals[j][i];
}
}
double * crossDvalSums = new double [numRecordsTrain];
Summator<double> summator;
double sum = summator.sum(DvalSums, numRecordsTrain);
double sqSum = summator.sumXY(DvalSums, DvalSums, numRecordsTrain);
tTest<double> Tstats;
int LO[2] = {0};
for(int i = 0; i < numRecordsTrain; i++)
{
for(int j = 0; j < numRecordsTrain; j++)
{
LO[0] = i; LO[1] = j; int numLO = (i==j) ? 1:2;
double adjMean = mean.getMeanLOO(DvalSums, numRecordsTrain, LO, numLO, sum);
double adjVar = var.getVarLOO(DvalSums, numRecordsTrain, LO, numLO, sum, sqSum, adjMean);
crossDvalSums[j] = 0;
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvalSums[j]+=(leftTrain.getRecordMeas(i,k)-rightTrain.getRecordMeas(j,k));
}
double tStat = Tstats.getTStatistic(crossDvalSums, j, adjMean, adjVar);
double pVal = Tstats.twoTailedPVal(tStat, numRecordsTrain-numLO);
cout<<leftTrain.getRecordId(j)<<"\t"<<rightTrain.getRecordId(i)<<"\t"<<pVal<<endl;
}
}
delete [] crossDvalSums;
}
if(LOOCV && abstTest)
{
double * DvalSums = new double [numRecordsTrain];
for(int i = 0; i < numRecordsTrain; i++)
{
DvalSums[i] = 0;
for(int j = 0; j < numMeasurementsTrain; j++)
{
DvalSums[i]+=abs(Dvals[j][i]);
}
DvalSums[i] = pow(DvalSums[i] + 0.00005, 0.33);
}
double * crossDvalSums = new double [numRecordsTrain];
Summator<double> summator;
double sum = summator.sum(DvalSums, numRecordsTrain);
double sqSum = summator.sumXY(DvalSums, DvalSums, numRecordsTrain);
tTest<double> Tstats;
int LO[2] = {0};
for(int i = 0; i < numRecordsTrain; i++)
{
for(int j = 0; j < numRecordsTrain; j++)
{
LO[0] = i; LO[1] = j; int numLO = (i==j) ? 1:2;
double adjMean = mean.getMeanLOO(DvalSums, numRecordsTrain, LO, numLO, sum);
double adjVar = var.getVarLOO(DvalSums, numRecordsTrain, LO, numLO, sum, sqSum, adjMean);
crossDvalSums[j] = 0;
for(int k = 0; k < numMeasurementsTrain; k++)
{
crossDvalSums[j]+=abs(leftTrain.getRecordMeas(i,k)-rightTrain.getRecordMeas(j,k));
}
crossDvalSums[j] = pow(crossDvalSums[j] + 0.00005, 0.33);
double tStat = Tstats.getTStatistic(crossDvalSums, j, adjMean, adjVar);
double pVal = Tstats.twoTailedPVal(tStat, numRecordsTrain-numLO);
pVal = pVal/2;
cout<<leftTrain.getRecordId(j)<<"\t"<<rightTrain.getRecordId(i)<<"\t"<<pVal<<endl;
}
}
delete [] crossDvalSums;
}
for(int i = 0; i < numMeasurementsTrain; i++){
delete [] Dvals [i];
delete [] cors [i];
}
delete [] Dvals;
delete [] cors;
t2=clock();
float diff ((float)t2-(float)t1);
float seconds = diff/CLOCKS_PER_SEC;
if(timeT)
cerr<<"RUN TIME "<<seconds<<endl;
return 0;
}
<file_sep>/bin/z-transform-method/src/Variance.h
/*
* Variance.h
*
* Created on: Jan 14, 2017
* Author: Julia
*/
#ifndef VARIANCE_H_
#define VARIANCE_H_
#include <iostream>
#include <math.h>
using namespace std;
template <class T>
class Variance {
public:
Variance();
virtual ~Variance();
double getVar(const T *, const int, const double) const;
double getVarLOO(const T *, const int, const int [], const int, const double, const double, const double);
};
template <class T>
Variance<T>::Variance() {};
template <class T>
Variance<T>::~Variance() {
}
template <class T>
double Variance<T>::getVar(const T * arr, const int arrSize, const double mean) const {
double sum = 0;
for(int i = 0; i < arrSize; i++)
{
sum+=(pow(arr[i] - mean, 2));
}
float size = arrSize;
return sum/(size-1);
}
template <class T>
double Variance<T>::getVarLOO(const T * arr, const int arrSize, const int LO [], const int numLO, const double sum, const double sqSum, const double mean) {
double firstTerm = sqSum;
for(int i = 0; i < numLO; i++)
firstTerm-=pow(arr[LO[i]],2);
double squaredMean = pow(mean,2);
double lastTerm = (arrSize-numLO) * squaredMean;
double sumLOO = sum;
for(int i = 0; i < numLO; i++)
sumLOO-=arr[LO[i]];
double middleTerm = -2*(mean * sumLOO);
double denominator = arrSize-1-numLO;
double newVar = (firstTerm + middleTerm + lastTerm)/denominator;
return newVar;
}
#endif /* VARIANCE_H_ */
<file_sep>/analytics/views.py
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from analytics.models.toolkits import Toolkit
from analytics.models.tools import Tool
from analytics.models.results import Result
from analytics.models.file_types import FileType
from analytics.forms.dynamic_form import DynamicForm
import time, json, os, shutil, errno
from analytics import tasks
from django.templatetags.static import static
from django.conf import settings
import pandas as pd
# Helpers
def makedirs(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno == 17:
# Dir already exists. No biggie.
pass
def handle_uploaded_file(file, user_id):
timestr = time.strftime("%Y%m%d-%H%M%S")
base_name, file_extension = os.path.splitext(file.name)
file_name = base_name + timestr + file_extension
file_url = settings.MEDIA_ROOT + '/user' + str(user_id) + '/' \
+ file_name
with open(file_url, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
destination.close()
return file_name
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def is_bool(s):
return isinstance(s, bool)
###### END HELPERS
def update_history(request):
if request.is_ajax() and request.method == 'POST':
results_to_be_updated = json.loads(request.body)
for key in results_to_be_updated:
try:
result = Result.objects.get(task_id=key)
results_to_be_updated[key] = result.status
except Result.DoesNotExist:
pass
return JsonResponse(results_to_be_updated)
def get_field_options(request):
dictionary = {}
if request.is_ajax() and request.method == 'POST':
file_name = json.loads(request.body)
file_url = settings.MEDIA_ROOT + '/user' + str(request.user.id) + '/' \
+ file_name
fields = pd.read_csv(file_url, sep=None, nrows=0).columns.tolist()
test_data = pd.read_csv(file_url, sep=None, nrows=1, skiprows=1).columns.tolist()
for counter, test in enumerate(test_data):
if is_number(test):
dictionary[fields[counter]] = "numeric"
elif is_bool(test):
dictionary[fields[counter]] = "bool"
else:
dictionary[fields[counter]] = "string"
return JsonResponse(dictionary)
def get_common_field_options(request):
dictionary = {}
if request.is_ajax() and request.method == 'POST':
file_name1 = json.loads(request.POST.get('file_name1'))
file_name2 = json.loads(request.POST.get('file_name2'))
file1_url = settings.MEDIA_ROOT + '/user' + str(request.user.id) + '/' \
+ file_name1
file2_url = settings.MEDIA_ROOT + '/user' + str(request.user.id) + '/' \
+ file_name2
fields1 = pd.read_csv(file1_url, sep=None, nrows=0).columns.tolist()
fields2 = pd.read_csv(file2_url, sep=None, nrows=0).columns.tolist()
common_fields = list(set(fields1).intersection(fields2))
test_data = pd.read_csv(file1_url, sep=None, nrows=1)
for counter, field in enumerate(common_fields):
if is_number(test_data.iloc[0][field]):
dictionary[field] = "numeric"
elif is_bool(test_data.iloc[0][field]):
dictionary[field] = "bool"
else:
dictionary[field] = "string"
return JsonResponse(dictionary)
# Create your views here.
def analytics_home(request):
t_all = Toolkit.objects.all()
if request.user.is_authenticated:
user_results = Result.objects.filter(user_id=request.user.id)
else:
user_results = Result.objects.none()
return render(request, 'analytics/home.html', {'toolkits': t_all, 'results': user_results})
def short_task(request, tool_id):
t_all = Toolkit.objects.all()
try:
if request.user.is_authenticated:
user_results = Result.objects.filter(user_id=request.user.id)
else:
user_results = Result.objects.none()
t = Tool.objects.get(id=tool_id)
extra = json.loads(request.POST.get('dynamicFields', "{}"))
form_data = json.loads(request.POST.get('myForm', "{}"))
tool_form = DynamicForm(request.user.id, t, extra, form_data or None)
if request.method == 'POST' and request.is_ajax():
if tool_form.is_valid():
method_to_call = getattr(tasks, t.tool_name.lower())
json_vals = json.dumps(tool_form.cleaned_data)
task = method_to_call.apply_async(args=(json_vals,), countdown=.5)
while task.state not in ('SUCCESS', 'FAILURE'):
time.sleep(0.6)
if task.failed():
tool_form.add_error(None, "Error completing task")
render(request, 'analytics/tools/%s.html' % t.tool_name.lower(),
{'form': tool_form, 'toolkits': t_all, 'tool': t, 'results': user_results})
task.forget()
else:
results = json.loads(task.get())
task.forget()
return JsonResponse(results)
else:
data = {key: '' for key in tool_form.data}
tool_form.data = data
return render(request, 'analytics/tools/%s.html' % t.tool_name.lower(),
{'form': tool_form, 'toolkits': t_all, 'tool': t, 'results': user_results})
except Tool.DoesNotExist:
pass
def upload_file(request, tool_id):
t_all = Toolkit.objects.all()
t = Tool.objects.get(id=tool_id)
try:
if request.user.is_authenticated:
user_results = Result.objects.filter(user_id=request.user.id)
makedirs(settings.MEDIA_ROOT+'/user' + str(request.user.id))
tool_form = DynamicForm(request.user.id, t, {}, request.POST or None, request.FILES or None)
file_types = FileType.objects.all()
if request.method == 'POST':
if tool_form.is_valid():
cleaned_data = tool_form.cleaned_data
for key in request.FILES:
file = request.FILES[key]
cleaned_data[key] = handle_uploaded_file(file, request.user.id)
file.close()
cleaned_data['user_id'] = request.user.id
json_vals = json.dumps(cleaned_data)
method_to_call = getattr(tasks, t.tool_name.lower())
method_signature = method_to_call.s(json_vals)
task = method_signature.freeze()
for key in request.FILES:
file_name = cleaned_data[key]
file_type_name = cleaned_data[key + '_file%type']
file_type = file_types.get(file_type_name=file_type_name)
Result.objects.create(file_name=file_name, user_id=request.user.id, task_id=task.id,
tool=t, file_type=file_type, status="PENDING")
method_signature.delay()
else:
data = {key: '' for key in tool_form.data}
tool_form.data = data
return render(request, 'analytics/tools/%s.html' % t.tool_name.lower(),
{'form': tool_form, 'toolkits': t_all, 'tool': t, 'results': user_results})
else:
user_results = Result.objects.none()
return render(request, 'analytics/user_not_authenticated.html',
{'toolkits': t_all, 'tool': t, 'results': user_results})
except Tool.DoesNotExist:
pass
def long_task(request, tool_id):
t_all = Toolkit.objects.all()
t = Tool.objects.get(id=tool_id)
try:
if request.user.is_authenticated:
user_results = {}
extra = json.loads(request.POST.get('dynamicFields', "{}"))
form_data = json.loads(request.POST.get('myForm', "{}"))
tool_form = DynamicForm(request.user.id, t, extra, form_data or None)
if request.method == 'POST' and request.is_ajax():
if tool_form.is_valid():
cleaned_data = tool_form.cleaned_data
cleaned_data['user_id'] = request.user.id
output_files = t.outputfile_set.all()
for output_file in output_files:
timestr = time.strftime("%Y%m%d-%H%M%S")
try:
file_name = output_file.file_base_name + timestr + "." + \
output_file.file_type.file_extension
except FileType.DoesNotExist:
file_name = output_file.file_base_name + timestr + ".txt"
cleaned_data[output_file.parameter_name] = file_name
json_vals = json.dumps(cleaned_data)
method_to_call = getattr(tasks, t.tool_name.lower())
method_signature = method_to_call.s(json_vals)
task = method_signature.freeze()
for output_file in output_files:
file_name = cleaned_data[output_file.parameter_name]
user_result = {'task_id': task.id, 'file_name': file_name,
'file_type': output_file.file_type.file_type_name, 'user_id': request.user.id}
Result.objects.create(file_name=file_name, user_id=request.user.id, task_id=task.id,
tool=t, file_type=output_file.file_type, status="PENDING")
user_results[task.id] = user_result
method_signature.delay()
return JsonResponse(user_results)
else:
user_history = Result.objects.filter(user_id=request.user.id)
data = {key: '' for key in tool_form.data}
tool_form.data = data
return render(request, 'analytics/tools/%s.html' % t.tool_name.lower(),
{'form': tool_form, 'toolkits': t_all, 'tool': t, 'results': user_history})
else:
user_results = Result.objects.none()
return render(request, 'analytics/user_not_authenticated.html',
{'toolkits': t_all, 'tool': t, 'results': user_results})
except Tool.DoesNotExist:
pass
<file_sep>/bin/z-transform-method/src/ZScoreMethod.cpp
/*
* ZScoreMethod.cpp
*
* Created on: Jan 16, 2017
* Author: Julia
*/
#include<iostream>
#include<math.h>
#include<Rcpp.h>
#include<RInside.h>
using namespace std;
#include "CompareClass.h"
#include "ZScoreMethod.h"
#include "Correlation.h"
ZScoreMethod::ZScoreMethod() {
}
ZScoreMethod::~ZScoreMethod() {
// TODO Auto-generated destructor stub
}
void ZScoreMethod::TwoTpValsToZ(double ** pVals, double ** Z, const int numRecords, const int numMeasPerRecord) {
for(int i = 0; i < numMeasPerRecord; i++)
{
for(int j = 0; j < numRecords; j++)
{
Z[i][j] = getZVal2T(pVals[i][j]);
}
}
}
void ZScoreMethod::OneTpValsToZ(double ** pVals, double ** Z, const int numRecords, const int numMeasPerRecord) {
for(int i = 0; i < numMeasPerRecord; i++)
{
for(int j = 0; j < numRecords; j++)
{
Z[i][j] = getZVal1T(pVals[i][j]);
}
}
}
void ZScoreMethod::TwoTpValsToOneToZ(double ** pVals, double ** Z, const int numRecords, const int numMeasPerRecord) {
for(int i = 0; i < numMeasPerRecord; i++)
{
for(int j = 0; j < numRecords; j++)
{
Z[i][j] = getZVal2T(pVals[i][j]);
}
}
}
void ZScoreMethod::combineZs(double ** Z, double * result, double * weights, double ** cor, const int numRecords, const int numMeasPerRecord){
double denominator = getDenominator(weights, cor, numMeasPerRecord);
for(int i = 0; i < numRecords; i++)
{
double numerator = getNumerator(Z, i, weights, numMeasPerRecord);
double val1 = numerator/denominator;
Rcpp::NumericVector x(1,val1);
Rcpp::NumericVector Z_final = Rcpp::pnorm(x, 0, 1, TRUE, FALSE); //SECOND TRUE FROM FALSE
double pZ = 1-Z_final[0];
result[i] = pZ;
}
}
double ZScoreMethod::combineZ(double Z [], double weights [], double ** cor, const int numMeasPerRecord){
double denominator = getDenominator(weights, cor, numMeasPerRecord);
double numerator = getNumerator(Z, weights, numMeasPerRecord);
double val1 = numerator/denominator;
Rcpp::NumericVector x(1,val1);
Rcpp::NumericVector Z_final = Rcpp::pnorm(x, 0, 1, TRUE, FALSE); //SECOND TRUE FROM FALSE
double pZ = 1-Z_final[0];
return pZ;
}
void ZScoreMethod::combineZs2T(double ** Z, double * result, double * weights, double ** cor, const int numRecords, const int numMeasPerRecord){
double denominator = getDenominator(weights, cor, numMeasPerRecord);
for(int i = 0; i < numRecords; i++)
{
double numerator = getNumerator(Z, i, weights, numMeasPerRecord);
double val1 = numerator/denominator;
Rcpp::NumericVector x(1,val1);
Rcpp::NumericVector Z = Rcpp::pnorm(x, 0, 1, TRUE, FALSE); //SECOND TRUE FROM FALSE
double pZ = 1-Z[0];
if(pZ < .5)
{
pZ=2*pZ;
}else{
pZ=2*(1-pZ);
}
result[i] = pZ;
}
}
double ZScoreMethod::combineZ2T(double Z [], double weights [], double ** cor, const int numMeasPerRecord){
double denominator = getDenominator(weights, cor, numMeasPerRecord);
double numerator = getNumerator(Z, weights, numMeasPerRecord);
double val1 = numerator/denominator;
Rcpp::NumericVector x(1,val1);
Rcpp::NumericVector Z_final = Rcpp::pnorm(x, 0, 1, TRUE, FALSE); //SECOND TRUE FROM FALSE
double pZ = 1-Z_final[0];
if(pZ < .5)
{
pZ=2*pZ;
}else{
pZ=2*(1-pZ);
}
return pZ;
}
double ZScoreMethod::combineZ2TOrdered(double Z [], double weights [], double ** cor, int orderZ [], int U, const int numMeasPerRecord){
sort(orderZ, orderZ+numMeasPerRecord, CompareClass(Z));
double denominator = getDenominatorOrdered(weights, cor, orderZ, U, numMeasPerRecord);
double numerator = getNumeratorOrdered(Z, weights, orderZ, U, numMeasPerRecord);
double val1 = numerator/denominator;
Rcpp::NumericVector x(1,val1);
Rcpp::NumericVector Z_final = Rcpp::pnorm(x, 0, 1, TRUE, FALSE); //SECOND TRUE FROM FALSE
double pZ = 1-Z_final[0];
if(pZ < .5)
{
pZ=2*pZ;
}else{
pZ=2*(1-pZ);
}
return pZ;
}
double ZScoreMethod::getZVal2T(const double pVal) {
long double val1 = (1-pVal/2);
if(val1 == 1) val1 = .99999999;
Rcpp::NumericVector x(1,val1);
Rcpp::NumericVector Z = Rcpp::qnorm(x,0,1,TRUE,FALSE); //SECOND TRUE FROM FALSE
return Z[0];
}
double ZScoreMethod::getZVal1T(const double pVal) {
long double val1 = (1-pVal);
if(val1 == 1) val1 = .99999999;
if(val1 == 0) val1 = .00000001;
Rcpp::NumericVector x(1,val1);
Rcpp::NumericVector Z = Rcpp::qnorm(x,0,1,TRUE,FALSE); //SECOND TRUE FROM FALSE
return Z[0];
}
double ZScoreMethod::getDenominator(double * weights, double ** cors, const int numPvals) {
double sum1 = 0;
for(int i = 0; i < numPvals; i++)
{
sum1+=(pow(weights[i],2));
}
double sum2 = 0;
for(int i = 0; i < numPvals; i++)
{
for(int j = i+1; j < numPvals; j++)
{
sum2+=(weights[i]*weights[j]*cors[i][j]);
}
}
double sum3 = sum1 + 2*sum2;
return sqrt(sum3);
}
double ZScoreMethod::getDenominatorOrdered(double * weights, double ** cors, int order [], int U, const int numPvals) {
double sum1 = 0;
for(int i = 0; i < U; i++)
{
sum1+=(pow(weights[order[i]],2));
}
double sum2 = 0;
for(int i = 0; i < U; i++)
{
for(int j = i+1; j < U; j++)
{
sum2+=(weights[order[i]]*weights[order[j]]*cors[order[i]][order[j]]);
}
}
double sum3 = sum1 + 2*sum2;
return sqrt(sum3);
}
double ZScoreMethod::getNumerator(double ** zScores, const int currRecord, double * weights, const int numPvals) {
double sum = 0;
for(int i = 0; i < numPvals; i++)
{
sum+=(weights[i]*zScores[i][currRecord]);
}
return sum;
}
double ZScoreMethod::getNumerator(double zScores [], double * weights, const int numPvals) {
double sum = 0;
for(int i = 0; i < numPvals; i++)
{
sum+=(weights[i]*zScores[i]);
}
return sum;
}
double ZScoreMethod::getNumeratorOrdered(double zScores [], double * weights, int order [], const int U, const int numPvals) {
double sum = 0;
for(int i = 0; i < U; i++)
{
sum+=(weights[order[i]]*zScores[order[i]]);
}
return sum;
}
<file_sep>/analytics/models/file_types.py
from django.db import models
from django.utils import timezone
class FileType(models.Model):
file_type_name = models.CharField(max_length=200)
display_name = models.CharField(max_length=200)
short_description = models.CharField(max_length=200)
file_extension = models.CharField(max_length=10)
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def __unicode__(self):
return u"%s" % self.file_type_name
def __str__(self):
return self.file_type_name
def save(self, *args, **kwargs):
"""On save update time stamp."""
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(FileType, self).save(*args, **kwargs) # call the real save method<file_sep>/bin/z-transform-method/src/tTest.h
/*
* tTest.h
*
* Created on: Jan 15, 2017
* Author: Julia
*/
#ifndef TTEST_H_
#define TTEST_H_
#include<iostream>
#include<math.h>
#include<Rcpp.h>
#include<RInside.h>
using namespace std;
template <class T>
class tTest {
public:
tTest();
void getPvals(const T *, T *, const double &, const double &, const double &);
double getTStatistic(const T *, const int &, const double &, const double &, const double &);
double getTStatistic(const T *, const int &, const double &, const double &);
double leftTailPVal(const double &, const int &);
double rightTailPVal(const double &, const int &);
double twoTailedPVal(const double &, const int &);
virtual ~tTest();
};
template <class T>
tTest<T>::tTest() {};
template <class T>
tTest<T>::~tTest() {
}
template <class T>
double tTest<T>::getTStatistic(const T * arr, const int & pos, const double & mean, const double & var, const double & sampleSize) {
return ((arr[pos]-mean)/(sqrt(var)/sampleSize));
}
template <class T>
double tTest<T>::getTStatistic(const T * arr, const int & pos, const double & mean, const double & var) {
return ((arr[pos]-mean)/(sqrt(var)));
}
template <class T>
void tTest<T>::getPvals(const T * arr, T * pArr, const double & mean, const double & var, const double & sampleSize) {
for(int i = 0; i < sampleSize; i++)
{
double Tstatistic = getTStatistic(arr, i, mean, var);
//cout<<"TSTAT "<<Tstatistic<<endl;
pArr[i] = twoTailedPVal(Tstatistic, sampleSize-1);
//cout<<pArr[i]<<" PVAL "<<endl;
}
}
template <class T>
double tTest<T>::leftTailPVal(const double & tStat, const int & df) {
Rcpp::NumericVector x(1,tStat);
Rcpp::NumericVector Y = Rcpp::pt(x, df, true, false);
return Y[0];
}
template <class T>
double tTest<T>::rightTailPVal(const double & tStat, const int & df) {
Rcpp::NumericVector x(1,tStat);
Rcpp::NumericVector Y = Rcpp::pt(x, df, false, false);
return Y[0];
}
template <class T>
double tTest<T>::twoTailedPVal(const double & tStat, const int & df) {
Rcpp::NumericVector x(1, tStat);
Rcpp::NumericVector Y = 2 * Rcpp::pt(Rcpp::abs(x), df, false, false);
return Y[0];
}
#endif /* TTEST_H_ */
<file_sep>/analytics/models/__init__.py
from .toolkits import Toolkit
from .tools import Tool
from .tools_input import InputParameter
from .file_types import FileType
from .tools_input import InputParameter
from .tools_input import InputParameterStringValueOption
from .tools_input import InputParameterNumericValueOption
from .tools_output import OutputFile
from .results import Result
<file_sep>/docker-compose.yml
version: '3'
services:
web:
build: .
ports:
- "8000:8000"
volumes:
- ./media:/app/media
depends_on:
- db
- redis
worker:
build: .
depends_on:
- redis
volumes:
- ./media:/app/media
command: celery worker -l info -A CoRA
redis:
image: 'redis:3.0-alpine'
sysctls:
net.core.somaxconn: 1024
command: redis-server
container_name: 'redis'
volumes:
- 'redis:/data'
ports:
- '6379:6379'
db:
image: "postgres:9.6"
ports:
- "5432:5432"
environment:
POSTGRES_PASSWORD: analytics
volumes:
- ./pgdata:/var/lib/postgresql/data
volumes:
redis:
<file_sep>/analytics/models/tools.py
from django.db import models
from django.utils import timezone
from .toolkits import Toolkit
class Tool(models.Model):
tool_name = models.CharField(max_length=200)
display_name = models.CharField(max_length=200)
short_description = models.CharField(max_length=200)
long_description = models.TextField()
toolkit = models.ForeignKey(Toolkit, on_delete=models.CASCADE,)
class Meta:
ordering = ['display_name']
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
upload_file = 'upload_file'
short_task = 'short_task'
long_task = 'long_task'
visualization = 'visualization'
tool_type_choices = (
(upload_file, 'Upload File'),
(short_task, 'Short Task'),
(long_task, 'Long Task'),
(visualization, 'Visualization'),
)
tool_type = models.CharField(max_length=200, choices=tool_type_choices)
def __unicode__(self):
return u"%s" % self.tool_name
def __str__(self):
return self.tool_name
def save(self, *args, **kwargs):
"""On save update timestamps"""
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(Tool, self).save(*args, **kwargs) #call the real method<file_sep>/analytics/forms/custom_admin_forms.py
from django import forms
from django.utils.translation import gettext_lazy as _
from django.core.validators import RegexValidator, MinLengthValidator
from analytics.models.toolkits import Toolkit
from analytics.models.tools import Tool
from analytics.models.file_types import FileType
from analytics.models.tools_input import InputParameter, InputParameterStringValueOption,\
InputParameterNumericValueOption
from analytics.models.tools_output import OutputFile
from analytics.validators.validators import validate_object_name, validate_object_name_strict
class CustomToolkitAdminForm(forms.ModelForm):
toolkit_name = forms.CharField(
max_length=200,
validators=[validate_object_name]
)
class CustomToolAdminForm(forms.ModelForm):
tool_name = forms.CharField(
max_length=200,
validators=[validate_object_name_strict]
)
display_name = forms.CharField(
max_length=200,
validators=[validate_object_name]
)
class CustomFileTypeAdminForm(forms.ModelForm):
file_type_name = forms.CharField(
max_length=200,
validators=[validate_object_name]
)
display_name = forms.CharField(
max_length=200,
validators=[validate_object_name]
)
file_extension = forms.CharField(
max_length=10,
validators=[RegexValidator(regex="^[a-z]+$",
message=_("Must only contain lowercase letters"),
code='invalid_file_extension'),
MinLengthValidator(2,
message=_("Minimum file extension length: 2")
)]
)
class CustomInputParameterAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CustomInputParameterAdminForm, self).__init__(*args, **kwargs)
if self.instance.id:
self.fields['requires'].queryset = InputParameter.objects.filter(tool=self.instance.tool) \
.exclude(id=self.instance.id)
self.fields['excludes'].queryset = InputParameter.objects.filter(tool=self.instance.tool) \
.exclude(id=self.instance.id)
else:
self.fields['requires'].queryset = InputParameter.objects.none()
self.fields['excludes'].queryset = InputParameter.objects.none()
parameter_name = forms.CharField(
max_length=200,
validators=[validate_object_name_strict]
)
def clean(self):
cleaned_data = super().clean()
parameter_type = cleaned_data.get("parameter_type")
parameter_required = cleaned_data.get("parameter_required")
if parameter_type == "String" and parameter_required:
try:
temp = InputParameterStringValueOption.objects.get(default_value=True)
raise forms.ValidationError(
_("Can't set \"parameter required\" as true. Default values exist."
"Please remove default values before setting \"parameter required\""
"as true.")
)
except InputParameterStringValueOption.DoesNotExist:
pass
class CustomInputParameterInlineForm(forms.ModelForm):
def __init__(self, *args, parent_object, **kwargs):
super(CustomInputParameterInlineForm, self).__init__(*args, **kwargs)
if self.instance.id:
self.fields['requires'].queryset = InputParameter.objects.filter(tool=parent_object) \
.exclude(id=self.instance.id)
self.fields['excludes'].queryset = InputParameter.objects.filter(tool=parent_object) \
.exclude(id=self.instance.id)
else:
self.fields['requires'].queryset = InputParameter.objects.filter(tool=parent_object)
self.fields['excludes'].queryset = InputParameter.objects.filter(tool=parent_object)
parameter_name = forms.CharField(
max_length=200,
validators=[validate_object_name_strict]
)
def clean(self):
cleaned_data = super().clean()
parameter_type = cleaned_data.get("parameter_type")
parameter_required = cleaned_data.get("parameter_required")
if parameter_type == "String" and parameter_required:
try:
temp = InputParameterStringValueOption.objects.get(default_value=True)
raise forms.ValidationError(
_("Can't set \"parameter required\" as true. Default values exist."
"Please remove default values before setting \"parameter required\""
"as true."), code='default_exists'
)
except InputParameterStringValueOption.DoesNotExist:
pass
class CustomOutputFileAdmin(forms.ModelForm):
parameter_name = forms.CharField(
max_length=200,
validators=[validate_object_name_strict]
)
file_base_name = forms.CharField(
max_length=200,
validators=[validate_object_name_strict]
)
class CustomInputParameterStringValueAdminForm(forms.ModelForm):
def __init__(self, *args, parent_object, **kwargs):
super(CustomInputParameterStringValueAdminForm, self).__init__(*args, **kwargs)
self.fields['requires'].queryset = InputParameter.objects.filter(tool=parent_object.tool)\
.exclude(id=parent_object.id)
self.fields['excludes'].queryset = InputParameter.objects.filter(tool=parent_object.tool) \
.exclude(id=parent_object.id)
def clean(self):
cleaned_data = super().clean()
parent_param = cleaned_data['parameter']
default_value = cleaned_data['default_value']
if default_value:
try:
temp = InputParameter.objects.get(id=parent_param.id)
if temp.parameter_required:
raise forms.ValidationError(
_("Can't have default value for parameter that "
"requires input"), code='requires_input'
)
except InputParameter.DoesNotExist:
raise forms.ValidationError(
_("Parameter you are adding value options to does "
"not exist. Please contact your admin."), code='parameter_does_not_exist'
)
class CustomInputParameterNumericValueAdminForm(forms.ModelForm):
def clean(self):
cleaned_data = super().clean()
parent_param = cleaned_data['parameter']
default_value = cleaned_data['default_value']
if default_value:
try:
temp = InputParameter.objects.get(id=parent_param)
if temp.parameter_required:
raise forms.ValidationError(
_("Can't have default value for parameter that "
"requires input"), code='requires_input'
)
except InputParameter.DoesNotExist:
raise forms.ValidationError(
_("Parameter you are adding value options to does "
"not exist"), code='requires_input'
)<file_sep>/README.md
# cora-analytics-docker
The dockerized version of Cora analytics
## Requirements
Docker
### Docker Installation:
https://docs.docker.com/install/
## Commandline installation
`cd cora-analytics-dockerized`
`docker-compose up`
The analytics homepage will be accessable at:
http://127.0.0.1:8000/analytics
The admin homepage will be accessable at:
http://127.0.0.1:8000/admin
## Integration with PyCharm Professional Version
https://www.jetbrains.com/help/pycharm/using-docker-compose-as-a-remote-interpreter-1.html
<file_sep>/bin/z-transform-method/src/LinearRegression.h
/*
* LinearRegression.h
*
* Created on: Feb 3, 2017
* Author: Julia
*/
#ifndef LINEARREGRESSION_H_
#define LINEARREGRESSION_H_
class LinearRegression {
public:
LinearRegression(double *, double *, const int);
virtual ~LinearRegression();
double getM(const int);
double getMLO(double *, double *, const int, const int [], const int);
double getB(const int);
double getBLO(double *, double *, const int, const int [], const int);
double getSE(double *, double *, const int);
double getSELO(double *, double *, const double, const int, const int [], const int);
double getTStatistic(const double *, const double *, const int &, const int &, const double &, const double &, const double &, const double &);
private:
double XXsum;
double Xsum;
double Ysum;
double XYsum;
};
#endif /* LINEARREGRESSION_H_ */
<file_sep>/bin/z-transform-method/src/LinearRegression.cpp
/*
* LinearRegression.cpp
*
* Created on: Feb 3, 2017
* Author: Julia
*/
#include <iostream>
#include<math.h>
using namespace std;
#include "Summator.h"
#include "LinearRegression.h"
LinearRegression::LinearRegression(double * X, double * Y, const int arrSize) {
Summator<double>sum;
XXsum = sum.sumXY(X, X, arrSize);
Xsum = sum.sum(X, arrSize);
Ysum = sum.sum(Y, arrSize);
XYsum = sum.sumXY(X,Y, arrSize);
}
LinearRegression::~LinearRegression() {
// TODO Auto-generated destructor stub
}
double LinearRegression::getM(const int arrSize) {
double numerator = (arrSize * XYsum)-(Xsum*Ysum);
double denominator = (arrSize * XXsum) - (Xsum * Xsum);
return numerator/denominator;
}
double LinearRegression::getMLO(double * X, double * Y, const int arrSize, const int LO [], const int numLO) {
double XXsumLO, XsumLO, YsumLO, XYsumLO = 0;
for(int i = 0; i < numLO; i++)
{
XXsumLO = XXsum - (X[LO[i]] * X[LO[i]]);
XsumLO = Xsum - X[LO[i]];
YsumLO = Ysum - Y[LO[i]];
XYsumLO = XYsum - X[LO[i]]*Y[LO[i]];
}
double numerator = ((arrSize-numLO) * XYsumLO)-(XsumLO*YsumLO);
double denominator = ((arrSize-numLO) * XXsumLO) - (XsumLO * XsumLO);
return numerator/denominator;
}
double LinearRegression::getB(const int arrSize) {
double numerator = (XXsum*Ysum)-(Xsum*XYsum);
double denominator = (arrSize * XXsum) - (Xsum * Xsum);
return numerator/denominator;
}
double LinearRegression::getBLO(double * X, double * Y, const int arrSize, const int LO [], const int numLO) {
double XXsumLO, XsumLO, YsumLO, XYsumLO = 0;
for(int i = 0; i < numLO; i++)
{
XXsumLO = XXsum - (X[LO[i]] * X[LO[i]]);
XsumLO = Xsum - X[LO[i]];
YsumLO = Ysum - Y[LO[i]];
XYsumLO = XYsum - X[LO[i]]*Y[LO[i]];
}
double numerator = (XXsumLO*YsumLO)-(XsumLO*XYsumLO);
double denominator = ((arrSize-numLO) * XXsumLO) - (XsumLO * XsumLO);
return numerator/denominator;
}
double LinearRegression::getSE(double * X, double * Y, const int arrSize) {
double M = getM(arrSize); double B = getB(arrSize);
double sum = 0;
for(int i = 0; i < arrSize; i++)
{
double predY = M * X[i] + B;
sum += pow(Y[i] - predY, 2);
}
double N = arrSize;
return sqrt(sum/N);
}
double LinearRegression::getSELO(double * X, double * Y, const double SE, const int arrSize, const int LO [], const int numLO) {
double M = getMLO(X, Y, arrSize, LO, numLO); double B = getBLO(X, Y, arrSize, LO, numLO);
double sum = pow(SE,2) * arrSize;
for(int i = 0; i < numLO; i++)
{
double predY = M * X[LO[i]] + B;
sum-= pow(Y[LO[i]] - predY, 2);
}
double N = arrSize-numLO;
return sqrt(sum/N);
}
double LinearRegression::getTStatistic(const double * X, const double * Y, const int & pos1, const int & pos2, const double & mean, const double & var, const double & SE, const double & arrSize) {
double M = getM(arrSize); double B = getB(arrSize);
double predY = M * X[pos1] + B;
double sum1 = pow((X[pos1] - mean),2)/(arrSize * var);
double numerator = predY - Y[pos2];
double denominator = SE * sqrt(1 + 1/arrSize + sum1);
return numerator/denominator;
}
<file_sep>/bin/z-transform-method/src/CSVIterator.cpp
/*
* CSVIterator.cpp
*
* Created on: Jan 15, 2017
* Author: Julia
*/
#include <iterator>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
#include "CSVRow.h"
#include "CSVIterator.h"
CSVIterator::CSVIterator(istream& str) :m_str(str.good()?&str:NULL) {
++(*this);
}
CSVIterator::CSVIterator() :m_str(NULL) {}
CSVIterator::~CSVIterator() {
// TODO Auto-generated destructor stub
}
CSVIterator& CSVIterator::operator++(){
if (m_str)
{
if (!((*m_str) >> m_row))
{
m_str = NULL;
}
}
return *this;
}
CSVIterator CSVIterator::operator++(int){
CSVIterator tmp(*this);++(*this);
return tmp;
}
CSVRow const& CSVIterator::operator*() const
{
return m_row;
}
CSVRow const* CSVIterator::operator->() const
{
return &m_row;
}
bool CSVIterator::operator==(CSVIterator const& rhs) {
return ((this == &rhs) || ((this->m_str == NULL) && (rhs.m_str == NULL)));
}
bool CSVIterator::operator!=(CSVIterator const& rhs) {
return !((*this) == rhs);
}
<file_sep>/analytics/static/analytics/js/tools/mergecolumns.js
$(document).ready(function(){
$('#add_more').click(
function(){
var name = "MergeColumn";
var fields = myDynamicFields();
if (name in fields){
name+= ('_' + String(fields[name]-2));
}
var currId = 'id_' + String(name);
console.log(currId);
var newElement = cloneField(currId);
console.log(newElement.attr("id"));
$('#' + currId).after(newElement);
$('#' + currId).after("<br>");
});
$('#id_InputFile').on('change', function(){
if($('#id_InputFile').val() != ''){
var fields = myDynamicFields();
var name = "MergeColumn"; var count = 1;
if(name in fields) {
count = fields[name];
}
var optionsLists = [];
optionsLists.push("id_MergeColumn");
$("#id_MergeColumn").empty();
for(var i = 1; i < count; i++){
var dName = "id_" + name + "_" + String(i-1);
optionsLists.push(dName);
$('#' + dName).empty();
}
var file_name = $('#id_InputFile').val();
appendFieldsFromFilesToFormFields(optionsLists, file_name, "", function () {
});
}
});
});<file_sep>/analytics/urls.py
from django.urls import path, re_path
from analytics.views import *
urlpatterns = [
re_path(r'^$', analytics_home, name='analytics_world'),
re_path(r'^home/$', analytics_home, name='hello_world'),
re_path(r'^tool/(?P<tool_id>[0-9]+)/short$', short_task, name='short_task'),
re_path(r'^tool/(?P<tool_id>[0-9]+)/long$', long_task, name='long_task'),
re_path(r'^tool/(?P<tool_id>[0-9]+)/upload$', upload_file, name='upload_file'),
re_path(r'^.+/update_history', update_history, name='update_history'),
re_path(r'^.+/get_field_options', get_field_options, name='get_field_options'),
re_path(r'^.+/get_common_field_options', get_common_field_options, name='get_common_field_options')
]
<file_sep>/analytics/static/analytics/js/tools/familytodnatype.js
$(document).ready(function(){
$('#id_RelationshipType').on('change', function(){
var selected_value = $('#id_RelationshipType').find(":selected").text();
if(selected_value == "Cousin") {
$('#CousinDegree_wrapper').css('display', 'block');
}else{
$('#CousinDegree_wrapper').css('display', 'none');
}
if(selected_value == "Direct Descendant" || selected_value == "Direct Ancestor"){
$('#Half_wrapper').css('display', 'none');
}else{
$('#Half_wrapper').css('display', 'block');
}
if(selected_value == "Sibling") {
$('#GenerationsRemoved_wrapper').css('display', 'none');
}else{
$('#GenerationsRemoved_wrapper').css('display', 'block');
}
if(selected_value == "Nephew" || selected_value == "Uncle") {
document.getElementById("id_MaleRelative").checked = true;
}else{
document.getElementById("id_MaleRelative").checked = false;
}
if(selected_value == "Niece" || selected_value == "Aunt") {
document.getElementById("id_FemaleRelative").checked = true;
}else{
document.getElementById("id_FemaleRelative").checked = false;
}
});
$('#id_MaleRelative').click(function() {
$('#id_FemaleRelative').prop('disabled', this.checked);
});
$('#id_FemaleRelative').click(function() {
$('#id_MaleRelative').prop('disabled', this.checked);
});
$('#id_MaleIndividual').click(function() {
$('#id_FemaleIndividual').prop('disabled', this.checked);
});
$('#id_FemaleIndividual').click(function() {
$('#id_MaleIndividual').prop('disabled', this.checked);
});
});
<file_sep>/bin/z-transform-method/src/SEinventory.cpp
/*
* SEinventory.cpp
*
* Created on: Jan 14, 2017
* Author: Julia
*/
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
#include "SEinventory.h"
SEinventory::SEinventory(): IDs(NULL), Measurements(NULL), numMeasPerRecord(0), numRecords(0), recordCapacity(0), idLength(0), elementType(NULL), elementSide(NULL) {
// TODO Auto-generated constructor stub
}
SEinventory::SEinventory(int nm, int rc, int ilen, string & et, string & es ): numMeasPerRecord(nm), numRecords(0), recordCapacity(rc), idLength(ilen),
elementType(et), elementSide(es){
Measurements = new double * [numMeasPerRecord];
for(int i = 0; i < numMeasPerRecord; i++)
{
Measurements[i] = new double [recordCapacity];
}
IDs = new char [recordCapacity * (idLength+1)];
}
SEinventory::~SEinventory() {
for(int i = 0; i < numMeasPerRecord; i++)
delete [] Measurements[i];
delete [] Measurements;
delete [] IDs;
}
void SEinventory::addMeasurements(string & id, float * & measures) {
strncpy(IDs+(numRecords*(idLength+1)), id.c_str(), idLength);
for(int i = 0; i < numMeasPerRecord; i++)
Measurements[i][numRecords] = measures[i];
numRecords++;
}
string SEinventory::getRecordId(int record) const{
int rPos = record * (idLength+1);
return string (IDs+rPos);
}
float SEinventory::getRecordMeas(int record, int meas) const{
return Measurements[meas][record];
}
string SEinventory::getElementType(void) const{
return elementType;
}
string SEinventory::getElementSide(void) const{
return elementSide;
}
<file_sep>/analytics/static/analytics/js/home.js
var width = 600, height = 400;
var n = 12, // number of nodes
m = 14, // number of links
charge = -1000;
var svg = d3.select("#dashboard")
.append("div")
.attr('id', 'dashboard-content')
.classed("svg-container", true)
.append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "-25 30 600 400")
.classed("svg-content-responsive", true)
.on("dblclick", create);
create();
function create () {
svg.selectAll(".link, .node").remove();
randomGraph(n, m, charge);
}
function randomGraph (n, m, charge) { //creates a random graph on n nodes and m links
var nodes = d3.range(n).map(Object),
list = randomChoose(unorderedPairs(d3.range(n)), m),
links = list.map(function (a) { return {source: a[0], target: a[1]} });
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links)
.charge(charge)
.on("tick", tick)
.start();
var svgLinks = svg.selectAll(".link").data(links)
.enter().append("line")
.attr("class", "link");
var svgNodes = svg.selectAll(".node").data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 3)
.style("fill", "white");
svgNodes.transition().duration(800)
.attr("r", function (d) { return 5 + 4 * d.weight })
.style("fill", "#E94F64");
svgLinks.transition().duration(800)
.style("stroke-width", 3);
function tick () {
svgNodes
.attr("cx", function(d) { return d.x })
.attr("cy", function(d) { return d.y });
svgLinks
.attr("x1", function(d) { return d.source.x })
.attr("y1", function(d) { return d.source.y })
.attr("x2", function(d) { return d.target.x })
.attr("y2", function(d) { return d.target.y });
}
}
function randomChoose (s, k) { // returns a random k element subset of s
var a = [], i = -1, j;
while (++i < k) {
j = Math.floor(Math.random() * s.length);
a.push(s.splice(j, 1)[0]);
};
return a;
}
function unorderedPairs (s) { // returns the list of all unordered pairs from s
var i = -1, a = [], j;
while (++i < s.length) {
j = i;
while (++j < s.length) a.push([s[i],s[j]])
};
return a;
}<file_sep>/analytics/templates/analytics/base.html
{% extends 'base.html' %}
{% load static%}
{% block styles %}
{{ block.super }}
<link rel="stylesheet", type="text/css", href="{% static 'analytics/css/base.css' %}"/>
{% endblock styles %}
{% block main %}
<nav class="navbar navbar-expand-md navbar-dark navbar-custom bg-dark">
<a href="#sidebar" id= "sidebar-toggler" data-toggle="collapse"><i class="fa fa-leaf fa-lg mr-2 ml-1"></i></a>
<a class="navbar-brand" href="{% url "hello_world" %}">CoRA Analytics</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span><i class="fa fa-question fa-lg"></i></span>
</button>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<i class="fa fa-history fa-lg"></i>
</button>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span><i class="fa fa-bars fa-lg"></i></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="{% url "hello_world" %}">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Login
</a>
<ul class="dropdown-menu dropdown-menu-right mt-1" aria-labelledby="navbarDropdownMenuLink">
<li class="p-3">
<form class="form" role="form">
<div class="form-group">
<input id="emailInput" placeholder="Email" class="form-control form-control-sm" type="text" required="">
</div>
<div class="form-group">
<input id="passwordInput" placeholder="<PASSWORD>" class="form-control form-control-sm" type="text" required="">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Login</button>
</div>
<div class="form-group text-xs-center">
<small><a href="#">Forgot password?</a></small>
</div>
</form>
</li>
</ul>
</li>
</ul>
</div>
</nav>
<div class="container-fluid">
<div class="row d-flex d-md-block flex-nowrap wrapper">
<div class="col-md-3 float-left col-1 px-0 py-0 collapse width show" id="sidebar">
<div class="col-12 list-group border-0 card text-center text-md-left">
{% for toolkit in toolkits %}
<a href= "#menu{{toolkit.id}}" class="list-group-item d-inline-block collapsed"
data-toggle="collapse" aria-expanded="false">
<i class="fa fa-angle-right"></i>
<span class="d-none d-md-inline">{{ toolkit.display_name }}</span></a>
<div class="collapse" id="menu{{ toolkit.id }}" data-parent="#sidebar">
{% for tool in toolkit.tool_set.all %}
{% if tool.tool_type == "short_task" %}
<a href="{% url "short_task" tool.id %}" class="list-group-item">{{ tool.display_name}}</a>
{% elif tool.tool_type == "long_task" %}
<a href="{% url "long_task" tool.id %}" class="list-group-item">{{ tool.display_name}}</a>
{% elif tool.tool_type == "upload_file" %}
<a href="{% url "upload_file" tool.id %}" class="list-group-item">{{ tool.display_name}}</a>
{% else %}
<a href="#" class="list-group-item">{{ tool.display_name}}</a>
{% endif %}
{% endfor %}
</div>
{% endfor %}
</div>
</div>
<div class="card float-right col-3 md-2 mt-2 d-none d-md-block" id="infobar">
<div class="card-header">
<button style="float: right" class="refresh_history"><span><i class="fa fa-refresh fa-lg"></i></span></button>
<ul class="nav nav-pills card-header-pills" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="history" data-toggle="tab"
href="#history-tab">History</a>
</li>
<li class="nav-item">
<a class="nav-link" id="help" data-toggle="tab"
href="#help-tab" >Help</a>
</li>
</ul>
</div>
<div class="card-body">
<div class="tab-content">
<div class="tab-pane fade active show" id="history-tab">
{% block history %}
{% if not results %}
<p>Welcome! You have no history.
{% if not request.user.is_authenticated %}
Please log in to see your history.
{% endif %}
</p>
{% else %}
{% for result in results %}
{% if result.status == "PENDING" %}
<div class="history pending-task">
<div class="float-right">
<button id="{{ result.task_id }}_remove" class="pending-task delete_history"><i class="fa fa-window-close"></i></button>
</div>
<div>
<a href="#" id="{{result.task_id}}" data-file_name="{{result.file_name}}" data-file_type="{{ result.file_type.file_type_name }}"
data-user_id = "{{result.user_id}}">{{result.file_name}}</a>
</div>
</div>
{% elif result.status == "ACTIVE"%}
<div class="history active-task">
<div class="float-right">
<button id="{{ result.task_id }}_remove" class="active-task delete_history"><i class="fa fa-window-close"></i></button>
</div>
<div>
<a href="#" data-file_name="{{result.file_name}}" data-file_type="{{ result.file_type.file_type_name }}"
data-user_id = "{{result.user_id}}">{{result.file_name}}</a>
</div>
</div>
{% elif result.status == "COMPLETE"%}
<div class="history complete-task">
<div class="float-right">
<button id="{{ result.task_id }}_remove" class="complete-task delete_history"><i class="fa fa-window-close"></i></button>
</div>
<div>
<a href="/media/user{{ result.user_id }}/{{ result.file_name }}" id="{{result.task_id}}" id="{{result.task_id}}" data-file_name={{result.file_name}}, data-file_type="{{ result.file_type.file_type_name }}"
data-user_id = "{{result.user_id}}" download>{{result.file_name}}</a>
</div>
</div>
{% elif result.status == "ERROR"%}
<div class="history error-task">
<div class="float-right">
<button id="{{ result.task_id }}_remove" class="error-task delete_history"><i class="fa fa-window-close"></i></button>
</div>
<div>
<a href="#" id="{{result.task_id}}" data-file_name="{{result.file_name}}" data-file_type="{{ result.file_type.file_type_name }}"
data-user_id = "{{result.user_id}}">{{result.file_name}}</a>
</div>
</div>
{% endif %}
{% endfor %}
{% endif %}
{% endblock history %}
</div>
<div class="tab-pane fade" id="help-tab">
{% block help %}
<p>Select a tool from the left side panel to begin.</p>
{% endblock %}
</div>
</div>
</div>
</div>
<div class="col-md-6 float-right col px-5 pl-md-3" id="middle-panel">
<div class="row wrapper d-flex flex-nowrap d-md-block" id="header-row">
<div class = "col-md-12 col" id="main-header">
<div class="page-header">
<br>
<button class="close" onclick="document.getElementById('main-header').style.display = 'none'">
<i class="fa fa-window-close"></i>
</button>
<h2>{% block header_title %}{% endblock %}</h2>
</div>
<p class="lead">{% block header_description %}{% endblock %}</p>
<div><hr></div>
</div>
</div>
<div class="row wrapper d-flex flex-nowrap d-md-block">
<main class="main col-md-12 col pt-2" id="dashboard">
{% block dashboard-content %}
{% endblock dashboard-content %}
</main>
</div>
</div>
</div>
</div>
{% endblock main %}
{% block extra_js %}
{{ block.super }}
<script src="{% static 'analytics/js/base.js' %}"></script>
{% endblock extra_js %}<file_sep>/analytics/models/toolkits.py
from django.db import models
from django.utils import timezone
class Toolkit(models.Model):
toolkit_name = models.CharField(max_length=200)
display_name = models.CharField(max_length=200)
short_description = models.CharField(max_length=200)
long_description = models.TextField()
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
class Meta:
ordering = ['display_name']
def __unicode__(self):
return u"%s" % self.toolkit_name
def __str__(self):
return self.toolkit_name
def save(self, *args, **kwargs):
"""On save update time stamp."""
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(Toolkit, self).save(*args, **kwargs) # call the real save method<file_sep>/bin/z-transform-method/src/Summator.h
/*
* Summator.h
*
* Created on: Jan 15, 2017
* Author: Julia
*/
#ifndef SUMMATOR_H_
#define SUMMATOR_H_
template <class T>
class Summator {
public:
Summator();
virtual ~Summator();
double sum(const T *, const int) const;
double sumLOO(const T *, const int, const int [], const int) const;
double sumXY(const T *, const T *, const int) const;
double sumXYLOO(const T *, const T *, const int, const int [], const int) const;
};
template <class T>
Summator<T>::Summator() {};
template <class T>
Summator<T>::~Summator() {
}
template <class T>
double Summator<T>::sum(const T * arr, const int arrSize) const {
double sum = 0;
for(int i = 0; i < arrSize; i++)
sum+=arr[i];
return sum;
}
template <class T>
double Summator<T>::sumLOO(const T * arr, const int arrSize, const int LOO[], const int numLO) const {
double sum = 0;
for(int i = 0; i < arrSize; i++)
sum+=arr[i];
for(int i = 0; i < numLO; i++)
sum-=arr[LOO[i]];
return sum;
}
template <class T>
double Summator<T>::sumXY(const T * X, const T * Y, const int arrSize) const {
double sum = 0;
for(int i = 0; i < arrSize; i++)
sum+=(X[i]*Y[i]);
return sum;
}
template <class T>
double Summator<T>::sumXYLOO(const T * X, const T * Y, const int arrSize, const int LOO[], const int numLO) const {
double sum = 0;
for(int i = 0; i < arrSize; i++)
sum+=(X[i]*Y[i]);
for(int i = 0; i < numLO; i++)
sum-=(X[LOO[i]] * Y[LOO[i]]);
return sum;
}
#endif /* SUMMATOR_H_ */
<file_sep>/analytics/models/tools_output.py
from django.db import models
from django.utils import timezone
from .tools import Tool
from .file_types import FileType
class OutputFile(models.Model):
parameter_name = models.CharField(max_length=200)
file_base_name = models.CharField(max_length=200)
short_description = models.CharField(max_length=200)
tool = models.ForeignKey(Tool, on_delete=models.CASCADE,)
file_type = models.ForeignKey(FileType, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def __unicode__(self):
return u"%s" % self.file_base_name
def __str__(self):
return self.file_base_name
def save(self, *args, **kwargs):
"""On save update timestamp"""
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(OutputFile, self).save(*args, **kwargs) # call the real save method
<file_sep>/Dockerfile
FROM python:3.6-alpine3.7
ENV INSTALL_PATH /app
RUN mkdir -p $INSTALL_PATH
WORKDIR $INSTALL_PATH
ENV CELERY_BROKER_URL redis://redis:6379/0
ENV CELERY_RESULT_BACKEND redis://redis:6379/0
ENV C_FORCE_ROOT true
ARG NUMPY_VERSION=1.13.1
ENV NUMPY_VERSION ${NUMPY_VERSION}
ARG PANDAS_VERSION=0.20.3
ENV PANDAS_VERSION ${PANDAS_VERSION}
ARG SCIPY_VERSION=0.19.1
ENV SCIPY_VERSION ${SCIPY_VERSION}
ARG SCIKIT_VERSION=0.19.0
ENV SCIKIT_VERSION ${SCIKIT_VERSION}
COPY requirements.txt requirements.txt
#move build-base, g++, R-dev to build-dependencies
RUN apk add --no-cache libstdc++ bash build-base R-dev && \
apk add --no-cache \
--virtual=.build-dependencies \
gfortran musl-dev \
postgresql-dev libffi-dev && \
apk add --no-cache R && \
ln -s locale.h /usr/include/xlocale.h && \
pip install numpy && \
pip install pandas && \
pip install -r requirements.txt && \
echo "r <- getOption('repos'); r['CRAN'] <- 'http://cran.us.r-project.org'; options(repos = r);" > ~/.Rprofile && \
Rscript -e "install.packages('Rcpp')" && \
Rscript -e "install.packages('RInside')" && \
rm -rf /tmp/* && \
find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + && \
runDeps="$( \
scanelf --needed --nobanner --recursive /usr/local \
| awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \
| sort -u \
| xargs -r apk info --installed \
| sort -u \
)" && \
rm /usr/include/xlocale.h && \
rm -r /root/.cache && \
apk add --virtual .rundeps $runDeps &&\
apk del .build-dependencies
WORKDIR $INSTALL_PATH
COPY ./bin /app/bin
RUN cd ./bin/z-transform-method && \
make && \
mv ./build/SE_Compare ../ && \
cd ../ && \
rm -rf z-transform-method
COPY . /app
EXPOSE 8000
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
<file_sep>/bin/z-transform-method/src/Correlation.h
/*
* Correlation.h
*
* Created on: Jan 14, 2017
* Author: Julia
*/
#ifndef CORRELATION_H_
#define CORRELATION_H_
template <class T>
class Correlation {
public:
Correlation();
virtual ~Correlation();
double getCor(const T *, const T *, const int, const double, const double) const;
double getCorAdj(const double, const double) const;
double getCorLO(const T *, const T *, const int,const int [], const int, const double, const double) const;
};
template <class T>
Correlation<T>::Correlation() {};
template <class T>
Correlation<T>::~Correlation() {
}
template <class T>
double Correlation<T>::getCor(const T * X, const T * Y, const int arrSize, const double meanX, const double meanY) const {
double numerator = 0; double sum1 = 0; double sum2 = 0;
for(int i = 0; i < arrSize; i++)
{
sum1+=pow((X[i]-meanX), 2); sum2+=pow((Y[i]-meanY), 2);
numerator+=((X[i]-meanX) * (Y[i]-meanY));
}
double denominator = (sqrt(sum1)*sqrt(sum2));
return numerator/denominator;
}
template <class T>
double Correlation<T>::getCorLO(const T * X, const T * Y, const int arrSize, const int LO [], const int numLO, const double meanX, const double meanY) const {
double numerator = 0; double sum1 = 0; double sum2 = 0;
for(int i = 0; i < arrSize; i++)
{
sum1+=pow((X[i]-meanX), 2); sum2+=pow((Y[i]-meanY), 2);
numerator+=((X[i]-meanX) * (Y[i]-meanY));
}
for(int i = 0; i < numLO; i++)
{
sum1-=pow((X[i]-meanX), 2);
sum2-=pow((Y[i]-meanY), 2);
numerator-=((X[i]-meanX) * (Y[i]-meanY));
}
double denominator = (sqrt(sum1)*sqrt(sum2));
return numerator/denominator;
}
template <class T>
double Correlation<T>::getCorAdj(const double r, const double size) const {
return r*(1+(1-pow(r,2))/(2*size));
}
#endif /* CORRELATION_H_ */
<file_sep>/bin/z-transform-method/src/CSVIterator.h
/*
* CSVIterator.h
*
* Created on: Jan 14, 2017
* Author: Julia
*/
#ifndef CSVITERATOR_H_
#define CSVITERATOR_H_
class CSVIterator {
public:
typedef std::input_iterator_tag iterator_category;
typedef CSVRow value_type;
typedef size_t difference_type;
typedef CSVRow* pointer;
typedef CSVRow& reference;
CSVIterator(istream&);
CSVIterator();
virtual ~CSVIterator();
CSVIterator& operator++();
CSVIterator operator++(int);
CSVRow const& operator*() const;
CSVRow const* operator->() const;
bool operator==(CSVIterator const&);
bool operator!=(CSVIterator const& rhs);
private:
istream* m_str;
CSVRow m_row;
};
#endif /* CSVITERATOR_H_ */
<file_sep>/requirements.txt
billiard==3.5.0.3
kombu==4.1.0
celery==4.1.0
Django==2.0.4
fuzzywuzzy==0.16.0
python-Levenshtein==0.12.0
python-dateutil==2.7.2
pytz==2018.4
redis==2.10.6
six==1.11.0
vine==1.1.4
psycopg2==2.7.4
<file_sep>/bin/z-transform-method/src/Mean.h
/*
* Mean.h
*
* Created on: Jan 14, 2017
* Author: Julia
*/
#ifndef MEAN_H_
#define MEAN_H_
#include <iostream>
using namespace std;
template <class T>
class Mean {
public:
Mean();
virtual ~Mean();
double getMean(const T *, const int) const;
double getMeanLOO(const T *, const int, const int [], const int, const double) const;
};
template <class T>
Mean<T>::Mean() {};
template <class T>
Mean<T>::~Mean() {
}
template <class T>
double Mean<T>::getMean(const T * arr, const int arrSize) const {
double sum = 0;
for(int i = 0; i < arrSize; i++)
{
sum+=arr[i];
}
float size = arrSize;
return sum/size;
}
template <class T>
double Mean<T>::getMeanLOO(const T * arr, const int arrSize, const int LO [], const int numLO, const double sum) const
{
double numerator = sum;
for(int i = 0; i < numLO; i++)
numerator-=arr[LO[i]];
double denominator = arrSize-numLO;
return (numerator/denominator);
}
#endif /* MEAN_H_ */
<file_sep>/analytics/forms/helpers.py
from django.forms import BaseInlineFormSet
from django.forms.widgets import Select
from django.conf import settings
import pandas as pd
class FormSetWithParentAccess(BaseInlineFormSet):
def get_form_kwargs(self, index):
kwargs = super().get_form_kwargs(index)
kwargs['parent_object'] = self.instance
return kwargs
class SelectWithCreateOption(Select):
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
disabled = False
if isinstance(label, dict):
label, disabled = label['label'], label['disabled']
option_dict = super(SelectWithCreateOption, self).create_option(name, value, label, selected, index,
subindex=subindex, attrs=attrs)
if disabled:
option_dict['attrs']['disabled'] = 'disabled'
return option_dict
def is_in_headers(header, user, file_name):
file_url = settings.MEDIA_ROOT + '/user' + str(user) + '/' \
+ file_name
fields = pd.read_csv(file_url, sep=None, nrows=0).columns.tolist()
if header in fields:
return True
return False
<file_sep>/bin/z-transform-method/src/CSVRow.h
/*
* CSVRow.h
*
* Created on: Jan 14, 2017
* Author: Julia
*/
#ifndef CSVROW_H_
#define CSVROW_H_
class CSVRow {
public:
CSVRow();
virtual ~CSVRow();
string const & operator[] (size_t) const;
size_t size() const;
void readNextRow(istream &);
friend istream & operator>>(istream&, CSVRow&);
private:
vector<string> m_data;
};
#endif /* CSVROW_H_ */
<file_sep>/analytics/forms/dynamic_form.py
from django import forms
from django.forms.forms import BaseForm
from django.utils.translation import gettext_lazy as _
from analytics.models.tools import Tool
from analytics.models.tools_input import InputParameter, InputParameterStringValueOption, \
InputParameterNumericValueOption
from analytics.models.tools_output import OutputFile
from analytics.models.file_types import FileType
from .helpers import SelectWithCreateOption, is_in_headers
from analytics.models.results import Result
import json
from django.http import JsonResponse, HttpResponse
class DynamicForm(forms.Form):
def __init__(self, user, tool, extra, *args, **kwargs):
self.user = user
super(DynamicForm, self).__init__(*args, **kwargs)
self.params = tool.inputparameter_set.all()
self.file_params = self.params.filter(parameter_type='FILE')
for file_param in self.file_params:
self.fields[file_param.parameter_name] = forms.FileField(label=file_param.display_name)
if file_param.parameter_required:
self.fields[file_param.parameter_name].required = True
else:
self.fields[file_param.parameter_name].required = False
file_types = FileType.objects.filter(inputparameter=file_param)
if file_types.exists():
choices = [(file_type.file_type_name, file_type.display_name) for file_type in
file_types]
choices.insert(0, ('', "----"))
self.fields[file_param.parameter_name + '_file%type'] = \
forms.ChoiceField(label="File Type", choices=choices) # modifies an input parameter
self.file_select_params = self.params.filter(parameter_type='FILE_SELECT')
for file_select_param in self.file_select_params:
self.fields[file_select_param.parameter_name] \
= forms.ChoiceField(label=file_select_param.display_name,
widget=forms.Select(attrs={'class': 'file_select'}),
choices=[('', "----"), ])
if file_select_param.parameter_required:
self.fields[file_select_param.parameter_name].required = True
else:
self.fields[file_select_param.parameter_name].required = False
if file_select_param.parameter_name in self.data:
try:
file_name = self.data.get(file_select_param.parameter_name)
result = Result.objects.filter(file_name=file_name).get()
self.fields[file_select_param.parameter_name].choices = [(result.file_name, result.file_name), ]
except Result.DoesNotExist:
pass
else:
pass
file_types = FileType.objects.filter(inputparameter=file_select_param)
if file_types.exists():
input_types = [(file_type.file_type_name, file_type.file_type_name) for file_type in
file_types]
json_data = json.dumps(input_types)
self.fields[file_select_param.parameter_name].widget.attrs.update({'data-input_types': json_data})
self.header_select_params = self.params.filter(parameter_type='HEADER_SELECT')
for header_select_param in self.header_select_params:
counter = extra.get(header_select_param.parameter_name, 1)
dynamic_tag = ''
for i in range(0, counter):
self.fields[header_select_param.parameter_name + dynamic_tag] \
= forms.ChoiceField(label=header_select_param.display_name,
widget=forms.Select(attrs={'class': 'header_select'}),
choices=[('', "----"), ])
if header_select_param.parameter_name + dynamic_tag in self.data:
header = self.data[header_select_param.parameter_name + dynamic_tag]
if header != '':
for file_select_param in self.file_select_params:
if file_select_param.parameter_name in self.data:
file_name = self.data[file_select_param.parameter_name]
if is_in_headers(header, self.user, file_name):
self.fields[header_select_param.parameter_name + dynamic_tag].choices = \
[(header, header), ]
break
if header_select_param.parameter_required:
self.fields[header_select_param.parameter_name + dynamic_tag].required = True
else:
self.fields[header_select_param.parameter_name + dynamic_tag].required = False
dynamic_tag = "_%d" % i
self.string_params = self.params.filter(parameter_type='STR')
for string_param in self.string_params:
counter = extra.get(string_param.parameter_name, 1)
dynamic_tag = ''
for i in range(0, counter):
string_values = string_param.inputparameterstringvalueoption_set.all()
if string_values.exists():
choices = [(string_value.string_value, string_value.string_value) for string_value in string_values]
choices.insert(0, ('', "----"))
self.fields[string_param.parameter_name + dynamic_tag ] = forms.ChoiceField(
choices=choices, label=string_param.display_name)
if string_param.parameter_required:
self.fields[string_param.parameter_name + dynamic_tag].required = True
else:
self.fields[string_param.parameter_name + dynamic_tag].required = False
try:
default = string_values.get(default_value=True)
self.fields[string_param.parameter_name+ dynamic_tag].initial = default.string_value
except InputParameterStringValueOption.DoesNotExist:
pass
else:
self.fields[string_param.parameter_name + dynamic_tag] = forms.CharField(max_length=200,
label=string_param.display_name)
if string_param.parameter_required:
self.fields[string_param.parameter_name + dynamic_tag].required = True
else:
self.fields[string_param.parameter_name + dynamic_tag].required = False
dynamic_tag = "_%d" % i
self.numeric_params = self.params.filter(parameter_type='NUMERIC')
for numeric_param in self.numeric_params:
counter = extra.get(numeric_param.parameter_name, 1)
dynamic_tag = ''
for i in range(0, counter):
numeric_values = numeric_param.inputparameternumericvalueoption_set.all()
if numeric_values.exists():
choices = [(numeric_value.numeric_value, numeric_value.numeric_value) for numeric_value in
numeric_values]
choices.insert(0, ('', "----"))
self.fields[numeric_param.parameter_name + dynamic_tag] = forms.ChoiceField(
choices=choices, label=numeric_param.display_name)
if numeric_param.parameter_required:
self.fields[numeric_param.parameter_name + dynamic_tag].required = True
else:
self.fields[numeric_param.parameter_name + dynamic_tag].required = False
try:
default = numeric_values.get(default_value=True)
self.fields[numeric_param.parameter_name + dynamic_tag].initial = default.numeric_value
except InputParameterNumericValueOption.DoesNotExist:
pass
else:
self.fields[numeric_param.parameter_name + dynamic_tag] = \
forms.FloatField(label=numeric_param.display_name)
if numeric_param.parameter_required:
self.fields[numeric_param.parameter_name + dynamic_tag].required = True
else:
self.fields[numeric_param.parameter_name+ dynamic_tag].required = False
dynamic_tag = "_%d" % i
self.bool_params = self.params.filter(parameter_type='BOOL')
for bool_param in self.bool_params:
counter = extra.get(bool_param.parameter_name, 1)
dynamic_tag = ''
for i in range(0, counter):
self.fields[bool_param.parameter_name + dynamic_tag] = forms.BooleanField(label=bool_param.display_name)
if bool_param.parameter_required:
self.fields[bool_param.parameter_name + dynamic_tag].required = True
else:
self.fields[bool_param.parameter_name + dynamic_tag].required = False
dynamic_tag = "_%d" % i
def fields_required(self, requiring_name, required_fields):
for field, field_display_name in required_fields:
if self.cleaned_data.get(field, False):
raise forms.ValidationError(
_("Field %s is required by %s") % (field_display_name, requiring_name), code='field_required'
)
def fields_excluded(self, requiring_name, excluded_fields):
for field, field_display_name in excluded_fields:
if self.cleaned_data.get(field):
raise forms.ValidationError(
_("Field %s is excluded by %s") % (field_display_name, requiring_name), code='field_excluded'
)
def clean(self):
cleaned_data = super(forms.Form, self).clean()
for key, field in cleaned_data.items():
if field and "%" not in key: # Check to see if it is modifier param
try:
param = self.params.get(parameter_name=key)
required_fields = param.requires.all()\
.values_list('parameter_name', 'display_name')
self.fields_required(param.display_name, required_fields)
excluded_fields = param.excludes.all() \
.values_list('parameter_name', 'display_name')
self.fields_excluded(param.display_name, excluded_fields)
except InputParameter.DoesNotExist :
pass
for param in self.string_params:
try:
string_value = cleaned_data.get(param.parameter_name)
try:
string_param_value = param.inputparameterstringvalueoption_set\
.get(string_value=string_value)
required_fields = string_param_value.requires.all() \
.values_list('parameter_name', 'display_name')
self.fields_required(string_value, required_fields)
excluded_fields = string_param_value.excludes.all() \
.values_list('parameter_name', 'display_name')
self.fields_excluded(string_value, excluded_fields)
except InputParameterStringValueOption.DoesNotExist :
pass
except InputParameter.DoesNotExist:
pass
for param in self.numeric_params:
try:
numeric_value = cleaned_data.get(param.parameter_name)
try:
numeric_param_value = param.inputparameternumericvalueoption_set \
.get(numeric_value=numeric_value)
required_fields = numeric_param_value.requires.all() \
.values_list('parameter_name', 'display_name')
self.fields_required(numeric_value, required_fields)
excluded_fields = numeric_param_value.excludes.all() \
.values_list('parameter_name', 'display_name')
self.fields_excluded(numeric_value, excluded_fields)
except InputParameterNumericValueOption.DoesNotExist:
pass
except InputParameter.DoesNotExist:
pass
def do_not_display(self, field):
self.fields[field].widget.attrs = {'display': 'none'}<file_sep>/analytics/migrations/0001_initial.py
# Generated by Django 2.0.4 on 2018-05-24 16:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='FileType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file_type_name', models.CharField(max_length=200)),
('display_name', models.CharField(max_length=200)),
('short_description', models.CharField(max_length=200)),
('file_extension', models.CharField(max_length=10)),
('created_at', models.DateTimeField(editable=False)),
('updated_at', models.DateTimeField()),
],
),
migrations.CreateModel(
name='InputParameter',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('parameter_name', models.CharField(max_length=200)),
('display_name', models.CharField(max_length=200)),
('short_description', models.CharField(max_length=200)),
('parameter_type', models.CharField(choices=[('BOOL', 'Boolean'), ('STR', 'String'), ('NUMERIC', 'Numerical'), ('FILE', 'File'), ('FILE_SELECT', 'File Select'), ('HEADER_SELECT', 'Header Select')], max_length=30)),
('parameter_required', models.BooleanField()),
('created_at', models.DateTimeField(editable=False)),
('updated_at', models.DateTimeField()),
('excludes', models.ManyToManyField(blank=True, related_name='excluded_parameters', to='analytics.InputParameter', verbose_name='Excludes input parameters')),
('file_type', models.ManyToManyField(blank=True, to='analytics.FileType')),
('requires', models.ManyToManyField(blank=True, related_name='requiring_parameters', to='analytics.InputParameter', verbose_name='Requires input parameters')),
],
),
migrations.CreateModel(
name='InputParameterNumericValueOption',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('numeric_value', models.FloatField(max_length=200)),
('short_description', models.CharField(max_length=200)),
('default_value', models.BooleanField()),
('created_at', models.DateTimeField(editable=False)),
('updated_at', models.DateTimeField()),
('parameter', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='analytics.InputParameter')),
],
),
migrations.CreateModel(
name='InputParameterStringValueOption',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('string_value', models.CharField(max_length=200)),
('short_description', models.CharField(max_length=200)),
('default_value', models.BooleanField()),
('created_at', models.DateTimeField(editable=False)),
('updated_at', models.DateTimeField()),
('excludes', models.ManyToManyField(blank=True, related_name='excluding_values', to='analytics.InputParameter', verbose_name='Excludes input parameters')),
('parameter', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='analytics.InputParameter')),
('requires', models.ManyToManyField(blank=True, related_name='requiring_values', to='analytics.InputParameter', verbose_name='Requires input parameters')),
],
),
migrations.CreateModel(
name='OutputFile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('parameter_name', models.CharField(max_length=200)),
('file_base_name', models.CharField(max_length=200)),
('short_description', models.CharField(max_length=200)),
('created_at', models.DateTimeField(editable=False)),
('updated_at', models.DateTimeField()),
('file_type', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='analytics.FileType')),
],
),
migrations.CreateModel(
name='Result',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file_name', models.CharField(max_length=300)),
('user_id', models.IntegerField()),
('task_id', models.CharField(max_length=300)),
('status', models.CharField(choices=[('PENDING', 'Pending'), ('ACTIVE', 'Running'), ('COMPLETE', 'Complete'), ('ERROR', 'Error')], max_length=10)),
('created_at', models.DateTimeField(editable=False)),
('updated_at', models.DateTimeField()),
('file_type', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='analytics.FileType')),
],
),
migrations.CreateModel(
name='Tool',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('tool_name', models.CharField(max_length=200)),
('display_name', models.CharField(max_length=200)),
('short_description', models.CharField(max_length=200)),
('long_description', models.TextField()),
('created_at', models.DateTimeField(editable=False)),
('updated_at', models.DateTimeField()),
('tool_type', models.CharField(choices=[('upload_file', 'Upload File'), ('short_task', 'Short Task'), ('long_task', 'Long Task'), ('visualization', 'Visualization')], max_length=200)),
],
options={
'ordering': ['display_name'],
},
),
migrations.CreateModel(
name='Toolkit',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('toolkit_name', models.CharField(max_length=200)),
('display_name', models.CharField(max_length=200)),
('short_description', models.CharField(max_length=200)),
('long_description', models.TextField()),
('created_at', models.DateTimeField(editable=False)),
('updated_at', models.DateTimeField()),
],
options={
'ordering': ['display_name'],
},
),
migrations.AddField(
model_name='tool',
name='toolkit',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='analytics.Toolkit'),
),
migrations.AddField(
model_name='result',
name='tool',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='analytics.Tool'),
),
migrations.AddField(
model_name='outputfile',
name='tool',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='analytics.Tool'),
),
migrations.AddField(
model_name='inputparameter',
name='tool',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='analytics.Tool'),
),
]
<file_sep>/analytics/tasks.py
from __future__ import absolute_import, unicode_literals
from celery import shared_task, Task
import json
from analytics.models import Result
import logging
import pandas as pd
from fuzzywuzzy import process
import subprocess
logger = logging.getLogger(__name__)
# helpers
class FinalizeTask(Task):
abstract = True
def on_failure(self, exc, task_id, args, kwargs, einfo):
logger.exception("Something happened when trying"
" to resolve %s" % args[0])
results = Result.objects.filter(task_id=task_id)
for result in results:
result.status = "ERROR"
result.save()
def on_success(self, retval, task_id, args, kwargs):
results = Result.objects.filter(task_id=task_id)
for result in results:
result.status = "COMPLETE"
result.save()
@shared_task(ignore_result=False)
def familytodnatype(json_vals):
values = json.loads(json_vals)
dna_avail = {'Autosomal': "No", 'Mitochondrial': "No", 'Y-STR': "No"}
if values.get('RelationshipType') == "Direct Descendant":
if values.get('GenerationsRemoved') == 'One':
dna_avail["Autosomal"] = "Yes"
if values.get('FemaleIndividual'):
dna_avail["Mitochondrial"] = "Yes"
if values.get('MaleIndividual'):
dna_avail["Y-STR"] = "Yes"
if values.get('RelationshipType') == "Sibling":
if not values.get('Half'):
if values.get('MaleRelative'):
dna_avail["Y-STR"] = "Yes"
dna_avail["Mitochondrial"] = "Yes"
dna_avail["Autosomal"] = "Yes"
if values.get('Matrilineal'):
dna_avail["Mitochondrial"] = "Yes"
if values.get('Patrilineal'):
dna_avail["Y-STR"] = "Yes"
if values.get('FemaleIndividual') or values.get('FemaleRelative'):
dna_avail["Y-STR"] = "No"
if not values.get('MaleIndividual') or not values.get('MaleRelative'):
dna_avail["Y-STR"] = "No"
return json.dumps(dna_avail)
@shared_task(base=FinalizeTask, ignore_result=True)
def uploadfile(json):
pass
@shared_task(base=FinalizeTask, ignore_result=True)
def mapcolumns(json_vals):
values = json.loads(json_vals)
input_file_location = "media/user" + str(values['user_id']) + "/" + values['InputFile']
map_file_location = "media/user" + str(values['user_id']) + "/" + values['MappingFile']
input_df = pd.read_csv(input_file_location, sep=None)
map_df = pd.read_csv(map_file_location, sep=None)
pos = 0
colname = map_df.columns[pos]
merged_df = pd.merge(input_df, map_df, how='left', on=colname)
if not values.get('KeepMapped'):
del merged_df[colname]
output_file_location = "media/user" + str(values['user_id']) + "/" + values['MappedFile']
merged_df.to_csv(output_file_location, sep='\t', index=False)
@shared_task(base=FinalizeTask, ignore_result=True)
def fuzzyrecordmatching(json_vals):
values = json.loads(json_vals)
master_file_location = "media/user" + str(values['user_id']) + "/" + values['MasterFile']
compare_file_location = "media/user" + str(values['user_id']) + "/" + values['ComparisonFile']
master_df = pd.read_csv(master_file_location, sep=None)
compare_df = pd.read_csv(compare_file_location, sep=None)
index_field = values['IndexField']
num_match = 3
master_index = master_df[index_field].tolist()
compare_index = compare_df[index_field].tolist()
gen = (x for x in compare_index if x not in master_index)
compare_list = list(gen)
fhp_new = [process.extract(x, master_df[index_field], limit=num_match) for x in compare_list]
lab = ""
i = 1
while i <= num_match:
lab = lab + " " + "Match" + str(i)
i += 1
fhp_matches = pd.DataFrame(fhp_new, columns=lab.split())
d = {}
d["Record Compared"] = compare_list
for x in range(1, num_match + 1):
d["Match{0}".format(x)] = [y[0] for y in fhp_matches['Match' + str(x)]]
d["Score{0}".format(x)] = [y[1] for y in fhp_matches['Match' + str(x)]]
out = pd.DataFrame(d, columns=d.keys())
output_file_location = "media/user" + str(values['user_id']) + "/" + values['InexactRecords']
out.to_csv(output_file_location, sep='\t', index=False)
@shared_task(base=FinalizeTask, ignore_result=True)
def effectzosteometricsorting(json_vals):
values = json.loads(json_vals)
program_path = "/app/bin/SE_Compare"
rtrain_file_location = "media/user" + str(values['user_id']) + "/" + values['rightTrain']
ltrain_file_location = "media/user" + str(values['user_id']) + "/" + values['leftTrain']
rclass_file_location = "media/user" + str(values['user_id']) + "/" + values['rightTest']
lclass_file_location = "media/user" + str(values['user_id']) + "/" + values['leftTest']
output_file_location = "media/user" + str(values['user_id']) + "/" + values['OsteometricSortingPvals']
outfile = open(output_file_location, "w")
subprocess.check_call(["R", "CMD", program_path, "--rTrain", rtrain_file_location, "--lTrain", ltrain_file_location ,
"--rClass", rclass_file_location, "--lClass", lclass_file_location, "--effectSizeZ", "TRUE"], stdout=outfile)
outfile.close()
return json.dumps(values['OsteometricSortingPvals'])
@shared_task(base=FinalizeTask, ignore_result=True)
def mergecolumns(json_vals):
values = json.loads(json_vals)
input_file_location = "media/user" + str(values['user_id']) + "/" + values['InputFile']
input_df = pd.read_csv(input_file_location, sep=None)
input_df[values['ResultColumn']] = input_df[values['MergeColumn']]
counter = 0
curr_param = 'MergeColumn_%s' % counter
while values.get(curr_param, 0):
input_df[values['ResultColumn']] += (" " + input_df[values[curr_param]].map(str))
counter += 1
curr_param = 'MergeColumn_%s' % counter
output_file_location = "media/user" + str(values['user_id']) + "/" + values['ResultFile']
input_df.to_csv(output_file_location, sep='\t', index=False)
def mergedata(json_vals):
values = json.loads(json_vals)
file_name1 = values["MasterFile"]
file_name2 = values["MergeFile"]
user_id = values["user_id"]
<file_sep>/bin/z-transform-method/src/CompareClass.h
/*
* CompareClass.h
*
* Created on: Feb 24, 2017
* Author: Julia
*/
#ifndef COMPARECLASS_H_
#define COMPARECLASS_H_
struct CompareClass {
public:
CompareClass(double * & Z): myArr(Z){;;;}
bool operator()(const int & i1, const int & i2)
{
return (myArr[i1] < myArr[i2]);
}
private:
double * myArr;
};
#endif /* COMPARECLASS_H_ */
<file_sep>/analytics/validators/validators.py
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
import re
def validate_object_name(value):
reg = re.compile(r"^([0-9A-Za-z_().\-!,]+ )*[0-9A-Za-z_().\-!,]+$")
if not reg.match(value):
raise ValidationError(_("Please enter a valid name."
"Single space between words. Valid special characters: [ _ ( ) . ! - ,]"),
code="invalid_object_name")
def validate_object_name_strict(value):
reg = re.compile(r"^[A-Za-z_.]+[A-Z0-9a-z_.]*$")
if not reg.match(value):
raise ValidationError(_("Parameter name must only contain alphanumeric values, underscores, or periods."
"No whitespaces. Must start with a letter."),
code="invalid_object_name_strict")<file_sep>/analytics/models/results.py
from django.db import models
from django.utils import timezone
from .tools import Tool
from .file_types import FileType
class Result(models.Model):
file_name = models.CharField(max_length=300)
user_id = models.IntegerField()
task_id = models.CharField(max_length=300)
tool = models.ForeignKey(Tool, null=True, on_delete=models.SET_NULL)
file_type = models.ForeignKey(FileType, null=True, on_delete=models.SET_NULL)
pending = 'PENDING'
active = 'ACTIVE'
complete = 'COMPLETE'
error = 'ERROR'
status_choices = (
(pending, 'Pending'),
(active, 'Running'),
(complete, 'Complete'),
(error, 'Error'),
)
status = models.CharField(max_length=10, choices=status_choices)
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def __unicode__(self):
return u"%s" % self.file_name
def __str__(self):
return self.file_name
def save(self, *args, **kwargs):
"""On save update timestamp"""
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(Result, self).save(*args, **kwargs) # call the real save method
<file_sep>/bin/z-transform-method/src/SEinventory.h
/*
* SEinventory.h
*
* Created on: Jan 14, 2017
* Author: Julia
*/
#ifndef SEINVENTORY_H_
#define SEINVENTORY_H_
class SEinventory {
public:
SEinventory();
SEinventory(int, int, int, string &, string &);
virtual ~SEinventory();
void addMeasurements(string &, float * &);
string getRecordId(int) const;
float getRecordMeas(int, int) const;
string getElementType(void) const;
string getElementSide(void) const;
private:
char * IDs;
double ** Measurements;
int numMeasPerRecord;
int numRecords;
int recordCapacity;
int idLength;
string elementType;
string elementSide;
};
#endif /* SEINVENTORY_H_ */
<file_sep>/bin/z-transform-method/Makefile
R_HOME := $(shell R RHOME)
TARGET_EXEC ?= SE_Compare
BUILD_DIR ?= ./build
SRC_DIRS ?= ./src
SRCS := $(shell find $(SRC_DIRS) -name *.cpp -or -name *.c -or -name *.s)
OBJS := $(SRCS:%=$(BUILD_DIR)/%.o)
DEPS := $(OBJS:.o=.d)
INC_DIRS := $(shell find $(SRC_DIRS) -type d)
INC_FLAGS := $(addprefix -I,$(INC_DIRS))
CPPFLAGS ?= $(INC_FLAGS) -MMD -MP
## include headers and libraries for R
RCPPFLAGS := $(shell $(R_HOME)/bin/R CMD config --cppflags)
RLDFLAGS := $(shell $(R_HOME)/bin/R CMD config --ldflags)
## include headers and libraries for Rcpp interface classes
RCPPINCL := $(shell echo 'Rcpp:::CxxFlags()' | $(R_HOME)/bin/R --vanilla --slave)
RCPPLIBS := $(shell echo 'Rcpp:::LdFlags()' | $(R_HOME)/bin/R --vanilla --slave)
## include headers and libraries for RInside embedding classes
RINSIDEINCL := $(shell echo 'RInside:::CxxFlags()' | $(R_HOME)/bin/R $(R_ARCH) --vanilla --slave)
RINSIDELIBS := $(shell echo 'RInside:::LdFlags()' | $(R_HOME)/bin/R $(R_ARCH) --vanilla --slave)
$(BUILD_DIR)/$(TARGET_EXEC): $(OBJS)
$(CXX) $(OBJS) -o $@ $(LDFLAGS) $(RLDFLAGS) $(RCPPLIBS) $(RINSIDELIBS)
# assembly
$(BUILD_DIR)/%.s.o: %.s
$(MKDIR_P) $(dir $@)
$(AS) $(ASFLAGS) -c $< -o $@
# c source
$(BUILD_DIR)/%.c.o: %.c
$(MKDIR_P) $(dir $@)
$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
# c++ source
$(BUILD_DIR)/%.cpp.o: %.cpp
$(MKDIR_P) $(dir $@)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) $(RCPPFLAGS) $(RCPPINCL) $(RINSIDEINCL) -c $< -o $@
.PHONY: clean
clean:
$(RM) -r $(BUILD_DIR)
-include $(DEPS)
MKDIR_P ?= mkdir -p
<file_sep>/bin/z-transform-method/src/ZScoreMethod.h
/*
* ZScoreMethod.h
*
* Created on: Jan 16, 2017
* Author: Julia
*/
#ifndef ZSCOREMETHOD_H_
#define ZSCOREMETHOD_H_
class ZScoreMethod {
public:
ZScoreMethod();
virtual ~ZScoreMethod();
void TwoTpValsToZ(double **, double **, const int, const int);
void OneTpValsToZ(double **, double **, const int, const int);
void TwoTpValsToOneToZ(double **, double **, const int, const int);
void combineZs(double **, double *, double *, double **, const int , const int);
double combineZ(double [], double *, double **, const int);
void combineZs2T(double **, double *, double *, double **, const int , const int);
double combineZ2T(double [], double [], double **, const int);
double combineZ2TOrdered(double [], double [], double **, int [], const int, const int);
double getZVal2T(const double);
double getZVal2TP(const double);
double getZVal1T(const double);
private:
double getDenominator(double *, double **, const int);
double getDenominatorOrdered(double *, double **, int [], const int, const int);
double getNumerator(double **, const int, double *, const int);
double getNumerator(double [], double *, const int);
double getNumeratorOrdered(double [], double *, int [], const int, const int);
};
#endif /* ZSCOREMETHOD_H_ */
|
998bfe6f493ae06cd30bd921a8324666edbbadf9
|
[
"YAML",
"HTML",
"Markdown",
"JavaScript",
"Makefile",
"Dockerfile",
"Python",
"Text",
"C++"
] | 42
|
Python
|
spawaskar-cora/cora-analytics-docker
|
038cddc4c0939b2e4b5a02e61eb6150eba6f4991
|
f2216203f970eae306b3625b209184193c35c6b8
|
refs/heads/master
|
<repo_name>lzzzz4/meeting-manger<file_sep>/src/main/java/cn/dubidubi/dao/DepartmentInfoMapper.java
package cn.dubidubi.dao;
import java.util.List;
import cn.dubidubi.model.DepartmentInfo;
import cn.dubidubi.model.dto.QueryDTO;
public interface DepartmentInfoMapper {
DepartmentInfo selectByPrimaryKey(Integer id);
List<DepartmentInfo> listAllDepartmentInfo();
List<DepartmentInfo> listDepartmentInfoByQuery(QueryDTO dto);
void saveOne(DepartmentInfo departmentInfo);
void updateOne(DepartmentInfo departmentInfo);
void delOne(Integer id);
}<file_sep>/src/main/java/cn/dubidubi/dao/RootLogMapper.java
package cn.dubidubi.dao;
import cn.dubidubi.model.RootLog;
public interface RootLogMapper {
RootLog selectByPrimaryKey(Integer id);
void saveOneLog(RootLog rootLog);
}<file_sep>/src/main/java/cn/dubidubi/controller/IndexController.java
package cn.dubidubi.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.dubidubi.model.base.UserDO;
import cn.dubidubi.model.json.IndexJSON;
import sun.tools.tree.IdentifierExpression;
@Controller
@RequestMapping("/index")
/**
*
* @author linzj
* @ClassName: IndexController
* @Description: 首页index
* @date 2018年4月16日 下午2:49:47
*/
public class IndexController {
static String URL = "http://dubidubi.cn/meetingroom-web/index/open.do?random=";
static String PcUrl = "http://39.108.77.70/dist/index.html#/";
/**
* @param @param request
* @param @return
* @return IndexJSON
* @throws
* @Title: init
* @Description: 初始化首页的状态栏
* @author linzj
* @date 2018年4月16日 下午2:49:57
*/
@RequestMapping("/init")
@ResponseBody
public IndexJSON init(HttpServletRequest request) {
IndexJSON indexJSON = new IndexJSON();
UserDO userDO = (UserDO) request.getSession().getAttribute("user");
// 用户信息的设置
indexJSON.setAccount(userDO.getAccount());
indexJSON.setUserId(userDO.getId());
indexJSON.setUsername(userDO.getUsername());
// 设置审核的url参数
String str = RandomStringUtils.randomAlphabetic(6);
String finalStr = str + "123456";
String base64 = Base64.encodeBase64URLSafeString(finalStr.getBytes());
// 设置url
String url = URL + base64 + "&account=" + userDO.getAccount();
indexJSON.setApiUrl(PcUrl + "loginAPI?account=" + userDO.getAccount() + "&password=" + <PASSWORD>());
return indexJSON;
}
}
<file_sep>/src/main/java/cn/dubidubi/service/impl/SystemRoleServiceImpl.java
package cn.dubidubi.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.dubidubi.dao.base.SystemRoleMapper;
import cn.dubidubi.dao.base.UserRoleMapper;
import cn.dubidubi.model.ShowRole;
import cn.dubidubi.model.base.SystemRole;
import cn.dubidubi.model.dto.AddRoleDTO;
import cn.dubidubi.model.dto.QueryDTO;
import cn.dubidubi.service.SystemRoleService;
@Service
public class SystemRoleServiceImpl implements SystemRoleService {
@Autowired
SystemRoleMapper systemRoleMapper;
@Autowired
UserRoleMapper userRoleMapper;
@Override
public List<SystemRole> listAll() {
return systemRoleMapper.listAll();
}
@Override
public void addUserRole(AddRoleDTO addRoleDTO) {
userRoleMapper.addUserRole(addRoleDTO);
}
@Override
public List<ShowRole> listShowRoleByQuery(QueryDTO dto) {
return systemRoleMapper.listUserAndRole(dto);
}
@Override
public Integer getIdByUserId(Integer id) {
return systemRoleMapper.getIdByUserId(id);
}
@Override
public void delOneById(Integer id) {
systemRoleMapper.delOneById(id);
}
}
<file_sep>/src/main/java/cn/dubidubi/controller/DepartmentController.java
package cn.dubidubi.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.dubidubi.model.DepartmentInfo;
import cn.dubidubi.model.base.UserDO;
import cn.dubidubi.model.base.dto.AjaxResultDTO;
import cn.dubidubi.model.dto.QueryDTO;
import cn.dubidubi.service.DepartmentService;
import cn.dubidubi.service.RootLogService;
@Controller
@RequestMapping("/department")
/**
* @author linzj
* @Description: 部门管理controller
* @ClassName: DepartmentController
* @date 2018年4月17日 下午12:46:26
*/
public class DepartmentController {
@Autowired
DepartmentService departmentService;
@Autowired
RootLogService logService;
/**
* @Title: init
* @Description: 初始化信息
* @param
* @return void
* @author linzj
* @date 2018年4月17日 下午12:47:29
* @throws
*/
@RequestMapping("/init")
@RequiresPermissions("pc:show")
@ResponseBody
public List<DepartmentInfo> init(QueryDTO queryDTO) {
if (StringUtils.isBlank(queryDTO.getSearch())) {
queryDTO.setSearch(null);
}
List<DepartmentInfo> list = departmentService.listDepartmentsByQuery(queryDTO);
return list;
}
/**
* @Title: add
* @Description: 增加数据接口
* @param @param departmentInfo
* @param @return
* @return AjaxResultDTO
* @author linzj
* @date 2018年4月18日 上午10:23:59
* @throws
*/
@RequestMapping("/add")
@RequiresPermissions("pc:show")
@ResponseBody
// 待更新,若存在则拒绝增加
public AjaxResultDTO add(DepartmentInfo departmentInfo, HttpServletRequest request) {
AjaxResultDTO ajaxResultDTO = new AjaxResultDTO();
departmentService.saveOne(departmentInfo);
ajaxResultDTO.setCode(200);
UserDO do1 = (UserDO) request.getSession().getAttribute("user");
logService.saveOneLog(do1.getAccount() + ":新增了部门" + departmentInfo.getDepartmentName());
return ajaxResultDTO;
}
/**
*
* @Title: update
* @Description: 更改部门信息 需要同时更改user,meeting等的信息
* @param @param departmentInfo
* @param @return
* @return AjaxResultDTO
* @author linzj
* @date 2018年4月19日 下午4:50:57
* @throws
*/
@RequestMapping("/update")
@RequiresPermissions("pc:show")
@ResponseBody
public AjaxResultDTO update(DepartmentInfo departmentInfo, HttpServletRequest request) {
AjaxResultDTO ajaxResultDTO = new AjaxResultDTO();
departmentService.updateOne(departmentInfo);
ajaxResultDTO.setCode(200);
UserDO do1 = (UserDO) request.getSession().getAttribute("user");
logService.saveOneLog(do1.getAccount() + ":更新了部门信息");
return ajaxResultDTO;
}
/**
* @Title: update
* @Description: 删除del
* @param @param id
* @param @return
* @return AjaxResultDTO
* @author linzj
* @date 2018年4月18日 上午11:13:29
* @throws
*/
@RequestMapping("/del")
@RequiresPermissions("pc:del")
@ResponseBody
public AjaxResultDTO update(Integer id, HttpServletRequest request) {
AjaxResultDTO ajaxResultDTO = new AjaxResultDTO();
departmentService.delOne(id);
ajaxResultDTO.setCode(200);
UserDO do1 = (UserDO) request.getSession().getAttribute("user");
logService.saveOneLog(do1.getAccount() + ":删除了部门信息");
return ajaxResultDTO;
}
}
<file_sep>/src/main/java/cn/dubidubi/dao/base/SystemRoleMapper.java
package cn.dubidubi.dao.base;
import java.util.List;
import cn.dubidubi.model.ShowRole;
import cn.dubidubi.model.base.SystemRole;
import cn.dubidubi.model.dto.QueryDTO;
public interface SystemRoleMapper {
SystemRole selectByPrimaryKey(Integer id);
List<SystemRole> listAll();
List<ShowRole> listUserAndRole(QueryDTO dto);
Integer getIdByUserId(Integer userId);
void delOneById(Integer id);
}<file_sep>/src/main/java/cn/dubidubi/model/json/IndexJSON.java
package cn.dubidubi.model.json;
import java.io.Serializable;
//初始化首页状态栏
public class IndexJSON implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private Integer userId;
private String account;
private String apiUrl;
public String getApiUrl() {
return apiUrl;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
}
<file_sep>/src/main/java/cn/dubidubi/service/impl/RootLogServiceImpl.java
package cn.dubidubi.service.impl;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import cn.dubidubi.dao.RootLogMapper;
import cn.dubidubi.model.RootLog;
import cn.dubidubi.service.RootLogService;
@Service
public class RootLogServiceImpl implements RootLogService {
@Autowired
RootLogMapper rootLogMapper;
@Override
@Async
public void saveOneLog(String log) {
RootLog rootLog = new RootLog();
rootLog.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
rootLog.setLog(log);
rootLogMapper.saveOneLog(rootLog);
}
}
<file_sep>/src/main/java/cn/dubidubi/model/json/MeetingRoomJSON.java
package cn.dubidubi.model.json;
import java.io.Serializable;
import java.util.List;
import cn.dubidubi.model.DepartmentInfo;
import cn.dubidubi.model.MeetingRoomDO;
public class MeetingRoomJSON implements Serializable {
private static final long serialVersionUID = 1L;
private List<MeetingRoomDO> list;
private Integer total;
private Integer currentPage;
private Integer totalPage;
private Integer currentDepartmentId;
private List<DepartmentInfo> departmentInfos;
public List<DepartmentInfo> getDepartmentInfos() {
return departmentInfos;
}
public void setDepartmentInfos(List<DepartmentInfo> departmentInfos) {
this.departmentInfos = departmentInfos;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public List<MeetingRoomDO> getList() {
return list;
}
public void setList(List<MeetingRoomDO> list) {
this.list = list;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Integer getCurrentDepartmentId() {
return currentDepartmentId;
}
public void setCurrentDepartmentId(Integer currentDepartmentId) {
this.currentDepartmentId = currentDepartmentId;
};
}
<file_sep>/src/main/webapp/static/business/depart.js
//初始化
$(function() {
mysearch();
})
//初始化复用函数
function init(search) {
if (typeof (search) == "undefined" || search.trim() == "") {
search = "";
}
$.post(url + "/department/init.do", {
"search" : search
}, function(data) {
if (data.code == 1000) {
window.location.href = url + data.url;
}
//清除动画
$("html").removeClass("loading")
$("#loading").hide()
//初始化表格内容
$("#tUser").empty();
$.each(data, function(index, value) {
$("#tUser").append("<tr>" +
"<td>" + value.id + "</td><td>" + value.departmentName + "</td>"
+ "<td>" + value.departmentSuperior + "</td>"
+ "<td><div class='am-btn-toolbar'><div class='am-btn-group am-btn-group-xs'><button type='button'"
+ "class='am-btn am-btn-default am-btn-xs am-text-secondary btnEdit' data-toggle='modal' data-target='#updateUser' onclick='update("
+ value.id + ",\"" + value.departmentName + "\",\"" + value.departmentSuperior
+ "\")'>"
+ "<span class='am-icon-pencil-square-o'></span> 编辑"
+ "</button>"
+ "<button type='button'"
+ "class='am-btn am-btn-default am-btn-xs am-text-danger am-hide-sm-only'"
+ "onclick='delUser(" + value.id + ")'>"
+ "<span class='am-icon-trash-o'></span> 删除"
+ "</button></div></div></td></tr>")
})
}, "json")
}
//搜索
function mysearch() {
var search = $("#departName").val()
init(search)
}
//点击搜索按钮事件
$("#btnsearch").click(function() {
mysearch()
})
//回车事件
$(document).keyup(function(event) {
if (event.keyCode == 13) {
mysearch(1)
}
});
//更新初始化模态框
function update(id, name, supername) {
$("#update_name").val(name);
$("#update_password").val(<PASSWORD>);
$("#update_id").val(id);
}
//新增add事件
$("#addSubmit").click(function() {
$("#addSubmit").attr("disabled", true);
var departmentSuperior = $("#add_super").val();
var departmentName = $("#add_name").val();
if (departmentName.trim() == "" || departmentSuperior.trim() == "") {
alert("输入错误")
$("#addSubmit").removeAttr("disabled");
return;
}
$.post(url + "/department/add.do", {
"departmentSuperior" : departmentSuperior,
"departmentName" : departmentName
}, function(data) {
if (data.code == 200) {
$('#addUser').modal('hide')
window.location.href = url + '/depart.html'
}
$("#addSubmit").removeAttr("disabled");
}, "json")
})
//更新事件
$("#updateUserSubmit").click(function() {
$("#updateUserSubmit").attr("disabled", true);
var departmentName = $("#update_name").val();
var departmentSuperior = $("#update_password").val();
var id = $("#update_id").val();
$.post(url + "/department/update.do", {
"departmentName" : departmentName,
"departmentSuperior" : departmentSuperior,
"id" : id
}, function(data) {
if (data.code == 200) {
window.location.href = url + '/depart.html'
}
$("#updateUserSubmit").removeAttr("disabled");
}, "json")
})
//删除事件
function delUser(id) {
var flag = confirm("确认删除?")
if (flag) {
$.post(url + "/department/del.do", {
"id" : id
}, function(data) {
if (data.code == 200) {
window.location.href = url + '/depart.html'
}else{
alert("您没有权限!")
}
}, "json")
}
}<file_sep>/src/main/java/cn/dubidubi/controller/ShowRoleController.java
package cn.dubidubi.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.dubidubi.model.ShowRole;
import cn.dubidubi.model.base.UserDO;
import cn.dubidubi.model.base.dto.AjaxResultDTO;
import cn.dubidubi.model.dto.QueryDTO;
import cn.dubidubi.service.RootLogService;
import cn.dubidubi.service.SystemRoleService;
/**
* @author linzj
* @Description: 查看权限分配情况
* @ClassName: ShowRoleController
* @date 2018年4月21日 下午9:08:47
*/
@Controller
@RequestMapping("/showRole")
public class ShowRoleController {
@Autowired
SystemRoleService systemRoleService;
@Autowired
RootLogService rootLogService;
/**
*
* @Title: show
* @Description: 查看权限信息,无需授权
* @param @param dto
* @param @return
* @return List<ShowRole>
* @author linzj
* @date 2018年4月21日 下午9:58:52
* @throws
*/
@RequestMapping("/show")
@ResponseBody
public List<ShowRole> show(QueryDTO dto, HttpServletRequest request) {
if (StringUtils.isBlank(dto.getSearch()) || dto.getSearch().equals("nosearch")) {
dto.setSearch(null);
}
UserDO do1 = (UserDO) request.getSession().getAttribute("user");
rootLogService.saveOneLog(do1.getAccount() + "查看了授权信息");
return systemRoleService.listShowRoleByQuery(dto);
}
/**
*
* @Title: del
* @Description: 根据id删除
* @param @param id
* @param @return
* @return AjaxResultDTO
* @author linzj
* @date 2018年4月21日 下午9:58:45
* @throws
*/
@RequestMapping("/del")
@ResponseBody
@RequiresPermissions("pc:role")
public AjaxResultDTO del(Integer id, HttpServletRequest request) {
systemRoleService.delOneById(id);
AjaxResultDTO ajaxResultDTO = new AjaxResultDTO();
ajaxResultDTO.setCode(200);
UserDO do1 = (UserDO) request.getSession().getAttribute("user");
rootLogService.saveOneLog(do1.getAccount() + "删除了授权信息");
return ajaxResultDTO;
}
}
<file_sep>/src/main/java/cn/dubidubi/model/DependUserInfo.java
package cn.dubidubi.model;
import java.io.Serializable;
/**
*
* @author linzj
* @Description: 依赖用户信息
* @ClassName: DependUserInfo
* @date 2018年4月16日 下午2:59:00
*/
public class DependUserInfo implements Serializable {
private Integer id;
private String account;
private String password;
private String name;
private String department;
private Integer departmentId;
private String mail;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account == null ? null : account.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department == null ? null : department.trim();
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}<file_sep>/src/main/webapp/static/business/index.js
$(function () {
$.post(url + "/index/init.do", {}, function (data) {
$("#username").text(data.username);
$("#userId").text(data.userId);
$("#logout").attr("href", url + "/logout.do")
$("#wait").attr("href", data.apiUrl)
}, "json");
$("#changePass").click(function () {
alert("待完成!")
})
})<file_sep>/src/main/java/cn/dubidubi/service/impl/MeetingRoomServiceImpl.java
package cn.dubidubi.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.dubidubi.dao.MeetingRoomDOMapper;
import cn.dubidubi.model.DepartmentInfo;
import cn.dubidubi.model.MeetingRoomDO;
import cn.dubidubi.model.dto.MeetingRoomDTO;
import cn.dubidubi.model.dto.QueryDTO;
import cn.dubidubi.service.MeetingRoomService;
@Service
public class MeetingRoomServiceImpl implements MeetingRoomService {
@Autowired
MeetingRoomDOMapper meetingRoomDOMapper;
@Override
public PageInfo<MeetingRoomDO> listAllMeetRoomByQuery(QueryDTO dto) {
PageHelper.startPage(dto.getPageNum(), 12);
List<MeetingRoomDO> list = meetingRoomDOMapper.listAllMeetingRoomByQuery(dto);
PageInfo<MeetingRoomDO> info = new PageInfo<>(list);
return info;
}
@Override
public void saveOne(MeetingRoomDTO meetingRoomDTO) {
meetingRoomDOMapper.saveOne(meetingRoomDTO);
}
@Override
public boolean isExistRoom(String roomName) {
Integer id = meetingRoomDOMapper.getIdByName(roomName);
// 为空则不存在
if (id == null) {
return false;
} else {
return true;
}
}
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ, readOnly = false, propagation = Propagation.REQUIRED)
public boolean updateOne(MeetingRoomDTO meetingRoomDTO) {
meetingRoomDOMapper.updateOne(meetingRoomDTO);
Integer count = getCount(meetingRoomDTO.getRoom());
if (count != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return false;
}
return true;
}
@Override
public void delOne(Integer id) {
meetingRoomDOMapper.delOneById(id);
}
@Override
public Integer getCount(String room) {
return meetingRoomDOMapper.countByRoom(room);
}
@Override
public void updateDepartmentByDepartmentId(DepartmentInfo departmentInfo) {
meetingRoomDOMapper.updateDepartmentByDepartmentId(departmentInfo);
}
}
<file_sep>/src/main/resources/db.properties
jdbc.url=jdbc:mysql://172.16.58.3:3306/meetingroom?useUnicode=true&characterEncoding=UTF-8
jdbc.user=root
jdbc.password=<PASSWORD>!!<file_sep>/src/main/java/cn/dubidubi/model/json/SystemRoleJson.java
package cn.dubidubi.model.json;
import java.io.Serializable;
import java.util.List;
import cn.dubidubi.model.base.SystemRole;
/**
* @author linzj
* @Description: 角色授权json对象
* @ClassName: SystemRoleJson
* @date 2018年4月21日 下午7:18:34
*/
public class SystemRoleJson implements Serializable {
private static final long serialVersionUID = 1L;
private List<SystemRole> list;
private Integer code;
public List<SystemRole> getList() {
return list;
}
public void setList(List<SystemRole> list) {
this.list = list;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
<file_sep>/src/main/webapp/static/business/role.js
$(function() {
init();
})
function init() {
$.post(url + "/shiro/show.do", {}, function(data) {
if (data.code == 200) {
$("#tUser").empty();
$.each(data.list, function(index, value) {
$("#tUser").append("<tr>" +
"<td>" + value.id + "</td><td>" + value.name + "</td>"
+ "<td><a href='#'>" + value.info + "</a></td>"
+ "<td><button type='button'"
+ "class='am-btn am-btn-default am-btn-xs am-text-secondary btnEdit' data-toggle='modal' data-target='#addUser' onclick='addinit("
+ value.id
+ ")'>"
+ "<span class='am-icon-pencil-square-o'></span> 授权"
+ "</button></td>"
+ "</tr>")
})
} else {
window.location.href = url + data.url
}
}, "json");
}
$("#add_account").blur(function() {
findUser();
})
function addinit(roleId) {
$("#add_role_id").val(roleId)
}
function findUser() {
var account = $("#add_account").val();
$.post(url + "/shiro/find.do", {
"account" : account
}, function(data) {
$("#add_name").val(data.username)
$("#add_id").val(data.id)
}, "json");
}
$("#addSubmit").click(function() {
$("#addSubmit").attr("disabled", "true");
var userId = $("#add_id").val()
var roleId = $("#add_role_id").val()
$.post(url + "/shiro/add.do", {
"userId" : userId,
"roleId" : roleId
}, function(data) {
if (data.code == 200) {
$("#addSubmit").removeAttr("disabled");
window.location.href = url + "/showRole.html";
} else if (data.code == 300) {
alert("当前用户已经拥有其它或当前权限!请确认!")
$("#addSubmit").removeAttr("disabled");
} else {
window.location.href = url + data.url
}
}, "json");
})<file_sep>/src/main/webapp/static/business/room.js
//初始化被包装在search函数中
//新增会议室信息
$("#addSubmit").click(function () {
//获取所有的被选中的checkedbox的值
var days = new Array()
$("#addSubmit").attr("disabled", true);
$("input:checkbox[name=day]:checked").each(function (i) {
days[i] = $(this).val()
})
//判断是否开启自动审核,并赋予值
var ischeck = "Y"
if ($("#autoReview").is(":checked")) {
} else {
ischeck = "N"
}
var add_room = $("#add_room").val()
var add_max = $("#add_max").val();
var add_start_time = $("#add_start_time").val()
var add_close_time = $("#add_close_time").val()
if (add_start_time >= add_close_time) {
alert("开放时间应在关闭时间前!")
$("#addSubmit").removeAttr("disabled");
return;
}
var add_department = $("#add_department").val()
var add_department_name = $("#add_department").find("option:selected").text();
if (days.length == 0) {
alert("会议室开放时间不能为空")
$("#addSubmit").removeAttr("disabled");
return;
}
if (add_room.trim() == "" || add_max.trim() == "" || add_start_time.trim() == "" || add_close_time.trim() == "") {
alert("输入错误!");
$("#addSubmit").removeAttr("disabled");
return;
}
$.post(url + "/room/add.do", {
"room": add_room,
"max": add_max,
"start_time": add_start_time,
"close_time": add_close_time,
"department": add_department,
"department_name": add_department_name,
"days": days,
"autoReview": ischeck
}, function (data) {
if (data.code == 1000) {
alert("您无权限!")
} else if (data.code == 300) {
alert("新增会议室已存在!")
$("#addSubmit").removeAttr("disabled");
} else {
$('#addUser').modal('hide')
$("#addSubmit").removeAttr("disabled");
window.location.href = url + '/room.html'
}
}, "json");
})
//更新会议室信息的模态框信息初始化
function update(id, name, max, openDate, endDate, openTime, closeTime, departmentName, departmentId, autoReview) {
var array = new Array();
array = openDate.split(",")
for (var i = 0; i < array.length; i++) {
$("#updateCheckbox" + array[i]).attr("checked", "true");
}
$("#update_room").val(name)
$("#update_max").val(max)
$("#update_open_time").val(openTime)
$("#update_close_time").val(closeTime)
$("#update_department").val(departmentId)
$("#update_end_date").val(endDate)
$("#update_id").val(id)
if (autoReview == "Y")
$("#update_auto").prop("checked", "checked")
else
$("#update_auto").removeProp("checked")
}
//更新update信息
$("#updateUserSubmit").click(function () {
var days = new Array()
$("input:checkbox[name=day]:checked").each(function (i) {
days[i] = $(this).val()
})
if (days.length == 0) {
alert("请选择时间!")
return;
}
var room = $("#update_room").val()
var max = $("#update_max").val()
var openTime = $("#update_open_time").val()
var closeTime = $("#update_close_time").val()
var departmentId = $("#update_department").val()
var id = $("#update_id").val()
var endDate = $("#update_end_date").val()
var update_department_name = $("#update_department").find("option:selected").text();
var auto = ""
if ($("#update_auto").is(":checked")) {
auto = "Y"
} else {
auto = "N"
}
if (openTime >= closeTime) {
alert("开始时间不能大于结束时间")
return;
}
$("#updateUserSubmit").attr("disabled", "true")
$.post(url + "/room/update.do", {
"id": id,
"room": room,
"max": max,
"start_time": openTime,
"close_time": closeTime,
"department": departmentId,
"department_name": update_department_name,
"days": days,
"autoReview": auto
}, function (data) {
$("#updateUserSubmit").removeAttr("disabled")
if (data.code == 200) {
window.location.href = url + '/room.html'
} else {
alert("会议室已经存在!")
$("#updateUserSubmit").removeAttr("disabled", "true")
}
}, "json")
})
//删除meeting
function delUser(id) {
var flag = confirm("确认删除?")
if (flag) {
$.post(url + "/room/del.do", {
"id": id
}, function (data) {
if (data.code == 200) {
window.location.href = url + '/room.html'
} else {
alert("您没有权限")
}
}, "json")
}
}
//页面初始化,并对权限进行校验
$(function () {
init(1)
})
//跳页
$("#go").click(function () {
$("#go").attr("disabled", "true");
page = $("#jump").val();
if (page == "") {
alert("请输入页数")
}
if (page > $("#finalPage").html()) {
//删除锁定
$("#go").removeAttr("disabled");
alert("超出总页数!")
return;
}
mysearch(page)
})
//select change函数
$("#selDepart").change(function () {
mysearch(1)
})
//搜索点击事件
$("#btnsearch").click(function () {
mysearch(1)
})
//回车事件
$(document).keyup(function (event) {
if (event.keyCode == 13) {
mysearch(1)
}
});
//页面初始化的复用函数
function init(page, changeId, search) {
if (typeof (changeId) == "undefined") {
changeId = 0;
}
if (typeof (search) == "undefined" || search.trim() == "") {
search = "nosearch";
}
$("html").addClass("loading")
$("#loading").show();
$.post(url + "/room/init.do", {
"pageNum": page,
"changeId": changeId,
"search": search
}, function (data) {
if (data.code == 1000) {
window.location.href = url + data.url;
} else {
//清除loading动画
$("html").removeClass("loading")
$("#loading").hide()
//删除锁定
$("#go").removeAttr("disabled");
//初始化部门信息,并清除原本的信息
$("#selDepart").empty();
$("#update_department").empty();
$("#add_department").empty();
//增加空
$("#selDepart").append("<option value='0'>全部</option>")
$.each(data.departmentInfos, function (index, value) {
$("#selDepart").append("<option value='" + value.id + "'>" + value.departmentName + "</option>")
//初始化模态框中的select中的部门信息
$("#update_department").append("<option value='" + value.id + "'>" + value.departmentName + "</option>")
$("#add_department").append("<option value='" + value.id + "'>" + value.departmentName + "</option>")
})
//设置select默认选择值
if (data.currentDepartmentId == null) {
data.currentDepartmentId = 0;
}
$("#selDepart").val(data.currentDepartmentId);
//初始化表格内容
$("#tUser").empty();
$.each(data.list, function (index, value) {
$("#tUser").append("<tr>" +
"<td>" + value.id + "</td><td>" + value.room + "</td>"
+ "<td>" + value.maxPeople + "</td>"
+ "<td>" + value.openDate + "</td>"
+ "<td>" + value.endDate + "</td>"
+ "<td>" + value.openTime + "</td>"
+ "<td>" + value.endTime + "</td>"
+ "<td>" + value.department + "</td>"
+ "<td>" + value.autoReview + "</td>"
+ "<td><div class='am-btn-toolbar'><div class='am-btn-group am-btn-group-xs'><button type='button'"
+ "class='am-btn am-btn-default am-btn-xs am-text-secondary btnEdit' data-toggle='modal' data-target='#updateUser' onclick='update("
+ value.id + ",\"" + value.room + "\",\"" + value.maxPeople + "\",\"" + value.openDate + "\",\"" + value.endDate + "\",\""
+ value.openTime + "\",\"" + value.endTime + "\",\""
+ value.department + "\",\"" + value.departmentId
+ "\",\""
+ value.autoReview
+ "\")'>"
+ "<span class='am-icon-pencil-square-o'></span> 编辑"
+ "</button>"
+ "<button type='button'"
+ "class='am-btn am-btn-default am-btn-xs am-text-danger am-hide-sm-only'"
+ "onclick='delUser(" + value.id + ")'>"
+ "<span class='am-icon-trash-o'></span> 删除"
+ "</button></div></div></td></tr>")
})
//初始化总条数
$("#totalCount").text(data.total + " 条记录 一页显示12条")
//初始化总页数
//最后一页
$("#finalPage").html(data.totalPage)
$("#finalPage").attr("onclick", "mysearch(" + data.totalPage + ")")
$("#current").html(data.currentPage)
//前进后退
$("#finalPage_li").removeClass("am-active");
if (data.currentPage > 1) {
var int = data.currentPage - 1
$("#pre").attr("onclick", "mysearch(" + int + ")")
}
else
$("#pre").attr("onclick", "mysearch(1)")
if (data.currentPage < data.totalPage) {
var int = data.currentPage + 1
$("#next").attr("onclick", "mysearch(" + int + ")")
$("#current").show();
$("#mid").show();
} else {
$("#next").attr("onclick", "mysearch(" + data.currentPage + ")")
$("#current").hide();
$("#finalPage_li").addClass("am-active");
$("#mid").hide();
}
}
}, "json");
}
//请求搜索的复用函数
function mysearch(page) {
var changeId = $("#selDepart").val();
var search2 = $("#search").val();
init(page, changeId, search2)
}<file_sep>/src/main/java/cn/dubidubi/controller/UserMangerController.java
package cn.dubidubi.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageInfo;
import cn.dubidubi.model.DepartmentInfo;
import cn.dubidubi.model.DependUserInfo;
import cn.dubidubi.model.base.UserDO;
import cn.dubidubi.model.base.dto.AjaxResultDTO;
import cn.dubidubi.model.dto.ClientUserDTO;
import cn.dubidubi.model.dto.QueryDTO;
import cn.dubidubi.model.json.UserInfoInitJSON;
import cn.dubidubi.service.ClientUserService;
import cn.dubidubi.service.DepartmentService;
import cn.dubidubi.service.RootLogService;
/**
* @author linzj
* @ClassName: IndexController
* @Description: 用户管理加载
* @date 2018年4月12日 下午5:44:13
*/
@Controller
@RequestMapping("/user")
public class UserMangerController {
@Autowired
ClientUserService clientUserService;
@Autowired
DepartmentService departmentService;
@Autowired
RootLogService log;
/**
* @Title: init
* @Description: 初始化获得页面所有的信息
* @param
* @return void
* @author linzj
* @date 2018年4月16日 下午1:56:06
* @throws
*/
@RequestMapping("/init")
@RequiresPermissions("pc:show")
@ResponseBody
public UserInfoInitJSON init(QueryDTO queryDTO) {
Integer pageNum = queryDTO.getPageNum();
// 判断页数
if (pageNum == null || pageNum == 0) {
pageNum = 1;
}
// 判断是否有查询与changeId
if (queryDTO.getChangeId() == null || queryDTO.getChangeId() == 0) {
queryDTO.setChangeId(null);
}
if (StringUtils.isBlank(queryDTO.getSearch()) || queryDTO.getSearch().equals("nosearch")) {
queryDTO.setSearch(null);
}
// 依据queryDTO查询表格信息
// 初始化表格信息
final UserInfoInitJSON infoInitJSON = new UserInfoInitJSON();
PageInfo<DependUserInfo> listAllDependUserInfoByPage = clientUserService
.listAllDependUserInfoByQueryDTO(queryDTO);
// 得到数据总个数
Long total = listAllDependUserInfoByPage.getTotal();
infoInitJSON.setTotal(total.intValue());
infoInitJSON.setDependUserInfos(listAllDependUserInfoByPage.getList());
// 初始化部门信息
infoInitJSON.setDepartmentInfos(departmentService.listAllDepartments());
// 初始化页数相关信息
infoInitJSON.setCurrentPage(pageNum);
infoInitJSON.setTotalPage(listAllDependUserInfoByPage.getPages());
// 设置默认的select
infoInitJSON.setCurrentDepartmentId(queryDTO.getChangeId());
return infoInitJSON;
}
/**
* @Title: showBrief
* @Description: 增加用户信息
* @param
* @return void
* @author linzj
* @date 2018年4月15日 下午3:31:38
* @throws
*/
@RequestMapping("/userAdd")
@RequiresPermissions("pc:show")
@ResponseBody
public AjaxResultDTO userAdd(ClientUserDTO clientUserDTO, HttpServletRequest request) {
AjaxResultDTO ajaxResultDTO = new AjaxResultDTO();
// 查询当前account是否存在,若存在则拒绝插入
Integer id = clientUserService.getIdByAccount(clientUserDTO.getAccount());
if (id != null) {
ajaxResultDTO.setCode(500);
return ajaxResultDTO;
}
DepartmentInfo department = departmentService.getOneDepartmentById(clientUserDTO.getDepartmentId());
clientUserDTO.setDepartment(department.getDepartmentName());
clientUserService.saveOneClientUser(clientUserDTO);
ajaxResultDTO.setCode(200);
UserDO do1 = (UserDO) request.getSession().getAttribute("user");
log.saveOneLog(do1.getAccount() + ":新增了用户depend信息" + clientUserDTO.getAccount());
return ajaxResultDTO;
}
/**
* @Title: update
* @Description: 更新用户信息,同时更新user
* @param @param clientUserDTO
* @param @return
* @return AjaxResultDTO
* @author linzj
* @date 2018年4月16日 下午8:34:21
* @throws
*/
@RequestMapping("/userUpdate")
@RequiresPermissions("pc:show")
@ResponseBody
public AjaxResultDTO update(ClientUserDTO clientUserDTO, HttpServletRequest request) {
AjaxResultDTO ajaxResultDTO = new AjaxResultDTO();
// 判断当前account是否存在
DepartmentInfo department = departmentService.getOneDepartmentById(clientUserDTO.getDepartmentId());
clientUserDTO.setDepartment(department.getDepartmentName());
boolean flag = clientUserService.updateOne(clientUserDTO);
if (flag)
ajaxResultDTO.setCode(200);
else {
ajaxResultDTO.setCode(500);
return ajaxResultDTO;
}
UserDO do1 = (UserDO) request.getSession().getAttribute("user");
log.saveOneLog(do1.getAccount() + ":更新了用户depend信息" + clientUserDTO.getAccount());
return ajaxResultDTO;
}
/**
* @Title: del
* @Description: 删除用户信息,同时删除user中
* @param @param id
* @param @return
* @return AjaxResultDTO
* @author linzj
* @date 2018年4月16日 下午8:33:02
* @throws
*/
@RequestMapping("/del")
@RequiresPermissions("pc:del")
@ResponseBody
public AjaxResultDTO del(Integer id, HttpServletRequest request) {
AjaxResultDTO ajaxResultDTO = new AjaxResultDTO();
clientUserService.delOneById(id);
ajaxResultDTO.setCode(200);
UserDO do1 = (UserDO) request.getSession().getAttribute("user");
log.saveOneLog(do1.getAccount() + ":删除了用户depend信息");
return ajaxResultDTO;
}
}
<file_sep>/src/main/java/cn/dubidubi/model/dto/ClientUserDTO.java
package cn.dubidubi.model.dto;
import java.io.Serializable;
/**
* @author linzj
* @ClassName: ClientUserDTO
* @Description: 上传的用户信息类
* @date 2018年4月15日 下午8:36:16
*/
public class ClientUserDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String account;
private String password;
private String name;
private String department;
private Integer departmentId;
private String mail;
private String oldAccount;
@Override
public String toString() {
return "ClientUserDTO [account=" + account + ", password=" + password + ", name=" + name + ", department="
+ department + ", departmentId=" + departmentId + "]";
}
public String getOldAccount() {
return oldAccount;
}
public void setOldAccount(String oldAccount) {
this.oldAccount = oldAccount;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
|
4f2eef2c0b873cef9da67d096b05ebc9695cf86b
|
[
"JavaScript",
"Java",
"INI"
] | 20
|
Java
|
lzzzz4/meeting-manger
|
bb9bbb1411874ca762da7994c73a81db77f07b5c
|
b641f66497ea7d65cb253668e0fb85dfa0b844f5
|
refs/heads/master
|
<file_sep># FD plugin
FD plugin provides metrics about file descriptors usage and limits per process for the docker and supervistor systems.
All metrics are extracted by reading `/proc/PID/limits` and `/proc/PID/fd` files.
Plugin works only on Linux systems.
## Measurements
- `proc_open_files_total` - number of open file descriptors by process
- `proc_open_files_limit` - limit of open file descriptors for process
## Dependencies
No dependencies. If docker system is not installed, no metrics will be collected. The same for the supervisor.
## Configuration
```
[[inputs.exec]]
commands = ["/path/to/plugin/fd.sh"]
timeout = "5s"
data_format = "influx"
```
## Output example
```
fd,process=nginx proc_open_files_total=2012
fd,process=nginx proc_open_files_limit=65536
fd,process=php-fpm proc_open_files_total=65
fd,process=php-fpm proc_open_files_limit=65536
```
<file_sep>#!/bin/bash
# outputs counts of UDP sockets
ss -u -a -n | awk 'END{print "netstat udp_socket=" NR-1}'
# outputs counts of TCP connections states
ss -t -a -n | awk 'BEGIN {
# initialization array of counts by states
arr["ESTAB"] = 0
arr["SYN-SENT"] = 0
arr["SYN-RECV"] = 0
arr["FIN-WAIT-1"] = 0
arr["FIN-WAIT-2"] = 0
arr["TIME-WAIT"] = 0
arr["UNCONN"] = 0
arr["CLOSE-WAIT"] = 0
arr["LAST-ACK"] = 0
arr["LISTEN"] = 0
arr["CLOSING"] = 0
arr["UNKNOWN"] = 0
}
NR > 1 {
# increase counts of states
arr[$1]+=1
}
END {
# output counts of states
print "netstat tcp_established="arr["ESTAB"]
print "netstat tcp_syn_sent="arr["SYN-SENT"]
print "netstat tcp_syn_recv="arr["SYN-RECV"]
print "netstat tcp_fin_wait1="arr["FIN-WAIT-1"]
print "netstat tcp_fin_wait2="arr["FIN-WAIT-2"]
print "netstat tcp_time_wait="arr["TIME-WAIT"]
print "netstat tcp_close="arr["UNCONN"]
print "netstat tcp_close_wait="arr["CLOSE-WAIT"]
print "netstat tcp_last_ack="arr["LAST-ACK"]
print "netstat tcp_listen="arr["LISTEN"]
print "netstat tcp_closing="arr["CLOSING"]
print "netstat tcp_none="arr["UNKNOWN"]
}'<file_sep># IOSTAT plugin
IOSTAT plugin provides metrics about I/O utilization.
All metrics are extracted from `iostat` command.
Plugin works only on Linux systems.
## Measurements
- `avgrq_size_total` - average queue size
- `await_milliseconds` - average request time in milliseconds
- `util_percents` - I/O utilization in percents (0..100)
## Dependencies
`iostat` MUST be installed to use this plugin.
## Configuration
```
[[inputs.exec]]
commands = ["/path/to/plugin/iostat.sh"]
timeout = "5s"
data_format = "influx"
```
## Output example
```
iostat,device=vda avgrq_size_total=374.29
iostat,device=vda await_milliseconds=22.59
iostat,device=vda util_percents=1.20
```
<file_sep>#!/bin/bash
# the receiving data in the format: avgrq-sz:await:%util:Device
iostat -dxyk 5 1 | grep . | tail -n +3 | awk '{print $1 " " $8 " " $10 " " $14}' | tr "," "." | while read device avgrq_size await util
do
# the creating and returning response
echo "iostat,device=$device avgrq_size_total=$avgrq_size"
echo "iostat,device=$device await_milliseconds=$await"
echo "iostat,device=$device util_percents=$util"
done
<file_sep># Plugins for Telegraf
Here you can find some useful third-party plugins for Telegraf:
- [IOSTAT](https://github.com/monitoring-tools/telegraf-plugins/tree/master/iostat) - I/O utilization and other information from iostat
- [NETSTAT](https://github.com/monitoring-tools/telegraf-plugins/tree/master/netstat) - TCP connections statuses and UDP sockets count
- [TOP](https://github.com/monitoring-tools/telegraf-plugins/tree/master/top) - resource usage by top processes
- [FD](https://github.com/monitoring-tools/telegraf-plugins/tree/master/fd) - file descriptors usage by processes
- [NETSPEED](https://github.com/monitoring-tools/telegraf-plugins/tree/master/netspeed) - speed of network interfaces
All plugins are tested and production-ready.
## Installation
1. Copy plugin to server where Telegraf is running
2. Add plugin to Telegraf config as [exec plugin](https://github.com/influxdata/telegraf/tree/master/plugins/inputs/exec)
3. Restart Telegraf
Please, note that plugins works only on Linux systems.
## About Telegraf
Telegraf is an agent written in Go for collecting, processing, aggregating, and writing metrics.
Telegraf official repository: https://github.com/influxdata/telegraf
<file_sep>#!/usr/bin/env bash
# outputs metric data
function output_metric {
while read total limit process; do
echo "fd,process=$process proc_open_files_total=$total"
echo "fd,process=$process proc_open_files_limit=$limit"
done
}
# loads the limit of process by PID
function load_limit {
echo $(cat /proc/$1/limits 2> /dev/null | awk '($2=="open") && ($3=="files") {print $4}')
}
# loads count of created descriptors by PID
function load_total {
echo $(sudo /bin/ls /proc/$1/fd/ 2> /dev/null | wc -l)
}
# loads limit and total of process and returns them with process name
function load_metric {
process_name=$(basename $(awk '-F\0' '{print $1}' < "/proc/$pid/cmdline"))
# if the process name is shell, skip it
if [[ $process_name = "sh" ]]; then
return 0
fi
limit=$(load_limit $pid)
# if it is not number, skip it
re='^[0-9]+$'
if ! [[ $limit =~ $re ]] ; then
return 0
fi
total=$(load_total $pid)
echo "$total $limit $process_name"
}
# loads and returns list of pid from supervisor
function load_pids_from_supervisorctl {
sudo /usr/bin/supervisorctl status | awk '{print $4}' | sed 's/,//g' | while read pid; do
re='^[0-9]+$'
if ! [[ $pid =~ $re ]] ; then
continue
fi
echo $pid
done
}
# loads and returns list of pid from docker
function load_pids_from_docker {
sudo /usr/bin/docker ps -q --no-trunc 2> /dev/null | while read container_id; do
pids=$(cat "/sys/fs/cgroup/pids/docker/$container_id/cgroup.procs" 2> /dev/null)
for pid in $pids
do
echo "$container_id,$pid"
done
done
}
# initialize vars for docker and supervisor pids
pids_from_supervisorct=""
pids_from_docker=""
# if there is a docker system, then outputs metrics for processes from supervisor
if [[ -x "/usr/bin/supervisorctl" ]]
then
# load pids from supervisor
pids_from_supervisorctl=$(load_pids_from_supervisorctl)
# loads and outputs file descriptors metrics for processes, which were launched by supervisor
echo "$pids_from_supervisorctl" | while read pid; do
re='^[0-9]+$'
if ! [[ $pid =~ $re ]] ; then
continue
fi
metric=$(load_metric $pid)
if [ -z "$metric" ]
then
continue
fi
echo "$metric"
done | output_metric
fi
# if there is a supervisor system, then outputs metrics for processes from docker
if [[ -x "/usr/bin/docker" ]]
then
# load pids from docker
pids_from_docker=$(load_pids_from_docker)
# loads and outputs file descriptors metrics for processes, which are located in the docker containers
echo "$pids_from_docker" | while read proc_data; do
IFS=', ' read -r -a proc_data_arr <<< "$proc_data"
container_id="${proc_data_arr[0]}"
pid="${proc_data_arr[1]}"
service_name=$(sudo /usr/bin/docker inspect $container_id 2> /dev/null | awk '-F=|"' '$2 == "APP" {print $3}')
if [[ -z "$service_name" ]]; then
continue
fi
metric=$(load_metric $pid)
if [ -z "$metric" ]
then
continue
fi
echo "$metric"
done | sort -k1nr | output_metric
fi
<file_sep># TOP plugin
TOP plugin provides metrics about top 5 processes by CPU and memory usage.
All metrics are extracted from `top` and `ps` command.
Plugin works only on Linux systems.
## Measurements
- `cpu_usage_percent` - CPU usage in percents by cores. Value: `0 .. 100 * cores_num`
- `memory_usage_percent` - CPU usage in percents. Value: `0..100`
## Dependencies
No dependencies - plugin uses `top` and `ps` as data source.
## Configuration
```
[[inputs.exec]]
commands = ["/path/to/plugin/top.sh"]
timeout = "5s"
data_format = "influx"
```
## Output example
```
proc,process=top cpu_usage_percent=1.2
proc,process=zabbix_agentd cpu_usage_percent=1.3
proc,process=writeback cpu_usage_percent=2
proc,process=mcollectived cpu_usage_percent=14.3
proc,process=prometheus cpu_usage_percent=57.2
proc,process=unbound memory_usage_percent=0.1
proc,process=docker memory_usage_percent=0.2
proc,process=mcollectived memory_usage_percent=0.4
proc,process=systemd-journal memory_usage_percent=0.4
proc,process=prometheus memory_usage_percent=7.6
```
<file_sep># NETSPEED plugin
NETSPEED plugin provides metrics about speed of network interfaces.
All metrics are extracted by reading `/sys/class/net` directory.
Plugin works only on Linux systems.
## Measurements
- `interface_speed` - speed of network interface
## Dependencies
No dependencies.
## Configuration
```
[[inputs.exec]]
commands = ["/path/to/plugin/netspeed.sh"]
timeout = "5s"
data_format = "influx"
```
## Output example
```
net,interface=eno1,speed=1000 interface_speed=1000
net,interface=ens1f0,speed=10000 interface_speed=10000
```
<file_sep>#!/bin/bash
top -n1 -b | tail -n +8 | awk '{arr[$12]+=$9} END {for (i in arr) {print i,arr[i]}}' | sort -n -k 2,2 | awk '{print "proc,process=" $1 " cpu_usage_percent=" $2}' | tail -5
ps axco command,pmem --no-headers | awk '{arr[$1]+=$2} END {for (i in arr) {print i,arr[i]}}' | sort -n -k 2,2 | awk '{print "proc,process=" $1 " memory_usage_percent=" $2}' | tail -5
<file_sep># NETSTAT plugin
NETSTAT plugin provides metrics about TCP connections and UDP sockets.
All metrics are extracted from `ss` command.
> Telegraf already has built-in [NETSTAT](https://github.com/influxdata/telegraf/blob/master/plugins/inputs/system/NETSTAT_README.md) plugin.
> But built-in plugin produces too much system calls and consumes up to 20% of total CPU even on modern servers.
Output of this plugin is completely compatible with built-in Telegraf NETSTAT plugin.
Plugin works only on Linux systems.
## Measurements
- `udp_socket` - UDP sockets count
- `tcp_established` - Established TCP connections count
- `tcp_syn_sent` - Connections waiting for an acknowledgment from the remote endpoint
- `tcp_syn_recv` - Connections that have received a connection request and sent an acknowledgment
- `tcp_fin_wait1` - Connections waiting for an acknowledgment of the connection termination request
- `tcp_fin_wait2` - Connections waiting for a connection termination request from the remote TCP
- `tcp_time_wait` - Connections waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request
- `tcp_close` - Represents no connection state at all
- `tcp_close_wait` - Connections waiting for a connection termination request from the local application
- `tcp_last_ack` - Connections waiting for an acknowledgment of the connection termination request previously sent to the remote TCP
- `tcp_listen` - Connections waiting for a connection request from a remote TCP application
- `tcp_closing` - Connections waiting for a connection termination request acknowledgment from the remote TCP
## Dependencies
`ss` MUST be installed to use this plugin.
## Configuration
```
[[inputs.exec]]
commands = ["/path/to/plugin/netstat.sh"]
timeout = "5s"
data_format = "influx"
```
## Output example
```
netstat udp_socket=10
netstat tcp_established=2
netstat tcp_syn_sent=0
netstat tcp_syn_recv=0
netstat tcp_fin_wait1=0
netstat tcp_fin_wait2=0
netstat tcp_time_wait=9
netstat tcp_close=0
netstat tcp_close_wait=0
netstat tcp_last_ack=0
netstat tcp_listen=11
netstat tcp_closing=0
```
<file_sep>#!/bin/bash
ls /sys/class/net 2> /dev/null | while read interface
do
speed=$(cat /sys/class/net/$interface/speed 2> /dev/null)
if [[ -z "$speed" ]]; then
continue
fi
# the speed is measured in megabytes
echo "net,interface=$interface,speed=$speed interface_speed=$speed"
done
|
b1699e4718054f218ee4a464f2d2a8788366a93b
|
[
"Markdown",
"Shell"
] | 11
|
Markdown
|
ryoung71/telegraf-plugins
|
9b5a5a29e56e055384a120274c96cd2694cefed0
|
d5b2a2549fa93e02729e45e7a5deed89aee0b706
|
refs/heads/master
|
<file_sep>// Put your main actions here<file_sep>const state = {
result: 3
};
const getters = {
result(state) {
return state.result
}
};
const mutations = {
increase(state, step) {
state.result += step
}
};
const actions = {
increaseResult: ({ commit }, delay) => {
setTimeout(() => {
commit('increase', 6)
}, delay)
}
}
export default {
state,
getters,
mutations,
actions
}<file_sep># Envato Tuts+ Tutorial: [How to Build Complex, Large-Scale Vue.js Apps With Vuex][published url]
## Instructor: [<NAME>][instructor url]
It's so easy to learn and use Vue.js that anyone can build a simple application with that framework. Even novices, with the help of Vue's documentation, can do the job. However, when complexity comes into play the things get a bit more serious. The truth is that multiple, deeply nested components with shared state can quickly turn your application into an unmaintainable mess.
The main problem in a complex application is how to manage the state between components without writing spaghetti code or producing side effects. In this tutorial you'll learn how to solve that problem by using Vuex: a state management library for building complex Vue.js applications.
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
# run unit tests
npm run unit
# run all tests
npm test
```
For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
------
These are source files for the Envato Tuts+ tutorial: [How to Build Complex, Large-Scale Vue.js Apps With Vuex][published url]
Available on [Envato Tuts+](https://tutsplus.com). Teaching skills to millions worldwide.
[published url]: [TUTORIAL URL]
[instructor url]: https://tutsplus.com/authors/ivaylo-gerchev
<file_sep>// Put your main state here<file_sep>const state = {
score: 0
};
const getters = {
score(state) {
return state.score
}
};
const mutations = {
increment(state, step) {
state.score += step
}
};
const actions = {
incrementScore: ({ commit }, delay) => {
setTimeout(() => {
commit('increment', 3)
}, delay)
}
}
export default {
state,
getters,
mutations,
actions
}<file_sep>// Put your main mutations here
|
a92d1f01ac1b1badb09d1472a44067129c81cd93
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
kabirutd/how-to-build-complex-large-scale-vuejs-apps-with-vuex
|
ab5db915839f46df03e1ff2d505ff83b0402d924
|
e391b8351387da2f940a5e52c0bd211d864e7cce
|
refs/heads/master
|
<file_sep>import {createMenuTemplate} from './components/menu';
import {createFilterTemplate} from './components/filter';
import {createBoardTemplate} from './components/board';
import {createTaskEditionFormTemplate} from './components/task-edition-form';
import {createTaskTemplate} from './components/task';
import {createLoadMoreButtonTemplate} from './components/load-more-button';
const TASKS_COUNT = 3;
const render = (container, template, place = `beforeend`) => {
container.insertAdjacentHTML(place, template);
};
const headerElement = document.querySelector(`.main__control`);
render(headerElement, createMenuTemplate());
const mainElement = document.querySelector(`.main`);
render(mainElement, createFilterTemplate());
render(mainElement, createBoardTemplate());
const tasksListElement = document.querySelector(`.board__tasks`);
render(tasksListElement, createTaskEditionFormTemplate());
new Array(TASKS_COUNT)
.fill(``)
.forEach(() => render(tasksListElement, createTaskTemplate()));
const boardElement = document.querySelector(`.board`);
render(boardElement, createLoadMoreButtonTemplate());
|
7b45d21ecb495238a31fe9ce1f80955dfda324ea
|
[
"JavaScript"
] | 1
|
JavaScript
|
bananafishh/18012-taskmanager-10
|
9c365fd95d0dee28afcbc7ae13ec1c1d429d4e89
|
1e2abcdc0e64973892797260e18b5bcc8e54afec
|
refs/heads/master
|
<file_sep>
package Logicas;
import Clases.Conectar;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proyectof.InicioDeSesion;
import proyectof.MenuPrincipal;
public class LogicaEmpleados {
private final String SQL_INSERT="INSERT INTO Empleados(idEmpleados, Nombres,Apellidos,Domicilio,Telefono,Salario,Horario,Contrasenia) values(?,?,?,?,?,?,?,?)";
private final String SQL_SELECT="SELECT * FROM Empleados";
private PreparedStatement PS;
private DefaultTableModel DT;
private ResultSet RS;
private Conectar CN;
public LogicaEmpleados() {
PS= null;
CN= new Conectar();
}
private DefaultTableModel setTitulos(){
DT= new DefaultTableModel();
DT.addColumn("Id ");
DT.addColumn("Nombres");
DT.addColumn("Apellidos");
DT.addColumn("Domicilio");
DT.addColumn("Telefono");
DT.addColumn("Salario");
DT.addColumn("Horario");
DT.addColumn("Contraseña");
return DT;
}
//metodo para listar todo lo de la tabla
public DefaultTableModel getDatos(){
try {
setTitulos();
PS=CN.getConnection().prepareStatement(SQL_SELECT);
RS=PS.executeQuery();
Object[] fila= new Object[8];
while(RS.next()){
fila[0]=RS.getInt(1);
fila[1]=RS.getString(2);
fila[2]=RS.getString(3);
fila[3]=RS.getString(4);
fila[4]=RS.getLong(5);
fila[5]=RS.getFloat(6);
fila[6]=RS.getString(7);
fila[7]=RS.getInt(8);
DT.addRow(fila);
}
} catch (SQLException e) {
System.out.println("error al listar los datos"+e.getMessage());
}finally{
PS=null;
RS=null;
CN.Desconectar();
}
return DT;
}
public DefaultTableModel getDato(int idCliente){
String SQL="SELECT*FROM Empleados where idEmpleados="+idCliente;
try {
setTitulos();
PS=CN.getConnection().prepareStatement(SQL);
RS=PS.executeQuery();
Object[] fila= new Object[8];
while(RS.next()){
fila[0]=RS.getInt(1);
fila[1]=RS.getString(2);
fila[2]=RS.getString(3);
fila[3]=RS.getString(4);
fila[4]=RS.getLong(5);
fila[5]=RS.getFloat(6);
fila[6]=RS.getString(7);
fila[7]=RS.getInt(8);
DT.addRow(fila);
}
} catch (SQLException e) {
System.out.println("error al listar los datos"+e.getMessage());
}finally{
PS=null;
RS=null;
CN.Desconectar();
}
return DT;
}
public int updateDatos(int idEmpleado,String Nom,String Ape ,String Dom,long Tel,float sal,String horario,int contra){
String SQL="UPDATE Empleados SET idEmpleados="+idEmpleado+",Nombres='"+Nom+"',Apellidos='"+Ape+"',Domicilio='"+Dom+"', Telefono="+Tel+", Salario="+sal+",Horario='"+horario+"',Contrasenia="+contra+" WHERE idEmpleados="+idEmpleado;
int res=0;
try {
PS=CN.getConnection().prepareStatement(SQL);
res=PS.executeUpdate();
if(res>0){
JOptionPane.showMessageDialog(null, "Registro se ha modificado con exito");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,"Error al modificar los datos"+e.getMessage());
}finally{
PS=null;
CN.Desconectar();
}
return res;
}
public void deleteDatos(int id){
String SQL="DELETE from Empleados WHERE idEmpleados="+id;
int res=0;
try {
PS=CN.getConnection().prepareStatement(SQL);
res=PS.executeUpdate();
if(res>0){
JOptionPane.showMessageDialog(null, "Registro se ha Eliminado");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,"Error al eliminar los datos"+e.getMessage());
}finally{
PS=null;
CN.Desconectar();
}
}
public int insertDatos(int idEmpleado,String Nom,String Ape,String Dom,long Tel,float Sal,String horario,int Con){
int res=0;
try {
PS=CN.getConnection().prepareStatement(SQL_INSERT);
PS.setInt(1,idEmpleado);
PS.setString(2, Nom);
PS.setString(3, Ape);
PS.setString(4, Dom);
PS.setLong(5, Tel);
PS.setFloat(6, Sal);
PS.setString(7, horario);
PS.setInt(8,Con);
res=PS.executeUpdate();
if(res>0){
JOptionPane.showMessageDialog(null, "Registro se ha guardado con exito");
}
} catch (SQLException e) {
}finally{
PS=null;
CN.Desconectar();
}
return res;
}
public int Acceder(int id){
int resultado=0;
try {
String sql="select* from Empleados where idEmpleados="+id;
Connection cn=CN.getConnection();
Statement st= cn.createStatement();
ResultSet rs= st.executeQuery(sql);
if(rs.next()){
resultado=1;
}
} catch (SQLException ex) {
Logger.getLogger(IngresarClientes.class.getName()).log(Level.SEVERE, null, ex);
}
return resultado;
}
public int login(String usuario ,String pass){
int resultado=0;
String sql="select* from empleados where idEmpleados= "+usuario+" and Contrasenia="+pass+"";
try {
Connection cn=CN.getConnection();
Statement st= cn.createStatement();
ResultSet rs= st.executeQuery(sql);
if(rs.next()){
resultado=1;
}
} catch (SQLException ex) {
Logger.getLogger(InicioDeSesion.class.getName()).log(Level.SEVERE, null, ex);
} finally{
}
return resultado;
}
}
<file_sep>
package proyectof;
import Clases.Conectar;
import Logicas.LogicaEmpleados;
import Logicas.LogicaGastos;
import java.sql.Connection;
import javax.swing.JOptionPane;
public class VisualGastos extends javax.swing.JFrame {
private LogicaGastos LG;
private LogicaEmpleados LE;
public VisualGastos() {
initComponents();
LG= new LogicaGastos();
LE= new LogicaEmpleados();
respuesta=0;
}
private void Listar(){
jTable1.setModel(LG.getDatos());
}
private void limpiar(){
txtidGastos.setText("");
txtluz.setText("");
txtagua.setText("");
txtrenta.setText("");
txtidEmpleados.setText("");
txtDiaPago.setText("");
txtMesPago.setText("");
txtAnioPago.setText("");
txtConsulta.setText("");
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
txtidEmpleados = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtidGastos = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtluz = new javax.swing.JTextField();
txtagua = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtrenta = new javax.swing.JTextField();
btModificar = new javax.swing.JButton();
btEliminar = new javax.swing.JButton();
btMostrarTodo = new javax.swing.JButton();
btRegistrar = new javax.swing.JButton();
btConsulta = new javax.swing.JButton();
btMenu = new javax.swing.JButton();
txtConsulta = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
txtDiaPago = new javax.swing.JTextField();
txtMesPago = new javax.swing.JTextField();
txtAnioPago = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyectof/empleos-online-con-mayor-demanda.jpg"))); // NOI18N
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(204, 204, 204));
jPanel1.setLayout(null);
jLabel7.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel7.setText("Id Empleado");
jPanel1.add(jLabel7);
jLabel7.setBounds(10, 200, 130, 22);
txtidEmpleados.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtidEmpleados.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtidEmpleadosActionPerformed(evt);
}
});
txtidEmpleados.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtluzKeyTyped(evt);
}
});
jPanel1.add(txtidEmpleados);
txtidEmpleados.setBounds(160, 200, 210, 20);
jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel2.setText("Id Gastos");
jPanel1.add(jLabel2);
jLabel2.setBounds(10, 80, 150, 20);
txtidGastos.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtidGastos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtidGastosActionPerformed(evt);
}
});
txtidGastos.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtluzKeyTyped(evt);
}
});
jPanel1.add(txtidGastos);
txtidGastos.setBounds(160, 76, 210, 20);
jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel4.setText("<NAME>");
jPanel1.add(jLabel4);
jLabel4.setBounds(10, 140, 160, 22);
jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel5.setText("<NAME>");
jPanel1.add(jLabel5);
jLabel5.setBounds(10, 110, 160, 22);
txtluz.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtluz.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtluzKeyTyped(evt);
}
});
jPanel1.add(txtluz);
txtluz.setBounds(160, 106, 210, 20);
txtagua.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtagua.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtaguaActionPerformed(evt);
}
});
txtagua.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtluzKeyTyped(evt);
}
});
jPanel1.add(txtagua);
txtagua.setBounds(160, 136, 210, 20);
jLabel6.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel6.setText("Gastos renta");
jPanel1.add(jLabel6);
jLabel6.setBounds(10, 170, 130, 22);
txtrenta.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtrenta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtrentaActionPerformed(evt);
}
});
txtrenta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtluzKeyTyped(evt);
}
});
jPanel1.add(txtrenta);
txtrenta.setBounds(160, 166, 210, 20);
btModificar.setText("Modificar");
btModificar.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 255, 204), new java.awt.Color(0, 204, 204)));
btModificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btModificarActionPerformed(evt);
}
});
jPanel1.add(btModificar);
btModificar.setBounds(390, 200, 100, 30);
btEliminar.setText("Eliminar");
btEliminar.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 255, 204), new java.awt.Color(0, 204, 204)));
btEliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btEliminarActionPerformed(evt);
}
});
jPanel1.add(btEliminar);
btEliminar.setBounds(390, 160, 100, 30);
btMostrarTodo.setText("Mostrar Todo");
btMostrarTodo.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 255, 204), new java.awt.Color(0, 204, 204)));
btMostrarTodo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btMostrarTodoActionPerformed(evt);
}
});
jPanel1.add(btMostrarTodo);
btMostrarTodo.setBounds(390, 120, 100, 30);
btRegistrar.setText("Registrar");
btRegistrar.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 255, 204), new java.awt.Color(0, 204, 204)));
btRegistrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btRegistrarActionPerformed(evt);
}
});
jPanel1.add(btRegistrar);
btRegistrar.setBounds(390, 80, 90, 30);
btConsulta.setText("Consulta");
btConsulta.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 255, 204), new java.awt.Color(0, 204, 204)));
btConsulta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btConsultaActionPerformed(evt);
}
});
jPanel1.add(btConsulta);
btConsulta.setBounds(510, 80, 100, 30);
btMenu.setText("Menú");
btMenu.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 255, 204), new java.awt.Color(0, 204, 204)));
btMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btMenuActionPerformed(evt);
}
});
jPanel1.add(btMenu);
btMenu.setBounds(10, 10, 80, 30);
txtConsulta.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtluzKeyTyped(evt);
}
});
jPanel1.add(txtConsulta);
txtConsulta.setBounds(510, 120, 100, 40);
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N
jLabel1.setText("Gastos");
jPanel1.add(jLabel1);
jLabel1.setBounds(240, 0, 190, 42);
jScrollPane1.setViewportView(jTable1);
jPanel1.add(jScrollPane1);
jScrollPane1.setBounds(20, 270, 620, 90);
jLabel8.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel8.setText("Fecha Pagos ");
jPanel1.add(jLabel8);
jLabel8.setBounds(10, 240, 140, 20);
jLabel9.setText(" /");
jPanel1.add(jLabel9);
jLabel9.setBounds(230, 240, 16, 14);
jLabel10.setText(" /");
jPanel1.add(jLabel10);
jLabel10.setBounds(310, 240, 40, 20);
txtDiaPago.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtDiaPago.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtluzKeyTyped(evt);
}
});
jPanel1.add(txtDiaPago);
txtDiaPago.setBounds(160, 240, 70, 16);
txtMesPago.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtMesPago.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtluzKeyTyped(evt);
}
});
jPanel1.add(txtMesPago);
txtMesPago.setBounds(250, 240, 60, 16);
txtAnioPago.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtAnioPago.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtAnioPagoActionPerformed(evt);
}
});
txtAnioPago.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtluzKeyTyped(evt);
}
});
jPanel1.add(txtAnioPago);
txtAnioPago.setBounds(350, 240, 55, 16);
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyectof/5765321-azul-de-fondo-de-burbujas-vector-de-la-ilustración-.jpg"))); // NOI18N
jPanel1.add(jLabel11);
jLabel11.setBounds(0, -50, 700, 430);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 699, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 361, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtidEmpleadosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtidEmpleadosActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtidEmpleadosActionPerformed
private void txtidGastosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtidGastosActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtidGastosActionPerformed
private void txtaguaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtaguaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtaguaActionPerformed
private void txtrentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtrentaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtrentaActionPerformed
private void btModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btModificarActionPerformed
// TODO add your handling code here:
int idGastos, idEmpleados;
float luz,agua,renta;
String fecha;
int idGAsto,banderagasto;
int idempleado, banderaempleado;
if(!txtidGastos.getText().isEmpty() && !txtluz.getText().isEmpty() && !txtagua.getText().isEmpty() && !txtrenta.getText().isEmpty() && !txtDiaPago.getText().isEmpty() && !txtMesPago.getText().isEmpty() && !txtAnioPago.getText().isEmpty() && !txtidEmpleados.getText().isEmpty())
{
if(txtidGastos.getText().length()-1<9){
if(txtidEmpleados.getText().length()-1<9){
if(txtluz.getText().length()-1<9){
if(txtagua.getText().length()-1<9){
if(txtrenta.getText().length()-1<9){
if(txtDiaPago.getText().length()-1<9 && txtMesPago.getText().length()-1<9 && txtAnioPago.getText().length()-1<9){
idGAsto=Integer.parseInt(txtidGastos.getText());
banderagasto=LG.Acceder(idGAsto);
idempleado=Integer.parseInt(txtidEmpleados.getText());
banderaempleado=LE.Acceder(idempleado);
if(banderagasto!=0){
if(banderaempleado!=0){
int dia=Integer.parseInt(txtDiaPago.getText());
int mes=Integer.parseInt(txtMesPago.getText());
int anio=Integer.parseInt(txtAnioPago.getText());
if(dia>=1 && dia<=31 && mes>=1 && mes<=12 ){
idGastos=Integer.parseInt(txtidGastos.getText());
luz=Float.parseFloat(txtluz.getText());
agua=Float.parseFloat(txtagua.getText());
renta=Float.parseFloat(txtrenta.getText());
fecha= txtAnioPago.getText()+"/"+txtMesPago.getText()+"/"+txtDiaPago.getText();
idEmpleados=Integer.parseInt(txtidEmpleados.getText());
respuesta=LG.updateDatos(idGastos, luz, agua, renta, fecha, idEmpleados);
}else{
JOptionPane.showMessageDialog(null ,"NO digito correctamente la fecha");
}
} else{
JOptionPane.showMessageDialog(null,"NO se puede realizar la modificacion ya que en el campo de id empleado no existe un empleado con ese id");
}
}else{
JOptionPane.showMessageDialog(null, "no se puede hacer la modificacion ya que no existe el id del gasto");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de digitos en la fecha");
}
}else{
JOptionPane.showMessageDialog(null,"Se ha pasado en el limite de digitos en la renta");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de digitos en el agua");
}
}else{
JOptionPane.showMessageDialog(null, "SE ha pasado del limite de digitos en la luz");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado del limite de digitos en el idEMpleados");
}
}else{
JOptionPane.showMessageDialog(null, "se ha pasado del limite de digitos en el idgastos");
}
}else{
JOptionPane.showMessageDialog(null, "usted ha dejado un campo o varios campos sin llenar");
}
limpiar();
}//GEN-LAST:event_btModificarActionPerformed
private void btEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEliminarActionPerformed
// TODO add your handling code here:
int id,bandera;
if(!txtidGastos.getText().isEmpty()){
if(txtidGastos.getText().length()-1<9){
id=Integer.parseInt(txtidGastos.getText());
bandera=LG.Acceder(id);
if(bandera!=0){
int idGastos=Integer.parseInt(txtidGastos.getText());
LG.deleteDatos(idGastos);
limpiar();
}else{
JOptionPane.showMessageDialog(null, "EL registro no se pudo borrar ya que no no hay un gasto con ese id");
limpiar();
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de digitos en el idGastos");
}
}else{
JOptionPane.showMessageDialog(null, "Usted ha dejado sin contestar el campo de idGastos y no se sabe cual registro vamos a eliminar");
}
limpiar();
}//GEN-LAST:event_btEliminarActionPerformed
private void btMostrarTodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btMostrarTodoActionPerformed
Listar();
}//GEN-LAST:event_btMostrarTodoActionPerformed
private void btRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRegistrarActionPerformed
// TODO add your handling code here:
int banderaGastos,idgasto;
int banderaEmpleado ,idempleado;
if(!txtidGastos.getText().isEmpty() && !txtluz.getText().isEmpty() && !txtagua.getText().isEmpty() && !txtrenta.getText().isEmpty() && !txtDiaPago.getText().isEmpty() && !txtMesPago.getText().isEmpty() && !txtAnioPago.getText().isEmpty() && !txtidEmpleados.getText().isEmpty()){
if(txtidGastos.getText().length()-1<9){
if(txtidEmpleados.getText().length()-1<9){
if(txtluz.getText().length()-1<10){
if(txtrenta.getText().length()-1<10){
if(txtagua.getText().length()-1<10){
if(txtDiaPago.getText().length()-1<9 && txtMesPago.getText().length()-1<9 && txtAnioPago.getText().length()-1<9){
idgasto=Integer.parseInt(txtidGastos.getText());
banderaGastos=LG.Acceder(idgasto);
idempleado=Integer.parseInt(txtidEmpleados.getText());
banderaEmpleado=LE.Acceder(idempleado);
if(banderaGastos==0){
if(banderaEmpleado!=0){
int dia=Integer.parseInt(txtDiaPago.getText());
int mes=Integer.parseInt(txtMesPago.getText());
int anio=Integer.parseInt(txtAnioPago.getText());
if(dia>=1 && dia<=31 && mes>=1 && mes<=12 ){
int idGastos, idEmpleados;
float luz,agua,renta;
String fecha;
idGastos=Integer.parseInt(txtidGastos.getText());
luz=Float.parseFloat(txtluz.getText());
agua=Float.parseFloat(txtagua.getText());
renta=Float.parseFloat(txtrenta.getText());
fecha= txtAnioPago.getText()+"/"+txtMesPago.getText()+"/"+txtDiaPago.getText();
idEmpleados=Integer.parseInt(txtidEmpleados.getText());
respuesta=LG.insertDatos(idGastos, luz, agua, renta, fecha, idEmpleados);
}else{
JOptionPane.showMessageDialog(null, "no digito bien la fecha");
}
}else{
JOptionPane.showMessageDialog(null, "no se puede hacer el registro ya que en el campo idEmleado no existe ese empleado");
}
}
else{
JOptionPane.showMessageDialog(null, "no se puede hacer el registro ya que hay otro gasto con el mismo id ");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de digitos en la fecha");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de digitos en el agua");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de Digitos en el campo Renta");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado del limite de digitos en el campo luz");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado del limite de digitos en idEmpleados");
}
}else{
JOptionPane.showMessageDialog(null, "se ha pasado del limite de digitos en idGastos");
}
}else{
JOptionPane.showMessageDialog(null, "ha dejado un campo o varios campos sin contestar");
}
limpiar();
}//GEN-LAST:event_btRegistrarActionPerformed
private void btConsultaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConsultaActionPerformed
// TODO add your handling code here:
int idCon,bandera;
if(!txtConsulta.getText().isEmpty()){
if(txtConsulta.getText().length()-1<9){
idCon=Integer.parseInt(txtConsulta.getText());
bandera=LG.Acceder(idCon);
if(bandera!=0){
int id=Integer.parseInt(txtConsulta.getText());
jTable1.setModel(LG.getDato(id));
}else{
JOptionPane.showMessageDialog(null, "No se realizo la consulta ya que no existe algun gasto con ese id");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de digitos en la consulta");
}
}else{
JOptionPane.showMessageDialog(null, "usted ha dejado sin contestar el campo consulta y no sabemos que registro desea ver");
}
limpiar();
}//GEN-LAST:event_btConsultaActionPerformed
private void btMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btMenuActionPerformed
MenuPrincipal menu=new MenuPrincipal();
menu.setLocationRelativeTo(null);
menu.setSize(708, 402);
menu.setVisible(true);
this.dispose();
}//GEN-LAST:event_btMenuActionPerformed
private void txtAnioPagoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtAnioPagoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtAnioPagoActionPerformed
private void txtluzKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtluzKeyTyped
// TODO add your handling code here:
char car= evt.getKeyChar();
if(car<'0' || car>'9'){
evt.consume();
}
}//GEN-LAST:event_txtluzKeyTyped
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btConsulta;
private javax.swing.JButton btEliminar;
private javax.swing.JButton btMenu;
private javax.swing.JButton btModificar;
private javax.swing.JButton btMostrarTodo;
private javax.swing.JButton btRegistrar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField txtAnioPago;
private javax.swing.JTextField txtConsulta;
private javax.swing.JTextField txtDiaPago;
private javax.swing.JTextField txtMesPago;
private javax.swing.JTextField txtagua;
private javax.swing.JTextField txtidEmpleados;
private javax.swing.JTextField txtidGastos;
private javax.swing.JTextField txtluz;
private javax.swing.JTextField txtrenta;
// End of variables declaration//GEN-END:variables
int respuesta;
public Conectar cc= new Conectar();
public Connection cn= cc.getConnection();
}
<file_sep>
package proyectof;
import Clases.Conectar;
import Logicas.LogicaEmpleados;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class InicioDeSesion extends javax.swing.JFrame {
private LogicaEmpleados LE;
int limite;
public InicioDeSesion() {
initComponents();
LE= new LogicaEmpleados();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtUsuario = new javax.swing.JTextField();
txtContrasenia = new javax.swing.JPasswordField();
jButton1 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(204, 255, 255));
jPanel1.setLayout(null);
jLabel1.setFont(new java.awt.Font("Comic Sans MS", 1, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 0, 204));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Inicio Sesion");
jLabel1.setBorder(new javax.swing.border.MatteBorder(null));
jPanel1.add(jLabel1);
jLabel1.setBounds(19, 21, 314, 39);
jLabel2.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N
jLabel2.setForeground(new java.awt.Color(51, 0, 153));
jLabel2.setText("USUARIO");
jLabel2.setBorder(new javax.swing.border.MatteBorder(null));
jPanel1.add(jLabel2);
jLabel2.setBounds(10, 87, 115, 39);
jLabel3.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(51, 0, 153));
jLabel3.setText("CONTRASEÑA");
jLabel3.setBorder(new javax.swing.border.MatteBorder(null));
jPanel1.add(jLabel3);
jLabel3.setBounds(10, 155, 124, 19);
txtUsuario.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtContraseniaKeyTyped(evt);
}
});
jPanel1.add(txtUsuario);
txtUsuario.setBounds(178, 93, 170, 30);
txtContrasenia.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtContrasenia.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtContraseniaKeyTyped(evt);
}
});
jPanel1.add(txtContrasenia);
txtContrasenia.setBounds(178, 144, 170, 32);
jButton1.setFont(new java.awt.Font("Comic Sans MS", 1, 24)); // NOI18N
jButton1.setForeground(new java.awt.Color(0, 0, 102));
jButton1.setText("Aceptar");
jButton1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1);
jButton1.setBounds(45, 218, 282, 71);
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyectof/sesiones.png"))); // NOI18N
jPanel1.add(jLabel4);
jLabel4.setBounds(0, 0, 360, 310);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if((!txtUsuario.getText().isEmpty()) && (!txtContrasenia.getText().isEmpty())){//Comprueba si el TextBox tiene texto
int bandera=0;//Inicializamos una bandera;
if(txtUsuario.getText().length()-1<9){ // comprueba de que el textfield de usuario no se pase de los limites de int
if(txtContrasenia.getText().length()-1<9){//comprueba de que el textfield de contraseña no se pase de los limites de int
bandera=LE.login(txtUsuario.getText(), txtContrasenia.getText());//Asigna condicion a una bandera
if(bandera==1 || txtContrasenia.getText().equals("1") && txtUsuario.getText().equals("123")){//Si la condicion es cierta hace
JOptionPane.showMessageDialog(null,"Se ha ingresado correctamente");//Muestra un mensaje de que todo se ha ingresado bien
this.dispose();//Para cuando cierres una pestaña no te cierre el programa
MenuPrincipal menu=new MenuPrincipal();//Hacemos una instancia de la clase MenuPrincipal
menu.setLocationRelativeTo(null);//Hace que la pantalla aparesca en el centro
menu.setVisible(true);//Hace que la pestaña menu se muestre
this.dispose();//Para cuando cierres una pestaña no te cierre el programa
}else{//Si es falsa la condicion Hace
JOptionPane.showMessageDialog(null,"los datos son erroneos");//Muestra Mensaje diciendo que los datos son erroneos
}
}else{
JOptionPane.showMessageDialog(null, "se ha pasado en el limite de nunmeros en la contrasenia");
}
}else{
JOptionPane.showMessageDialog(null, "se ha pasado en el limite de nunmeroa en el usuario");
}
}
else{//Si los textbox estan vacios hace lo siguiente
JOptionPane.showMessageDialog(null,"Usted ha dejado un registro sin contestar");//Muestra el mensaje
}
}//GEN-LAST:event_jButton1ActionPerformed
private void txtContraseniaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtContraseniaKeyTyped
// TODO add your handling code here:
char car= evt.getKeyChar();
if(car<'0' || car>'9'){
evt.consume();
}
}//GEN-LAST:event_txtContraseniaKeyTyped
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(InicioDeSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InicioDeSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InicioDeSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InicioDeSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new InicioDeSesion().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPasswordField txtContrasenia;
private javax.swing.JTextField txtUsuario;
// End of variables declaration//GEN-END:variables
public Conectar cc= new Conectar();
public Connection cn= cc.getConnection();
//public int resultado=0;
}<file_sep>compile.on.save=true
file.reference.mysql-connector-java-5.1.13-bin.jar=C:\\Users\\<NAME>\\Desktop\\ingeneria en ciencias computacionales\\mysql-connector-java-5.1.13-bin.jar
user.properties.file=/home/luis/.netbeans/8.2/build.properties
<file_sep>
-- Volcando estructura de base de datos para tintoreria
CREATE DATABASE IF NOT EXISTS `tintoreria` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `tintoreria`;
-- Volcando estructura para tabla tintoreria.clientes
DROP TABLE IF EXISTS `clientes`;
CREATE TABLE IF NOT EXISTS `clientes` (
`idClientes` int(11) NOT NULL,
`Nombres` varchar(50) NOT NULL,
`Apellidos` varchar(50) NOT NULL,
`Telefono` bigint(20) NOT NULL,
`Domicilio` varchar(59) NOT NULL,
PRIMARY KEY (`idClientes`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Volcando datos para la tabla tintoreria.clientes: ~4 rows (aproximadamente)
/*!40000 ALTER TABLE `clientes` DISABLE KEYS */;
INSERT INTO `clientes` (`idClientes`, `Nombres`, `Apellidos`, `Telefono`, `Domicilio`) VALUES
(1, 'raul', 'corona', 789, '42'),
(2, 'mirsha', 'espinoza', 789, 'Basilio Vadillo'),
(3, 'arturo', 'gonzalez', 123, 'hacienda real'),
(4, 'guilermo', 'gomez', 123, 'valle'),
(5, 'q', 'q', 8888888888, 'q');
/*!40000 ALTER TABLE `clientes` ENABLE KEYS */;
-- Volcando estructura para tabla tintoreria.empleados
DROP TABLE IF EXISTS `empleados`;
CREATE TABLE IF NOT EXISTS `empleados` (
`idEmpleados` int(11) NOT NULL,
`Nombres` varchar(50) NOT NULL,
`Apellidos` varchar(50) NOT NULL,
`Domicilio` varchar(50) NOT NULL,
`Telefono` bigint(20) NOT NULL,
`Salario` float NOT NULL,
`Horario` varchar(20) NOT NULL,
`Contrasenia` int(11) NOT NULL,
PRIMARY KEY (`idEmpleados`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Volcando datos para la tabla tintoreria.empleados: ~4 rows (aproximadamente)
/*!40000 ALTER TABLE `empleados` DISABLE KEYS */;
INSERT INTO `empleados` (`idEmpleados`, `Nombres`, `Apellidos`, `Domicilio`, `Telefono`, `Salario`, `Horario`, `Contrasenia`) VALUES
(1, 'q', 'q', 'q', 11111111, 1111110000, 'Matutino', 1),
(111, 'qww', 'wwq', 'qww', 1, 1, 'Matutino', 1),
(345, 'luis', 'gonzalez', '<NAME>', 753140, 300, 'Matutino', 456),
(700, 'jose', 'hrndz', 'salvaodr', 753140113, 500, 'Matutino', 69);
/*!40000 ALTER TABLE `empleados` ENABLE KEYS */;
-- Volcando estructura para tabla tintoreria.gastos
DROP TABLE IF EXISTS `gastos`;
CREATE TABLE IF NOT EXISTS `gastos` (
`idGastos` int(11) NOT NULL,
`luz` float NOT NULL,
`Agua` float NOT NULL,
`Renta` float NOT NULL,
`fechaPagos` date NOT NULL,
`idEmpleados` int(11) NOT NULL,
PRIMARY KEY (`idGastos`),
KEY `idEmpleados` (`idEmpleados`),
CONSTRAINT `gastos_ibfk_1` FOREIGN KEY (`idEmpleados`) REFERENCES `empleados` (`idEmpleados`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Volcando datos para la tabla tintoreria.gastos: ~2 rows (aproximadamente)
/*!40000 ALTER TABLE `gastos` DISABLE KEYS */;
INSERT INTO `gastos` (`idGastos`, `luz`, `Agua`, `Renta`, `fechaPagos`, `idEmpleados`) VALUES
(2, 12, 12, 12, '0003-03-03', 111),
(12, 2, 2, 2, '0001-01-01', 111),
(111111111, 11, 1, 1, '0002-02-02', 1);
/*!40000 ALTER TABLE `gastos` ENABLE KEYS */;
-- Volcando estructura para tabla tintoreria.servicios
DROP TABLE IF EXISTS `servicios`;
CREATE TABLE IF NOT EXISTS `servicios` (
`idServicios` int(11) NOT NULL,
`NumeroPrendas` int(11) NOT NULL,
`PrecioTotal` float NOT NULL,
`FechaIngreso` date DEFAULT NULL,
`idClientes` int(11) NOT NULL,
`idEmpleados` int(11) NOT NULL,
PRIMARY KEY (`idServicios`),
KEY `idClientes` (`idClientes`),
KEY `idEmpleados` (`idEmpleados`),
CONSTRAINT `servicios_ibfk_1` FOREIGN KEY (`idClientes`) REFERENCES `clientes` (`idClientes`),
CONSTRAINT `servicios_ibfk_2` FOREIGN KEY (`idEmpleados`) REFERENCES `empleados` (`idEmpleados`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Volcando datos para la tabla tintoreria.servicios: ~5 rows (aproximadamente)
/*!40000 ALTER TABLE `servicios` DISABLE KEYS */;
INSERT INTO `servicios` (`idServicios`, `NumeroPrendas`, `PrecioTotal`, `FechaIngreso`, `idClientes`, `idEmpleados`) VALUES
(1, 200, 100, '1998-11-16', 1, 1),
(2, 2, 2, '1998-11-11', 1, 1),
(3, 3, 3, '1998-11-15', 1, 1),
(4, 10, 100, '2018-05-09', 1, 1),
(111, 1, 1, '0001-01-01', 1, 1);
/*!40000 ALTER TABLE `servicios` ENABLE KEYS */;
drop database tintoreria;<file_sep>
package proyectof;
import Clases.Conectar;
import Logicas.IngresarClientes;
import Logicas.LogicaEmpleados;
import Logicas.LogicaServicios;
import java.sql.Connection;
import javax.swing.JOptionPane;
public class VisualServicios extends javax.swing.JFrame {
private LogicaServicios LS;
private LogicaEmpleados LE;
private IngresarClientes LC;
public VisualServicios() {
initComponents();
LS= new LogicaServicios();
LC= new IngresarClientes();
LE= new LogicaEmpleados();
respuesta=0;
}
private void listar(){
jTable1.setModel(LS.getDatos());
}
private void Limpiar(){
txtIdServicios.setText("");
txtNumeroPrendas.setText("");
txtPrecioTotal.setText("");
txtDia.setText("");
txtMes.setText("");
txtAnio.setText("");
txtIdClientes.setText("");
txtidEmpleados.setText("");
txtConsulta.setText("");
txtDiaInicialConsulta.setText("");
txtMesInicialConsulta.setText("");
txtAnioInicialConsulta.setText("");
txtDiaFinalconsulta.setText("");
txtMesFinalConsulta.setText("");
txtAnio.setText("");
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel3 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
txtIdClientes = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtIdServicios = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtNumeroPrendas = new javax.swing.JTextField();
txtPrecioTotal = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtDia = new javax.swing.JTextField();
btModificar = new javax.swing.JButton();
btEliminar = new javax.swing.JButton();
btMostrarTodo = new javax.swing.JButton();
btRegistrar = new javax.swing.JButton();
btConsulta = new javax.swing.JButton();
btMenu = new javax.swing.JButton();
txtConsulta = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel8 = new javax.swing.JLabel();
txtidEmpleados = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
txtMes = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
txtAnio = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
txtDiaInicialConsulta = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
txtMesInicialConsulta = new javax.swing.JTextField();
jLabel13 = new javax.swing.JLabel();
txtAnioInicialConsulta = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
txtDiaFinalconsulta = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
txtMesFinalConsulta = new javax.swing.JTextField();
txtAnioFInalconsulta = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
txtConsultaMes = new javax.swing.JButton();
jLabel18 = new javax.swing.JLabel();
jLabel3.setText("jLabel3");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel2.setLayout(null);
jLabel7.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel7.setText("Fecha de ingreso");
jPanel2.add(jLabel7);
jLabel7.setBounds(10, 170, 130, 22);
txtIdClientes.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtIdClientes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIdClientesActionPerformed(evt);
}
});
txtIdClientes.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtidEmpleadosKeyTyped(evt);
}
});
jPanel2.add(txtIdClientes);
txtIdClientes.setBounds(160, 206, 210, 20);
jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel2.setText("Id Servicio");
jPanel2.add(jLabel2);
jLabel2.setBounds(10, 80, 150, 20);
txtIdServicios.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtIdServicios.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIdServiciosActionPerformed(evt);
}
});
txtIdServicios.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtidEmpleadosKeyTyped(evt);
}
});
jPanel2.add(txtIdServicios);
txtIdServicios.setBounds(160, 76, 210, 20);
jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel4.setText("Precio");
jPanel2.add(jLabel4);
jLabel4.setBounds(10, 140, 160, 22);
jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel5.setText("Número Prendas");
jPanel2.add(jLabel5);
jLabel5.setBounds(10, 110, 160, 22);
txtNumeroPrendas.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtNumeroPrendas.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtidEmpleadosKeyTyped(evt);
}
});
jPanel2.add(txtNumeroPrendas);
txtNumeroPrendas.setBounds(160, 106, 210, 20);
txtPrecioTotal.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtPrecioTotal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPrecioTotalActionPerformed(evt);
}
});
txtPrecioTotal.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtidEmpleadosKeyTyped(evt);
}
});
jPanel2.add(txtPrecioTotal);
txtPrecioTotal.setBounds(160, 136, 210, 20);
jLabel6.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel6.setText("Id Cliente");
jPanel2.add(jLabel6);
jLabel6.setBounds(10, 200, 130, 22);
txtDia.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtDia.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDiaActionPerformed(evt);
}
});
txtDia.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtidEmpleadosKeyTyped(evt);
}
});
jPanel2.add(txtDia);
txtDia.setBounds(160, 180, 40, 17);
btModificar.setBackground(new java.awt.Color(204, 204, 204));
btModificar.setText("Modificar");
btModificar.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(102, 255, 204), new java.awt.Color(0, 204, 204)));
btModificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btModificarActionPerformed(evt);
}
});
jPanel2.add(btModificar);
btModificar.setBounds(390, 200, 100, 30);
btEliminar.setBackground(new java.awt.Color(204, 204, 204));
btEliminar.setText("Eliminar");
btEliminar.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(102, 255, 204), new java.awt.Color(0, 204, 204)));
btEliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btEliminarActionPerformed(evt);
}
});
jPanel2.add(btEliminar);
btEliminar.setBounds(390, 160, 100, 30);
btMostrarTodo.setBackground(new java.awt.Color(204, 204, 204));
btMostrarTodo.setText("Mostrar Todo");
btMostrarTodo.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(102, 255, 204), new java.awt.Color(0, 204, 204)));
btMostrarTodo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btMostrarTodoActionPerformed(evt);
}
});
jPanel2.add(btMostrarTodo);
btMostrarTodo.setBounds(390, 120, 100, 30);
btRegistrar.setBackground(new java.awt.Color(204, 204, 204));
btRegistrar.setText("Registrar");
btRegistrar.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(102, 255, 204), new java.awt.Color(0, 204, 204)));
btRegistrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btRegistrarActionPerformed(evt);
}
});
jPanel2.add(btRegistrar);
btRegistrar.setBounds(390, 80, 90, 30);
btConsulta.setBackground(new java.awt.Color(204, 204, 204));
btConsulta.setText("Consulta");
btConsulta.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(102, 255, 204), new java.awt.Color(0, 204, 204)));
btConsulta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btConsultaActionPerformed(evt);
}
});
jPanel2.add(btConsulta);
btConsulta.setBounds(510, 80, 100, 30);
btMenu.setText("Menú");
btMenu.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(102, 255, 204), new java.awt.Color(0, 204, 204)));
btMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btMenuActionPerformed(evt);
}
});
jPanel2.add(btMenu);
btMenu.setBounds(10, 10, 80, 30);
txtConsulta.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtidEmpleadosKeyTyped(evt);
}
});
jPanel2.add(txtConsulta);
txtConsulta.setBounds(510, 120, 100, 40);
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N
jLabel1.setText("Servicios");
jPanel2.add(jLabel1);
jLabel1.setBounds(380, 0, 190, 42);
jTable1.setBackground(new java.awt.Color(204, 204, 204));
jScrollPane1.setViewportView(jTable1);
jPanel2.add(jScrollPane1);
jScrollPane1.setBounds(10, 270, 850, 90);
jLabel8.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel8.setText("Id Empleado");
jPanel2.add(jLabel8);
jLabel8.setBounds(10, 230, 110, 30);
txtidEmpleados.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtidEmpleados.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtidEmpleadosKeyTyped(evt);
}
});
jPanel2.add(txtidEmpleados);
txtidEmpleados.setBounds(150, 236, 220, 20);
jLabel9.setText(" /");
jPanel2.add(jLabel9);
jLabel9.setBounds(200, 180, 34, 20);
txtMes.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtMes.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtidEmpleadosKeyTyped(evt);
}
});
jPanel2.add(txtMes);
txtMes.setBounds(230, 180, 50, 17);
jLabel10.setText(" /");
jPanel2.add(jLabel10);
jLabel10.setBounds(280, 180, 40, 15);
txtAnio.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtAnio.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtidEmpleadosKeyTyped(evt);
}
});
jPanel2.add(txtAnio);
txtAnio.setBounds(320, 180, 40, 17);
jLabel11.setText("Consulta del mes");
jPanel2.add(jLabel11);
jLabel11.setBounds(670, 60, 220, 15);
txtDiaInicialConsulta.setText("dia");
txtDiaInicialConsulta.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtDiaInicialConsulta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDiaInicialConsultaActionPerformed(evt);
}
});
txtDiaInicialConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtDiaInicialConsultaKeyTyped(evt);
}
});
jPanel2.add(txtDiaInicialConsulta);
txtDiaInicialConsulta.setBounds(630, 110, 60, 17);
jLabel12.setText(" /");
jPanel2.add(jLabel12);
jLabel12.setBounds(690, 110, 9, 15);
txtMesInicialConsulta.setText("mes");
txtMesInicialConsulta.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtMesInicialConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtDiaInicialConsultaKeyTyped(evt);
}
});
jPanel2.add(txtMesInicialConsulta);
txtMesInicialConsulta.setBounds(710, 110, 60, 17);
jLabel13.setText(" /");
jPanel2.add(jLabel13);
jLabel13.setBounds(770, 110, 12, 15);
txtAnioInicialConsulta.setText("año");
txtAnioInicialConsulta.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtAnioInicialConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtDiaInicialConsultaKeyTyped(evt);
}
});
jPanel2.add(txtAnioInicialConsulta);
txtAnioInicialConsulta.setBounds(800, 110, 70, 17);
jLabel14.setText("Digite la fecha inicial donde quiere ver los servicios");
jPanel2.add(jLabel14);
jLabel14.setBounds(620, 74, 300, 20);
jLabel15.setText("DIgite la fecha final hasta donde quiera ver los servcios");
jPanel2.add(jLabel15);
jLabel15.setBounds(620, 140, 290, 15);
txtDiaFinalconsulta.setText("dia");
txtDiaFinalconsulta.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtDiaFinalconsulta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtDiaInicialConsultaKeyTyped(evt);
}
});
jPanel2.add(txtDiaFinalconsulta);
txtDiaFinalconsulta.setBounds(610, 170, 70, 17);
jLabel16.setText(" /");
jPanel2.add(jLabel16);
jLabel16.setBounds(680, 170, 15, 15);
txtMesFinalConsulta.setText("mes");
txtMesFinalConsulta.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtMesFinalConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtDiaInicialConsultaKeyTyped(evt);
}
});
jPanel2.add(txtMesFinalConsulta);
txtMesFinalConsulta.setBounds(720, 170, 60, 17);
txtAnioFInalconsulta.setText("año");
txtAnioFInalconsulta.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
txtAnioFInalconsulta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtDiaInicialConsultaKeyTyped(evt);
}
});
jPanel2.add(txtAnioFInalconsulta);
txtAnioFInalconsulta.setBounds(810, 170, 70, 17);
jLabel17.setText(" /");
jPanel2.add(jLabel17);
jLabel17.setBounds(780, 170, 30, 15);
txtConsultaMes.setBackground(new java.awt.Color(204, 204, 204));
txtConsultaMes.setText("Consulta del mes ");
txtConsultaMes.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(102, 255, 204), new java.awt.Color(0, 204, 204)));
txtConsultaMes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtConsultaMesActionPerformed(evt);
}
});
jPanel2.add(txtConsultaMes);
txtConsultaMes.setBounds(660, 210, 180, 19);
jLabel18.setForeground(new java.awt.Color(255, 255, 255));
jLabel18.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyectof/5765321-azul-de-fondo-de-burbujas-vector-de-la-ilustración-.jpg"))); // NOI18N
jLabel18.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel2.add(jLabel18);
jLabel18.setBounds(-350, -60, 1550, 760);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 907, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtIdServiciosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdServiciosActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtIdServiciosActionPerformed
private void txtPrecioTotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPrecioTotalActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPrecioTotalActionPerformed
private void txtDiaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDiaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtDiaActionPerformed
private void btModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btModificarActionPerformed
int idServicios,NumeroPrendas,idClientes,idEmpleados;
float PrecioTotal;
String fecha;
int idS,banderaS,idC,banderaC,idE,banderaE;
if(!txtIdServicios.getText().isEmpty() && !txtNumeroPrendas.getText().isEmpty() && !txtPrecioTotal.getText().isEmpty() && !txtDia.getText().isEmpty() && !txtMes.getText().isEmpty() && !txtAnio.getText().isEmpty() && !txtIdClientes.getText().isEmpty() && !txtidEmpleados.getText().isEmpty()){
if(txtIdServicios.getText().length()-1<9){
if(txtNumeroPrendas.getText().length()-1<9){
if(txtPrecioTotal.getText().length()-1<9){
if(txtDia.getText().length()-1<9 && txtMes.getText().length()-1<9 && txtAnio.getText().length()-1<9){
if(txtIdClientes.getText().length()-1<9){
if(txtidEmpleados.getText().length()-1<9){
idS=Integer.parseInt(txtIdServicios.getText());
banderaS=LS.Acceder(idS);
idC=Integer.parseInt(txtIdClientes.getText());
banderaC=LC.Acceder(idC);
idE=Integer.parseInt(txtidEmpleados.getText());
banderaE=LE.Acceder(idE);
if(banderaS!=0){
if(banderaC!=0){
if(banderaE!=0){
int dia=Integer.parseInt(txtDia.getText());
int mes= Integer.parseInt(txtMes.getText());
int anio=Integer.parseInt(txtAnio.getText());
if(dia>=1 && dia<=31 && mes>=1 && mes<=12){
idServicios=Integer.parseInt(txtIdServicios.getText());
NumeroPrendas=Integer.parseInt(txtNumeroPrendas.getText());
PrecioTotal=Float.parseFloat(txtPrecioTotal.getText());
fecha= txtAnio.getText()+"/"+txtMes.getText()+"/"+txtDia.getText();
idClientes=Integer.parseInt(txtIdClientes.getText());
idEmpleados=Integer.parseInt(txtidEmpleados.getText());
respuesta=LS.updateDatos(idServicios, NumeroPrendas, PrecioTotal, fecha, idClientes, idEmpleados);
}
else{
JOptionPane.showMessageDialog(null, "DIgito mal la fecha");
}
}else{
JOptionPane.showMessageDialog(null, "no existe ese Empleado");
}
}else{
JOptionPane.showMessageDialog(null, "no existe ese cliente");
}
}else{
JOptionPane.showMessageDialog(null, "no se puede modificar ya que no existe ese servicio");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado de los limites de digitos en el idEmpleados");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en los limites de digitos en el idClientes");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de digitos en la fecha de registro");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado de los limites de digitos en el Precio Total");
}
}else{
JOptionPane.showMessageDialog(null, "se ha pasado en el limite de digitos en el numero de Prendas");
}
}else{
JOptionPane.showMessageDialog(null, "se ha pasado en el limite de digitos en el idServicios");
}
}else{
JOptionPane.showMessageDialog(null, "NO ha llenado todos los campos necesarios");
}
Limpiar();
}//GEN-LAST:event_btModificarActionPerformed
private void btEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEliminarActionPerformed
// TODO add your handling code here:
int idS,banderaS;
if(!txtIdServicios.getText().isEmpty()){
if(txtIdServicios.getText().length()-1<9){
idS=Integer.parseInt(txtIdServicios.getText());
banderaS=LS.Acceder(idS);
if(banderaS!=0){
int idServicios=Integer.parseInt(txtIdServicios.getText());
LS.deleteDatos(idServicios);
}else{
JOptionPane.showMessageDialog(null, "no se pudo elimiinar ya que no existe ese servicio");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en los limites de digitos en el idServicios");
}
}else{
JOptionPane.showMessageDialog(null, "no ha llenado el campo idServicios y no se sabe cual servicio vamos a eliminar");
}
Limpiar();
}//GEN-LAST:event_btEliminarActionPerformed
private void btMostrarTodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btMostrarTodoActionPerformed
// TODO add your handling code here:
listar();
}//GEN-LAST:event_btMostrarTodoActionPerformed
private void btRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRegistrarActionPerformed
// TODO add your handling code here:
int idS,banderaS,idC,banderaC,idE,banderaE;
int idServicios,NumeroPrendas,idClientes,idEmpleados;
float PrecioTotal;
String fecha;
if(!txtIdServicios.getText().isEmpty() && !txtNumeroPrendas.getText().isEmpty() && !txtPrecioTotal.getText().isEmpty() && !txtDia.getText().isEmpty() && !txtMes.getText().isEmpty() && !txtAnio.getText().isEmpty() && !txtIdClientes.getText().isEmpty() && !txtidEmpleados.getText().isEmpty()){
if(txtIdServicios.getText().length()-1<9){
if(txtNumeroPrendas.getText().length()-1<9){
if(txtPrecioTotal.getText().length()-1<9){
if(txtDia.getText().length()-1<9 && txtMes.getText().length()-1<9 && txtAnio.getText().length()-1<9){
if(txtIdClientes.getText().length()-1<9){
if(txtidEmpleados.getText().length()-1<9){
idS=Integer.parseInt(txtIdServicios.getText());
banderaS=LS.Acceder(idS);
idC=Integer.parseInt(txtIdClientes.getText());
banderaC=LC.Acceder(idC);
idE=Integer.parseInt(txtidEmpleados.getText());
banderaE=LE.Acceder(idE);
if(banderaS==0){
if(banderaC!=0){
if(banderaE!=0){
int dia=Integer.parseInt(txtDia.getText());
int mes= Integer.parseInt(txtMes.getText());
int anio=Integer.parseInt(txtAnio.getText());
if(dia>=1 && dia<=31 && mes>=1 && mes<=12){
idServicios=Integer.parseInt(txtIdServicios.getText());
NumeroPrendas=Integer.parseInt(txtNumeroPrendas.getText());
PrecioTotal=Float.parseFloat(txtPrecioTotal.getText());
fecha= txtAnio.getText()+"/"+txtMes.getText()+"/"+txtDia.getText();
idClientes=Integer.parseInt(txtIdClientes.getText());
idEmpleados=Integer.parseInt(txtidEmpleados.getText());
respuesta=LS.insertDatos(idServicios, NumeroPrendas, PrecioTotal, fecha, idClientes, idEmpleados);
}else{
JOptionPane.showMessageDialog(null, "Digito mal la fecha");
}
}else{
JOptionPane.showMessageDialog(null, "No existe ese empleado con id");
}
}else{
JOptionPane.showMessageDialog(null, "no existe ese cliente");
}
}else{
JOptionPane.showMessageDialog(null, "existe un servicio con ese mismo id");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el numero de digitos de idEmpleados");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el numero de digitos de idClientes");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de digitos en la fecha");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado en el limite de digitos en el Precio");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado del limite de digitos en el numero de prendas");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado del limite de digitos en el idServicios");
}
}else{
JOptionPane.showMessageDialog(null,"usted no ha llenado los campos necesarios");
}
Limpiar();
}//GEN-LAST:event_btRegistrarActionPerformed
private void btConsultaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConsultaActionPerformed
// TODO add your handling code here:
int idS,banderaS;
if(!txtConsulta.getText().isEmpty()){
if(txtConsulta.getText().length()-1<9){
idS=Integer.parseInt(txtConsulta.getText());
banderaS=LS.Acceder(idS);
if(banderaS!=0){
int id=Integer.parseInt(txtConsulta.getText());
jTable1.setModel(LS.getDato(id));
}else{
JOptionPane.showMessageDialog(null, "no se pudo realizar la consulta ya que no existe ese servicio");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado de los limites de digitos en consulta");
}
}else{
JOptionPane.showMessageDialog(null, "No ha llenado el campo consulta");
}
Limpiar();
}//GEN-LAST:event_btConsultaActionPerformed
private void btMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btMenuActionPerformed
MenuPrincipal menu=new MenuPrincipal();
menu.setLocationRelativeTo(null);
menu.setSize(708, 402);
menu.setVisible(true);
this.dispose();
}//GEN-LAST:event_btMenuActionPerformed
private void txtIdClientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdClientesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtIdClientesActionPerformed
private void txtidEmpleadosKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtidEmpleadosKeyTyped
// TODO add your handling code here
char car= evt.getKeyChar();
if(car<'0' || car>'9'){
evt.consume();
}
}//GEN-LAST:event_txtidEmpleadosKeyTyped
private void txtConsultaMesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtConsultaMesActionPerformed
String FechaInicial,FechaFinal;
int diaI,mesI,anioI;
int diaF,mesF,anioF;
if(!txtDiaInicialConsulta.getText().isEmpty() && !txtMesInicialConsulta.getText().isEmpty() && !txtAnioInicialConsulta.getText().isEmpty() && !txtDiaFinalconsulta.getText().isEmpty() && !txtMesFinalConsulta.getText().isEmpty() && !txtAnioFInalconsulta.getText().isEmpty()){
if(txtDiaInicialConsulta.getText().length()-1<9 && txtMesInicialConsulta.getText().length()-1<9 && txtAnioInicialConsulta.getText().length()-1<9){
if(txtDiaFinalconsulta.getText().length()-1<9 && txtMesFinalConsulta.getText().length()-1<9 && txtAnioFInalconsulta.getText().length()-1<9){
diaI=Integer.parseInt(txtDiaInicialConsulta.getText());
mesI=Integer.parseInt(txtMesInicialConsulta.getText());
anioI=Integer.parseInt(txtAnioInicialConsulta.getText());
diaF=Integer.parseInt(txtDiaFinalconsulta.getText());
mesF=Integer.parseInt(txtMesFinalConsulta.getText());
anioF=Integer.parseInt(txtAnioFInalconsulta.getText());
if(diaI>=1 && diaI<=31 && mesI>=1 && mesI<=12 && diaF>=1 &&diaF<=31 && mesF>=1 && mesF<=12 ){
FechaInicial=txtAnioInicialConsulta.getText()+"/"+txtMesInicialConsulta.getText()+"/"+txtDiaInicialConsulta.getText();
FechaFinal=txtAnioFInalconsulta.getText()+"/"+txtMesFinalConsulta.getText()+"/"+txtDiaFinalconsulta.getText();
jTable1.setModel(LS.getFecha(FechaInicial, FechaFinal));
}else{
JOptionPane.showMessageDialog(null, "verifique que los dias y meses sean correctos");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado de los limites de digitos en la fecha final");
}
}else{
JOptionPane.showMessageDialog(null, "Se ha pasado de los limites de digitos en la fecha inicial");
}
}else{
JOptionPane.showMessageDialog(null, "ha dejado campos sin llenar");
}
Limpiar();
}//GEN-LAST:event_txtConsultaMesActionPerformed
private void txtDiaInicialConsultaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDiaInicialConsultaKeyTyped
// TODO add your handling code here:
char car= evt.getKeyChar();
if(car<'0' || car>'9'){
evt.consume();
}
}//GEN-LAST:event_txtDiaInicialConsultaKeyTyped
private void txtDiaInicialConsultaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDiaInicialConsultaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtDiaInicialConsultaActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btConsulta;
private javax.swing.JButton btEliminar;
private javax.swing.JButton btMenu;
private javax.swing.JButton btModificar;
private javax.swing.JButton btMostrarTodo;
private javax.swing.JButton btRegistrar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField txtAnio;
private javax.swing.JTextField txtAnioFInalconsulta;
private javax.swing.JTextField txtAnioInicialConsulta;
private javax.swing.JTextField txtConsulta;
private javax.swing.JButton txtConsultaMes;
private javax.swing.JTextField txtDia;
private javax.swing.JTextField txtDiaFinalconsulta;
private javax.swing.JTextField txtDiaInicialConsulta;
private javax.swing.JTextField txtIdClientes;
private javax.swing.JTextField txtIdServicios;
private javax.swing.JTextField txtMes;
private javax.swing.JTextField txtMesFinalConsulta;
private javax.swing.JTextField txtMesInicialConsulta;
private javax.swing.JTextField txtNumeroPrendas;
private javax.swing.JTextField txtPrecioTotal;
private javax.swing.JTextField txtidEmpleados;
// End of variables declaration//GEN-END:variables
int respuesta;
public Conectar cc= new Conectar();
public Connection cn= cc.getConnection();
}
|
7ca32cd17959c81f3b2dad56d2ed8b37f178eec9
|
[
"Java",
"SQL",
"INI"
] | 6
|
Java
|
luis5648/tintoreria
|
1d78643e80dbc9863c9a1d1e51c1faa0dd29590b
|
b9696eddb3ec015a060e4659e8e9d0f9d3ac5467
|
refs/heads/main
|
<file_sep>// Copyright 2011 <NAME>
// Copyright 2013, 2017-2018 Cray, Inc.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Cray C++ compiler setup.
//
// There are a few parameters that affect the macros defined in this file:
//
// - What version of CCE (Cray Compiling Environment) are we running? This
// comes from the '_RELEASE_MAJOR', '_RELEASE_MINOR', and
// '_RELEASE_PATCHLEVEL' macros.
// - What C++ standards conformance level are we using (e.g. '-h
// std=c++14')? This comes from the '__cplusplus' macro.
// - Are we using GCC extensions ('-h gnu' or '-h nognu')? If we have '-h
// gnu' then CCE emulates GCC, and the macros '__GNUC__',
// '__GNUC_MINOR__', and '__GNUC_PATCHLEVEL__' are defined.
//
// This file is organized as follows:
//
// - Verify that the combination of parameters listed above is supported.
// If we have an unsupported combination, we abort with '#error'.
// - Establish baseline values for all Boost macros.
// - Apply changes to the baseline macros based on compiler version. These
// changes are cummulative so each version section only describes the
// changes since the previous version.
// - Within each version section, we may also apply changes based on
// other parameters (i.e. C++ standards conformance level and GCC
// extensions).
//
// To test changes to this file:
//
// ```
// module load cce/8.6.5 # Pick the version you want to test.
// cd bho/libs/config/test/all
// b2 -j 8 toolset=cray cxxstd=03 cxxstd=11 cxxstd=14 cxxstd-dialect=gnu linkflags=-lrt
// ```
// Note: Using 'cxxstd-dialect=iso' is not supported at this time (the
// tests run, but many tests fail).
//
// Note: 'linkflags=-lrt' is needed in Cray Linux Environment. Otherwise
// you get an 'undefined reference to clock_gettime' error.
//
// Note: If a test '*_fail.cpp' file compiles, but fails to run, then it is
// reported as a defect. However, this is not actually a defect. This is an
// area where the test system is somewhat broken. Tests that are failing
// because of this problem are noted in the comments.
//
// Pay attention to the macro definitions for the macros you wish to
// modify. For example, only macros categorized as compiler macros should
// appear in this file; platform macros should not appear in this file.
// Also, some macros have to be defined to specific values; it is not
// always enough to define or undefine a macro.
//
// Macro definitions are available in the source code at:
//
// `bho/libs/config/doc/html/boost_config/boost_macro_reference.html`
//
// Macro definitions are also available online at:
//
// http://www.boost.org/doc/libs/master/libs/config/doc/html/boost_config/boost_macro_reference.html
//
// Typically, if you enable a feature, and the tests pass, then you have
// nothing to worry about. However, it's sometimes hard to figure out if a
// disabled feature needs to stay disabled. To get a list of disabled
// features, run 'b2' in 'bho/libs/config/checks'. These are the macros
// you should pay attention to (in addition to macros that cause test
// failures).
////
//// Front matter
////
// In a developer build of the Cray compiler (i.e. a compiler built by a
// Cray employee), the release patch level is reported as "x". This gives
// versions that look like e.g. "8.6.x".
//
// To accomplish this, the the Cray compiler preprocessor inserts:
//
// #define _RELEASE_PATCHLEVEL x
//
// If we are using a developer build of the compiler, we want to use the
// configuration macros for the most recent patch level of the release. To
// accomplish this, we'll pretend that _RELEASE_PATCHLEVEL is 99.
//
// However, it's difficult to detect if _RELEASE_PATCHLEVEL is x. We must
// consider that the x will be expanded if x is defined as a macro
// elsewhere. For example, imagine if someone put "-D x=3" on the command
// line, and _RELEASE_PATCHLEVEL is x. Then _RELEASE_PATCHLEVEL would
// expand to 3, and we could not distinguish it from an actual
// _RELEASE_PATCHLEVEL of 3. This problem only affects developer builds; in
// production builds, _RELEASE_PATCHLEVEL is always an integer.
//
// IMPORTANT: In developer builds, if x is defined as a macro, you will get
// an incorrect configuration. The behavior in this case is undefined.
//
// Even if x is not defined, we have to use some trickery to detect if
// _RELEASE_PATCHLEVEL is x. First we define BHO_CRAY_x to some arbitrary
// magic value, 9867657. Then we use BHO_CRAY_APPEND to append the
// expanded value of _RELEASE_PATCHLEVEL to the string "BHO_CRAY_".
//
// - If _RELEASE_PATCHLEVEL is undefined, we get "BHO_CRAY_".
// - If _RELEASE_PATCHLEVEL is 5, we get "BHO_CRAY_5".
// - If _RELEASE_PATCHLEVEL is x (and x is not defined) we get
// "BHO_CRAY_x":
//
// Then we check if BHO_CRAY_x is equal to the output of
// BHO_CRAY_APPEND. In other words, the output of BHO_CRAY_APPEND is
// treated as a macro name, and expanded again. If we can safely assume
// that BHO_CRAY_ is not a macro defined as our magic number, and
// BHO_CRAY_5 is not a macro defined as our magic number, then the only
// way the equality test can pass is if _RELEASE_PATCHLEVEL expands to x.
//
// So, that is how we detect if we are using a developer build of the Cray
// compiler.
#define BHO_CRAY_x 9867657 // Arbitrary number
#define BHO_CRAY_APPEND(MACRO) BHO_CRAY_APPEND_INTERNAL(MACRO)
#define BHO_CRAY_APPEND_INTERNAL(MACRO) BHO_CRAY_##MACRO
#if BHO_CRAY_x == BHO_CRAY_APPEND(_RELEASE_PATCHLEVEL)
// This is a developer build.
//
// - _RELEASE_PATCHLEVEL is defined as x, and x is not defined as a macro.
// Pretend _RELEASE_PATCHLEVEL is 99, so we get the configuration for the
// most recent patch level in this release.
#define BHO_CRAY_VERSION (_RELEASE_MAJOR * 10000 + _RELEASE_MINOR * 100 + 99)
#else
// This is a production build.
//
// _RELEASE_PATCHLEVEL is not defined as x, or x is defined as a macro.
#define BHO_CRAY_VERSION (_RELEASE_MAJOR * 10000 + _RELEASE_MINOR * 100 + _RELEASE_PATCHLEVEL)
#endif // BHO_CRAY_x == BHO_CRAY_APPEND(_RELEASE_PATCHLEVEL)
#undef BHO_CRAY_APPEND_INTERNAL
#undef BHO_CRAY_APPEND
#undef BHO_CRAY_x
#ifdef __GNUC__
# define BHO_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
#ifndef BHO_COMPILER
# define BHO_COMPILER "Cray C++ version " BHO_STRINGIZE(_RELEASE_MAJOR) "." BHO_STRINGIZE(_RELEASE_MINOR) "." BHO_STRINGIZE(_RELEASE_PATCHLEVEL)
#endif
// Since the Cray compiler defines '__GNUC__', we have to emulate some
// additional GCC macros in order to make everything work.
//
// FIXME: Perhaps Cray should fix the compiler to define these additional
// macros for GCC emulation?
#if __cplusplus >= 201103L && defined(__GNUC__) && !defined(__GXX_EXPERIMENTAL_CXX0X__)
# define __GXX_EXPERIMENTAL_CXX0X__ 1
#endif
////
//// Parameter validation
////
// FIXME: Do we really need to support compilers before 8.5? Do they pass
// the Boost.Config tests?
#if BHO_CRAY_VERSION < 80000
# error "Boost is not configured for Cray compilers prior to version 8, please try the configure script."
#endif
// We only support recent EDG based compilers.
#ifndef __EDG__
# error "Unsupported Cray compiler, please try running the configure script."
#endif
////
//// Baseline values
////
#include <asio2/bho/config/compiler/common_edg.hpp>
#define BHO_HAS_NRVO
#define BHO_NO_COMPLETE_VALUE_INITIALIZATION
#define BHO_NO_CXX11_AUTO_DECLARATIONS
#define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#define BHO_NO_CXX11_CHAR16_T
#define BHO_NO_CXX11_CHAR32_T
#define BHO_NO_CXX11_CONSTEXPR
#define BHO_NO_CXX11_DECLTYPE
#define BHO_NO_CXX11_DECLTYPE_N3276
#define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#define BHO_NO_CXX11_DELETED_FUNCTIONS
#define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#define BHO_NO_CXX11_FINAL
#define BHO_NO_CXX11_OVERRIDE
#define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define BHO_NO_CXX11_LAMBDAS
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_RAW_LITERALS
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_RVALUE_REFERENCES
#define BHO_NO_CXX11_SCOPED_ENUMS
#define BHO_NO_CXX11_SFINAE_EXPR
#define BHO_NO_CXX11_STATIC_ASSERT
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_UNICODE_LITERALS
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#define BHO_NO_CXX11_USER_DEFINED_LITERALS
#define BHO_NO_CXX11_VARIADIC_MACROS
#define BHO_NO_CXX11_VARIADIC_TEMPLATES
#define BHO_NO_CXX11_UNRESTRICTED_UNION
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_TWO_PHASE_NAME_LOOKUP
//#define BHO_BCB_PARTIAL_SPECIALIZATION_BUG
#define BHO_MATH_DISABLE_STD_FPCLASSIFY
//#define BHO_HAS_FPCLASSIFY
#define BHO_SP_USE_PTHREADS
#define BHO_AC_USE_PTHREADS
//
// Everything that follows is working around what are thought to be
// compiler shortcomings. Revist all of these regularly.
//
//#define BHO_USE_ENUM_STATIC_ASSERT
//#define BHO_BUGGY_INTEGRAL_CONSTANT_EXPRESSIONS //(this may be implied by the previous #define
// These constants should be provided by the compiler.
#ifndef __ATOMIC_RELAXED
#define __ATOMIC_RELAXED 0
#define __ATOMIC_CONSUME 1
#define __ATOMIC_ACQUIRE 2
#define __ATOMIC_RELEASE 3
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_SEQ_CST 5
#endif
////
//// Version changes
////
//
// 8.5.0
//
#if BHO_CRAY_VERSION >= 80500
#if __cplusplus >= 201103L
#undef BHO_HAS_NRVO
#undef BHO_NO_COMPLETE_VALUE_INITIALIZATION
#undef BHO_NO_CXX11_AUTO_DECLARATIONS
#undef BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#undef BHO_NO_CXX11_CHAR16_T
#undef BHO_NO_CXX11_CHAR32_T
#undef BHO_NO_CXX11_CONSTEXPR
#undef BHO_NO_CXX11_DECLTYPE
#undef BHO_NO_CXX11_DECLTYPE_N3276
#undef BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#undef BHO_NO_CXX11_DELETED_FUNCTIONS
#undef BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#undef BHO_NO_CXX11_FINAL
#undef BHO_NO_CXX11_OVERRIDE
#undef BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#undef BHO_NO_CXX11_LAMBDAS
#undef BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#undef BHO_NO_CXX11_NOEXCEPT
#undef BHO_NO_CXX11_NULLPTR
#undef BHO_NO_CXX11_RANGE_BASED_FOR
#undef BHO_NO_CXX11_RAW_LITERALS
#undef BHO_NO_CXX11_REF_QUALIFIERS
#undef BHO_NO_CXX11_RVALUE_REFERENCES
#undef BHO_NO_CXX11_SCOPED_ENUMS
#undef BHO_NO_CXX11_SFINAE_EXPR
#undef BHO_NO_CXX11_STATIC_ASSERT
#undef BHO_NO_CXX11_TEMPLATE_ALIASES
#undef BHO_NO_CXX11_THREAD_LOCAL
#undef BHO_NO_CXX11_UNICODE_LITERALS
#undef BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#undef BHO_NO_CXX11_USER_DEFINED_LITERALS
#undef BHO_NO_CXX11_VARIADIC_MACROS
#undef BHO_NO_CXX11_VARIADIC_TEMPLATES
#undef BHO_NO_CXX11_UNRESTRICTED_UNION
#undef BHO_NO_SFINAE_EXPR
#undef BHO_NO_TWO_PHASE_NAME_LOOKUP
#undef BHO_MATH_DISABLE_STD_FPCLASSIFY
#undef BHO_SP_USE_PTHREADS
#undef BHO_AC_USE_PTHREADS
#define BHO_HAS_VARIADIC_TMPL
#define BHO_HAS_UNISTD_H
#define BHO_HAS_TR1_COMPLEX_INVERSE_TRIG
#define BHO_HAS_TR1_COMPLEX_OVERLOADS
#define BHO_HAS_STDINT_H
#define BHO_HAS_STATIC_ASSERT
#define BHO_HAS_SIGACTION
#define BHO_HAS_SCHED_YIELD
#define BHO_HAS_RVALUE_REFS
#define BHO_HAS_PTHREADS
#define BHO_HAS_PTHREAD_YIELD
#define BHO_HAS_PTHREAD_MUTEXATTR_SETTYPE
#define BHO_HAS_PARTIAL_STD_ALLOCATOR
#define BHO_HAS_NRVO
#define BHO_HAS_NL_TYPES_H
#define BHO_HAS_NANOSLEEP
#define BHO_NO_CXX11_SMART_PTR
#define BHO_NO_CXX11_HDR_FUNCTIONAL
#define BHO_NO_CXX14_CONSTEXPR
#define BHO_HAS_LONG_LONG
#define BHO_HAS_FLOAT128
#if __cplusplus < 201402L
#define BHO_NO_CXX11_DECLTYPE_N3276
#endif // __cplusplus < 201402L
#endif // __cplusplus >= 201103L
#endif // BHO_CRAY_VERSION >= 80500
//
// 8.6.4
// (versions prior to 8.6.5 do not define _RELEASE_PATCHLEVEL)
//
#if BHO_CRAY_VERSION >= 80600
#if __cplusplus >= 199711L
#define BHO_HAS_FLOAT128
#define BHO_HAS_PTHREAD_YIELD // This is a platform macro, but it improves test results.
#define BHO_NO_COMPLETE_VALUE_INITIALIZATION // This is correct. Test compiles, but fails to run.
#undef BHO_NO_CXX11_CHAR16_T
#undef BHO_NO_CXX11_CHAR32_T
#undef BHO_NO_CXX11_INLINE_NAMESPACES
#undef BHO_NO_CXX11_FINAL
#undef BHO_NO_CXX11_OVERRIDE
#undef BHO_NO_CXX11_FIXED_LENGTH_VARIADIC_TEMPLATE_EXPANSION_PACKS
#undef BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define BHO_NO_CXX11_SFINAE_EXPR // This is correct, even though '*_fail.cpp' test fails.
#undef BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#undef BHO_NO_CXX11_VARIADIC_MACROS
#undef BHO_NO_CXX11_VARIADIC_TEMPLATES
// 'BHO_NO_DEDUCED_TYPENAME' test is broken. The test files are enabled /
// disabled with an '#ifdef BHO_DEDUCED_TYPENAME'. However,
// 'bho/libs/config/include/bho/config/detail/suffix.hpp' ensures that
// 'BHO_DEDUCED_TYPENAME' is always defined (the value it is defined as
// depends on 'BHO_NO_DEDUCED_TYPENAME'). So, modifying
// 'BHO_NO_DEDUCED_TYPENAME' has no effect on which tests are run.
//
// The 'no_ded_typename_pass.cpp' test should always compile and run
// successfully, because 'BHO_DEDUCED_TYPENAME' must always have an
// appropriate value (it's not just something that you turn on or off).
// Therefore, if you wish to test changes to 'BHO_NO_DEDUCED_TYPENAME',
// you have to modify 'no_ded_typename_pass.cpp' to unconditionally include
// 'boost_no_ded_typename.ipp'.
#undef BHO_NO_DEDUCED_TYPENAME // This is correct. Test is broken.
#undef BHO_NO_SFINAE_EXPR
#undef BHO_NO_TWO_PHASE_NAME_LOOKUP
#endif // __cplusplus >= 199711L
#if __cplusplus >= 201103L
#undef BHO_NO_CXX11_ALIGNAS
#undef BHO_NO_CXX11_DECLTYPE_N3276
#define BHO_NO_CXX11_HDR_ATOMIC
#undef BHO_NO_CXX11_HDR_FUNCTIONAL
#define BHO_NO_CXX11_HDR_REGEX // This is correct. Test compiles, but fails to run.
#undef BHO_NO_CXX11_SFINAE_EXPR
#undef BHO_NO_CXX11_SMART_PTR
#undef BHO_NO_CXX11_TRAILING_RESULT_TYPES
#endif // __cplusplus >= 201103L
#if __cplusplus >= 201402L
#undef BHO_NO_CXX14_CONSTEXPR
#define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif // __cplusplus == 201402L
#endif // BHO_CRAY_VERSION >= 80600
//
// 8.6.5
// (no change from 8.6.4)
//
//
// 8.7.0
//
#if BHO_CRAY_VERSION >= 80700
#if __cplusplus >= 199711L
#endif // __cplusplus >= 199711L
#if __cplusplus >= 201103L
#undef BHO_NO_CXX11_HDR_ATOMIC
#undef BHO_NO_CXX11_HDR_REGEX
#endif // __cplusplus >= 201103L
#if __cplusplus >= 201402L
#endif // __cplusplus == 201402L
#endif // BHO_CRAY_VERSION >= 80700
//
// Next release
//
#if BHO_CRAY_VERSION > 80799
#if __cplusplus >= 199711L
#endif // __cplusplus >= 199711L
#if __cplusplus >= 201103L
#endif // __cplusplus >= 201103L
#if __cplusplus >= 201402L
#endif // __cplusplus == 201402L
#endif // BHO_CRAY_VERSION > 80799
////
//// Remove temporary macros
////
// I've commented out some '#undef' statements to signify that we purposely
// want to keep certain macros.
//#undef __GXX_EXPERIMENTAL_CXX0X__
//#undef BHO_COMPILER
#undef BHO_GCC_VERSION
#undef BHO_CRAY_VERSION
<file_sep>#include "unit_test.hpp"
#include <asio2/util/md5.hpp>
void md5_test()
{
asio2::md5 md5;
std::string src = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
ASIO2_CHECK(asio2::md5(src).str(true ) == "B9B3CC3F3A30D8EF2BB1E2E267ED97DE");
ASIO2_CHECK(asio2::md5(src).str(false) == "b9b3cc3f3a30d8ef2bb1e2e267ed97de");
}
ASIO2_TEST_SUITE
(
"md5",
ASIO2_TEST_CASE(md5_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_EXTERNAL_PFR_HPP__
#define __ASIO2_EXTERNAL_PFR_HPP__
#include <asio2/external/config.hpp>
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/core/type_name.hpp>)
#include <boost/core/type_name.hpp>
#else
#include <asio2/bho/core/type_name.hpp>
#endif
#include <string>
#include <unordered_map>
#include <memory>
#include <functional>
#include <type_traits>
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/pfr.hpp>)
#include <boost/pfr.hpp>
namespace pfr = ::boost::pfr;
#else
#include <asio2/bho/pfr.hpp>
namespace pfr = ::bho::pfr;
#endif
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/pfr.hpp>)
namespace boost::pfr
#else
namespace bho::pfr
#endif
{
namespace detail
{
template<int N> struct refl_encode_counter : refl_encode_counter<N - 1> {};
template<> struct refl_encode_counter<0> {};
struct __refl_members_iterator_dummy__
{
template<typename ThisType, typename Func>
static inline void for_each_field(ThisType&, Func&)
{
}
template<typename Func>
static inline void for_each_field_name(Func&)
{
}
};
}
//---------------------------------------------------------------------------------------------
// this code is refrenced from : https://zhuanlan.zhihu.com/p/320061875
// this code has some unresolved problems.
// eg:
// struct actor : public dynamic_creator<actor, std::string, const char*>
// create<actor>("abc", "xyz");
// the create function will failed, beacuse the "abc" type is not equal to std::string, and the
// "xyz" type is not equal to const char*
// you must call the create function like this:
// create<actor>(std::string("abc"), (const char*)"xyz");
// This is terrible.
// Is it possible to use serialization to solve this problem?
//---------------------------------------------------------------------------------------------
template<typename BaseT, typename... Args>
class class_factory
{
private:
class_factory() {}
~class_factory() {}
public:
static class_factory<BaseT, Args...>& instance()
{
static class_factory<BaseT, Args...> inst{};
return inst;
}
bool regist(std::string name, std::function<BaseT*(Args&&... args)> fn)
{
if (!fn)
return(false);
return create_functions_.emplace(std::move(name), std::move(fn)).second;
}
BaseT* create(const std::string& name, Args&&... args)
{
auto iter = create_functions_.find(name);
if (iter == create_functions_.end())
{
return (nullptr);
}
else
{
return ((iter->second)(std::forward<Args>(args)...));
}
}
private:
std::unordered_map<std::string, std::function<BaseT*(Args&&...)>> create_functions_;
};
template<typename BaseT, typename T, typename ...Args>
class base_dynamic_creator
{
public:
struct registor
{
registor()
{
std::string name;
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/core/type_name.hpp>)
name = boost::core::type_name<T>();
#else
name = bho::core::type_name<T>();
#endif
class_factory<BaseT, Args...>::instance().regist(std::move(name), create);
}
inline void makesure_construct() const noexcept { };
};
explicit base_dynamic_creator() noexcept
{
registor_.makesure_construct();
}
virtual ~base_dynamic_creator() noexcept
{
registor_.makesure_construct();
};
private:
static BaseT* create(Args&&... args)
{
return (new T(std::forward<Args>(args)...));
}
private:
static inline registor registor_{};
};
template<typename BaseT, typename T, typename ...Args>
using dynamic_creator = base_dynamic_creator<BaseT, T, Args...>;
template<typename T, typename ...Args>
class self_dynamic_creator
{
public:
struct registor
{
registor()
{
std::string name;
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/core/type_name.hpp>)
name = boost::core::type_name<T>();
#else
name = bho::core::type_name<T>();
#endif
class_factory<T, Args...>::instance().regist(std::move(name), create);
}
inline void makesure_construct() const noexcept { };
};
explicit self_dynamic_creator() noexcept
{
registor_.makesure_construct();
}
virtual ~self_dynamic_creator() noexcept
{
registor_.makesure_construct();
};
private:
static T* create(Args&&... args)
{
return (new T(std::forward<Args>(args)...));
}
private:
static inline registor registor_{};
};
template<typename BaseT>
class create_helper
{
public:
// dont use Args&&... args
// it will cause issue like this:
// int i = 2;
// create("dog", i);
// the i will be parsed as int&
template<typename ...Args>
static inline BaseT* create(const std::string& name, Args... args)
{
return (class_factory<BaseT, Args...>::instance().create(
name, std::move(args)...));
}
};
template<typename BaseT>
class create_helper<BaseT*>
{
public:
template<typename ...Args>
static inline BaseT* create(const std::string& name, Args... args)
{
return (class_factory<BaseT, Args...>::instance().create(
name, std::move(args)...));
}
};
template<typename BaseT>
class create_helper<std::shared_ptr<BaseT>>
{
public:
template<typename ...Args>
static inline std::shared_ptr<BaseT> create(const std::string& name, Args... args)
{
return std::shared_ptr<BaseT>(class_factory<BaseT, Args...>::instance().create(
name, std::move(args)...));
}
};
template<typename BaseT>
class create_helper<std::unique_ptr<BaseT>>
{
public:
template<typename ...Args>
static inline std::unique_ptr<BaseT> create(const std::string& name, Args... args)
{
return std::unique_ptr<BaseT>(class_factory<BaseT, Args...>::instance().create(
name, std::move(args)...));
}
};
}
// this code is refrenced from :
// https://github.com/yuanzhubi/reflect_struct
// boost/typeof/dmc/typeof_impl.hpp
#ifndef MAX_REFLECT_COUNT
#define MAX_REFLECT_COUNT 480
#endif
#define BHO_REFLECT_INDEX(counter) \
((sizeof(*counter((pfr::detail::refl_encode_counter<MAX_REFLECT_COUNT>*)0)) - \
sizeof(*counter((void*)0))) / sizeof(char)) \
#define BHO_REFLECT_INCREASE(counter, index) \
static constexpr std::size_t index = BHO_REFLECT_INDEX(counter); \
static char (*counter(pfr::detail::refl_encode_counter< \
sizeof(*counter((void*)0)) / sizeof(char) + index + 1>*)) \
[sizeof(*counter((void*)0)) / sizeof(char) + index + 1]; \
#define BHO_REFLECT_FIELD_INDEX(name) ASIO2_JOIN(__reflect_index_, name)
#define F_FIELD_MEMBER_ITERATOR(type, name) \
private: \
BHO_REFLECT_INCREASE(__refl_field_counter__, BHO_REFLECT_FIELD_INDEX(name)) \
template <typename T> \
struct __refl_members_iterator__<T, BHO_REFLECT_FIELD_INDEX(name)> \
{ \
typedef __refl_members_iterator__<T, BHO_REFLECT_FIELD_INDEX(name) + 1> next_type; \
template<typename ThisType, typename Func> \
static void for_each_field(ThisType& This, Func& func) noexcept \
{ \
func(ASIO2_STRINGIZE(name), This.name); \
next_type::for_each_field(This, func); \
} \
template<typename Func> \
static void for_each_field_name(Func& func) noexcept \
{ \
func(ASIO2_STRINGIZE(name)); \
next_type::for_each_field_name(func); \
} \
} \
#define F_BEGIN(Class) \
private: \
static char (*__refl_field_counter__(...))[1]; \
template<typename T, int N = -1> struct __refl_members_iterator__ : \
public pfr::detail::__refl_members_iterator_dummy__{}; \
public: \
template<typename Func> \
void for_each_field(Func&& func) noexcept \
{ \
decltype(auto) fun = std::forward<Func>(func); \
__refl_members_iterator__<int, 0>::for_each_field(*this, fun); \
} \
template<typename Func> \
static void for_each_field_name(Func&& func) noexcept \
{ \
decltype(auto) fun = std::forward<Func>(func); \
__refl_members_iterator__<int, 0>::for_each_field_name(fun); \
} \
inline static constexpr std::string_view get_class_name() noexcept \
{ \
return ASIO2_STRINGIZE(Class); \
} \
template<typename T, int N> friend struct __refl_members_iterator__ \
#define F_FIELD(type, name) \
public: \
type name{}; \
F_FIELD_MEMBER_ITERATOR(type, name) \
#define F_END() \
public: \
constexpr static std::size_t get_field_count() noexcept \
{ \
constexpr std::size_t field_count = BHO_REFLECT_INDEX(__refl_field_counter__); \
return field_count; \
} \
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : mqtt_cpp/include/mqtt/broker/security.hpp
*/
#ifndef __ASIO2_MQTT_SECURITY_HPP__
#define __ASIO2_MQTT_SECURITY_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <algorithm>
#include <variant>
#include <map>
#include <set>
#include <optional>
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/iterator/function_output_iterator.hpp>)
#include <boost/iterator/function_output_iterator.hpp>
#else
#include <asio2/bho/iterator/function_output_iterator.hpp>
#endif
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/algorithm/hex.hpp>)
#include <boost/algorithm/hex.hpp>
#else
#include <asio2/bho/algorithm/hex.hpp>
#endif
#include <asio2/base/iopool.hpp>
#include <asio2/util/string.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
#if !defined(INCLUDE_NLOHMANN_JSON_HPP_) && !defined(NLOHMANN_JSON_HPP)
#include <asio2/external/json.hpp>
#endif
#include <asio2/mqtt/message.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
#include <asio2/mqtt/detail/mqtt_subscription_map.hpp>
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#include <openssl/evp.h>
#endif
namespace asio2::mqtt
{
struct security
{
static constexpr char const* any_group_name = "@any";
struct authentication
{
enum class method : std::uint8_t
{
sha256,
plain_password,
client_cert,
anonymous,
unauthenticated
};
authentication(
method auth_method = method::sha256,
std::optional<std::string> digest = std::nullopt,
std::string salt = std::string()
)
: auth_method(auth_method)
, digest(std::move(digest))
, salt(std::move(salt))
{
}
method auth_method;
std::optional<std::string> digest;
std::string salt;
std::vector<std::string> groups;
};
struct authorization
{
enum class type : std::uint8_t
{
deny, allow, none
};
authorization(std::string_view topic, std::size_t rule_nr)
: topic(topic)
, rule_nr(rule_nr)
, sub_type(type::none)
, pub_type(type::none)
{
}
std::vector<std::string> topic_tokens;
std::string topic;
std::size_t rule_nr;
type sub_type;
std::set<std::string> sub;
type pub_type;
std::set<std::string> pub;
};
struct group
{
std::string name;
std::vector<std::string> members;
};
/** Return username of anonymous user */
std::optional<std::string> const& login_anonymous() const
{
asio2::shared_locker g(this->security_mutex_);
return this->anonymous_;
}
/** Return username of unauthorized user */
std::optional<std::string> const& login_unauthenticated() const
{
asio2::shared_locker g(this->security_mutex_);
return this->unauthenticated_;
}
template<typename T>
static std::string to_hex(T start, T end)
{
std::string result;
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/algorithm/hex.hpp>)
boost::algorithm::hex(start, end, std::back_inserter(result));
#else
bho::algorithm::hex(start, end, std::back_inserter(result));
#endif
return result;
}
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
static std::string sha256hash(string_view message) {
std::shared_ptr<EVP_MD_CTX> mdctx(EVP_MD_CTX_new(), EVP_MD_CTX_free);
EVP_DigestInit_ex(mdctx.get(), EVP_sha256(), NULL);
EVP_DigestUpdate(mdctx.get(), message.data(), message.size());
std::vector<unsigned char> digest(static_cast<std::size_t>(EVP_MD_size(EVP_sha256())));
unsigned int digest_size = static_cast<unsigned int>(digest.size());
EVP_DigestFinal_ex(mdctx.get(), digest.data(), &digest_size);
return to_hex(digest.data(), digest.data() + digest_size);
}
#else
static std::string sha256hash(std::string_view message)
{
return std::string(message);
}
#endif
bool login_cert(std::string_view username) const
{
asio2::shared_locker g(this->security_mutex_);
auto i = authentication_.find(std::string(username));
return
i != authentication_.end() &&
i->second.auth_method == security::authentication::method::client_cert;
}
std::optional<std::string> login(std::string_view username, std::string_view password) const
{
asio2::shared_locker g(this->security_mutex_);
auto i = authentication_.find(std::string(username));
if (i != authentication_.end() &&
i->second.auth_method == security::authentication::method::sha256)
{
return [&]() -> std::optional<std::string>
{
if (asio2::iequals(
i->second.digest.value(),
sha256hash(i->second.salt + std::string(password))))
{
return std::string(username);
}
else
{
return std::nullopt;
}
} ();
}
else if (
i != authentication_.end() &&
i->second.auth_method == security::authentication::method::plain_password)
{
return [&]() -> std::optional<std::string>
{
if (i->second.digest.value() == password)
{
return std::string(username);
}
else
{
return std::nullopt;
}
} ();
}
return std::nullopt;
}
static authorization::type get_auth_type(std::string_view type)
{
if (type == "allow") return authorization::type::allow;
if (type == "deny") return authorization::type::deny;
throw std::runtime_error(
"An invalid authorization type was specified: " +
std::string(type)
);
}
static bool is_valid_group_name(std::string_view name)
{
return !name.empty() && name[0] == '@'; // TODO: validate utf-8
}
static bool is_valid_user_name(std::string_view name)
{
return !name.empty() && name[0] != '@'; // TODO: validate utf-8
}
std::size_t get_next_rule_nr() const
{
asio2::shared_locker g(this->security_mutex_);
return this->get_next_rule_nr_impl();
}
void default_config()
{
asio2::unique_locker g(this->security_mutex_);
char const* username = "anonymous";
authentication login(authentication::method::anonymous);
authentication_.emplace(username, login);
anonymous_ = username;
char const* topic = "#";
authorization auth(topic, get_next_rule_nr_impl());
auth.topic_tokens = get_topic_filter_tokens("#");
auth.sub_type = authorization::type::allow;
auth.sub.emplace(username);
auth.pub_type = authorization::type::allow;
auth.pub.emplace(username);
authorization_.push_back(auth);
groups_.emplace(std::string(any_group_name), group());
validate();
}
std::size_t add_auth(
std::string const& topic_filter,
std::set<std::string> const& pub,
authorization::type auth_pub_type,
std::set<std::string> const& sub,
authorization::type auth_sub_type
)
{
asio2::unique_locker g(this->security_mutex_);
for(auto const& j : pub)
{
if (!is_valid_user_name(j) && !is_valid_group_name(j))
{
throw std::runtime_error(
"An invalid username or groupname was specified for the authorization: " + j
);
}
validate_entry("topic " + topic_filter, j);
}
for(auto const& j : sub)
{
if (!is_valid_user_name(j) && !is_valid_group_name(j))
{
throw std::runtime_error(
"An invalid username or groupname was specified for the authorization: " + j
);
}
validate_entry("topic " + topic_filter, j);
}
std::size_t rule_nr = get_next_rule_nr_impl();
authorization auth(topic_filter, rule_nr);
auth.topic_tokens = get_topic_filter_tokens(topic_filter);
auth.pub = pub;
auth.pub_type = auth_pub_type;
auth.sub = sub;
auth.sub_type = auth_sub_type;
for (auto const& j: sub)
{
auth_sub_map_.insert_or_assign(
topic_filter,
j,
std::make_pair(auth_sub_type, rule_nr)
);
}
for (auto const& j: pub)
{
auth_pub_map_.insert_or_assign(
topic_filter,
j,
std::make_pair(auth_pub_type, rule_nr)
);
}
authorization_.push_back(auth);
return rule_nr;
}
void remove_auth(std::size_t rule_nr)
{
asio2::unique_locker g(this->security_mutex_);
for (auto i = authorization_.begin(); i != authorization_.end(); ++i)
{
if (i->rule_nr == rule_nr)
{
for (auto const& j : i->sub)
{
auth_sub_map_.erase(i->topic, j);
}
for (auto const& j : i->pub)
{
auth_pub_map_.erase(i->topic, j);
}
authorization_.erase(i);
return;
}
}
}
void add_sha256_authentication(std::string username, std::string digest, std::string salt)
{
asio2::unique_locker g(this->security_mutex_);
authentication auth(authentication::method::sha256, std::move(digest), std::move(salt));
authentication_.emplace(std::move(username), std::move(auth));
}
void add_plain_password_authentication(std::string username, std::string password)
{
asio2::unique_locker g(this->security_mutex_);
authentication auth(authentication::method::plain_password, std::move(password));
authentication_.emplace(std::move(username), std::move(auth));
}
void add_certificate_authentication(std::string username)
{
asio2::unique_locker g(this->security_mutex_);
authentication auth(authentication::method::client_cert);
authentication_.emplace(std::move(username), std::move(auth));
}
void load_json(std::istream& input)
{
using json = nlohmann::json;
json j;
input >> j;
asio2::unique_locker g(this->security_mutex_);
groups_.emplace(std::string(any_group_name), group());
if (auto& j_authentication = j["authentication"]; j_authentication.is_array())
{
for (auto& i : j_authentication)
{
auto& j_name = i["name"];
if (!j_name.is_string())
{
ASIO2_ASSERT(false);
continue;
}
std::string name = j_name.get<std::string>();
if (!is_valid_user_name(name))
{
ASIO2_ASSERT(false);
continue;
}
auto& j_method = i["method"];
if (!j_method.is_string())
{
ASIO2_ASSERT(false);
continue;
}
std::string method = j_method.get<std::string>();
if (method == "sha256")
{
auto& j_digest = i["digest"];
auto& j_salt = i["salt"];
if (j_digest.is_string())
{
std::string digest = j_digest.get<std::string>();
std::string salt;
if (j_salt.is_string())
salt = j_salt.get<std::string>();
authentication auth(authentication::method::sha256, std::move(digest), std::move(salt));
authentication_.emplace(std::move(name), std::move(auth));
}
}
else if (method == "plain_password")
{
auto& j_password = i["password"];
if (j_password.is_string())
{
std::string digest = j_password.get<std::string>();
authentication auth(authentication::method::plain_password, digest);
authentication_.emplace(std::move(name), std::move(auth));
}
}
else if (method == "client_cert")
{
authentication auth(authentication::method::client_cert);
authentication_.emplace(std::move(name), std::move(auth));
}
else if (method == "anonymous")
{
if (anonymous_)
{
ASIO2_ASSERT(false && "Only a single anonymous user can be configured");
}
else
{
anonymous_ = name;
authentication auth(authentication::method::anonymous);
authentication_.emplace(std::move(name), std::move(auth));
}
}
else if (method == "unauthenticated")
{
if (unauthenticated_)
{
ASIO2_ASSERT(false && "Only a single unauthenticated user can be configured");
}
else
{
unauthenticated_ = name;
authentication auth(authentication::method::unauthenticated);
authentication_.emplace(std::move(name), std::move(auth));
}
}
else
{
ASIO2_ASSERT(false);
}
}
}
if (auto& j_groups = j["groups"]; j_groups.is_array())
{
for (auto& i : j_groups)
{
auto& j_name = i["name"];
if (!j_name.is_string())
{
ASIO2_ASSERT(false);
continue;
}
std::string name = j_name.get<std::string>();
if (!is_valid_group_name(name))
{
ASIO2_ASSERT(false);
continue;
}
group group;
if (auto& j_members = j["members"]; j_members.is_array())
{
for (auto& j_username : j_members)
{
if (!j_username.is_string())
{
ASIO2_ASSERT(false);
continue;
}
auto username = j_username.get<std::string>();
if (!is_valid_user_name(username))
{
ASIO2_ASSERT(false);
continue;
}
group.members.emplace_back(std::move(username));
}
}
else
{
ASIO2_ASSERT(false);
}
groups_.emplace(std::move(name), std::move(group));
}
}
if (auto& j_authorization = j["authorization"]; j_authorization.is_array())
{
for (auto& i : j_authorization)
{
auto& j_name = i["topic"];
if (!j_name.is_string())
{
ASIO2_ASSERT(false);
continue;
}
std::string name = j_name.get<std::string>();
if (!validate_topic_filter(name))
{
ASIO2_ASSERT(false);
continue;
}
authorization auth(name, get_next_rule_nr_impl());
auth.topic_tokens = get_topic_filter_tokens(name);
if (auto& j_allow = i["allow"]; j_allow.is_object())
{
if (auto& j_sub = j_allow["sub"]; j_sub.is_array())
{
for (auto& j_username : j_sub)
{
if (j_username.is_string())
{
auth.sub.emplace(j_username.get<std::string>());
}
}
auth.sub_type = authorization::type::allow;
}
if (auto& j_pub = j_allow["pub"]; j_pub.is_array())
{
for (auto& j_username : j_pub)
{
if (j_username.is_string())
{
auth.pub.emplace(j_username.get<std::string>());
}
}
auth.pub_type = authorization::type::allow;
}
}
if (auto& j_deny = i["deny"]; j_deny.is_object())
{
if (auto& j_sub = j_deny["sub"]; j_sub.is_array())
{
for (auto& j_username : j_sub)
{
if (j_username.is_string())
{
auth.sub.emplace(j_username.get<std::string>());
}
}
auth.sub_type = authorization::type::deny;
}
if (auto& j_pub = j_deny["pub"]; j_pub.is_array())
{
for (auto& j_username : j_pub)
{
auth.pub.emplace(j_username.get<std::string>());
}
auth.pub_type = authorization::type::deny;
}
}
authorization_.emplace_back(std::move(auth));
}
}
validate();
}
template<typename T>
void get_auth_sub_by_user(std::string_view username, T&& callback) const
{
std::set<std::string> username_and_groups;
username_and_groups.insert(std::string(username));
asio2::shared_locker g(this->security_mutex_);
for (auto const& i : groups_)
{
if (i.first == any_group_name ||
std::find(i.second.members.begin(), i.second.members.end(), username) != i.second.members.end())
{
username_and_groups.insert(i.first);
}
}
for (auto const& i : authorization_)
{
if (i.sub_type != authorization::type::none)
{
bool sets_intersect = false;
auto store_intersect = [&sets_intersect](std::string const&) mutable
{
sets_intersect = true;
};
std::set_intersection(
i.sub.begin(),
i.sub.end(),
username_and_groups.begin(),
username_and_groups.end(),
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/iterator/function_output_iterator.hpp>)
boost::make_function_output_iterator(std::ref(store_intersect))
#else
bho::make_function_output_iterator(std::ref(store_intersect))
#endif
);
if (sets_intersect)
{
std::forward<T>(callback)(i);
}
}
}
}
authorization::type auth_pub(std::string_view topic, std::string_view username)
{
authorization::type result_type = authorization::type::deny;
std::set<std::string> username_and_groups;
username_and_groups.insert(std::string(username));
asio2::shared_locker g(this->security_mutex_);
for (auto const& i : groups_)
{
if (i.first == any_group_name ||
std::find(i.second.members.begin(), i.second.members.end(), username) != i.second.members.end())
{
username_and_groups.insert(i.first);
}
}
std::size_t priority = 0;
auth_pub_map_.match(topic,
[&](const std::string& allowed_username, std::pair<authorization::type, std::size_t>& entry) mutable
{
if (username_and_groups.find(allowed_username) != username_and_groups.end())
{
if (entry.second >= priority)
{
result_type = entry.first;
priority = entry.second;
}
}
}
);
return result_type;
}
std::map<std::string, authorization::type> auth_sub(std::string_view topic)
{
std::map<std::string, authorization::type> result;
std::size_t priority = 0;
auth_sub_map_.match(topic,
[&](const std::string& allowed_username, std::pair<authorization::type, std::size_t>& entry)
{
if (entry.second >= priority)
{
result[allowed_username] = entry.first;
priority = entry.second;
}
}
);
return result;
}
authorization::type auth_sub_user(
std::map<std::string, authorization::type> const& result, std::string const& username)
{
auto it = result.find(username);
if (it != result.end())
return it->second;
asio2::shared_locker g(this->security_mutex_);
for (auto& [k, v] : groups_)
{
if (k == any_group_name ||
std::find(v.members.begin(), v.members.end(), username) != v.members.end())
{
auto j = result.find(k);
if (j != result.end())
return j->second;
}
}
return authorization::type::deny;
}
static bool is_hash(std::string_view level) { return level == "#"; }
static bool is_plus(std::string_view level) { return level == "+"; }
static bool is_literal(std::string_view level) { return !is_hash(level) && !is_plus(level); }
static std::optional<std::string> is_subscribe_allowed(
std::vector<std::string> const& authorized_filter,std::string_view subscription_filter)
{
std::optional<std::string> result;
auto append_result = [&result](std::string_view token)
{
if (result)
{
result.value() += topic_filter_separator;
result.value().append(token.data(), token.size());
}
else
{
result = std::string(token);
}
};
auto filter_begin = authorized_filter.begin();
auto subscription_begin = subscription_filter.begin();
auto subscription_next = topic_filter_tokenizer_next(subscription_begin, subscription_filter.end());
while (true)
{
if (filter_begin == authorized_filter.end())
{
return std::nullopt;
}
auto auth = *filter_begin;
++filter_begin;
if (is_hash(auth))
{
append_result(std::string_view(&(*subscription_begin),
std::distance(subscription_begin, subscription_filter.end())));
return result;
}
auto sub = std::string_view(&(*subscription_begin),
std::distance(subscription_begin, subscription_next));
if (is_hash(sub))
{
append_result(auth);
while (filter_begin < authorized_filter.end())
{
append_result(*filter_begin);
++filter_begin;
}
return result;
}
if (is_plus(auth))
{
append_result(sub);
}
else if (is_plus(sub))
{
append_result(auth);
}
else
{
if (auth != sub)
{
return std::nullopt;
}
append_result(auth);
}
if (subscription_next == subscription_filter.end())
break;
subscription_begin = std::next(subscription_next);
subscription_next = topic_filter_tokenizer_next(subscription_begin, subscription_filter.end());
}
if (filter_begin < authorized_filter.end())
{
return std::nullopt;
}
return result;
}
static bool is_subscribe_denied(
std::vector<std::string> const& deny_filter, std::string_view subscription_filter)
{
bool result = true;
auto filter_begin = deny_filter.begin();
auto tokens_count = topic_filter_tokenizer(subscription_filter,
[&](auto sub)
{
if (filter_begin == deny_filter.end())
{
result = false;
return false;
};
std::string deny = *filter_begin;
++filter_begin;
if (deny != sub)
{
if (is_hash(deny))
{
result = true;
return false;
}
if (is_hash(sub))
{
result = false;
return false;
}
if (is_plus(deny))
{
result = true;
return true;
}
result = false;
return false;
}
return true;
}
);
return result && (tokens_count == deny_filter.size());
}
std::vector<std::string> get_auth_sub_topics(std::string_view username, std::string_view topic_filter) const
{
std::vector<std::string> auth_topics;
get_auth_sub_by_user(username,
[&](authorization const& i)
{
if (i.sub_type == authorization::type::allow)
{
auto entry = is_subscribe_allowed(i.topic_tokens, topic_filter);
if (entry)
{
auth_topics.push_back(entry.value());
}
}
else
{
for (auto j = auth_topics.begin(); j != auth_topics.end();)
{
if (is_subscribe_denied(i.topic_tokens, topic_filter))
{
j = auth_topics.erase(j);
}
else
{
++j;
}
}
}
}
);
return auth_topics;
}
/**
* @brief Determine if user is allowed to subscribe to the specified topic filter
* @param username - The username to check
* @param topic_filter - Topic filter the user would like to subscribe to
* @return true if the user is authorized
*/
bool is_subscribe_authorized(std::string_view username, std::string_view topic_filter) const
{
return !get_auth_sub_topics(username, topic_filter).empty();
}
// Get the individual path elements of the topic filter
static std::vector<std::string> get_topic_filter_tokens(std::string_view topic_filter)
{
std::vector<std::string> result;
topic_filter_tokenizer(topic_filter,
[&result](auto str)
{
result.push_back(std::string(str));
return true;
}
);
return result;
}
inline bool enabled() const noexcept { return enabled_; }
inline void enabled(bool v) noexcept { enabled_ = v; }
/// use rwlock to make thread safe
mutable asio2::shared_mutexer security_mutex_;
bool enabled_ = true;
std::map<std::string, authentication> authentication_ ASIO2_GUARDED_BY(security_mutex_);
std::map<std::string, group > groups_ ASIO2_GUARDED_BY(security_mutex_);
std::vector<authorization> authorization_ ASIO2_GUARDED_BY(security_mutex_);
std::optional<std::string> anonymous_ ASIO2_GUARDED_BY(security_mutex_);
std::optional<std::string> unauthenticated_ ASIO2_GUARDED_BY(security_mutex_);
using auth_map_type = subscription_map<std::string, std::pair<authorization::type, std::size_t>>;
auth_map_type auth_pub_map_;
auth_map_type auth_sub_map_;
protected:
std::size_t get_next_rule_nr_impl() const ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::size_t rule_nr = 0;
for (auto const& i : authorization_)
{
rule_nr = (std::max)(rule_nr, i.rule_nr);
}
return rule_nr + 1;
}
void validate_entry(std::string const& context, std::string const& name) const ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
if (is_valid_group_name(name) && groups_.find(name) == groups_.end())
{
throw std::runtime_error("An invalid group name was specified for " + context + ": " + name);
}
if (is_valid_user_name(name) && authentication_.find(name) == authentication_.end())
{
throw std::runtime_error("An invalid username name was specified for " + context + ": " + name);
}
}
void validate() ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
for (auto const& i : groups_)
{
for (auto const& j : i.second.members)
{
auto iter = authentication_.find(j);
if (is_valid_user_name(j) && iter == authentication_.end())
throw std::runtime_error("An invalid username name was specified for group " + i.first + ": " + j);
}
}
std::string unsalted;
for (auto const& i : authentication_)
{
if (i.second.auth_method == authentication::method::sha256 && i.second.salt.empty())
{
if (!unsalted.empty()) unsalted += ", ";
unsalted += i.first;
}
}
if (!unsalted.empty())
{
//MQTT_LOG("mqtt_broker", warning)
// << "The following users have no salt specified: "
// << unsalted;
}
for (auto const& i : authorization_)
{
for (auto const& j : i.sub)
{
validate_entry("topic " + i.topic, j);
if (is_valid_user_name(j) || is_valid_group_name(j))
{
auth_sub_map_.insert_or_assign(i.topic, j, std::make_pair(i.sub_type, i.rule_nr));
}
}
for (auto const& j : i.pub)
{
validate_entry("topic " + i.topic, j);
if (is_valid_user_name(j) || is_valid_group_name(j))
{
auth_pub_map_.insert_or_assign(i.topic, j, std::make_pair(i.pub_type, i.rule_nr));
}
}
}
}
};
}
#endif // __ASIO2_MQTT_SECURITY_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include <asio2/bho/predef/architecture/x86/32.h>
#include <asio2/bho/predef/architecture/x86/64.h>
#ifndef BHO_PREDEF_ARCHITECTURE_X86_H
#define BHO_PREDEF_ARCHITECTURE_X86_H
/* tag::reference[]
= `BHO_ARCH_X86`
http://en.wikipedia.org/wiki/X86[Intel x86] architecture. This is
a category to indicate that either `BHO_ARCH_X86_32` or
`BHO_ARCH_X86_64` is detected.
*/ // end::reference[]
#define BHO_ARCH_X86 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if BHO_ARCH_X86_32 || BHO_ARCH_X86_64
# undef BHO_ARCH_X86
# define BHO_ARCH_X86 BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_X86
# define BHO_ARCH_X86_AVAILABLE
#endif
#define BHO_ARCH_X86_NAME "Intel x86"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_X86,BHO_ARCH_X86_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_WATCOM_H
#define BHO_PREDEF_COMPILER_WATCOM_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_WATCOM`
http://en.wikipedia.org/wiki/Watcom[Watcom {CPP}] compiler.
Version number available as major, and minor.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__WATCOMC__+` | {predef_detection}
| `+__WATCOMC__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_WATCOM BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__WATCOMC__)
# define BHO_COMP_WATCOM_DETECTION BHO_PREDEF_MAKE_10_VVRR(__WATCOMC__)
#endif
#ifdef BHO_COMP_WATCOM_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_WATCOM_EMULATED BHO_COMP_WATCOM_DETECTION
# else
# undef BHO_COMP_WATCOM
# define BHO_COMP_WATCOM BHO_COMP_WATCOM_DETECTION
# endif
# define BHO_COMP_WATCOM_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_WATCOM_NAME "Watcom C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_WATCOM,BHO_COMP_WATCOM_NAME)
#ifdef BHO_COMP_WATCOM_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_WATCOM_EMULATED,BHO_COMP_WATCOM_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : mqtt_cpp/include/mqtt/broker/shared_target.hpp
*/
#ifndef __ASIO2_MQTT_SHARED_TARGET_HPP__
#define __ASIO2_MQTT_SHARED_TARGET_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <string>
#include <string_view>
#include <type_traits>
#include <optional>
#include <thread>
#include <map>
#include <unordered_map>
#include <chrono>
#include <set>
#include <vector>
#include <asio2/base/detail/shared_mutex.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
namespace asio2::mqtt
{
// v is shared target node
template<typename STNode>
auto round_shared_target_method(STNode& v) ->
std::shared_ptr<typename asio2::detail::remove_cvref_t<STNode>::session_type>
{
using session_type = typename asio2::detail::remove_cvref_t<STNode>::session_type;
std::weak_ptr<session_type> session;
if (!v.session_map.empty())
{
if (v.last == v.session_map.end())
v.last = v.session_map.begin();
else
{
v.last = std::next(v.last);
if (v.last == v.session_map.end())
v.last = v.session_map.begin();
}
session = v.last->second;
}
return session.lock();
}
template<typename STNode>
class shared_target
{
public:
struct hasher
{
inline std::size_t operator()(std::pair<std::string_view, std::string_view> const& pair) const noexcept
{
std::size_t v = asio2::detail::fnv1a_hash<std::size_t>(
(const unsigned char*)(pair.first.data()), pair.first.size());
return asio2::detail::fnv1a_hash<std::size_t>(v,
(const unsigned char*)(pair.second.data()), pair.second.size());
}
};
shared_target()
{
set_policy(std::bind(round_shared_target_method<STNode>, std::placeholders::_1));
}
~shared_target() = default;
using session_t = typename STNode::session_type;
using session_type = typename STNode::session_type;
template<class Function>
inline shared_target& set_policy(Function&& fun)
{
asio2::unique_locker g(this->shared_target_mutex_);
policy_ = std::forward<Function>(fun);
return (*this);
}
public:
void insert(std::shared_ptr<session_t>& session, std::string_view share_name, std::string_view topic_filter)
{
auto key = std::pair{ share_name, topic_filter };
asio2::unique_locker g(this->shared_target_mutex_);
auto it = targets_.find(key);
if (it == targets_.end())
{
STNode v{ share_name, topic_filter };
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
session->shared_target_key_ = ns;
v.session_map.emplace(ns, session);
v.session_set.emplace(session.get());
key = std::pair{ v.share_name_view(), v.topic_filter_view() };
it = targets_.emplace(std::move(key), std::move(v)).first;
}
else
{
STNode& v = it->second;
if (v.session_set.find(session.get()) != v.session_set.end())
return;
for (;;)
{
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
auto it_map = v.session_map.find(ns);
if (it_map != v.session_map.end())
{
std::this_thread::yield();
continue;
}
session->shared_target_key_ = ns;
v.session_map.emplace(ns, session);
v.session_set.emplace(session.get());
break;
}
}
}
void erase(std::shared_ptr<session_t>& session, std::string_view share_name, std::string_view topic_filter)
{
auto key = std::pair{ share_name, topic_filter };
asio2::unique_locker g(this->shared_target_mutex_);
auto it = targets_.find(key);
if (it == targets_.end())
return;
STNode& v = it->second;
auto it_map = v.session_map.find(session->shared_target_key_);
if (it_map != v.session_map.end())
{
if (v.last == it_map)
{
if (it_map != v.session_map.begin())
v.last = std::prev(v.last);
else
v.last = std::next(v.last);
}
v.session_map.erase(it_map);
}
auto it_set = v.session_set.find(session.get());
if (it_set != v.session_set.end())
{
v.session_set.erase(it_set);
}
}
//void erase(std::shared_ptr<session_t>& session, std::set<std::string_view> share_names)
//{
// for (std::string_view share_name : share_names)
// {
// auto it = targets_.find(share_name);
// if (it == targets_.end())
// continue;
// std::unordered_map<std::string_view, entry>& map_inner = it->second;
// auto it_map = map_inner.find(session->client_id());
// if (it_map == map_inner.end())
// continue;
// map_inner.erase(it_map);
// }
//}
std::shared_ptr<session_t> get_target(std::string_view share_name, std::string_view topic_filter)
{
auto key = std::pair{ share_name, topic_filter };
asio2::shared_locker g(this->shared_target_mutex_);
auto it = targets_.find(key);
if (it == targets_.end())
return std::shared_ptr<session_t>();
STNode& v = it->second;
return policy_(v);
}
protected:
/// use rwlock to make thread safe
mutable asio2::shared_mutexer shared_target_mutex_;
/// key : share_name - topic_filter, val : shared target node
std::unordered_map<std::pair<std::string_view, std::string_view>, STNode, hasher> targets_ ASIO2_GUARDED_BY(shared_target_mutex_);
std::function<std::shared_ptr<session_type>(STNode&)> policy_ ASIO2_GUARDED_BY(shared_target_mutex_);
};
template<class session_t>
struct stnode
{
template <class> friend class mqtt::shared_target;
using session_type = session_t;
explicit stnode(std::string_view _share_name, std::string_view _topic_filter)
{
share_name.resize(_share_name.size());
std::memcpy((void*)share_name.data(), (const void*)_share_name.data(), _share_name.size());
topic_filter.resize(_topic_filter.size());
std::memcpy((void*)topic_filter.data(), (const void*)_topic_filter.data(), _topic_filter.size());
last = session_map.end();
}
inline std::string_view share_name_view()
{
return std::string_view{ share_name.data(), share_name.size() };
}
inline std::string_view topic_filter_view()
{
return std::string_view{ topic_filter.data(), topic_filter.size() };
}
std::vector<char> share_name ; // vector has no SSO
std::vector<char> topic_filter;
/// session map ordered by steady_clock
std::map<std::chrono::nanoseconds::rep, std::weak_ptr<session_t>> session_map;
/// session unique
std::set<session_t*> session_set;
/// last session for shared subscribe
typename std::map<std::chrono::nanoseconds::rep, std::weak_ptr<session_t>>::iterator last;
};
}
#endif // !__ASIO2_MQTT_SHARED_TARGET_HPP__
<file_sep>// (C) Copyright <NAME> 2007.
// Copyright 2017, NVIDIA CORPORATION.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// PGI C++ compiler setup:
#define BHO_COMPILER_VERSION __PGIC__##__PGIC_MINOR__
#define BHO_COMPILER "PGI compiler version " BHO_STRINGIZE(BHO_COMPILER_VERSION)
// PGI is mostly GNU compatible. So start with that.
#include <asio2/bho/config/compiler/gcc.hpp>
// Now adjust for things that are different.
// __float128 is a typedef, not a distinct type.
#undef BHO_HAS_FLOAT128
// __int128 is not supported.
#undef BHO_HAS_INT128
<file_sep>#ifndef BHO_ENDIAN_DETAIL_IS_SCOPED_ENUM_HPP_INCLUDED
#define BHO_ENDIAN_DETAIL_IS_SCOPED_ENUM_HPP_INCLUDED
// Copyright 2020 <NAME>
//
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
#include <type_traits>
namespace bho
{
namespace endian
{
namespace detail
{
template<class T> struct negation: std::integral_constant<bool, !T::value> {};
template<class T> struct is_scoped_enum:
std::conditional<
std::is_enum<T>::value,
negation< std::is_convertible<T, int> >,
std::false_type
>::type
{
};
} // namespace detail
} // namespace endian
} // namespace bho
#endif // BHO_ENDIAN_DETAIL_IS_SCOPED_ENUM_HPP_INCLUDED
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_HTTP_DETAIL_RFC7230_HPP
#define BHO_BEAST_HTTP_DETAIL_RFC7230_HPP
#include <asio2/bho/beast/core/string.hpp>
#include <iterator>
#include <utility>
namespace bho {
namespace beast {
namespace http {
namespace detail {
BHO_BEAST_DECL
bool
is_digit(char c);
BHO_BEAST_DECL
char
is_alpha(char c);
BHO_BEAST_DECL
char
is_text(char c);
BHO_BEAST_DECL
char
is_token_char(char c);
BHO_BEAST_DECL
char
is_qdchar(char c);
BHO_BEAST_DECL
char
is_qpchar(char c);
// converts to lower case,
// returns 0 if not a valid text char
//
BHO_BEAST_DECL
char
to_value_char(char c);
// VFALCO TODO Make this return unsigned?
BHO_BEAST_DECL
std::int8_t
unhex(char c);
BHO_BEAST_DECL
string_view
trim(string_view s);
struct param_iter
{
using iter_type = string_view::const_iterator;
iter_type it;
iter_type first;
iter_type last;
std::pair<string_view, string_view> v;
bool
empty() const
{
return first == it;
}
BHO_BEAST_DECL
void
increment();
};
/*
#token = [ ( "," / token ) *( OWS "," [ OWS token ] ) ]
*/
struct opt_token_list_policy
{
using value_type = string_view;
BHO_BEAST_DECL
bool
operator()(value_type& v,
char const*& it, string_view s) const;
};
} // detail
} // http
} // beast
} // bho
#ifdef BEAST_HEADER_ONLY
#include <asio2/bho/beast/http/detail/rfc7230.ipp>
#endif
#endif
<file_sep>#include <asio2/serial_port/serial_port.hpp>
int main()
{
std::string_view device = "COM1"; // for windows
//std::string_view device = "/dev/ttyS0"; // for linux
std::string_view baud_rate = "9600";
asio2::serial_port sp;
sp.bind_init([&]()
{
// Set other serial port parameters at here
sp.set_option(asio::serial_port::flow_control(asio::serial_port::flow_control::type::none));
sp.set_option(asio::serial_port::parity(asio::serial_port::parity::type::none));
sp.set_option(asio::serial_port::stop_bits(asio::serial_port::stop_bits::type::one));
sp.set_option(asio::serial_port::character_size(8));
}).bind_recv([&](std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
sp.async_send(data);
}).bind_start([&]()
{
printf("start : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
printf("stop : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
});
//sp.start(device, baud_rate);
sp.start(device, baud_rate, '\n');
//sp.start(device, baud_rate, "\r\n");
//sp.start(device, baud_rate, match_role);
//sp.start(device, baud_rate, asio::transfer_at_least(1));
//sp.start(device, baud_rate, asio::transfer_exactly(10));
sp.async_send("abc0123456789xyz\n", [](std::size_t bytes_sent)
{
printf("send : %zu %d %s\n", bytes_sent,
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_TIMER_HPP__
#define __ASIO2_TIMER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdint>
#include <memory>
#include <chrono>
#include <atomic>
#include <string>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/log.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/object.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/impl/thread_id_cp.hpp>
#include <asio2/base/impl/user_timer_cp.hpp>
#include <asio2/base/impl/post_cp.hpp>
#include <asio2/base/impl/condition_event_cp.hpp>
namespace asio2::detail
{
struct template_args_timer
{
static constexpr std::size_t allocator_storage_size = 256;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
template<class derived_t, class args_t = template_args_timer>
class timer_impl_t
: public object_t <derived_t >
, public iopool_cp <derived_t, args_t>
, public thread_id_cp <derived_t, args_t>
, public user_timer_cp <derived_t, args_t>
, public post_cp <derived_t, args_t>
, public condition_event_cp<derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
public:
using super = object_t <derived_t >;
using self = timer_impl_t<derived_t, args_t>;
using iopoolcp = iopool_cp<derived_t, args_t>;
using args_type = args_t;
/**
* @brief constructor
*/
explicit timer_impl_t()
: super()
, iopool_cp <derived_t, args_t>(1)
, user_timer_cp <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp<derived_t, args_t>()
, io_ (iopoolcp::_get_io(0))
{
this->start();
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit timer_impl_t(Scheduler&& scheduler)
: super()
, iopool_cp <derived_t, args_t>(std::forward<Scheduler>(scheduler))
, user_timer_cp <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp<derived_t, args_t>()
, io_ (iopoolcp::_get_io(0))
{
#if defined(ASIO2_ENABLE_LOG)
#if defined(ASIO2_ALLOCATOR_STORAGE_SIZE)
static_assert(decltype(wallocator_)::storage_size == ASIO2_ALLOCATOR_STORAGE_SIZE);
#else
static_assert(decltype(wallocator_)::storage_size == args_t::allocator_storage_size);
#endif
#endif
this->start();
}
/**
* @brief destructor
*/
~timer_impl_t()
{
this->stop();
}
/**
* @brief start
*/
inline bool start()
{
derived_t& derive = this->derived();
// if log is enabled, init the log first, otherwise when "Too many open files" error occurs,
// the log file will be created failed too.
#if defined(ASIO2_ENABLE_LOG)
asio2::detail::get_logger();
#endif
bool ret = this->start_iopool(); // start the io_context pool
if (ret)
{
derive.io().regobj(&derive);
derive.dispatch([&derive]() mutable
{
// init the running thread id
derive.io().init_thread_id();
});
}
return ret;
}
/**
* @brief stop
*/
inline void stop()
{
if (this->is_iopool_stopped())
return;
derived_t& derive = this->derived();
derive.io().unregobj(&derive);
// close user custom timers
this->stop_all_timers();
// close all posted timed tasks
this->stop_all_timed_tasks();
// close all async_events
this->notify_all_condition_events();
// stop the io_context pool
this->stop_iopool();
}
public:
/**
* @brief get the io object refrence
*/
inline io_t & io() noexcept { return this->io_; }
protected:
/**
* @brief get the recv/read allocator object refrence
*/
inline auto & rallocator() noexcept { return this->wallocator_; }
/**
* @brief get the send/write allocator object refrence
*/
inline auto & wallocator() noexcept { return this->wallocator_; }
protected:
/// The io_context wrapper used to handle the accept event.
io_t & io_;
/// The memory to use for handler-based custom memory allocation. used fo send/write.
handler_memory<std::false_type, assizer<args_t>> wallocator_;
};
}
namespace asio2
{
class timer : public detail::timer_impl_t<timer, detail::template_args_timer>
{
public:
using detail::timer_impl_t<timer, detail::template_args_timer>::timer_impl_t;
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_TIMER_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_TCPS_CLIENT_HPP__
#define __ASIO2_TCPS_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_client.hpp>
#include <asio2/tcp/impl/ssl_stream_cp.hpp>
#include <asio2/tcp/impl/ssl_context_cp.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class derived_t, class args_t = template_args_tcp_client>
class tcps_client_impl_t
: public ssl_context_cp <derived_t, args_t>
, public tcp_client_impl_t <derived_t, args_t>
, public ssl_stream_cp <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using super = tcp_client_impl_t <derived_t, args_t>;
using self = tcps_client_impl_t<derived_t, args_t>;
using args_type = args_t;
using buffer_type = typename args_t::buffer_t;
using ssl_context_comp = ssl_context_cp<derived_t, args_t>;
using ssl_stream_comp = ssl_stream_cp <derived_t, args_t>;
public:
/**
* @brief constructor
*/
template<class... Args>
explicit tcps_client_impl_t(
asio::ssl::context::method method = asio::ssl::context::sslv23,
Args&&... args
)
: ssl_context_comp(method)
, super(std::forward<Args>(args)...)
, ssl_stream_comp(this->io_, *this, asio::ssl::stream_base::client)
{
}
/**
* @brief destructor
*/
~tcps_client_impl_t()
{
this->stop();
}
/**
* @brief get the stream object refrence
*
*/
inline typename ssl_stream_comp::ssl_stream_type& stream() noexcept
{
return this->derived().ssl_stream();
}
public:
/**
* @brief bind ssl handshake listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_handshake(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::handshake,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<typename C>
inline void _do_init(std::shared_ptr<ecs_t<C>>& ecs)
{
super::_do_init(ecs);
this->derived()._ssl_init(ecs, this->socket_, *this);
}
template<typename DeferEvent>
inline void _post_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_LOG_DEBUG("tcps_client::_post_shutdown: {} {}", ec.value(), ec.message());
this->derived()._ssl_stop(this_ptr, defer_event
{
[this, ec, this_ptr, e = chain.move_event()] (event_queue_guard<derived_t> g) mutable
{
super::_post_shutdown(ec, std::move(this_ptr), defer_event(std::move(e), std::move(g)));
}, chain.move_guard()
});
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
set_last_error(ec);
derived_t& derive = this->derived();
if (ec)
{
return derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
derive._ssl_start(this_ptr, ecs, this->socket_, *this);
derive._post_handshake(std::move(this_ptr), std::move(ecs), std::move(chain));
}
inline void _fire_handshake(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_handshake must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
detail::ignore_unused(this_ptr);
this->listener_.notify(event_type::handshake);
}
};
}
namespace asio2
{
using tcps_client_args = detail::template_args_tcp_client;
template<class derived_t, class args_t>
using tcps_client_impl_t = detail::tcps_client_impl_t<derived_t, args_t>;
/**
* @brief ssl tcp client
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
template<class derived_t>
class tcps_client_t : public detail::tcps_client_impl_t<derived_t, detail::template_args_tcp_client>
{
public:
using detail::tcps_client_impl_t<derived_t, detail::template_args_tcp_client>::tcps_client_impl_t;
};
/**
* @brief ssl tcp client
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
class tcps_client : public tcps_client_t<tcps_client>
{
public:
using tcps_client_t<tcps_client>::tcps_client_t;
};
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct tcps_rate_client_args : public tcps_client_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
template<class derived_t>
class tcps_rate_client_t : public asio2::tcps_client_impl_t<derived_t, tcps_rate_client_args>
{
public:
using asio2::tcps_client_impl_t<derived_t, tcps_rate_client_args>::tcps_client_impl_t;
};
class tcps_rate_client : public asio2::tcps_rate_client_t<tcps_rate_client>
{
public:
using asio2::tcps_rate_client_t<tcps_rate_client>::tcps_rate_client_t;
};
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_TCPS_CLIENT_HPP__
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_RESPONSE_IMPL_HPP__
#define __ASIO2_HTTP_RESPONSE_IMPL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/filesystem.hpp>
#include <asio2/base/impl/user_data_cp.hpp>
#include <asio2/http/detail/flex_body.hpp>
#include <asio2/http/detail/http_util.hpp>
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::http
#else
namespace boost::beast::http
#endif
{
class response_defer
{
public:
response_defer(std::function<void()> cb, std::shared_ptr<void> session)
: cb_(std::move(cb)), session_(std::move(session))
{
ASIO2_ASSERT(session_);
}
~response_defer()
{
if (cb_) { cb_(); }
}
protected:
std::function<void()> cb_;
// hold the http_session ptr, otherwise when the cb_ is calling, the session
// maybe destroyed already, then the response("rep_") in the cb_ is destroyed
// already, then it cause crash.
std::shared_ptr<void> session_;
};
}
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class Body, class Fields = http::fields>
class http_response_impl_t
: public http::message<false, Body, Fields>
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, public user_data_cp<http_response_impl_t<Body, Fields>>
#endif
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
public:
using self = http_response_impl_t<Body, Fields>;
using super = http::message<false, Body, Fields>;
using header_type = typename super::header_type;
using body_type = typename super::body_type;
public:
/**
* @brief constructor
* this default constructor it used for rdc call, beacuse the default status of
* http response is 200, and if the rdc call failed, the status of the returned
* http response is 200 too, so we set the status to another value at here.
*/
explicit http_response_impl_t()
: super()
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
super::result(http::status::unknown);
}
template<typename... Args>
explicit http_response_impl_t(Args&&... args)
: super(std::forward<Args>(args)...)
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
}
http_response_impl_t(const http_response_impl_t& o)
: super()
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
this->base() = o.base();
this->root_directory_ = o.root_directory_;
this->defer_callback_ = o.defer_callback_;
this->defer_guard_ = o.defer_guard_;
this->session_ptr_ = o.session_ptr_;
}
http_response_impl_t(http_response_impl_t&& o)
: super()
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
this->base() = std::move(o.base());
this->root_directory_ = o.root_directory_;
this->defer_callback_ = o.defer_callback_;
this->defer_guard_ = o.defer_guard_;
this->session_ptr_ = o.session_ptr_;
}
self& operator=(const http_response_impl_t& o)
{
this->base() = o.base();
this->root_directory_ = o.root_directory_;
this->defer_callback_ = o.defer_callback_;
this->defer_guard_ = o.defer_guard_;
this->session_ptr_ = o.session_ptr_;
return *this;
}
self& operator=(http_response_impl_t&& o)
{
this->base() = std::move(o.base());
this->root_directory_ = o.root_directory_;
this->defer_callback_ = o.defer_callback_;
this->defer_guard_ = o.defer_guard_;
this->session_ptr_ = o.session_ptr_;
return *this;
}
template<class BodyT = Body>
http_response_impl_t(const http::message<false, BodyT, Fields>& rep)
: super()
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
this->base() = rep;
}
template<class BodyT = Body>
http_response_impl_t(http::message<false, BodyT, Fields>&& rep)
: super()
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
this->base() = std::move(rep);
}
template<class BodyT = Body>
self& operator=(const http::message<false, BodyT, Fields>& rep)
{
this->base() = rep;
return *this;
}
template<class BodyT = Body>
self& operator=(http::message<false, BodyT, Fields>&& rep)
{
this->base() = std::move(rep);
return *this;
}
//-------------------------------------------------
http_response_impl_t(const http::message<false, http::string_body, Fields>& rep)
: super()
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
this->base().base() = rep.base();
this->body().text() = rep.body();
http::try_prepare_payload(*this);
}
http_response_impl_t(http::message<false, http::string_body, Fields>&& rep)
: super()
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
this->base().base() = std::move(rep.base());
this->body().text() = std::move(rep.body());
http::try_prepare_payload(*this);
}
self& operator=(const http::message<false, http::string_body, Fields>& rep)
{
this->base().base() = rep.base();
this->body().text() = rep.body();
http::try_prepare_payload(*this);
return *this;
}
self& operator=(http::message<false, http::string_body, Fields>&& rep)
{
this->base().base() = std::move(rep.base());
this->body().text() = std::move(rep.body());
http::try_prepare_payload(*this);
return *this;
}
//-------------------------------------------------
http_response_impl_t(const http::message<false, http::file_body, Fields>& rep)
: super()
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
this->base().base() = rep.base();
this->body().file() = rep.body();
http::try_prepare_payload(*this);
}
http_response_impl_t(http::message<false, http::file_body, Fields>&& rep)
: super()
#ifdef ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
, user_data_cp<http_response_impl_t<Body, Fields>>()
#endif
{
this->base().base() = std::move(rep.base());
this->body().file() = std::move(rep.body());
http::try_prepare_payload(*this);
}
self& operator=(const http::message<false, http::file_body, Fields>& rep)
{
this->base().base() = rep.base();
this->body().file() = rep.body();
http::try_prepare_payload(*this);
return *this;
}
self& operator=(http::message<false, http::file_body, Fields>&& rep)
{
this->base().base() = std::move(rep.base());
this->body().file() = std::move(rep.body());
http::try_prepare_payload(*this);
return *this;
}
/**
* @brief destructor
*/
~http_response_impl_t()
{
}
/// Returns the base portion of the message
inline super const& base() const noexcept
{
return *this;
}
/// Returns the base portion of the message
inline super& base() noexcept
{
return *this;
}
inline void reset()
{
static_cast<super&>(*this) = {};
this->result(http::status::unknown);
}
/**
* @brief set the root directory where we load the files.
*/
inline self& set_root_directory(std::filesystem::path path)
{
this->root_directory_ = std::move(path);
return *this;
}
/**
* @brief get the root directory where we load the files.
*/
inline const std::filesystem::path& get_root_directory() noexcept
{
return this->root_directory_;
}
/**
* @brief create a deferred http response, the response will not be send immediately,
* the http response will be sent only when the returned std::shared_ptr<http::response_defer>
* is completely destroyed
*/
inline std::shared_ptr<http::response_defer> defer()
{
this->defer_guard_ = std::make_shared<http::response_defer>(
this->defer_callback_, this->session_ptr_.lock());
return this->defer_guard_;
}
public:
/**
* @brief Respond to http request with plain text content
* @param content - the response body, it's usually a simple string,
* and the content-type is "text/plain" by default.
*/
template<class StringT>
inline self& fill_text(StringT&& content, http::status result = http::status::ok,
std::string_view mimetype = "text/plain", unsigned version = 11)
{
// must clear file_body
this->body().file().close();
this->set(http::field::server, BEAST_VERSION_STRING);
this->set(http::field::content_type, mimetype.empty() ? "text/plain" : mimetype);
this->result(result);
this->version(version < 10 ? 11 : version);
this->body().text() = detail::to_string(std::forward<StringT>(content));
http::try_prepare_payload(*this);
return (*this);
}
/**
* @brief Respond to http request with json content
*/
template<class StringT>
inline self& fill_json(StringT&& content, http::status result = http::status::ok,
std::string_view mimetype = "application/json", unsigned version = 11)
{
return this->fill_text(std::forward<StringT>(content), result,
mimetype.empty() ? "application/json" : mimetype, version);
}
/**
* @brief Respond to http request with html content
* @param content - the response body, may be a plain text string, or a stardand
* <html>...</html> string, it's just that the content-type is "text/html" by default.
*/
template<class StringT>
inline self& fill_html(StringT&& content, http::status result = http::status::ok,
std::string_view mimetype = "text/html", unsigned version = 11)
{
return this->fill_text(std::forward<StringT>(content), result,
mimetype.empty() ? "text/html" : mimetype, version);
}
/**
* @brief Respond to http request with pre-prepared error page content
* Generated a standard html error page automatically use the status coe 'result',
* like <html>...</html>, and the content-type is "text/html" by default.
*/
template<class StringT = std::string_view>
inline self& fill_page(http::status result, StringT&& desc = std::string_view{},
std::string_view mimetype = "text/html", unsigned version = 11)
{
return this->fill_text(http::error_page(result, std::forward<StringT>(desc)), result,
mimetype.empty() ? "text/html" : mimetype, version);
}
/**
* @brief Respond to http request with local file
*/
inline self& fill_file(std::filesystem::path path,
http::status result = http::status::ok, unsigned version = 11)
{
// if you want to build a absolute path by youself and passed it to fill_file function,
// call set_root_directory("") first, then passed you absolute path to fill_file is ok.
// Build the path to the requested file
std::filesystem::path filepath;
if (this->root_directory_.empty())
{
filepath = std::move(path);
filepath.make_preferred();
}
else
{
filepath = this->root_directory_;
filepath.make_preferred();
filepath /= path.make_preferred().relative_path();
}
// Attempt to open the file
beast::error_code ec;
this->body().file().open(filepath.string().c_str(), beast::file_mode::scan, ec);
// Handle the case where the file doesn't exist
if (ec == beast::errc::no_such_file_or_directory)
return this->fill_page(http::status::not_found, {}, {}, version);
// Handle an unknown error
if (ec)
return this->fill_page(http::status::not_found, ec.message(), {}, version);
// Cache the size since we need it after the move
auto const size = this->body().size();
// Respond to GET request
this->content_length(size);
this->set(http::field::server, BEAST_VERSION_STRING);
this->set(http::field::content_type, http::extension_to_mimetype(path.extension().string()));
this->result(result);
this->version(version < 10 ? 11 : version);
return (*this);
}
/**
* @brief Returns `true` if this HTTP response's Content-Type is "multipart/form-data";
*/
inline bool has_multipart() noexcept
{
return http::has_multipart(*this);
}
/**
* @brief Get the "multipart/form-data" body content.
*/
inline decltype(auto) get_multipart()
{
return http::multipart(*this);
}
/**
* @brief Get the "multipart/form-data" body content. same as get_multipart
*/
inline decltype(auto) multipart()
{
return this->get_multipart();
}
protected:
std::filesystem::path root_directory_ = std::filesystem::current_path();
std::function<void()> defer_callback_;
std::shared_ptr<http::response_defer> defer_guard_;
std::weak_ptr<void> session_ptr_;
};
}
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::http
#else
namespace boost::beast::http
#endif
{
using web_response = asio2::detail::http_response_impl_t<http::flex_body>;
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTP_RESPONSE_IMPL_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_SEND_OP_HPP__
#define __ASIO2_MQTT_SEND_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <vector>
#include <variant>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class mqtt_send_op
{
public:
/**
* @brief constructor
*/
mqtt_send_op() {}
/**
* @brief destructor
*/
~mqtt_send_op() = default;
protected:
template<class Data, class Callback>
inline bool _mqtt_send(Data& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
// why don't use std::string ?
// beacuse std::string has a SSO(Small String Optimization) mechanism
// https://stackoverflow.com/questions/34788789/disable-stdstrings-sso
// std::string str;
// str.reserve(sizeof(str) + 1);
// Test whether the vector has SSO mechanism
#if defined(_DEBUG) || defined(DEBUG)
static bool flag = false;
if (flag == false)
{
flag = true;
std::vector<char> v1{ 'a','b','c' };
std::string_view sv{ v1.data(),v1.size() };
std::vector<char> v2 = std::move(v1);
ASIO2_ASSERT(sv.data() == v2.data());
}
#endif
std::vector<char> binary;
using data_type = typename detail::remove_cvref_t<Data>;
if constexpr (std::is_same_v<mqtt::message, data_type>)
{
std::visit([&binary](auto& message) mutable
{
binary.reserve(message.required_size());
message.serialize(binary);
}, data);
}
else if constexpr (detail::is_template_instance_of_v<std::variant, data_type>)
{
std::visit([&binary](auto& message) mutable
{
binary.reserve(message.required_size());
message.serialize(binary);
}, data);
}
else
{
binary.reserve(data.required_size());
data.serialize(binary);
}
auto buffer = asio::buffer(binary);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
asio::async_write(derive.stream(), buffer,
make_allocator(derive.wallocator(), [&derive, p = derive.selfptr(),
binary = std::move(binary), callback = std::forward<Callback>(callback)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
callback(ec, bytes_sent);
if (ec)
{
// must stop, otherwise re-sending will cause body confusion
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, std::move(p));
}
}
}));
return true;
}
};
}
#endif // !__ASIO2_MQTT_SEND_OP_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_HTTPS_DOWNLOAD_HPP__
#define __ASIO2_HTTPS_DOWNLOAD_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <fstream>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/http/detail/http_util.hpp>
#include <asio2/http/detail/http_make.hpp>
#include <asio2/http/detail/http_traits.hpp>
#include <asio2/component/socks/socks5_client.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t, bool Enable = is_https_execute_download_enabled<args_t>::value()>
struct https_download_impl_bridge;
template<class derived_t, class args_t>
struct https_download_impl_bridge<derived_t, args_t, false>
{
};
template<class derived_t, class args_t>
struct https_download_impl_bridge<derived_t, args_t, true>
{
protected:
template<typename String, typename StrOrInt, class HeaderCallback, class BodyCallback, class Proxy,
class Body, class Fields, class Buffer>
static void _download_with_socks5(
asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
asio::ssl::stream<asio::ip::tcp::socket&>& stream,
Buffer& buffer,
String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, HeaderCallback&& cbh, BodyCallback&& cbb, Proxy&& proxy)
{
auto sk5 = detail::to_shared_ptr(std::forward<Proxy>(proxy));
std::string_view h{ sk5->host() };
std::string_view p{ sk5->port() };
// Look up the domain name
resolver.async_resolve(h, p, [&, s5 = std::move(sk5)]
(const error_code& ec1, const asio::ip::tcp::resolver::results_type& endpoints) mutable
{
if (ec1) { set_last_error(ec1); return; }
// Make the connection on the IP address we get from a lookup
asio::async_connect(socket, endpoints,
[&, s5 = std::move(s5)](const error_code& ec2, const asio::ip::tcp::endpoint&) mutable
{
if (ec2) { set_last_error(ec2); return; }
detail::socks5_client_connect_op
{
ioc,
detail::to_string(std::forward<String >(host)),
detail::to_string(std::forward<StrOrInt>(port)),
socket,
std::move(s5),
[&](error_code ecs5) mutable
{
if (ecs5) { set_last_error(ecs5); return; }
// https://github.com/djarek/certify
if (auto it = req.find(http::field::host); it != req.end())
{
std::string hostname(it->value());
SSL_set_tlsext_host_name(stream.native_handle(), hostname.data());
}
stream.async_handshake(asio::ssl::stream_base::client,
[&](const error_code& ec3) mutable
{
if (ec3) { set_last_error(ec3); return; }
http::async_write(stream, req, [&](const error_code& ec4, std::size_t) mutable
{
// can't use stream.shutdown(),in some case the shutdowm will blocking forever.
if (ec4) { set_last_error(ec4); stream.async_shutdown([](const error_code&) {}); return; }
http::read_large_body<false>(stream, buffer,
std::forward<HeaderCallback>(cbh), std::forward<BodyCallback>(cbb));
stream.async_shutdown([](const error_code&) mutable {});
});
});
}
};
});
});
}
template<typename String, typename StrOrInt, class HeaderCallback, class BodyCallback,
class Body, class Fields, class Buffer>
static void _download_trivially(
asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
asio::ssl::stream<asio::ip::tcp::socket&>& stream,
Buffer& buffer,
String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, HeaderCallback&& cbh, BodyCallback&& cbb)
{
detail::ignore_unused(ioc);
// Look up the domain name
resolver.async_resolve(std::forward<String>(host), detail::to_string(std::forward<StrOrInt>(port)),
[&](const error_code& ec1, const asio::ip::tcp::resolver::results_type& endpoints) mutable
{
if (ec1) { set_last_error(ec1); return; }
// Make the connection on the IP address we get from a lookup
asio::async_connect(socket, endpoints,
[&](const error_code& ec2, const asio::ip::tcp::endpoint&) mutable
{
if (ec2) { set_last_error(ec2); return; }
// https://github.com/djarek/certify
if (auto it = req.find(http::field::host); it != req.end())
{
std::string hostname(it->value());
SSL_set_tlsext_host_name(stream.native_handle(), hostname.data());
}
stream.async_handshake(asio::ssl::stream_base::client,
[&](const error_code& ec3) mutable
{
if (ec3) { set_last_error(ec3); return; }
http::async_write(stream, req, [&](const error_code& ec4, std::size_t) mutable
{
// can't use stream.shutdown(),in some case the shutdowm will blocking forever.
if (ec4) { set_last_error(ec4); stream.async_shutdown([](const error_code&) {}); return; }
http::read_large_body<false>(stream, buffer,
std::forward<HeaderCallback>(cbh), std::forward<BodyCallback>(cbb));
stream.async_shutdown([](const error_code&) mutable {});
});
});
});
});
}
template<typename String, typename StrOrInt, class HeaderCallback, class BodyCallback, class Proxy,
class Body, class Fields, class Buffer>
static void _download_impl(
asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
asio::ssl::stream<asio::ip::tcp::socket&>& stream,
Buffer& buffer,
String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, HeaderCallback&& cbh, BodyCallback&& cbb, Proxy&& proxy)
{
// if has socks5 proxy
if constexpr (std::is_base_of_v<asio2::socks5::option_base,
typename detail::element_type_adapter<detail::remove_cvref_t<Proxy>>::type>)
{
derived_t::_download_with_socks5(ioc, resolver, socket, stream, buffer
, std::forward<String>(host), std::forward<StrOrInt>(port)
, req, std::forward<HeaderCallback>(cbh), std::forward<BodyCallback>(cbb)
, std::forward<Proxy>(proxy)
);
}
else
{
detail::ignore_unused(proxy);
derived_t::_download_trivially(ioc, resolver, socket, stream, buffer
, std::forward<String>(host), std::forward<StrOrInt>(port)
, req, std::forward<HeaderCallback>(cbh), std::forward<BodyCallback>(cbb)
);
}
}
public:
/**
* @brief blocking download the http file until it is returned on success or failure
* @param ctx - asio ssl context.
* @param host - The ip of the server.
* @param port - The port of the server.
* @param req - The http request object to send to the https server.
* @param cbh - A function that recv the http response header message. void(auto& message)
* @param cbb - A function that circularly receives the contents of the file in chunks. void(std::string_view data)
* @param proxy - socks5 proxy, if you do not need a proxy, pass "nullptr" is ok.
*/
template<typename String, typename StrOrInt, class HeaderCallback, class BodyCallback, class Proxy,
class Body = http::string_body, class Fields = http::fields, class Buffer = beast::flat_buffer>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, bool>
static inline download(const asio::ssl::context& ctx, String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, HeaderCallback&& cbh, BodyCallback&& cbb, Proxy&& proxy)
{
// First assign default value 0 to last error
clear_last_error();
// The io_context is required for all I/O
asio::io_context ioc;
// These objects perform our I/O
asio::ip::tcp::resolver resolver{ ioc };
asio::ip::tcp::socket socket{ ioc };
asio::ssl::stream<asio::ip::tcp::socket&> stream(socket, const_cast<asio::ssl::context&>(ctx));
// This buffer is used for reading and must be persisted
Buffer buffer;
// Some sites must set the http::field::user_agent
if (req.find(http::field::user_agent) == req.end())
req.set(http::field::user_agent,
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36");
// do work
derived_t::_download_impl(ioc, resolver, socket, stream, buffer
, std::forward<String>(host), std::forward<StrOrInt>(port)
, req, std::forward<HeaderCallback>(cbh), std::forward<BodyCallback>(cbb)
, std::forward<Proxy>(proxy)
);
// timedout run
ioc.run();
error_code ec_ignore{};
// Gracefully close the socket
socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec_ignore);
socket.cancel(ec_ignore);
socket.close(ec_ignore);
return bool(!get_last_error());
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking download the http file until it is returned on success or failure
* @param url - The url of the file to download.
* @param filepath - The file path to saved the received file content.
*/
template<class String1, class String2>
typename std::enable_if_t<detail::can_convert_to_string_v<detail::remove_cvref_t<String1>> &&
detail::can_convert_to_string_v<detail::remove_cvref_t<String2>>, bool>
static inline download(const asio::ssl::context& ctx, String1&& url, String2&& filepath)
{
http::web_request req = http::make_request(std::forward<String1>(url));
if (get_last_error())
return false;
std::filesystem::path path(std::forward<String2>(filepath));
std::filesystem::create_directories(path.parent_path(), get_last_error());
std::fstream file(path, std::ios::out | std::ios::binary | std::ios::trunc);
if (!file)
{
set_last_error(asio::error::access_denied); // Permission denied
return false;
}
auto cbh = [](const auto&) {};
auto cbb = [&file](std::string_view chunk) mutable
{
file.write(chunk.data(), chunk.size());
};
return derived_t::download(ctx, req.host(), req.port(), req.base(), cbh, cbb, std::in_place);
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking download the http file until it is returned on success or failure
* @param url - The url of the file to download.
* @param filepath - The file path to saved the received file content.
*/
template<class String1, class String2>
typename std::enable_if_t<detail::can_convert_to_string_v<detail::remove_cvref_t<String1>> &&
detail::can_convert_to_string_v<detail::remove_cvref_t<String2>>, bool>
static inline download(String1&& url, String2&& filepath)
{
return derived_t::download(asio::ssl::context{ asio::ssl::context::sslv23 },
std::forward<String1>(url), std::forward<String2>(filepath));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking download the http file until it is returned on success or failure
* @param url - The url of the file to download.
* @param cbb - A function that circularly receives the contents of the file in chunks. void(std::string_view data)
*/
template<class String1, class BodyCallback>
typename std::enable_if_t<detail::can_convert_to_string_v<detail::remove_cvref_t<String1>> &&
detail::is_callable_v<BodyCallback>, bool>
static inline download(const asio::ssl::context& ctx, String1&& url, BodyCallback&& cbb)
{
http::web_request req = http::make_request(std::forward<String1>(url));
if (get_last_error())
return false;
auto cbh = [](const auto&) {};
return derived_t::download(ctx, req.host(), req.port(), req.base(), cbh, cbb, std::in_place);
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking download the http file until it is returned on success or failure
* @param url - The url of the file to download.
* @param cbb - A function that circularly receives the contents of the file in chunks. void(std::string_view data)
*/
template<class String1, class BodyCallback>
typename std::enable_if_t<detail::can_convert_to_string_v<detail::remove_cvref_t<String1>> &&
detail::is_callable_v<BodyCallback>, bool>
static inline download(String1&& url, BodyCallback&& cbb)
{
return derived_t::download(asio::ssl::context{ asio::ssl::context::sslv23 },
std::forward<String1>(url), std::forward<BodyCallback>(cbb));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking download the http file until it is returned on success or failure
* @param url - The url of the file to download.
* @param cbh - A function that recv the http response header message. void(auto& message)
* @param cbb - A function that circularly receives the contents of the file in chunks. void(std::string_view data)
*/
template<class String1, class HeaderCallback, class BodyCallback>
typename std::enable_if_t<detail::can_convert_to_string_v<detail::remove_cvref_t<String1>> &&
detail::is_callable_v<BodyCallback>, bool>
static inline download(const asio::ssl::context& ctx, String1&& url, HeaderCallback&& cbh, BodyCallback&& cbb)
{
http::web_request req = http::make_request(std::forward<String1>(url));
if (get_last_error())
return false;
return derived_t::download(ctx, req.host(), req.port(), req.base(), cbh, cbb, std::in_place);
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking download the http file until it is returned on success or failure
* @param url - The url of the file to download.
* @param cbh - A function that recv the http response header message. void(auto& message)
* @param cbb - A function that circularly receives the contents of the file in chunks. void(std::string_view data)
*/
template<class String1, class HeaderCallback, class BodyCallback>
typename std::enable_if_t<detail::can_convert_to_string_v<detail::remove_cvref_t<String1>> &&
detail::is_callable_v<BodyCallback>, bool>
static inline download(String1&& url, HeaderCallback&& cbh, BodyCallback&& cbb)
{
return derived_t::download(asio::ssl::context{ asio::ssl::context::sslv23 },
std::forward<String1>(url), std::forward<HeaderCallback>(cbh), std::forward<BodyCallback>(cbb));
}
};
template<class derived_t, class args_t = void>
struct https_download_impl : public https_download_impl_bridge<derived_t, args_t> {};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTPS_DOWNLOAD_HPP__
#endif
<file_sep>#include <asio2/udp/udp_client.hpp>
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8035";
asio2::udp_client client;
client.bind_recv([&](std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
std::string s;
s += '<';
int len = 33 + std::rand() % (126 - 33);
for (int i = 0; i < len; i++)
{
s += (char)((std::rand() % 26) + 'a');
}
s += '>';
client.async_send(std::move(s));
});
client.start(host, port);
client.async_send("<abcdefghijklmnopqrstovuxyz0123456789>");
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
/*
Perfect capture in C++20
template <typename ... Args>
auto f(Args&& args){
return [... args = std::forward<Args>(args)]{
// use args
};
}
C++17 and C++14 workaround
In C++17 we can use a workaround with tuples:
template <typename ... Args>
auto f(Args&& ... args){
return [args = std::make_tuple(std::forward<Args>(args) ...)]()mutable{
return std::apply([](auto&& ... args){
// use args
}, std::move(args));
};
}
*/
#ifndef __ASIO2_RPC_CALL_COMPONENT_HPP__
#define __ASIO2_RPC_CALL_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <queue>
#include <any>
#include <future>
#include <tuple>
#include <unordered_map>
#include <type_traits>
#include <map>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/rpc/detail/rpc_serialization.hpp>
#include <asio2/rpc/detail/rpc_protocol.hpp>
#include <asio2/rpc/detail/rpc_invoker.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class rpc_call_cp
{
public:
/**
* @brief constructor
*/
rpc_call_cp(io_t&, rpc_serializer& sr, rpc_deserializer& dr)
: sr_(sr), dr_(dr)
{
}
/**
* @brief destructor
*/
~rpc_call_cp() = default;
protected:
template<class derive_t>
struct sync_call_op
{
template<class return_t, class Rep, class Period, class ...Args>
inline static return_t exec(derive_t& derive,
std::chrono::duration<Rep, Period> timeout, std::string name, Args&&... args)
{
using result_t = typename rpc_result_t<return_t>::type;
if (!derive.is_started())
{
set_last_error(rpc::make_error_code(rpc::error::not_connected));
if constexpr (!std::is_void_v<return_t>)
{
return result_t{};
}
else
{
return;
}
}
std::shared_ptr<result_t> result = std::make_shared<result_t>();
set_last_error(rpc::make_error_code(rpc::error::success));
rpc_header::id_type id = derive.mkid();
rpc_request<Args...> req(id, std::move(name), std::forward<Args>(args)...);
std::shared_ptr<std::promise<error_code>> promise = std::make_shared<std::promise<error_code>>();
std::future<error_code> future = promise->get_future();
auto ex = [&derive, result, id, pm = std::move(promise)]
(error_code ec, std::string_view data) mutable
{
detail::ignore_unused(data);
// when async_send failed, the error category is not rpc category.
//ASIO2_ASSERT(std::string_view(ec.category().name()) == rpc::rpc_category().name());
ASIO2_ASSERT(derive.io().running_in_this_thread());
if (!ec)
{
try
{
derive.dr_ >> ec;
if constexpr (!std::is_void_v<return_t>)
{
if (!ec)
derive.dr_ >> (*result);
}
else
{
std::ignore = result;
}
}
catch (cereal::exception const&)
{
ec = rpc::make_error_code(rpc::error::no_data);
}
catch (std::exception const&)
{
ec = rpc::make_error_code(rpc::error::unspecified_error);
}
}
if (std::addressof(ec.category()) != std::addressof(rpc::rpc_category()))
{
ec.assign(ec.value(), rpc::rpc_category());
}
ASIO2_ASSERT(std::string_view(ec.category().name()) == rpc::rpc_category().name());
set_last_error(ec);
pm->set_value(ec);
derive.reqs_.erase(id);
};
asio::post(derive.io().context(), make_allocator(derive.callocator_,
[&derive, req = std::move(req), ex = std::move(ex), p = derive.selfptr()]() mutable
{
detail::ignore_unused(p);
derive.reqs_.emplace(req.id(), std::move(ex));
derive.async_send((derive.sr_.reset() << req).str(),
[&derive, id = req.id()]() mutable
{
if (get_last_error()) // send data failed with error
{
auto iter = derive.reqs_.find(id);
if (iter != derive.reqs_.end())
{
auto& ex = iter->second;
ex(get_last_error(), std::string_view{});
}
}
});
}));
// Whether we run on the io_context thread
if (!derive.io().running_in_this_thread())
{
std::future_status status = future.wait_for(timeout);
if (status == std::future_status::ready)
{
set_last_error(future.get());
}
else
{
set_last_error(rpc::make_error_code(rpc::error::timed_out));
asio::post(derive.io().context(), make_allocator(derive.callocator_,
[&derive, id, p = derive.selfptr()]() mutable
{
detail::ignore_unused(p);
derive.reqs_.erase(id);
}));
}
}
else
{
// If invoke synchronization rpc call function in communication thread, it will degenerates
// into async_call and the return value is empty.
asio::post(derive.io().context(), make_allocator(derive.callocator_,
[&derive, id, p = derive.selfptr()]() mutable
{
detail::ignore_unused(p);
derive.reqs_.erase(id);
}));
set_last_error(rpc::make_error_code(rpc::error::in_progress));
}
ASIO2_ASSERT(std::string_view(get_last_error().category().name()) == rpc::rpc_category().name());
// [20210818] don't throw an error, you can use get_last_error() to check
// is there any exception.
if constexpr (!std::is_void_v<return_t>)
{
return std::move(*result);
}
else
{
return;
}
}
};
template<class derive_t>
struct async_call_op
{
template<class Callback>
inline static auto to_safe_callback(Callback&& cb)
{
using cbtype = typename detail::remove_cvref_t<Callback>;
if constexpr (detail::has_bool_operator<cbtype>::value)
{
using fun_traits_type = function_traits<cbtype>;
if (!cb)
return cbtype{ typename fun_traits_type::stl_lambda_type{} };
else
return std::forward<Callback>(cb);
}
else
{
return std::forward<Callback>(cb);
}
}
template<class return_t, class Callback>
inline static auto make_callback(derive_t& derive, Callback&& cb)
{
return async_call_op<derive_t>::template make_callback_impl<return_t>(
derive, async_call_op<derive_t>::to_safe_callback(std::forward<Callback>(cb)));
}
template<class Callback>
inline static auto make_callback(derive_t& derive, Callback&& cb)
{
using fun_traits_type = function_traits<std::remove_cv_t<std::remove_reference_t<Callback>>>;
return async_call_op<derive_t>::template make_callback_argc(
derive, async_call_op<derive_t>::to_safe_callback(std::forward<Callback>(cb)),
std::integral_constant<int, fun_traits_type::argc>{});
}
template<class Callback>
inline static auto make_callback_argc(derive_t& derive, Callback&& cb, std::integral_constant<int, 0>)
{
return async_call_op<derive_t>::template make_callback_impl<void>(
derive, std::forward<Callback>(cb));
}
template<class Callback>
inline static auto make_callback_argc(derive_t& derive, Callback&& cb, std::integral_constant<int, 1>)
{
using fun_traits_type = function_traits<std::remove_cv_t<std::remove_reference_t<Callback>>>;
using return_type = typename fun_traits_type::template args<0>::type;
static_assert(!std::is_same_v<return_type, void>);
return async_call_op<derive_t>::template make_callback_impl<return_type>(
derive, std::forward<Callback>(cb));
}
template<class return_t, class Callback>
inline static auto make_callback_impl_0(derive_t& derive, Callback&& cb)
{
return [&derive, cb = std::forward<Callback>(cb)](auto ec, std::string_view) mutable
{
try
{
if (!ec)
derive.dr_ >> ec;
}
catch (cereal::exception const&)
{
ec = rpc::make_error_code(rpc::error::no_data);
}
catch (std::exception const&)
{
ec = rpc::make_error_code(rpc::error::unspecified_error);
}
if (std::addressof(ec.category()) != std::addressof(rpc::rpc_category()))
{
ec.assign(ec.value(), rpc::rpc_category());
}
ASIO2_ASSERT(std::string_view(ec.category().name()) == rpc::rpc_category().name());
set_last_error(ec);
cb();
};
}
template<class return_t, class Callback>
inline static auto make_callback_impl_1(derive_t& derive, Callback&& cb)
{
return [&derive, cb = std::forward<Callback>(cb)](auto ec, std::string_view data) mutable
{
detail::ignore_unused(data);
typename rpc_result_t<return_t>::type result{};
try
{
if (!ec)
derive.dr_ >> ec;
if (!ec)
derive.dr_ >> result;
}
catch (cereal::exception const&)
{
ec = rpc::make_error_code(rpc::error::no_data);
}
catch (std::exception const&)
{
ec = rpc::make_error_code(rpc::error::unspecified_error);
}
if (std::addressof(ec.category()) != std::addressof(rpc::rpc_category()))
{
ec.assign(ec.value(), rpc::rpc_category());
}
ASIO2_ASSERT(std::string_view(ec.category().name()) == rpc::rpc_category().name());
set_last_error(ec);
cb(std::move(result));
};
}
template<class return_t, class Callback>
inline static auto make_callback_impl(derive_t& derive, Callback&& cb)
{
if constexpr (std::is_same_v<return_t, void>)
{
return async_call_op<derive_t>::make_callback_impl_0<return_t>(
derive, std::forward<Callback>(cb));
}
else
{
return async_call_op<derive_t>::make_callback_impl_1<return_t>(
derive, std::forward<Callback>(cb));
}
}
template<class Req>
inline static void exec(derive_t& derive, Req&& req)
{
ASIO2_ASSERT(!req.id());
if (!derive.is_started())
{
set_last_error(rpc::make_error_code(rpc::error::not_connected));
return;
}
set_last_error(rpc::make_error_code(rpc::error::success));
asio::post(derive.io().context(), make_allocator(derive.callocator_,
[&derive, req = std::forward<Req>(req), p = derive.selfptr()]() mutable
{
detail::ignore_unused(p);
derive.async_send((derive.sr_.reset() << req).str());
}));
}
template<class Callback, class Rep, class Period, class Req>
inline static void exec(derive_t& derive, rpc_header::id_type id,
std::chrono::duration<Rep, Period> timeout, Callback&& cb, Req&& req)
{
ASIO2_ASSERT(id);
req.id(id);
// 2020-12-03 Fix possible bug: move the "timer->async_wait" into the io_context thread.
// otherwise the "derive.send" maybe has't called, the "timer->async_wait" has called
// already.
std::shared_ptr<asio::steady_timer> timer =
std::make_shared<asio::steady_timer>(derive.io().context());
auto ex = [&derive, id, timer, cb = std::forward<Callback>(cb)]
(error_code ec, std::string_view data) mutable
{
ASIO2_ASSERT(derive.io().running_in_this_thread());
detail::cancel_timer(*timer);
cb(ec, data);
derive.reqs_.erase(id);
};
if (!derive.is_started())
{
set_last_error(rpc::make_error_code(rpc::error::not_connected));
// bug fixed : can't call ex(...) directly, it will
// cause "reqs_.erase(id)" be called in multithread
asio::post(derive.io().context(), make_allocator(derive.callocator_,
[ex = std::move(ex), p = derive.selfptr()]() mutable
{
detail::ignore_unused(p);
set_last_error(rpc::make_error_code(rpc::error::not_connected));
ex(rpc::make_error_code(rpc::error::not_connected), std::string_view{});
}));
return;
}
set_last_error(rpc::make_error_code(rpc::error::success));
// 2019-11-28 fixed the bug of issue #6 : task() cannot be called directly
// 2021-12-10 : can't save the request id in async_send's callback.
// The following will occurs when using async_send with callback :
// 1. call async_send with callback
// 2. recv response by rpc_recv_op
// 3. the callback was called
// It means that : The callback function of async_send may be called after
// recved response data.
asio::post(derive.io().context(), make_allocator(derive.callocator_,
[&derive, timer = std::move(timer), timeout, req = std::forward<Req>(req),
ex = std::move(ex), p = derive.selfptr()]() mutable
{
// 1. first, save the request id
derive.reqs_.emplace(req.id(), std::move(ex));
// 2. second, start the timeout timer.
// note : cannot put "start timer" after "async_send", beacust the async_send
// maybe failed immediately with the "derive.is_started() == false", then the
// callback of async_send will be called immediately, and the "ex" will be called,
// and the timer will be canceled, but at this time, the timer has't start yet,
// when async_send is return, the timer will be begin "async_wait", but the timer
// "cancel" is called already, so this will cause some small problem.
// must start a timeout timer, othwise if not recved response, it will cause the
// request id in the map forever.
timer->expires_after(timeout);
timer->async_wait(
[this_ptr = std::move(p), &derive, id = req.id()]
(const error_code& ec) mutable
{
if (ec == asio::error::operation_aborted)
return;
auto iter = derive.reqs_.find(id);
if (iter != derive.reqs_.end())
{
auto& ex = iter->second;
ex(rpc::make_error_code(rpc::error::timed_out), std::string_view{});
}
});
// 3. third, send request.
derive.async_send((derive.sr_.reset() << req).str(),
[&derive, id = req.id()]() mutable
{
if (get_last_error()) // send data failed with error
{
auto iter = derive.reqs_.find(id);
if (iter != derive.reqs_.end())
{
auto& ex = iter->second;
ex(get_last_error(), std::string_view{});
}
}
});
}));
}
};
template<class derive_t>
class sync_caller
{
template <class, class> friend class rpc_call_cp;
protected:
sync_caller(derive_t& d) noexcept
: derive(d), id_(0), tm_(d.get_default_timeout()) {}
sync_caller(sync_caller&& o) noexcept
: derive(o.derive), id_(std::move(o.id_)), tm_(std::move(o.tm_)) {}
sync_caller(const sync_caller&) = delete;
sync_caller& operator=(sync_caller&&) = delete;
sync_caller& operator=(const sync_caller&) = delete;
public:
~sync_caller() = default;
/**
* @brief Set the timeout of this rpc call, only valid for this once call.
*/
template<class Rep, class Period>
inline sync_caller& set_timeout(std::chrono::duration<Rep, Period> timeout) noexcept
{
this->tm_ = std::move(timeout);
return (*this);
}
/**
* @brief Set the timeout of this rpc call, only valid for this once call. same as set_timeout
*/
template<class Rep, class Period>
inline sync_caller& timeout(std::chrono::duration<Rep, Period> timeout) noexcept
{
return this->set_timeout(std::move(timeout));
}
// If invoke synchronization rpc call function in communication thread, it will degenerates
// into async_call and the return value is empty.
template<class return_t, class ...Args>
inline return_t call(std::string name, Args&&... args)
{
return sync_call_op<derive_t>::template exec<return_t>(
derive, tm_, std::move(name), std::forward<Args>(args)...);
}
protected:
derive_t& derive;
rpc_header::id_type id_;
asio::steady_timer::duration tm_;
};
template<class derive_t>
class async_caller
{
template <class, class> friend class rpc_call_cp;
protected:
async_caller(derive_t& d) noexcept
: derive(d), id_(0), tm_(d.get_default_timeout()) {}
async_caller(async_caller&& o) noexcept
: derive(o.derive)
, id_(std::move(o.id_)), tm_(std::move(o.tm_))
, cb_(std::move(o.cb_)), fn_(std::move(o.fn_)) {}
async_caller(const async_caller&) = delete;
async_caller& operator=(async_caller&&) = delete;
async_caller& operator=(const async_caller&) = delete;
using defer_fn = std::function<void(rpc_header::id_type, asio::steady_timer::duration,
std::function<void(error_code, std::string_view)>)>;
public:
~async_caller()
{
if (this->fn_)
{
(this->fn_)(std::move(this->id_), std::move(this->tm_), std::move(this->cb_));
}
}
/**
* @brief Set the timeout of this rpc call, only valid for this once call.
*/
template<class Rep, class Period>
inline async_caller& set_timeout(std::chrono::duration<Rep, Period> timeout) noexcept
{
this->tm_ = timeout;
return (*this);
}
/**
* @brief Set the timeout of this rpc call, only valid for this once call. same as set_timeout
*/
template<class Rep, class Period>
inline async_caller& timeout(std::chrono::duration<Rep, Period> timeout) noexcept
{
return this->set_timeout(std::move(timeout));
}
/**
* @brief Set the callback function of this rpc call, only valid for this once call.
*/
template<class Callback>
inline async_caller& response(Callback&& cb)
{
this->id_ = derive.mkid();
this->cb_ = async_call_op<derive_t>::template make_callback(derive, std::forward<Callback>(cb));
return (*this);
}
template<class ...Args>
inline async_caller& async_call(std::string name, Args&&... args)
{
derive_t& deriv = derive;
this->fn_ = [&deriv, req = rpc_request<Args...>{ std::move(name),std::forward<Args>(args)... }]
(rpc_header::id_type id, asio::steady_timer::duration timeout,
std::function<void(error_code, std::string_view)> cb) mutable
{
if (!id)
{
async_call_op<derive_t>::template exec(deriv, std::move(req));
}
else
{
if (!cb)
{
async_call_op<derive_t>::template exec(deriv, std::move(id), std::move(timeout),
[](error_code, std::string_view) {}, std::move(req));
}
else
{
async_call_op<derive_t>::template exec(deriv, std::move(id), std::move(timeout),
std::move(cb), std::move(req));
}
}
};
return (*this);
}
protected:
derive_t& derive;
rpc_header::id_type id_;
asio::steady_timer::duration tm_;
std::function<void(error_code, std::string_view)> cb_;
defer_fn fn_;
};
template<class derive_t>
class base_caller
{
template <class, class> friend class rpc_call_cp;
protected:
base_caller(derive_t& d) noexcept
: derive(d), tm_(d.get_default_timeout()) {}
base_caller(base_caller&& o) noexcept
: derive(o.derive), tm_(std::move(o.tm_)) {}
base_caller& operator=(base_caller&&) = delete;
base_caller(const base_caller&) = delete;
base_caller& operator=(const base_caller&) = delete;
public:
~base_caller() = default;
/**
* @brief Set the timeout of this rpc call, only valid for this once call.
*/
template<class Rep, class Period>
inline base_caller& set_timeout(std::chrono::duration<Rep, Period> timeout) noexcept
{
this->tm_ = std::move(timeout);
return (*this);
}
/**
* @brief Set the timeout of this rpc call, only valid for this once call. same as set_timeout
*/
template<class Rep, class Period>
inline base_caller& timeout(std::chrono::duration<Rep, Period> timeout) noexcept
{
return this->set_timeout(std::move(timeout));
}
/**
* @brief Set the callback function of this rpc call, only valid for this once call.
*/
template<class Callback>
inline async_caller<derive_t> response(Callback&& cb)
{
async_caller<derive_t> caller{ derive };
caller.set_timeout(std::move(this->tm_));
caller.response(std::forward<Callback>(cb));
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
// If invoke synchronization rpc call function in communication thread, it will degenerates
// into async_call and the return value is empty.
template<class return_t, class ...Args>
inline return_t call(std::string name, Args&&... args)
{
return sync_call_op<derive_t>::template exec<return_t>(derive, this->tm_,
std::move(name), std::forward<Args>(args)...);
}
template<class ...Args>
inline async_caller<derive_t> async_call(std::string name, Args&&... args)
{
async_caller<derive_t> caller{ derive };
caller.set_timeout(std::move(this->tm_));
caller.async_call(std::move(name), std::forward<Args>(args)...);
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
protected:
derive_t& derive;
asio::steady_timer::duration tm_;
};
public:
/**
* @brief call a rpc function
* If invoke synchronization rpc call function in communication thread, it will degenerates
* into async_call and the return value is empty.
* You can use get_last_error to check whether there is an error of the call
*/
template<class return_t, class Rep, class Period, class ...Args>
inline return_t call(std::chrono::duration<Rep, Period> timeout, std::string name, Args&&... args)
{
derived_t& derive = static_cast<derived_t&>(*this);
return sync_call_op<derived_t>::template exec<return_t>(derive, timeout,
std::move(name), std::forward<Args>(args)...);
}
/**
* @brief call a rpc function
* If invoke synchronization rpc call function in communication thread, it will degenerates
* into async_call and the return value is empty.
* You can use get_last_error to check whether there is an error of the call
*/
template<class return_t, class ...Args>
inline return_t call(std::string name, Args&&... args)
{
derived_t& derive = static_cast<derived_t&>(*this);
return sync_call_op<derived_t>::template exec<return_t>(derive,
derive.get_default_timeout(), std::move(name), std::forward<Args>(args)...);
}
/**
* @brief asynchronous call a rpc function
* Callback signature : void(DataType result) example : [](std::string result){}
* if result type is void, the Callback signature is : void()
* Because the result value type is not specified in the first template parameter,
* so the result value type must be specified in the Callback lambda.
*/
template<class Callback, class ...Args>
inline typename std::enable_if_t<is_callable_v<Callback>, void>
async_call(Callback&& cb, std::string name, Args&&... args)
{
derived_t& derive = static_cast<derived_t&>(*this);
async_call_op<derived_t>::template exec(derive, derive.mkid(), derive.get_default_timeout(),
async_call_op<derived_t>::template make_callback(derive, std::forward<Callback>(cb)),
rpc_request<Args...>{ std::move(name), std::forward<Args>(args)... });
}
/**
* @brief asynchronous call a rpc function
* Callback signature : void(DataType result) example : [](std::string result){}
* if result type is void, the Callback signature is : void()
* Because the result value type is not specified in the first template parameter,
* so the result value type must be specified in the Callback lambda
*/
template<class Callback, class Rep, class Period, class ...Args>
inline typename std::enable_if_t<is_callable_v<Callback>, void>
async_call(Callback&& cb, std::chrono::duration<Rep, Period> timeout, std::string name, Args&&... args)
{
derived_t& derive = static_cast<derived_t&>(*this);
async_call_op<derived_t>::template exec(derive, derive.mkid(), timeout,
async_call_op<derived_t>::template make_callback(derive, std::forward<Callback>(cb)),
rpc_request<Args...>{ std::move(name), std::forward<Args>(args)... });
}
/**
* @brief asynchronous call a rpc function
* Callback signature : void(return_t result)
* the return_t is the first template parameter.
* if result type is void, the Callback signature is : void()
*/
template<class return_t, class Callback, class ...Args>
inline typename std::enable_if_t<detail::is_template_callable_v<Callback, return_t>, void>
async_call(Callback&& cb, std::string name, Args&&... args)
{
derived_t& derive = static_cast<derived_t&>(*this);
async_call_op<derived_t>::template exec(derive, derive.mkid(), derive.get_default_timeout(),
async_call_op<derived_t>::template make_callback<return_t>(
derive, std::forward<Callback>(cb)),
rpc_request<Args...>{ std::move(name), std::forward<Args>(args)... });
}
/**
* @brief asynchronous call a rpc function
* Callback signature : void(return_t result)
* the return_t is the first template parameter.
* if result type is void, the Callback signature is : void()
*/
template<class return_t, class Callback, class Rep, class Period, class ...Args>
inline typename std::enable_if_t<detail::is_template_callable_v<Callback, return_t>, void>
async_call(Callback&& cb, std::chrono::duration<Rep, Period> timeout, std::string name, Args&&... args)
{
derived_t& derive = static_cast<derived_t&>(*this);
async_call_op<derived_t>::template exec(derive, derive.mkid(), timeout,
async_call_op<derived_t>::template make_callback<return_t>(
derive, std::forward<Callback>(cb)),
rpc_request<Args...>{ std::move(name), std::forward<Args>(args)... });
}
/**
* @brief asynchronous call a rpc function
*/
template<class ...Args>
inline async_caller<derived_t> async_call(std::string name, Args&&... args)
{
async_caller<derived_t> caller{ static_cast<derived_t&>(*this) };
caller.async_call(std::move(name), std::forward<Args>(args)...);
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
/**
* @brief Set the timeout of this rpc call, only valid for this once call.
*/
template<class Rep, class Period>
inline base_caller<derived_t> set_timeout(std::chrono::duration<Rep, Period> timeout)
{
base_caller<derived_t> caller{ static_cast<derived_t&>(*this) };
caller.set_timeout(timeout);
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
/**
* @brief Set the timeout of this rpc call, only valid for this once call. same as set_timeout
*/
template<class Rep, class Period>
inline base_caller<derived_t> timeout(std::chrono::duration<Rep, Period> timeout)
{
return this->set_timeout(std::move(timeout));
}
/**
* @brief Set the callback function of this rpc call, only valid for this once call.
*/
template<class Callback>
inline async_caller<derived_t> response(Callback&& cb)
{
async_caller<derived_t> caller{ static_cast<derived_t&>(*this) };
caller.response(std::forward<Callback>(cb));
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
protected:
rpc_serializer & sr_;
rpc_deserializer & dr_;
/// The memory to use for handler-based custom memory allocation. used fo async_call.
handler_memory<std::false_type, assizer<args_t>> callocator_;
std::map<rpc_header::id_type, std::function<void(error_code, std::string_view)>> reqs_;
};
}
#endif // !__ASIO2_RPC_CALL_COMPONENT_HPP__
<file_sep>// eventpp library
// Copyright (C) 2018 <NAME> (wqking)
// Github: https://github.com/wqking/eventpp
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* This code is modified from eventpp
*
* author : zhllxt
* email : <EMAIL>
*
*/
//{
// std::cout << std::endl << "event_dispatcher tutorial 1, basic" << std::endl;
//
// // The namespace is asio2
// // The first template parameter int is the event type,
// // the event type can be any type such as std::string, int, etc.
// // The second is the prototype of the listener.
// asio2::event_dispatcher<int, void ()> dispatcher;
//
// // Add a listener. As the type of dispatcher,
// // here 3 and 5 is the event type,
// // []() {} is the listener.
// // Lambda is not required, any function or std::function
// // or whatever function object with the required prototype is fine.
// dispatcher.append_listener(3, []() {
// std::cout << "Got event 3." << std::endl;
// });
// dispatcher.append_listener(5, []() {
// std::cout << "Got event 5." << std::endl;
// });
// dispatcher.append_listener(5, []() {
// std::cout << "Got another event 5." << std::endl;
// });
//
// // Dispatch the events, the first argument is always the event type.
// dispatcher.dispatch(3);
// dispatcher.dispatch(5);
//}
//
//{
// std::cout << std::endl << "event_dispatcher tutorial 2, listener with parameters" << std::endl;
//
// // The listener has two parameters.
// asio2::event_dispatcher<int, void (const std::string &, const bool)> dispatcher;
//
// dispatcher.append_listener(3, [](const std::string & s, const bool b) {
// std::cout << std::boolalpha << "Got event 3, s is " << s << " b is " << b << std::endl;
// });
// // The listener prototype doesn't need to be exactly same as the dispatcher.
// // It would be find as long as the arguments is compatible with the dispatcher.
// dispatcher.append_listener(5, [](std::string s, int b) {
// std::cout << std::boolalpha << "Got event 5, s is " << s << " b is " << b << std::endl;
// });
// dispatcher.append_listener(5, [](const std::string & s, const bool b) {
// std::cout << std::boolalpha << "Got another event 5, s is " << s << " b is " << b << std::endl;
// });
//
// // Dispatch the events, the first argument is always the event type.
// dispatcher.dispatch(3, "Hello", true);
// dispatcher.dispatch(5, "World", false);
//}
//
//{
// std::cout << std::endl << "event_dispatcher tutorial 3, customized Event struct" << std::endl;
//
// // Define an Event to hold all parameters.
// struct MyEvent
// {
// int type;
// std::string message;
// int param;
// };
//
// // Define policies to let the dispatcher knows how to
// // extract the event type.
// struct MyEventPolicies
// {
// static int get_event(const MyEvent & e, bool /*b*/)
// {
// return e.type;
// }
//
// // single_thread, free lock
// using thread_t = asio2::dispatcheres::single_thread;
// };
//
// // Pass MyEventPolicies as the third template argument of event_dispatcher.
// // Note: the first template argument is the event type type int, not MyEvent.
// asio2::event_dispatcher<
// int,
// void (const MyEvent &, bool),
// MyEventPolicies
// > dispatcher;
//
// // Add a listener.
// // Note: the first argument is the event type of type int, not MyEvent.
// dispatcher.append_listener(3, [](const MyEvent & e, bool b) {
// std::cout
// << std::boolalpha
// << "Got event 3" << std::endl
// << "Event::type is " << e.type << std::endl
// << "Event::message is " << e.message << std::endl
// << "Event::param is " << e.param << std::endl
// << "b is " << b << std::endl
// ;
// });
//
// // Dispatch the event.
// // The first argument is Event.
// dispatcher.dispatch(MyEvent { 3, "Hello world", 38 }, true);
//}
//
//struct Tutor4MyEvent {
// Tutor4MyEvent() : type(0), canceled(false)
// {
// }
// explicit Tutor4MyEvent(const int type)
// : type(type), canceled(false)
// {
// }
//
// int type;
// mutable bool canceled;
//};
//
//struct Tutor4MyEventPolicies
//{
// // E is Tutor4MyEvent and get_event doesn't need to be template.
// // We make it template to show get_event can be templated member.
// template <typename E>
// static int get_event(const E & e)
// {
// return e.type;
// }
//
// // E is Tutor4MyEvent and can_continue_invoking doesn't need to be template.
// // We make it template to show can_continue_invoking can be templated member.
// template <typename E>
// static bool can_continue_invoking(const E & e)
// {
// return ! e.canceled;
// }
//};
//
//{
// std::cout << std::endl << "event_dispatcher tutorial 4, event canceling" << std::endl;
//
// asio2::event_dispatcher<int, void (const Tutor4MyEvent &), Tutor4MyEventPolicies> dispatcher;
//
// dispatcher.append_listener(3, [](const Tutor4MyEvent & e) {
// std::cout << "Got event 3" << std::endl;
// e.canceled = true;
// });
// dispatcher.append_listener(3, [](const Tutor4MyEvent & /*e*/) {
// std::cout << "Should not get this event 3" << std::endl;
// });
//
// dispatcher.dispatch(Tutor4MyEvent(3));
//}
//
//{
// std::cout << std::endl << "event_dispatcher tutorial 5, event filter" << std::endl;
//
// struct MyPolicies {
// using mixins_t = asio2::dispatcheres::mixin_list<asio2::dispatcheres::mixin_filter>;
// };
// asio2::event_dispatcher<int, void (int e, int i, std::string), MyPolicies> dispatcher;
//
// dispatcher.append_listener(3, [](const int /*e*/, const int i, const std::string & s) {
// std::cout
// << "Got event 3, i was 1 but actural is " << i
// << " s was Hello but actural is " << s
// << std::endl
// ;
// });
// dispatcher.append_listener(5, [](const int /*e*/, const int /*i*/, const std::string & /*s*/) {
// std::cout << "Shout not got event 5" << std::endl;
// });
//
// // Add three event filters.
//
// // The first filter modifies the input arguments to other values, then the subsequence filters
// // and listeners will see the modified values.
// dispatcher.append_filter([](const int e, int & i, std::string & s) -> bool {
// std::cout << "Filter 1, e is " << e << " passed in i is " << i << " s is " << s << std::endl;
// i = 38;
// s = "Hi";
// std::cout << "Filter 1, changed i is " << i << " s is " << s << std::endl;
// return true;
// });
//
// // The second filter filters out all event of 5. So no listeners on event 5 can be triggered.
// // The third filter is not invoked on event 5 also.
// dispatcher.append_filter([](const int e, int & i, std::string & s) -> bool {
// std::cout << "Filter 2, e is " << e << " passed in i is " << i << " s is " << s << std::endl;
// if(e == 5) {
// return false;
// }
// return true;
// });
//
// // The third filter just prints the input arguments.
// dispatcher.append_filter([](const int e, int & i, std::string & s) -> bool {
// std::cout << "Filter 3, e is " << e << " passed in i is " << i << " s is " << s << std::endl;
// return true;
// });
//
// // Dispatch the events, the first argument is always the event type.
// dispatcher.dispatch(3, 1, "Hello");
// dispatcher.dispatch(5, 2, "World");
//}
#ifndef __ASIO2_EVENT_DISPATCHER_HPP__
#define __ASIO2_EVENT_DISPATCHER_HPP__
#include <cassert>
#include <string>
#include <functional>
#include <type_traits>
#include <mutex>
#include <shared_mutex>
#include <memory>
#include <utility>
#include <tuple>
#include <atomic>
#include <condition_variable>
#include <map>
#include <unordered_map>
#include <list>
#include <thread>
#include <initializer_list>
#include <vector>
#include <optional>
// when compiled with "Visual Studio 2017 - Windows XP (v141_xp)"
// there is hasn't shared_mutex
#ifndef ASIO2_HAS_SHARED_MUTEX
#if defined(_MSC_VER)
#if defined(_HAS_SHARED_MUTEX)
#if _HAS_SHARED_MUTEX
#define ASIO2_HAS_SHARED_MUTEX 1
#define asio2_shared_mutex std::shared_mutex
#define asio2_shared_lock std::shared_lock
#define asio2_unique_lock std::unique_lock
#else
#define ASIO2_HAS_SHARED_MUTEX 0
#define asio2_shared_mutex std::mutex
#define asio2_shared_lock std::lock_guard
#define asio2_unique_lock std::lock_guard
#endif
#else
#define ASIO2_HAS_SHARED_MUTEX 1
#define asio2_shared_mutex std::shared_mutex
#define asio2_shared_lock std::shared_lock
#define asio2_unique_lock std::unique_lock
#endif
#else
#define ASIO2_HAS_SHARED_MUTEX 1
#define asio2_shared_mutex std::shared_mutex
#define asio2_shared_lock std::shared_lock
#define asio2_unique_lock std::unique_lock
#endif
#endif
namespace asio2 {
namespace dispatcheres {
template <typename F, template <typename> class T>
struct transform_arguments;
template <template <typename> class T, typename RT, typename ...Args>
struct transform_arguments <RT (Args...), T>
{
using type = RT (typename T<Args>::type...);
};
template <typename F, typename Replacement>
struct replace_return_type;
template <typename Replacement, typename RT, typename ...Args>
struct replace_return_type <RT (Args...), Replacement>
{
using type = Replacement (Args...);
};
template <int N, int M>
struct int_to_constant_helper
{
template <typename C, typename ...Args>
static auto find(const int index, C && c, Args && ...args)
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
{
if(N == index)
{
return c.template operator()<N>(std::forward<Args>(args)...);
}
else
{
return int_to_constant_helper<N + 1, M>::find(index, std::forward<C>(c), std::forward<Args>(args)...);
}
}
};
template <int M>
struct int_to_constant_helper <M, M>
{
template <typename C, typename ...Args>
static auto find(const int /*index*/, C && c, Args && ...args)
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
{
return decltype(c.template operator()<0>(std::forward<Args>(args)...))();
}
};
template <int M, typename C, typename ...Args>
auto int_to_constant(const int index, C && c, Args && ...args)
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
{
return int_to_constant_helper<0, M>::find(index, std::forward<C>(c), std::forward<Args>(args)...);
}
template <typename F, typename ...Args>
struct can_invoke
{
template <typename U, typename ...X>
static auto invoke(int) -> decltype(std::declval<U>()(std::declval<X>()...), std::true_type());
template <typename U, typename ...X>
static auto invoke(...) -> std::false_type;
enum
{
value = !! decltype(invoke<F, Args...>(0))()
};
};
template <typename T>
struct shift_tuple;
template <typename A, typename ...Args>
struct shift_tuple <std::tuple<A, Args...> >
{
using type = std::tuple<Args...>;
};
template <>
struct shift_tuple <std::tuple<> >
{
using type = std::tuple<>;
};
// for compile time debug
template<typename T>
void print_type_in_compile_time(T * = 0)
{
static_assert(std::is_same<T, int>::value && ! std::is_same<T, int>::value, "The error shows the type name.");
}
template<int N>
void print_int_in_compile_time()
{
int n = 0;
switch(n)
{
case N:
case N:
break;
};
}
} //namespace dispatcheres
//-------------------------------------------------------------------------------------------------
namespace dispatcheres {
struct tag_homo {};
struct tag_callback_list : public tag_homo {};
struct tag_event_dispatcher : public tag_homo {};
struct tag_event_queue : public tag_homo {};
template <
typename MutexT = asio2_shared_mutex,
template <typename > class SharedLockT = asio2_shared_lock,
template <typename > class UniqueLockT = asio2_unique_lock,
template <typename > class AtomicT = std::atomic,
typename ConditionVariableT = std::condition_variable
>
struct general_thread
{
using mutex = MutexT;
template <typename T>
using shared_lock = SharedLockT<T>;
template <typename T>
using unique_lock = UniqueLockT<T>;
template <typename T>
using atomic = AtomicT<T>;
using condition_variable = ConditionVariableT;
};
struct multiple_thread
{
using mutex = asio2_shared_mutex;
template <typename T>
using shared_lock = asio2_shared_lock<T>;
template <typename T>
using unique_lock = asio2_unique_lock<T>;
template <typename T>
using atomic = std::atomic<T>;
using condition_variable = std::condition_variable;
};
struct single_thread
{
struct mutex
{
inline void lock () noexcept {}
inline void unlock() noexcept {}
};
template <typename T>
struct shared_lock
{
using mutex_type = T;
inline shared_lock() noexcept = default;
inline shared_lock(shared_lock&& other) noexcept = default;
inline explicit shared_lock(mutex_type&) noexcept {}
inline ~shared_lock() noexcept {};
inline void lock () noexcept {}
inline void unlock() noexcept {}
};
template <typename T>
struct unique_lock
{
using mutex_type = T;
inline unique_lock() noexcept = default;
inline unique_lock(unique_lock&& other) noexcept = default;
inline explicit unique_lock(mutex_type&) noexcept {}
inline ~unique_lock() noexcept {};
inline void lock () noexcept {}
inline void unlock() noexcept {}
};
template <typename T>
struct atomic
{
inline atomic() = default;
constexpr atomic(T desired) noexcept
: value(desired)
{
}
inline void store(T desired, std::memory_order /*order*/ = std::memory_order_seq_cst) noexcept
{
value = desired;
}
inline T load(std::memory_order /*order*/ = std::memory_order_seq_cst) const noexcept
{
return value;
}
inline T exchange(T desired, std::memory_order /*order*/ = std::memory_order_seq_cst) noexcept
{
const T old = value;
value = desired;
return old;
}
inline T operator ++ () noexcept
{
return ++value;
}
inline T operator -- () noexcept
{
return --value;
}
T value{};
};
struct condition_variable
{
inline void notify_one() noexcept
{
}
template <class Predicate>
inline void wait(std::unique_lock<std::mutex> & /*lock*/, Predicate /*pred*/) noexcept
{
}
template <class Rep, class Period, class Predicate>
inline bool wait_for(std::unique_lock<std::mutex> & /*lock*/,
const std::chrono::duration<Rep, Period> & /*rel_time*/,
Predicate /*pred*/) noexcept
{
return true;
}
};
};
struct argument_passing_auto_detect
{
enum
{
can_include_event_type = true,
can_exclude_event_type = true
};
};
struct argument_passing_include_event
{
enum
{
can_include_event_type = true,
can_exclude_event_type = false
};
};
struct argument_passing_exclude_event
{
enum
{
can_include_event_type = false,
can_exclude_event_type = true
};
};
struct default_policy
{
};
template <template <typename> class ...user_mixins>
struct mixin_list
{
};
} //namespace dispatcheres
//-------------------------------------------------------------------------------------------------
namespace dispatcheres {
template <typename T>
struct has_type_argument_passing_mode
{
template <typename C> static std::true_type test(typename C::argument_passing_mode *) ;
template <typename C> static std::false_type test(...);
enum { value = !! decltype(test<T>(0))() };
};
template <typename T, bool, typename Default>
struct select_argument_passing_mode { using type = typename T::argument_passing_mode; };
template <typename T, typename Default>
struct select_argument_passing_mode <T, false, Default> { using type = Default; };
// https://en.cppreference.com/w/cpp/types/void_t
// primary template handles types that have no nested ::type member:
template< class, class = void >
struct has_type_thread_t : std::false_type { };
// specialization recognizes types that do have a nested ::type member:
template< class T >
struct has_type_thread_t<T, std::void_t<typename T::thread_t>> : std::true_type { };
template <typename T, bool> struct select_thread { using type = typename T::thread_t; };
template <typename T> struct select_thread <T, false> { using type = multiple_thread; };
// primary template handles types that have no nested ::type member:
template< class, class = void >
struct has_type_callback_t : std::false_type { };
// specialization recognizes types that do have a nested ::type member:
template< class T >
struct has_type_callback_t<T, std::void_t<typename T::callback_t>> : std::true_type { };
template <typename T, bool, typename D> struct select_callback { using type = typename T::callback_t; };
template <typename T, typename D> struct select_callback<T, false, D> { using type = D; };
// primary template handles types that have no nested ::type member:
template< class, class = void >
struct has_type_user_data_t : std::false_type { };
// specialization recognizes types that do have a nested ::type member:
template< class T >
struct has_type_user_data_t<T, std::void_t<typename T::user_data_t>> : std::true_type { };
// primary template handles types that have no nested ::type member:
template< class, class = void >
struct has_type_listener_name_t : std::false_type { };
// specialization recognizes types that do have a nested ::type member:
template< class T >
struct has_type_listener_name_t<T, std::void_t<typename T::listener_name_t>> : std::true_type { };
template <typename T, bool, typename D> struct select_listener_name { using type = typename T::listener_name_t; };
template <typename T, typename D> struct select_listener_name<T, false, D> { using type = D; };
template <typename T, typename ...Args>
struct has_function_get_event
{
template <typename C> static std::true_type test(decltype(C::get_event(std::declval<Args>()...)) *);
template <typename C> static std::false_type test(...);
enum { value = !! decltype(test<T>(0))() };
};
template <typename E>
struct default_get_event
{
template <typename U, typename ...Args>
static E get_event(U && e, Args && ...)
{
return e;
}
};
template <typename T, typename Key, bool> struct select_get_event { using type = T; };
template <typename T, typename Key> struct select_get_event<T, Key, false> { using type = default_get_event<Key>; };
template <typename T, typename ...Args>
struct has_function_can_continue_invoking
{
template <typename C> static std::true_type test(decltype(C::can_continue_invoking(std::declval<Args>()...)) *) ;
template <typename C> static std::false_type test(...);
enum { value = !! decltype(test<T>(0))() };
};
struct default_can_continue_invoking
{
template <typename ...Args>
static bool can_continue_invoking(Args && ...)
{
return true;
}
};
template <typename T, bool> struct select_can_continue_invoking { using type = T; };
template <typename T> struct select_can_continue_invoking<T, false> { using type = default_can_continue_invoking; };
template <typename T>
struct has_template_map_t
{
template <typename C> static std::true_type test(typename C::template map_t<int, int> *) ;
template <typename C> static std::false_type test(...);
enum { value = !! decltype(test<T>(0))() };
};
template <typename T>
class has_std_hash
{
template <typename C> static std::true_type test(decltype(std::hash<C>()(std::declval<C>())) *) ;
template <typename C> static std::false_type test(...);
public:
enum { value = !! decltype(test<T>(0))() };
};
template <typename Key, typename Value, typename T, bool>
struct select_map
{
using type = typename T::template map_t<Key, Value>;
};
template <typename Key, typename Value, typename T>
struct select_map<Key, Value, T, false>
{
using type = typename std::conditional<
has_std_hash<Key>::value,
std::unordered_map<Key, Value>,
std::map<Key, Value>
>::type;
};
template <typename ListenerNameType, typename EventType, typename Value, typename T, bool>
struct select_listener_name_map
{
using type = typename T::template map_t<ListenerNameType, typename T::template map_t<EventType, Value>>;
};
template <typename ListenerNameType, typename EventType, typename Value, typename T>
struct select_listener_name_map<ListenerNameType, EventType, Value, T, false>
{
using type = typename std::conditional<
has_std_hash<ListenerNameType>::value,
typename std::conditional_t<
has_std_hash<EventType>::value,
std::unordered_map<ListenerNameType, std::unordered_multimap<EventType, Value>>,
std::unordered_map<ListenerNameType, std::multimap<EventType, Value>>
>,
typename std::conditional_t<
has_std_hash<EventType>::value,
std::map<ListenerNameType, std::unordered_multimap<EventType, Value>>,
std::map<ListenerNameType, std::multimap<EventType, Value>>
>
>::type;
};
template <typename T>
struct has_template_queue_list_t
{
template <typename C> static std::true_type test(typename C::template queue_list_t<int> *);
template <typename C> static std::false_type test(...);
enum { value = !! decltype(test<T>(0))() };
};
template <typename Value, typename T, bool>
struct select_queue_list
{
using type = typename T::template queue_list_t<Value>;
};
template <typename Value, typename T>
struct select_queue_list<Value, T, false>
{
using type = std::list<Value>;
};
template <typename T>
struct has_type_mixins_t
{
template <typename C> static std::true_type test(typename C::mixins_t *) ;
template <typename C> static std::false_type test(...);
enum { value = !! decltype(test<T>(0))() };
};
template <typename T, bool> struct select_mixins { using type = typename T::mixins_t; };
template <typename T> struct select_mixins <T, false> { using type = mixin_list<>; };
template <typename Root, typename TList>
struct inherit_mixins;
template <typename Root, template <typename> class T, template <typename> class ...Args>
struct inherit_mixins <Root, mixin_list<T, Args...> >
{
using type = T <typename inherit_mixins<Root, mixin_list<Args...> >::type>;
};
template <typename Root>
struct inherit_mixins <Root, mixin_list<> >
{
using type = Root;
};
template <typename Root, typename TList, typename Func>
struct for_each_mixins;
template <typename Func, typename Root, template <typename> class T, template <typename> class ...Args>
struct for_each_mixins <Root, mixin_list<T, Args...>, Func>
{
using type = typename inherit_mixins<Root, mixin_list<T, Args...> >::type;
template <typename ...A>
static bool for_each(A && ...args)
{
if(Func::template for_each<type>(args...))
{
return for_each_mixins<Root, mixin_list<Args...>, Func>::for_each(std::forward<A>(args)...);
}
return false;
}
};
template <typename Root, typename Func>
struct for_each_mixins <Root, mixin_list<>, Func>
{
using type = Root;
template <typename ...A>
static bool for_each(A && .../*args*/)
{
return true;
}
};
template <typename T, typename ...Args>
struct has_function_mixin_before_dispatch
{
template <typename C> static std::true_type test(
decltype(std::declval<C>().mixin_before_dispatch(std::declval<Args>()...)) *
);
template <typename C> static std::false_type test(...);
enum { value = !! decltype(test<T>(0))() };
};
} //namespace dispatcheres
//-------------------------------------------------------------------------------------------------
namespace dispatcheres {
template <
typename EventTypeT,
typename ProtoType,
typename PolicyType
>
class callback_list_base;
template <
typename EventTypeT,
typename PrototypeT,
typename PolicyT,
typename MixinRootT
>
class event_dispatcher_base;
template <
typename EventTypeT,
typename PolicyType,
bool HasTypeUserData,
typename ProtoType
>
class node_traits;
template <
typename EventTypeT,
typename PolicyType,
typename ReturnType, typename ...Args
>
class node_traits<
EventTypeT,
PolicyType,
true,
ReturnType (Args...)
>
{
private:
template <
typename,
typename,
typename
>
friend class callback_list_base;
template <
typename,
typename,
typename,
typename
>
friend class event_dispatcher_base;
public:
using policy_type = PolicyType;
using event_type = EventTypeT;
using callback_type = typename select_callback<
policy_type,
has_type_callback_t<policy_type>::value,
std::function<ReturnType (Args...)>
>::type;
using listener_name_type = typename select_listener_name<
policy_type,
has_type_listener_name_t<policy_type>::value,
std::string_view
>::type;
using user_data_type = typename policy_type::user_data_t;
struct node;
using node_ptr = std::shared_ptr<node>;
struct node
{
private:
template <
typename,
typename,
typename
>
friend class callback_list_base;
template <
typename,
typename,
typename,
typename
>
friend class event_dispatcher_base;
public:
using counter_type = unsigned int;
node(const listener_name_type& nm, const event_type& e, callback_type cb, const counter_type count)
: evt(e), callback(std::move(cb)), counter(count), name(nm)
{
}
inline const event_type get_event_type() const noexcept { return evt; }
inline const listener_name_type get_listener_name() const noexcept { return name; }
inline node& set_user_data(user_data_type data) noexcept { userdata = std::move(data); return (*this); }
inline const user_data_type& get_user_data() const noexcept { return userdata; }
protected:
event_type evt;
callback_type callback;
counter_type counter;
listener_name_type name{};
user_data_type userdata{};
node_ptr prev;
node_ptr next;
};
};
template <
typename EventTypeT,
typename PolicyType,
typename ReturnType, typename ...Args
>
class node_traits<
EventTypeT,
PolicyType,
false,
ReturnType (Args...)
>
{
private:
template <
typename,
typename,
typename
>
friend class callback_list_base;
template <
typename,
typename,
typename,
typename
>
friend class event_dispatcher_base;
public:
using policy_type = PolicyType;
using event_type = EventTypeT;
using callback_type = typename select_callback<
policy_type,
has_type_callback_t<policy_type>::value,
std::function<ReturnType (Args...)>
>::type;
using listener_name_type = typename select_listener_name<
policy_type,
has_type_listener_name_t<policy_type>::value,
std::string_view
>::type;
using user_data_type = void;
struct node;
using node_ptr = std::shared_ptr<node>;
struct node
{
private:
template <
typename,
typename,
typename
>
friend class callback_list_base;
template <
typename,
typename,
typename,
typename
>
friend class event_dispatcher_base;
public:
using counter_type = unsigned int;
node(const listener_name_type& nm, const event_type& e, callback_type cb, const counter_type count)
: evt(e), callback(std::move(cb)), counter(count), name(nm)
{
}
inline const event_type get_event_type() const noexcept { return evt; }
inline const listener_name_type get_listener_name() const noexcept { return name; }
protected:
event_type evt;
callback_type callback;
counter_type counter;
listener_name_type name{};
node_ptr prev;
node_ptr next;
};
};
template <
typename EventTypeT,
typename PolicyType,
typename ReturnType, typename ...Args
>
class callback_list_base<
EventTypeT,
ReturnType (Args...),
PolicyType
> : public node_traits<EventTypeT, PolicyType, has_type_user_data_t<PolicyType>::value, ReturnType(Args...)>
{
private:
template <
typename,
typename,
typename,
typename
>
friend class event_dispatcher_base;
public:
using node_traits_type =
node_traits<EventTypeT, PolicyType, has_type_user_data_t<PolicyType>::value, ReturnType(Args...)>;
using this_type = callback_list_base<
EventTypeT,
ReturnType(Args...),
PolicyType
>;
using policy_type = PolicyType;
using event_type = EventTypeT;
using thread_type = typename select_thread<policy_type, has_type_thread_t<policy_type>::value>::type;
using callback_type = typename node_traits_type::callback_type;
using listener_name_type = typename node_traits_type::listener_name_type;
using can_continue_invoking_type = typename select_can_continue_invoking<
policy_type, has_function_can_continue_invoking<policy_type, Args...>::value
>::type;
using node = typename node_traits_type::node;
using node_ptr = typename node_traits_type::node_ptr;
class handle_type : public std::weak_ptr<node>
{
private:
using super = std::weak_ptr<node>;
public:
using super::super;
inline operator bool () const noexcept
{
return ! this->expired();
}
};
using counter_type = typename node::counter_type;
static constexpr counter_type removed_counter = 0;
public:
using node_wptr = handle_type;
using mutex_type = typename thread_type::mutex;
public:
callback_list_base() noexcept
: head()
, tail()
, list_mtx_()
, current_counter_(0)
{
}
callback_list_base(const callback_list_base & other)
: callback_list_base()
{
size_ = other.size_;
copy_from(other.head);
}
callback_list_base(callback_list_base && other) noexcept
: callback_list_base()
{
swap(other);
}
// If we use pass by value idiom and omit the 'this' check,
// when assigning to self there is a deep copy which is inefficient.
callback_list_base & operator = (const callback_list_base & other)
{
if(this != &other)
{
callback_list_base copied(other);
swap(copied);
}
return *this;
}
callback_list_base & operator = (callback_list_base && other) noexcept
{
if(this != &other)
{
do_free_all_nodes();
head = std::move(other.head);
tail = std::move(other.tail);
current_counter_ = other.current_counter_.load();
size_ = other.size_;
}
return *this;
}
~callback_list_base()
{
// Don't lock mutex here since it may throw exception
do_free_all_nodes();
}
void swap(callback_list_base & other) noexcept
{
using std::swap;
swap(head, other.head);
swap(tail, other.tail);
swap(size_, other.size_);
const auto value = current_counter_.load();
current_counter_.exchange(other.current_counter_.load());
other.current_counter_.exchange(value);
}
inline bool empty() const noexcept
{
// Don't lock the mutex for performance reason.
// !head still works even when the underlying raw pointer is garbled (for other thread is writting to head)
// And empty() doesn't guarantee the list is still empty after the function returned.
//std::lock_guard<mutex_type> guard(list_mtx_);
return ! head;
}
inline operator bool() const noexcept
{
return ! empty();
}
node_wptr append(const listener_name_type& name, const event_type& e, callback_type cb)
{
node_ptr n(do_allocate_node(name, e, std::move(cb)));
typename thread_type::template unique_lock<mutex_type> guard(list_mtx_);
if(head)
{
n->prev = tail;
tail->next = n;
tail = n;
}
else
{
head = n;
tail = n;
}
++size_;
return node_wptr(n);
}
node_wptr prepend(const listener_name_type& name, const event_type& e, callback_type cb)
{
node_ptr n(do_allocate_node(name, e, std::move(cb)));
typename thread_type::template unique_lock<mutex_type> guard(list_mtx_);
if(head)
{
n->next = head;
head->prev = n;
head = n;
}
else
{
head = n;
tail = n;
}
++size_;
return node_wptr(n);
}
node_wptr insert(const listener_name_type& name, const event_type& e, callback_type cb, const node_wptr & before)
{
node_ptr before_node = before.lock();
if(before_node)
{
node_ptr n(do_allocate_node(name, e, std::move(cb)));
typename thread_type::template unique_lock<mutex_type> guard(list_mtx_);
do_insert(n, before_node);
++size_;
return node_wptr(n);
}
return append(name, e, std::move(cb));
}
bool remove(const node_wptr & nwptr)
{
auto n = nwptr.lock();
if (n)
{
typename thread_type::template unique_lock<mutex_type> guard(list_mtx_);
do_free_node(n);
--size_;
return true;
}
return false;
}
inline std::size_t size() const noexcept
{
return size_;
}
inline void clear() noexcept
{
callback_list_base other{};
swap(other);
}
protected:
inline void iterator_move_to_next(node_ptr& n) noexcept
{
typename thread_type::template shared_lock<mutex_type> guard(list_mtx_);
n = n->next;
}
inline void iterator_move_to_prev(node_ptr& n) noexcept
{
typename thread_type::template shared_lock<mutex_type> guard(list_mtx_);
n = n->prev;
}
public:
class iterator
{
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = node_ptr;
using difference_type = std::ptrdiff_t;
using pointer = value_type&;
using reference = value_type&;
explicit iterator(this_type& m) : master_(m)
{
}
explicit iterator(this_type& m, value_type v) : master_(m), value_(std::move(v))
{
}
explicit iterator(const this_type& m) : master_(const_cast<this_type&>(m))
{
}
explicit iterator(const this_type& m, value_type v) : master_(const_cast<this_type&>(m)), value_(std::move(v))
{
}
[[nodiscard]] reference operator*() noexcept
{
return value_;
}
[[nodiscard]] pointer operator->() noexcept
{
return value_;
}
iterator& operator++() noexcept
{
if (value_)
{
master_.iterator_move_to_next(value_);
}
return (*this);
}
iterator& operator--() noexcept
{
if (value_)
{
master_.iterator_move_to_prev(value_);
}
return (*this);
}
[[nodiscard]] bool operator==(const iterator& right) const
{
return (value_.get() == right.value_.get());
}
[[nodiscard]] bool operator!=(const iterator& right) const
{
return (value_.get() != right.value_.get());
}
protected:
this_type& master_;
value_type value_{};
};
using const_iterator = iterator;
/// Return a const iterator to the beginning of the field sequence.
inline iterator begin() noexcept
{
typename thread_type::template shared_lock<mutex_type> guard(list_mtx_);
return iterator(*this, head);
}
/// Return a const iterator to the end of the field sequence.
inline iterator end() noexcept
{
return iterator(*this);
}
/// Return a const iterator to the beginning of the field sequence.
inline const_iterator begin() const noexcept
{
typename thread_type::template shared_lock<mutex_type> guard(list_mtx_);
return (const_iterator(*this, head));
}
/// Return a const iterator to the end of the field sequence.
inline const_iterator end() const noexcept
{
return (const_iterator(*this));
}
/// Return a const iterator to the beginning of the field sequence.
inline const_iterator cbegin() const noexcept
{
return (begin());
}
/// Return a const iterator to the end of the field sequence.
inline const_iterator cend() const noexcept
{
return (end());
}
template <typename Func>
void for_each(Func && func) const
{
do_for_each_if([&func, this](node_ptr & n) -> bool
{
do_for_each_invoke<void>(func, n);
return true;
});
}
template <typename Func>
bool for_each_if(Func && func) const
{
return do_for_each_if([&func, this](node_ptr & n) -> bool
{
return do_for_each_invoke<bool>(func, n);
});
}
#if !defined(__GNUC__) || __GNUC__ >= 5
void operator() (Args ...args) const
{
for_each_if([&args...](callback_type & cb) -> bool
{
// We can't use std::forward here, because if we use std::forward,
// for arg that is passed by value, and the callback prototype accepts it by value,
// std::forward will move it and may cause the original value invalid.
// That happens on any value-to-value passing, no matter the callback moves it or not.
cb(args...);
return can_continue_invoking_type::can_continue_invoking(args...);
});
}
#else
// This is a patch version for GCC 4. It inlines the unrolled do_for_each_if.
// GCC 4.8.3 doesn't supporting parameter pack catpure in lambda, see,
// https://github.com/wqking/eventpp/issues/19
// This is a compromised patch for GCC 4, it may be not maintained or updated unless there are bugs.
// We don't use the patch as main code because the patch generates longer code, and duplicated with do_for_each_if.
void operator() (Args ...args) const
{
node_ptr n;
{
typename thread_type::template shared_lock<mutex_type> guard(list_mtx_);
n = head;
}
const counter_type counter = current_counter_.load(std::memory_order_acquire);
while(n)
{
if(n->counter != removed_counter && counter >= n->counter)
{
n->callback(args...);
if(! can_continue_invoking_type::can_continue_invoking(args...))
{
break;
}
}
{
typename thread_type::template shared_lock<mutex_type> guard(list_mtx_);
n = n->next;
}
}
}
#endif
private:
template <typename F>
bool do_for_each_if(F && f) const
{
node_ptr n;
{
typename thread_type::template shared_lock<mutex_type> guard(list_mtx_);
n = head;
}
const counter_type counter = current_counter_.load(std::memory_order_acquire);
while(n)
{
if(n->counter != removed_counter && counter >= n->counter)
{
if(! f(n))
{
return false;
}
}
{
typename thread_type::template shared_lock<mutex_type> guard(list_mtx_);
n = n->next;
}
}
return true;
}
template <typename RT, typename Func>
inline auto do_for_each_invoke(Func && func, node_ptr & n) const
-> typename std::enable_if<can_invoke<Func, node_wptr, callback_type &>::value, RT>::type
{
return func(node_wptr(n), n->callback);
}
template <typename RT, typename Func>
inline auto do_for_each_invoke(Func && func, node_ptr & n) const
-> typename std::enable_if<can_invoke<Func, callback_type &>::value, RT>::type
{
return func(n->callback);
}
void do_insert(node_ptr & n, node_ptr & before_node)
{
n->prev = before_node->prev;
n->next = before_node;
if(before_node->prev)
{
before_node->prev->next = n;
}
before_node->prev = n;
if(before_node == head)
{
head = n;
}
}
inline node_ptr do_allocate_node(const listener_name_type& name, const event_type& e, callback_type cb)
{
return std::make_shared<node>(name, e, std::move(cb), get_next_counter());
}
void do_free_node(const node_ptr & cn)
{
node_ptr & n = const_cast<node_ptr &>(cn);
if(n->next)
{
n->next->prev = n->prev;
}
if(n->prev)
{
n->prev->next = n->next;
}
// Mark it as deleted, this must be before the assignment of head and tail below,
// because node can be a reference to head or tail, and after the assignment, node
// can be null pointer.
n->counter = removed_counter;
if(head == n)
{
head = n->next;
}
if(tail == n)
{
tail = n->prev;
}
// don't modify n->prev or n->next
// because node may be still used in a loop.
}
void do_free_all_nodes()
{
node_ptr n = head;
head.reset();
while(n)
{
node_ptr next = n->next;
n->prev.reset();
n->next.reset();
n = next;
}
n.reset();
}
counter_type get_next_counter()
{
counter_type result = ++current_counter_;;
if(result == 0)
{
// overflow, let's reset all nodes' counters.
{
typename thread_type::template unique_lock<mutex_type> guard(list_mtx_);
node_ptr n = head;
while(n)
{
n->counter = 1;
n = n->next;
}
}
result = ++current_counter_;
}
return result;
}
void copy_from(const node_ptr & from_head)
{
node_ptr from_node(from_head);
node_ptr n;
const counter_type counter = get_next_counter();
while(from_node)
{
const node_ptr next_node(std::make_shared<node>(from_node->evt, from_node->callback, counter));
next_node->prev = n;
if(n)
{
n->next = next_node;
}
else
{
n = next_node;
head = n;
}
n = next_node;
from_node = from_node->next;
}
tail = n;
}
private:
node_ptr head;
node_ptr tail;
mutable mutex_type list_mtx_;
typename thread_type::template atomic<counter_type> current_counter_;
std::size_t size_ = 0;
};
} //namespace dispatcheres
namespace dispatcheres {
template <
typename EventTypeT,
typename PrototypeT,
typename PolicyT = default_policy
>
class callback_list : public dispatcheres::callback_list_base<EventTypeT, PrototypeT, PolicyT>, public tag_callback_list
{
private:
using super = dispatcheres::callback_list_base<EventTypeT, PrototypeT, PolicyT>;
public:
using super::super;
friend void swap(callback_list & first, callback_list & second) noexcept
{
first.swap(second);
}
};
} //namespace dispatcheres
//-------------------------------------------------------------------------------------------------
namespace dispatcheres {
template <
typename EventTypeT,
typename PolicyT,
typename MixinRootT,
typename ReturnType, typename ...Args
>
class event_dispatcher_base <
EventTypeT,
ReturnType (Args...),
PolicyT,
MixinRootT
>
{
public:
using this_type = event_dispatcher_base<
EventTypeT,
ReturnType (Args...),
PolicyT,
MixinRootT
>;
using mixin_root_type = typename std::conditional<
std::is_same<MixinRootT, void>::value,
this_type,
MixinRootT
>::type;
using policy_type = PolicyT;
using thread_type = typename select_thread<PolicyT, has_type_thread_t<PolicyT>::value>::type;
using argument_passing_mode_type = typename select_argument_passing_mode<
PolicyT,
has_type_argument_passing_mode<PolicyT>::value,
argument_passing_auto_detect
>::type;
using callback_type = typename select_callback<
PolicyT,
has_type_callback_t<PolicyT>::value,
std::function<ReturnType (Args...)>
>::type;
using callback_list_type = callback_list<EventTypeT, ReturnType (Args...), PolicyT>;
using listener_name_type = typename callback_list_type::listener_name_type;
using proto_type = ReturnType (Args...);
using map_type = typename select_map<
EventTypeT,
callback_list_type,
PolicyT,
has_template_map_t<PolicyT>::value
>::type;
using listener_name_map_type = typename select_listener_name_map<
listener_name_type,
EventTypeT,
typename callback_list_type::node_wptr,
PolicyT,
has_template_map_t<PolicyT>::value
>::type;
using mixins_type = typename dispatcheres::select_mixins<
PolicyT,
dispatcheres::has_type_mixins_t<PolicyT>::value
>::type;
public:
using listener_wptr = typename callback_list_type::node_wptr;
using listener_type = listener_wptr;
using event_type = EventTypeT;
using mutex_type = typename thread_type::mutex;
public:
event_dispatcher_base()
: listener_map_()
, listener_mtx_()
, listener_name_map_()
{
}
event_dispatcher_base(const event_dispatcher_base & other)
: listener_map_(other.listener_map_)
, listener_mtx_()
, listener_name_map_(other.listener_name_map_)
{
}
event_dispatcher_base(event_dispatcher_base && other) noexcept
: listener_map_(std::move(other.listener_map_))
, listener_mtx_()
, listener_name_map_(std::move(other.listener_name_map_))
{
}
event_dispatcher_base & operator = (const event_dispatcher_base & other)
{
listener_map_ = other.listener_map_;
listener_name_map_ = other.listener_name_map_;
return *this;
}
event_dispatcher_base & operator = (event_dispatcher_base && other) noexcept
{
listener_map_ = std::move(other.listener_map_);
listener_name_map_ = std::move(other.listener_name_map_);
return *this;
}
void swap(event_dispatcher_base & other) noexcept
{
using std::swap;
swap(listener_map_, other.listener_map_);
swap(listener_name_map_, other.listener_name_map_);
}
listener_wptr append_listener(const event_type& e, callback_type cb)
{
return append_listener(listener_name_type{}, e, std::move(cb));
}
std::vector<listener_wptr> append_listener(const std::initializer_list<event_type>& es, const callback_type& cb)
{
return append_listener(listener_name_type{}, es, cb);
}
listener_wptr prepend_listener(const event_type& e, callback_type cb)
{
return prepend_listener(listener_name_type{}, e, std::move(cb));
}
std::vector<listener_wptr> prepend_listener(const std::initializer_list<event_type>& es, const callback_type& cb)
{
return prepend_listener(listener_name_type{}, es, cb);
}
listener_wptr insert_listener(const event_type& e, callback_type cb, const listener_wptr & before)
{
return insert_listener(listener_name_type{}, e, std::move(cb), before);
}
template<class Function>
typename std::enable_if_t<can_invoke<Function, typename callback_list_type::node_ptr&>::value, listener_wptr>
insert_listener(const event_type& e, callback_type cb, Function&& pred)
{
return insert_listener(listener_name_type{}, e, std::move(cb), std::forward<Function>(pred));
}
listener_wptr append_listener(const listener_name_type& name, const event_type& e, callback_type cb)
{
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
listener_wptr ptr = listener_map_[e].append(name, e, std::move(cb));
listener_name_map_[name].emplace(e, ptr);
return ptr;
}
std::vector<listener_wptr> append_listener(
const listener_name_type& name, const std::initializer_list<event_type>& es, const callback_type& cb)
{
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
std::vector<listener_wptr> v;
v.reserve(es.size());
for (auto& e : es)
{
listener_wptr ptr = listener_map_[e].append(name, e, cb);
listener_name_map_[name].emplace(e, ptr);
v.emplace_back(std::move(ptr));
}
return v;
}
listener_wptr prepend_listener(const listener_name_type& name, const event_type & e, callback_type cb)
{
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
listener_wptr ptr = listener_map_[e].prepend(name, e, std::move(cb));
listener_name_map_[name].emplace(e, ptr);
return ptr;
}
std::vector<listener_wptr> prepend_listener(
const listener_name_type& name, const std::initializer_list<event_type>& es, const callback_type& cb)
{
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
std::vector<listener_wptr> v;
v.reserve(es.size());
for (auto it = std::rbegin(es); it != std::rend(es); ++it)
{
listener_wptr ptr = listener_map_[*it].prepend(name, *it, cb);
listener_name_map_[name].emplace(*it, ptr);
v.emplace(v.begin(), std::move(ptr));
}
return v;
}
listener_wptr insert_listener(
const listener_name_type& name, const event_type& e, callback_type cb, const listener_wptr & before)
{
auto n = before.lock();
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
if (n)
{
if (n->evt != e)
{
#if defined(_DEBUG) || defined(DEBUG)
assert(false);
#endif
return listener_wptr();
}
}
listener_wptr ptr = listener_map_[e].insert(name, e, std::move(cb), before);
listener_name_map_[name].emplace(e, ptr);
return ptr;
}
/**
* @param pred The check function, use to determin which listener of the new listener will be insert before
* the "pred" Function signature : bool(auto& listener_ptr)
* eg:
* dispatcher.insert_listener("listener_a", 3,
* []()
* {
* // this is the listener callback function
* },
* [index](auto& listener_ptr) -> bool
* {
* // this is the check function
*
* return (index < listener_ptr->get_user_data());
*
* // if this function return true , the new listener will be insert before "listener_ptr"
* // if this function return false, then will be check the next listener in the list
* // if all checks return false, then the new listener will be append after the tail.
* }
* );
*/
template<class Function>
typename std::enable_if_t<can_invoke<Function, typename callback_list_type::node_ptr&>::value, listener_wptr>
insert_listener(const listener_name_type& name, const event_type & e, callback_type cb, Function&& pred)
{
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
// Returns a reference to the value that is mapped to a key equivalent to key,
// performing an insertion if such key does not already exist.
callback_list_type& cblist = listener_map_[e];
for (auto it = cblist.begin(); it != cblist.end(); ++it)
{
if (pred(*it))
{
listener_wptr ptr = cblist.insert(name, e, std::move(cb), *it);
listener_name_map_[name].emplace(e, ptr);
return ptr;
}
}
listener_wptr ptr = cblist.append(name, e, std::move(cb));
listener_name_map_[name].emplace(e, ptr);
return ptr;
}
bool remove_listener(const listener_wptr& listener)
{
auto n = listener.lock();
if (n)
{
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
auto it1 = listener_name_map_.find(n->name);
if (it1 != this->listener_name_map_.end())
{
auto& inner_map = it1->second;
auto&& [beg, end] = inner_map.equal_range(n->evt);
for (auto it = beg; it != end; ++it)
{
if (it->second.lock().get() == n.get())
{
inner_map.erase(it);
break;
}
}
if (inner_map.empty())
{
listener_name_map_.erase(n->name);
}
}
auto it2 = this->listener_map_.find(n->evt);
if (it2 != this->listener_map_.end())
{
callback_list_type& cblist = it2->second;
bool r = cblist.remove(listener);
if (cblist.empty())
{
this->listener_map_.erase(n->evt);
}
return r;
}
}
return false;
}
bool remove_listener(const listener_name_type& name, const event_type & e)
{
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
auto it1 = this->listener_name_map_.find(name);
auto it2 = this->listener_map_.find(e);
if (it1 != this->listener_name_map_.end() && it2 != this->listener_map_.end())
{
callback_list_type& cblist = it2->second;
auto& inner_map = it1->second;
auto&& [beg, end] = inner_map.equal_range(e);
bool r = false;
for (auto it = beg; it != end;)
{
r |= cblist.remove(it->second);
it = inner_map.erase(it);
}
if (inner_map.empty())
{
this->listener_name_map_.erase(name);
}
if (cblist.empty())
{
this->listener_map_.erase(e);
}
return r;
}
return false;
}
bool remove_listener(const listener_name_type& name)
{
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
auto it1 = listener_name_map_.find(name);
if (it1 != this->listener_name_map_.end())
{
bool r = false;
auto& inner_map = it1->second;
for (auto it = inner_map.begin(); it != inner_map.end();)
{
auto n = it->second.lock();
if (n)
{
auto it2 = this->listener_map_.find(n->evt);
if (it2 != this->listener_map_.end())
{
callback_list_type& cblist = it2->second;
r |= cblist.remove(it->second);
if (cblist.empty())
{
this->listener_map_.erase(n->evt);
}
}
}
it = inner_map.erase(it);
}
if (inner_map.empty())
{
listener_name_map_.erase(name);
}
return r;
}
return false;
}
void clear_listeners() noexcept
{
typename thread_type::template unique_lock<mutex_type> guard(listener_mtx_);
for (auto& [e, cblist] : listener_map_)
{
std::ignore = e;
cblist.clear();
}
listener_map_.clear();
listener_name_map_.clear();
}
std::size_t get_listener_count(const event_type& e)
{
const callback_list_type* callable_list = do_find_callable_list(e);
if (callable_list)
{
return callable_list->size();
}
return 0;
}
/**
* Note : the "listener_name_type" maybe equal to the "event_type".
* so we can't use this function overloading, but we can use the std::optional<event_type>.
*/
//std::size_t get_listener_count_by_name(const listener_name_type& name) {...}
std::size_t get_listener_count(const listener_name_type& name, std::optional<event_type> e = std::nullopt)
{
if (listener_name_map_.empty())
return 0;
typename thread_type::template shared_lock<mutex_type> guard(listener_mtx_);
auto it = listener_name_map_.find(name);
if (it != listener_name_map_.end())
{
if (e.has_value())
return it->second.count(e.value());
else
return it->second.size();
}
return 0;
}
std::size_t get_listener_count()
{
if (listener_map_.empty())
return 0;
std::size_t count = 0;
typename thread_type::template shared_lock<mutex_type> guard(listener_mtx_);
for (auto& [e, cblist] : listener_map_)
{
std::ignore = e;
count += cblist.size();
}
#if defined(_DEBUG) || defined(DEBUG)
std::size_t count2 = 0;
for (auto&[name, mulmap] : listener_name_map_)
{
std::ignore = name;
count2 += mulmap.size();
}
assert(count == count2);
#endif
return count;
}
bool has_any_listener(const event_type & e) const
{
const callback_list_type * callable_list = do_find_callable_list(e);
if(callable_list)
{
return ! callable_list->empty();
}
return false;
}
inline callback_list_type* find_listeners(const event_type & e)
{
return do_find_callable_list(e);
}
/**
* @param pred Find the listener by user defined rule
* the "pred" Function signature : bool(auto& listener_ptr)
*/
template<class Function>
inline listener_wptr find_listener_if(const event_type & e, Function&& pred)
{
typename thread_type::template shared_lock<mutex_type> guard(listener_mtx_);
auto it1 = this->listener_map_.find(e);
if (it1 != this->listener_map_.end())
{
callback_list_type& cblist = it1->second;
for (auto it2 = cblist.begin(); it2 != cblist.end(); ++it2)
{
if (pred(*it2))
{
return listener_wptr(*it2);
}
}
}
return listener_wptr();
}
template <typename Func>
void for_each(const event_type & e, Func && func) const
{
const callback_list_type * callable_list = do_find_callable_list(e);
if(callable_list)
{
callable_list->for_each(std::forward<Func>(func));
}
}
template <typename Func>
bool for_each_if(const event_type & e, Func && func) const
{
const callback_list_type * callable_list = do_find_callable_list(e);
if (callable_list)
{
return callable_list->for_each_if(std::forward<Func>(func));
}
return true;
}
void dispatch(Args ...args) const
{
static_assert(argument_passing_mode_type::can_include_event_type,
"Dispatching arguments count doesn't match required (event type should be included).");
using get_event_t = typename select_get_event<
PolicyT, EventTypeT, has_function_get_event<PolicyT, Args...>::value>::type;
const event_type e = get_event_t::get_event(args...);
direct_dispatch(e, std::forward<Args>(args)...);
}
template <typename T>
void dispatch(T && first, Args ...args) const
{
static_assert(argument_passing_mode_type::can_exclude_event_type,
"Dispatching arguments count doesn't match required (event type should NOT be included).");
using get_event_t = typename select_get_event<
PolicyT, EventTypeT, has_function_get_event<PolicyT, T &&, Args...>::value>::type;
const event_type e = get_event_t::get_event(std::forward<T>(first), args...);
direct_dispatch(e, std::forward<Args>(args)...);
}
// Bypass any get_event policy. The first argument is the event type.
// Most used for internal purpose.
void direct_dispatch(const event_type & e, Args ...args) const
{
if(! dispatcheres::for_each_mixins<mixin_root_type, mixins_type, do_mixin_before_dispatch>::for_each(
this, typename std::add_lvalue_reference<Args>::type(args)...))
{
return;
}
const callback_list_type * callable_list = do_find_callable_list(e);
if(callable_list)
{
(*callable_list)(std::forward<Args>(args)...);
}
}
protected:
inline const callback_list_type * do_find_callable_list(const event_type & e) const
{
return do_find_callable_list_helper(this, e);
}
inline callback_list_type * do_find_callable_list(const event_type & e)
{
return do_find_callable_list_helper(this, e);
}
private:
// template helper to avoid code duplication in do_find_callable_list
template <typename T>
static auto do_find_callable_list_helper(T * self, const event_type & e)
-> typename std::conditional<std::is_const<T>::value, const callback_list_type *, callback_list_type *>::type
{
if (self->listener_map_.empty())
return nullptr;
typename thread_type::template shared_lock<mutex_type> guard(self->listener_mtx_);
auto it = self->listener_map_.find(e);
if(it != self->listener_map_.end())
{
return &it->second;
}
else
{
return nullptr;
}
}
private:
// Mixin related
struct do_mixin_before_dispatch
{
template <typename T, typename Self, typename ...A>
static auto for_each(const Self * self, A && ...args)
-> typename std::enable_if<has_function_mixin_before_dispatch<T, A...>::value, bool>::type
{
return static_cast<const T *>(self)->mixin_before_dispatch(std::forward<A>(args)...);
}
template <typename T, typename Self, typename ...A>
static auto for_each(const Self * /*self*/, A && ... /*args*/)
-> typename std::enable_if<! has_function_mixin_before_dispatch<T, A...>::value, bool>::type
{
return true;
}
};
private:
map_type listener_map_;
mutable mutex_type listener_mtx_;
listener_name_map_type listener_name_map_;
};
} //namespace dispatcheres
//-------------------------------------------------------------------------------------------------
namespace dispatcheres {
template <typename Base>
class mixin_filter : public Base
{
private:
using super = Base;
using bool_reference_prototype = typename dispatcheres::replace_return_type<
typename dispatcheres::transform_arguments<
typename super::proto_type,
std::add_lvalue_reference
>::type,
bool
>::type;
using filter_func_type = std::function<bool_reference_prototype>;
using filter_list_type = callback_list<char, bool_reference_prototype>;
using listener_name_type = typename filter_list_type::listener_name_type;
public:
using filter_wptr = typename filter_list_type::node_wptr;
using filter_type = filter_wptr;
public:
inline filter_wptr append_filter(const filter_func_type& filter_func)
{
return filter_list_.append(listener_name_type{}, '0', filter_func);
}
inline bool remove_filter(const filter_wptr & filter)
{
return filter_list_.remove(filter);
}
inline void clear_filters() noexcept
{
return filter_list_.clear();
}
inline std::size_t get_filter_count() const noexcept
{
return filter_list_.size();
}
template <typename ...Args>
inline bool mixin_before_dispatch(Args && ...args) const
{
if(! filter_list_.empty())
{
if(! filter_list_.for_each_if([&args...](typename filter_list_type::callback_type & cb)
{
return cb(args...);
})
)
{
return false;
}
}
return true;
}
private:
filter_list_type filter_list_;
};
} //namespace dispatcheres
//-------------------------------------------------------------------------------------------------
template <
typename EventT,
typename PrototypeT,
typename PolicyT = dispatcheres::default_policy
>
class event_dispatcher : public dispatcheres::inherit_mixins<
dispatcheres::event_dispatcher_base<EventT, PrototypeT, PolicyT, void>,
typename dispatcheres::select_mixins<PolicyT, dispatcheres::has_type_mixins_t<PolicyT>::value >::type
>::type, public dispatcheres::tag_event_dispatcher
{
private:
using super = typename dispatcheres::inherit_mixins<
dispatcheres::event_dispatcher_base<EventT, PrototypeT, PolicyT, void>,
typename dispatcheres::select_mixins<PolicyT, dispatcheres::has_type_mixins_t<PolicyT>::value >::type
>::type;
public:
using super::super;
friend void swap(event_dispatcher & first, event_dispatcher & second) noexcept
{
first.swap(second);
}
};
} //namespace asio2
#endif
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_CORE_HPP
#define BHO_BEAST_CORE_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/beast/core/async_base.hpp>
#include <asio2/bho/beast/core/basic_stream.hpp>
#include <asio2/bho/beast/core/bind_handler.hpp>
#include <asio2/bho/beast/core/buffer_traits.hpp>
#include <asio2/bho/beast/core/buffered_read_stream.hpp>
#include <asio2/bho/beast/core/buffers_adaptor.hpp>
#include <asio2/bho/beast/core/buffers_cat.hpp>
#include <asio2/bho/beast/core/buffers_prefix.hpp>
#include <asio2/bho/beast/core/buffers_range.hpp>
#include <asio2/bho/beast/core/buffers_suffix.hpp>
#include <asio2/bho/beast/core/buffers_to_string.hpp>
#include <asio2/bho/beast/core/detect_ssl.hpp>
#include <asio2/bho/beast/core/error.hpp>
#include <asio2/bho/beast/core/file.hpp>
#include <asio2/bho/beast/core/file_base.hpp>
#include <asio2/bho/beast/core/file_stdio.hpp>
#include <asio2/bho/beast/core/flat_buffer.hpp>
#include <asio2/bho/beast/core/flat_static_buffer.hpp>
#include <asio2/bho/beast/core/flat_stream.hpp>
#include <asio2/bho/beast/core/make_printable.hpp>
#include <asio2/bho/beast/core/multi_buffer.hpp>
#include <asio2/bho/beast/core/ostream.hpp>
#include <asio2/bho/beast/core/rate_policy.hpp>
#include <asio2/bho/beast/core/read_size.hpp>
#include <asio2/bho/beast/core/role.hpp>
#include <asio2/bho/beast/core/saved_handler.hpp>
#include <asio2/bho/beast/core/span.hpp>
#include <asio2/bho/beast/core/static_buffer.hpp>
#include <asio2/bho/beast/core/static_string.hpp>
#include <asio2/bho/beast/core/stream_traits.hpp>
#include <asio2/bho/beast/core/string.hpp>
#include <asio2/bho/beast/core/tcp_stream.hpp>
#endif
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_DETAIL_STATIC_CONST_HPP
#define BHO_BEAST_DETAIL_STATIC_CONST_HPP
/* This is a derivative work, original copyright:
Copyright <NAME> 2013-present
Use, modification and distribution is subject to the
Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
Project home: https://github.com/ericniebler/range-v3
*/
namespace bho {
namespace beast {
namespace detail {
template<typename T>
struct static_const
{
static constexpr T value {};
};
template<typename T>
constexpr T static_const<T>::value;
#define BHO_BEAST_INLINE_VARIABLE(name, type) \
namespace \
{ \
constexpr auto& name = \
::bho::beast::detail::static_const<type>::value; \
}
} // detail
} // beast
} // bho
#endif
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_BUFFERS_TO_STRING_HPP
#define BHO_BEAST_BUFFERS_TO_STRING_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/beast/core/buffer_traits.hpp>
#include <asio2/bho/beast/core/buffers_range.hpp>
#include <asio2/external/asio.hpp>
#include <string>
namespace bho {
namespace beast {
/** Return a string representing the contents of a buffer sequence.
This function returns a string representing an entire buffer
sequence. Nulls and unprintable characters in the buffer
sequence are inserted to the resulting string as-is. No
character conversions are performed.
@param buffers The buffer sequence to convert
@par Example
This function writes a buffer sequence converted to a string
to `std::cout`.
@code
template<class ConstBufferSequence>
void print(ConstBufferSequence const& buffers)
{
std::cout << buffers_to_string(buffers) << std::endl;
}
@endcode
*/
template<class ConstBufferSequence>
std::string
buffers_to_string(ConstBufferSequence const& buffers)
{
static_assert(
net::is_const_buffer_sequence<ConstBufferSequence>::value,
"ConstBufferSequence type requirements not met");
std::string result;
result.reserve(buffer_bytes(buffers));
for(auto const buffer : buffers_range_ref(buffers))
result.append(static_cast<char const*>(
buffer.data()), buffer.size());
return result;
}
} // beast
} // bho
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_CLOSE_COMPONENT_HPP__
#define __ASIO2_CLOSE_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class close_cp
{
public:
using self = close_cp<derived_t, args_t>;
public:
/**
* @brief constructor
*/
close_cp() noexcept {}
/**
* @brief destructor
*/
~close_cp() = default;
protected:
template<typename DeferEvent>
inline void _do_close(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
ASIO2_LOG_DEBUG("close_cp::_do_close enter: {} {}", ec.value(), ec.message());
// Normally, do close function will be called in the io_context thread, but if some
// exception occured, do close maybe called in the "catch(){ ... }", then this maybe
// not in the io_context thread.
// When the stop() is called for each session in the server's _post_stop, this maybe also
// not in the io_context thread.
// If the session_ptr->stop() is called not in io_context thread, then this will be not in
// the io_context thread.
// If we don't ensure this function is called in the io_context thread, the session status
// maybe stopping in the bind_recv callback.
// use disp event to change the state to avoid this problem:
// 1. when the event queue is not empty, call client stop, then the stop event will pushed
// into the event queue.
// 2. in the io_context thread, the do close is called directly (without event queue),
// it will change the state to stopping.
// 3. when the client _do stop is called, the state is not equal to stopped, it is equal to
// stopping.
derive.disp_event(
[&derive, ec, this_ptr = std::move(this_ptr), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
set_last_error(ec);
defer_event chain(std::move(e), std::move(g));
ASIO2_LOG_DEBUG("close_cp::_do_close leave: {} {} state={}",
ec.value(), ec.message(), detail::to_string(derive.state().load()));
state_t expected = state_t::started;
if (derive.state().compare_exchange_strong(expected, state_t::stopping))
{
return derive._post_close(ec, std::move(this_ptr), expected, std::move(chain));
}
expected = state_t::starting;
if (derive.state().compare_exchange_strong(expected, state_t::stopping))
{
return derive._post_close(ec, std::move(this_ptr), expected, std::move(chain));
}
}, chain.move_guard());
}
template<typename DeferEvent, bool IsSession = args_t::is_session>
inline typename std::enable_if_t<!IsSession, void>
_post_close(const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
ASIO2_LOG_DEBUG("close_cp::_post_close: {} {}", ec.value(), ec.message());
// All pending sending events will be cancelled after enter the callback below.
derive.disp_event(
[&derive, ec, this_ptr = std::move(this_ptr), old_state, e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
set_last_error(ec);
defer_event chain(std::move(e), std::move(g));
// When the connection is closed, should we set the state to stopping or stopped?
// If the state is set to stopped, then the user wants to use client.is_stopped() to
// determine whether the client has stopped. The result is inaccurate because the client
// has not stopped completely, such as the timer is still running.
// If the state is set to stopping, the user will fail to reconnect the client using
// client.start(...) in the bind_disconnect callback. because the client.start(...)
// function will detects the value of state and the client.start(...) will only executed
// if the state is stopped.
state_t expected = state_t::stopping;
if (derive.state().compare_exchange_strong(expected, state_t::stopped))
{
if (old_state == state_t::started)
{
derive._fire_disconnect(this_ptr);
}
}
else
{
ASIO2_ASSERT(false);
}
if (chain.empty())
{
derive._handle_close(ec, this_ptr, defer_event
{
[&derive, this_ptr](event_queue_guard<derived_t> g) mutable
{
// Use disp_event to ensure that reconnection will not executed until
// all events are completed.
derive.disp_event([&derive, this_ptr = std::move(this_ptr)]
(event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(this_ptr, g);
if (derive.reconnect_enable_)
derive._wake_reconnect_timer();
else
derive._stop_reconnect_timer();
}, std::move(g));
}, chain.move_guard()
});
}
else
{
derive._handle_close(ec, std::move(this_ptr), std::move(chain));
}
// can't call derive._do_stop() here, it will cause the auto reconnect invalid when
// server is closed. so we use the chain to determine whether we should call
// derive._do_stop()
}, chain.move_guard());
}
template<typename DeferEvent, bool IsSession = args_t::is_session>
inline typename std::enable_if_t<IsSession, void>
_post_close(const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
ASIO2_LOG_DEBUG("close_cp::_post_close: {} {}", ec.value(), ec.message());
// close the socket by post a event
// asio don't allow operate the same socket in multi thread,if you close socket
// in one thread and another thread is calling socket's async_... function,it
// will crash.so we must care for operate the socket. when need close the
// socket, we use the context to post a event, make sure the socket's close
// operation is in the same thread.
// First ensure that all send and recv events are not executed again
derive.disp_event(
[&derive, ec, old_state, this_ptr = std::move(this_ptr), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
// All pending sending events will be cancelled when code run to here.
// We must use the asio::post function to execute the task, otherwise :
// when the server acceptor thread is same as this session thread,
// when the server stop, will call sessions_.for_each -> session_ptr->stop() ->
// derived().disp_event -> sessions_.erase => this can leads to a dead lock
defer_event chain(std::move(e), std::move(g));
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[&derive, ec, old_state, this_ptr = std::move(this_ptr), chain = std::move(chain)]
() mutable
{
// Second ensure that this session has removed from the session map.
derive.sessions_.erase(this_ptr,
[&derive, ec, old_state, this_ptr, chain = std::move(chain)]
(bool erased) mutable
{
set_last_error(ec);
state_t expected = state_t::stopping;
if (derive.state().compare_exchange_strong(expected, state_t::stopped))
{
if (old_state == state_t::started && erased)
derive._fire_disconnect(const_cast<std::shared_ptr<derived_t>&>(this_ptr));
}
else
{
ASIO2_ASSERT(false);
}
// Third we can stop this session and close this socket now.
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[&derive, ec, this_ptr = std::move(this_ptr), chain = std::move(chain)]
() mutable
{
// call CRTP polymorphic stop
derive._handle_close(ec, std::move(this_ptr), std::move(chain));
}));
});
}));
}, chain.move_guard());
}
template<typename DeferEvent>
inline void _handle_close(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
ASIO2_LOG_DEBUG("close_cp::_handle_close: {} {}", ec.value(), ec.message());
derive._post_disconnect(ec, std::move(this_ptr), std::move(chain));
}
};
}
#endif // !__ASIO2_CLOSE_COMPONENT_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_CONNECT_TIMEOUT_COMPONENT_HPP__
#define __ASIO2_CONNECT_TIMEOUT_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <chrono>
#include <asio2/base/iopool.hpp>
#include <asio2/base/log.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class connect_timeout_cp
{
public:
/**
* @brief constructor
*/
connect_timeout_cp() = default;
/**
* @brief destructor
*/
~connect_timeout_cp() = default;
/**
* @brief get the connect timeout
*/
inline std::chrono::steady_clock::duration get_connect_timeout() noexcept
{
return this->connect_timeout_;
}
/**
* @brief set the connect timeout
*/
template<class Rep, class Period>
inline derived_t& set_connect_timeout(std::chrono::duration<Rep, Period> timeout) noexcept
{
if (timeout > std::chrono::duration_cast<
std::chrono::duration<Rep, Period>>((std::chrono::steady_clock::duration::max)()))
this->connect_timeout_ = (std::chrono::steady_clock::duration::max)();
else
this->connect_timeout_ = timeout;
return static_cast<derived_t&>(*this);
}
protected:
template<class Rep, class Period>
inline void _make_connect_timeout_timer(
std::shared_ptr<derived_t> this_ptr, std::chrono::duration<Rep, Period> duration)
{
derived_t& derive = static_cast<derived_t&>(*this);
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = std::move(this_ptr), duration = std::move(duration)]() mutable
{
derived_t& derive = static_cast<derived_t&>(*this);
if (this->connect_timeout_timer_)
{
this->connect_timeout_timer_->cancel();
}
this->connect_timeout_timer_ = std::make_shared<safe_timer>(derive.io().context());
derive._post_connect_timeout_timer(std::move(this_ptr), this->connect_timeout_timer_, duration);
}));
}
template<class Rep, class Period>
inline void _post_connect_timeout_timer(std::shared_ptr<derived_t> this_ptr,
std::shared_ptr<safe_timer> timer_ptr, std::chrono::duration<Rep, Period> duration)
{
derived_t& derive = static_cast<derived_t&>(*this);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_stop_connect_timeout_timer_called_ == false);
#endif
// a new timer is maked, this is the prev timer, so return directly.
if (timer_ptr.get() != this->connect_timeout_timer_.get())
return;
safe_timer* ptimer = timer_ptr.get();
ptimer->timer.expires_after(duration);
ptimer->timer.async_wait(
[&derive, this_ptr = std::move(this_ptr), timer_ptr = std::move(timer_ptr)]
(const error_code& ec) mutable
{
// bug fixed :
// note : after call derive._handle_connect_timeout_timer(ec, std::move(this_ptr));
// the pointer of "this" can no longer be used immediately, beacuse when
// this_ptr's reference counter is 1, after call
// derive._handle_connect_timeout_timer(ec, std::move(this_ptr)); the this_ptr's
// object will be destroyed, then below code "this->..." will cause crash.
derive._handle_connect_timeout_timer(ec, std::move(this_ptr), std::move(timer_ptr));
// after call derive._handle_connect_timeout_timer(ec, std::move(this_ptr));
// can't do it like below, beacuse "this" maybe deleted already.
// this->...
});
}
template<class D = derived_t>
inline void _handle_connect_timeout_timer(
const error_code& ec, std::shared_ptr<D> this_ptr, std::shared_ptr<safe_timer> timer_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT((!ec) || ec == asio::error::operation_aborted);
// a new timer is maked, this is the prev timer, so return directly.
if (timer_ptr.get() != this->connect_timeout_timer_.get())
return;
// member variable timer should't be empty
if (!this->connect_timeout_timer_)
{
ASIO2_ASSERT(false);
return;
}
this->connect_timeout_timer_.reset();
// ec maybe zero when timer_canceled_ is true.
if (ec == asio::error::operation_aborted || timer_ptr->canceled.test_and_set())
return;
if constexpr (D::is_session())
{
if (!ec)
{
derive._do_disconnect(asio::error::timed_out, std::move(this_ptr));
}
else
{
// should't go to here
ASIO2_ASSERT(false);
derive._do_disconnect(ec, std::move(this_ptr));
}
}
else
{
// no errors indicating that the client connection timed out
if (!ec)
{
// we close the socket, so the async_connect will returned
// with operation_aborted.
error_code ec_ignore{};
derive.socket().shutdown(asio::socket_base::shutdown_both, ec_ignore);
derive.socket().cancel(ec_ignore);
derive.socket().close(ec_ignore);
ASIO2_ASSERT(!derive.socket().is_open());
}
}
}
inline void _stop_connect_timeout_timer()
{
// 2021-12-10 bug fix : when a client connected, the tcp_session::start will be
// called, and super::start will be called in tcp_session::start, so session::start
// will be called, and session::start will call _post_connect_timeout_timer, but
// session::start is not running in the io thread, so it will post a event, then
// tcp_session::_handle_connect will be called, and tcp_session::_done_connect
// will be called, and _stop_connect_timeout_timer will be called, but at this
// time, the _post_connect_timeout_timer in the session::start has't called yet,
// this will cause the client to be fore disconnect with timeout error.
// so we should ensure the _stop_connect_timeout_timer and _post_connect_timeout_timer
// was called in the io thread.
derived_t& derive = static_cast<derived_t&>(*this);
derive.dispatch([this]() mutable
{
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_connect_timeout_timer_called_ = true;
#endif
if (this->connect_timeout_timer_)
{
this->connect_timeout_timer_->cancel();
}
});
}
protected:
/// beacuse the connect timeout timer is used only when connect, so we use a pointer
/// to reduce memory space occupied when running
std::shared_ptr<safe_timer> connect_timeout_timer_;
std::chrono::steady_clock::duration connect_timeout_ = std::chrono::seconds(30);
#if defined(_DEBUG) || defined(DEBUG)
bool is_stop_connect_timeout_timer_called_ = false;
#endif
};
}
#endif // !__ASIO2_CONNECT_TIMEOUT_COMPONENT_HPP__
<file_sep>// Boost config.hpp configuration header file ------------------------------//
// (C) Copyright <NAME> 2002.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for most recent version.
// Boost config.hpp policy and rationale documentation has been moved to
// http://www.boost.org/libs/config
//
// CAUTION: This file is intended to be completely stable -
// DO NOT MODIFY THIS FILE!
//
#ifndef BHO_CONFIG_HPP
#define BHO_CONFIG_HPP
// if we don't have a user config, then use the default location:
#if !defined(BHO_USER_CONFIG) && !defined(BHO_NO_USER_CONFIG)
# define BHO_USER_CONFIG <asio2/bho/config/user.hpp>
#if 0
// For dependency trackers:
# include <asio2/bho/config/user.hpp>
#endif
#endif
// include it first:
#ifdef BHO_USER_CONFIG
# include BHO_USER_CONFIG
#endif
// if we don't have a compiler config set, try and find one:
#if !defined(BHO_COMPILER_CONFIG) && !defined(BHO_NO_COMPILER_CONFIG) && !defined(BHO_NO_CONFIG)
# include <asio2/bho/config/detail/select_compiler_config.hpp>
#endif
// if we have a compiler config, include it now:
#ifdef BHO_COMPILER_CONFIG
# include BHO_COMPILER_CONFIG
#endif
// if we don't have a std library config set, try and find one:
#if !defined(BHO_STDLIB_CONFIG) && !defined(BHO_NO_STDLIB_CONFIG) && !defined(BHO_NO_CONFIG) && defined(__cplusplus)
# include <asio2/bho/config/detail/select_stdlib_config.hpp>
#endif
// if we have a std library config, include it now:
#ifdef BHO_STDLIB_CONFIG
# include BHO_STDLIB_CONFIG
#endif
// if we don't have a platform config set, try and find one:
#if !defined(BHO_PLATFORM_CONFIG) && !defined(BHO_NO_PLATFORM_CONFIG) && !defined(BHO_NO_CONFIG)
# include <asio2/bho/config/detail/select_platform_config.hpp>
#endif
// if we have a platform config, include it now:
#ifdef BHO_PLATFORM_CONFIG
# include BHO_PLATFORM_CONFIG
#endif
// get config suffix code:
#include <asio2/bho/config/detail/suffix.hpp>
#ifdef BHO_HAS_PRAGMA_ONCE
#pragma once
#endif
#endif // BHO_CONFIG_HPP
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_MESSAGE_ROUTER_HPP__
#define __ASIO2_MQTT_MESSAGE_ROUTER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <optional>
#include <asio2/base/iopool.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
/**
* used for:
*
* bool ret = client.subscribe("/usr/topic1", 0, [](mqtt::message& msg){});
* util recvd the suback message, then the ret is true.
*
* bool ret = client.publish("/usr/topic1", "...payload...", 0);
* util recvd the puback message, then the ret is true.
*
* and so on...
*/
template<class derived_t, class args_t>
class mqtt_message_router_t
{
friend derived_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using self = mqtt_message_router_t<derived_t, args_t>;
using args_type = args_t;
using subnode_type = typename args_type::template subnode<derived_t>;
using key_type = std::pair<mqtt::control_packet_type, mqtt::two_byte_integer::value_type>;
using val_type = detail::function<void(mqtt::message&)>;
struct hasher
{
inline std::size_t operator()(key_type const& pair) const noexcept
{
std::size_t v = detail::fnv1a_hash<std::size_t>(
(const unsigned char*)(std::addressof(pair.first)), sizeof(pair.first));
return detail::fnv1a_hash<std::size_t>(v,
(const unsigned char*)(std::addressof(pair.second)), sizeof(pair.second));
}
};
/**
* @brief constructor
*/
mqtt_message_router_t() = default;
/**
* @brief destructor
*/
~mqtt_message_router_t() = default;
protected:
template<class FunctionT>
inline bool _add_router(mqtt::message& msg, FunctionT&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
bool r = false;
std::visit([&derive, &callback, &r](auto& m) mutable
{
r = derive._add_router(m, std::forward<FunctionT>(callback));
}, msg.base());
return r;
}
template<class Message, class FunctionT>
typename std::enable_if_t<mqtt::is_rawmsg<Message>(), bool>
inline _add_router(Message& msg, FunctionT&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
using message_type = typename detail::remove_cvref_t<Message>;
if constexpr (!mqtt::has_packet_id<message_type>::value)
{
static_assert(detail::always_false_v<Message> && "This mqtt message don't has Packet Identifier");
return false;
}
else
{
ASIO2_ASSERT(
msg.packet_type() >= mqtt::control_packet_type::connect &&
msg.packet_type() <= mqtt::control_packet_type::auth);
if (!(
msg.packet_type() >= mqtt::control_packet_type::connect &&
msg.packet_type() <= mqtt::control_packet_type::auth))
{
return false;
}
key_type key = { msg.packet_type(), msg.packet_id() };
return derive._add_router(std::move(key), std::forward<FunctionT>(callback));
}
}
template<class FunctionT>
inline bool _add_router(key_type key, FunctionT&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.dispatch([&derive, key, cb = std::forward<FunctionT>(callback)]() mutable
{
derive._do_add_router(std::move(key), std::move(cb));
});
return true;
}
template<class FunctionT>
inline bool _do_add_router(key_type key, FunctionT&& callback)
{
using fun_traits_type = function_traits<FunctionT>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
asio2::unique_locker g(this->message_router_mutex_);
if constexpr (std::is_same_v<arg0_type, mqtt::message>)
{
auto[_1, inserted] = this->message_router_.insert_or_assign(std::move(key),
std::forward<FunctionT>(callback));
ASIO2_ASSERT(inserted);
asio2::ignore_unused(_1, inserted);
}
else
{
auto[_1, inserted] = this->message_router_.insert_or_assign(std::move(key),
[cb = std::forward<FunctionT>(callback)](mqtt::message& msg) mutable
{
arg0_type* p = std::get_if<arg0_type>(std::addressof(msg.base()));
if (p)
{
cb(*p);
}
});
ASIO2_ASSERT(inserted);
asio2::ignore_unused(_1, inserted);
}
return true;
}
inline void _del_router(mqtt::message& msg)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::visit([&derive](auto& m) mutable
{
derive._del_router(m);
}, msg.base());
}
template<class Message>
typename std::enable_if_t<mqtt::is_rawmsg<Message>(), void>
inline _del_router(Message& msg)
{
derived_t& derive = static_cast<derived_t&>(*this);
using message_type = typename detail::remove_cvref_t<Message>;
if constexpr (!mqtt::has_packet_id<message_type>::value)
{
static_assert(detail::always_false_v<Message> && "This mqtt message don't has Packet Identifier");
return;
}
else
{
ASIO2_ASSERT(
msg.packet_type() >= mqtt::control_packet_type::connect &&
msg.packet_type() <= mqtt::control_packet_type::auth);
if (!(
msg.packet_type() >= mqtt::control_packet_type::connect &&
msg.packet_type() <= mqtt::control_packet_type::auth))
{
return;
}
key_type key = { msg.packet_type(), msg.packet_id() };
derive._del_router(std::move(key));
}
}
inline void _del_router(key_type key)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.dispatch([this, key = std::move(key)]() mutable
{
asio2::unique_locker g(this->message_router_mutex_);
this->message_router_.erase(key);
});
}
inline bool _match_router(mqtt::message& msg)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::optional<key_type> key = derive._generate_key(msg);
if (!key.has_value())
return false;
return derive._call_router(key.value(), msg);
}
inline bool _call_router(key_type key, mqtt::message& msg)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.dispatch([this, msg, key = std::move(key)]() mutable
{
asio2::unique_locker g(this->message_router_mutex_);
auto it = this->message_router_.find(key);
if (it == this->message_router_.end())
return;
(it->second)(msg);
this->message_router_.erase(it);
});
return true;
}
inline std::optional<key_type> _generate_key(mqtt::message& msg)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::optional<key_type> r;
std::visit([&derive, &r](auto& m) mutable
{
r = derive._generate_key(m);
}, msg.base());
return r;
}
template<class Message>
typename std::enable_if_t<mqtt::is_rawmsg<Message>(), std::optional<key_type>>
inline _generate_key(Message& msg)
{
using message_type = typename detail::remove_cvref_t<Message>;
if constexpr (!mqtt::has_packet_id<message_type>::value)
{
return std::nullopt;
}
else
{
ASIO2_ASSERT(
msg.packet_type() >= mqtt::control_packet_type::connect &&
msg.packet_type() <= mqtt::control_packet_type::auth);
if (!(
msg.packet_type() >= mqtt::control_packet_type::connect &&
msg.packet_type() <= mqtt::control_packet_type::auth))
{
return std::nullopt;
}
std::optional<key_type> key;
if /**/ constexpr (mqtt::is_puback_message<message_type>())
{
key = { mqtt::control_packet_type::publish, msg.packet_id() };
}
else if constexpr (mqtt::is_pubcomp_message<message_type>())
{
key = { mqtt::control_packet_type::publish, msg.packet_id() };
}
else if constexpr (mqtt::is_suback_message<message_type>())
{
key = { mqtt::control_packet_type::subscribe, msg.packet_id() };
}
else if constexpr (mqtt::is_unsuback_message<message_type>())
{
key = { mqtt::control_packet_type::unsubscribe, msg.packet_id() };
}
else
{
return std::nullopt;
}
return key;
}
}
protected:
/// use rwlock to make thread safe
mutable asio2::shared_mutexer message_router_mutex_;
/// router map, key - pair<mqtt::control_packet_type, packet id>
std::unordered_map<key_type, val_type, hasher> message_router_ ASIO2_GUARDED_BY(message_router_mutex_);
};
}
#endif // !__ASIO2_MQTT_MESSAGE_ROUTER_HPP__
<file_sep>
#include <asio2/base/detail/push_options.hpp>
#include <asio.hpp>
using asio::ip::udp;
std::string strmsg(1024, 'A');
class client
{
public:
client(asio::io_context& io_context, std::string ip, short port)
: socket_(io_context, udp::endpoint(udp::v4(), 0))
{
udp::resolver resolver(io_context);
udp::resolver::results_type endpoints =
resolver.resolve(udp::v4(), ip, std::to_string(port));
dest_endpoint_ = *endpoints.begin();
socket_.async_send_to(
asio::buffer(strmsg), dest_endpoint_,
[this](const asio::error_code& error, size_t bytes_recvd)
{
handle_send_to(error, bytes_recvd);
});
}
void handle_receive_from(const asio::error_code& error,
size_t bytes_recvd)
{
if (!error && bytes_recvd > 0)
{
socket_.async_send_to(
asio::buffer(data_, bytes_recvd), sender_endpoint_,
[this](const asio::error_code& error, size_t bytes_recvd)
{
handle_send_to(error, bytes_recvd);
});
}
else
{
socket_.async_receive_from(asio::buffer(data_, max_length), sender_endpoint_,
[this](const asio::error_code& error, size_t bytes_recvd)
{
handle_receive_from(error, bytes_recvd);
});
}
}
void handle_send_to(const asio::error_code& /*error*/,
size_t /*bytes_sent*/)
{
socket_.async_receive_from(asio::buffer(data_, max_length), sender_endpoint_,
[this](const asio::error_code& error, size_t bytes_recvd)
{
handle_receive_from(error, bytes_recvd);
});
}
private:
udp::socket socket_;
udp::endpoint sender_endpoint_;
udp::endpoint dest_endpoint_;
enum { max_length = 1500 };
char data_[max_length];
};
int main()
{
asio::io_context io_context;
client s(io_context, "127.0.0.1", 8115);
io_context.run();
while (std::getchar() != '\n');
return 0;
}
<file_sep># asio2
### 中文 | [English](README.en.md)
Header only c++ network library, based on asio,support tcp,udp,http,websocket,rpc,ssl,icmp,serial_port.
<a href="https://996.icu"><img src="https://img.shields.io/badge/link-996.icu-red.svg" alt="996.icu" /></a>
[](https://996.icu)
[](https://github.com/996icu/996.ICU/blob/master/LICENSE)
* header only,不依赖boost库,不需要单独编译,在工程的Include目录中添加asio2路径,在源码中#include <asio2/asio2.hpp>即可使用;
* 支持tcp, udp, http, websocket, rpc, ssl, icmp, serial_port;
* 支持可靠UDP(基于KCP),支持SSL;
* TCP支持各种数据拆包功能(单个字符或字符串或用户自定义协议等);
* 跨平台,支持windows,linux,macos,arm,android,32位,64位等;在msvc gcc clang ndk mingw下编译通过;
* 基于C++17,基于asio (standalone asio或boost::asio均可);
* example目录包含大量示例代码,各种使用方法请参考示例代码;
#### QQ交流群:833425075
## 一些基础用法文章教程:
- [1、基本概念和使用说明](/doc/blog/zh-cn/introduction.md)
- [2、各个回调函数的触发顺序和执行流程](/doc/blog/zh-cn/workflow.md)
- [3、各个回调函数的触发线程以及多线程总结](/doc/blog/zh-cn/thread.md)
- [4、rpc使用教程](/doc/blog/zh-cn/rpc.md)
- [asio做tcp的自动拆包时,asio的match condition如何使用的详细说明](/doc/blog/zh-cn/match_condition.md)
## 重大的接口变更:
* 将原来的异步函数send拆分为send和async_send两个函数,现在send表示同步发送,async_send表示异步发送(查找你代码中的send直接替换为async_send即可).现在send函数的返回值为发送数据的字节数(以前是bool),async_send的返回值为void.如果在通信线程中调用了同步发送函数send,则会退化为异步调用;
* 将http回调函数中的http::request和http::response修改为http::web_request和http::web_response,目的是为了兼容boost(查找你代码中的http::request直接替换为http::web_request即可,response同理,具体可参考example/http代码示例).
* 删除了所有回调函数中的错误码参数,比如以前是bind_start([](asio::error_code ec){});现在是bind_start([](){}); 现在需要用asio2::get_last_error();函数来判断是否有错误;修改的接口包括:bind_start,bind_stop,bind_connect,bind_disconnect,以及rpc的async_call的回调函数等;
* 删除了若干函数中的错误码参数,主要包括http_client::execute,ping::execute,http::make_request,http::make_response等,现在需要使用asio2::get_last_error()来判断是否发生错误;
## 与其它框架的一点区别:
```c++
目前看到的很多基于asio的框架的模式大都如下:
tcp_server server; // 声明一个server
server.run(); // 调用run函数,run函数是阻塞的,run之后怎么退出却不知道.
这种模式需要用户自己去处理程序退出后的逻辑,包括连接的正常关闭,
资源释放等问题,而这些问题自己处理起来是很烦琐的.
asio2框架已经处理过了这些问题,你可以在如MFC的OnInitDialog等地方调用server.start(...),
start(...)函数是非阻塞的,什么时候想退出了只需要server.stop()即可.stop()是阻塞的,
stop时如果有未发送完的数据,会保证一定在数据发送完之后才会退出,
tcp下也会保证所有连接都正常关闭以后才会退出,你不用考虑资源的正确释放等一系列琐碎的问题.
```
## TCP:
##### 服务端:
```c++
asio2::tcp_server server;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view s)
{
printf("recv : %zu %.*s\n", s.size(), (int)s.size(), s.data());
// 异步发送(所有发送操作都是异步且线程安全的)
session_ptr->async_send(s);
// 发送时指定一个回调函数,当发送完成后会调用此回调函数,bytes_sent表示实际发送的字节数,
// 发送是否有错误可以用asio2::get_last_error()函数来获取错误码
// session_ptr->async_send(s, [](std::size_t bytes_sent) {});
}).bind_connect([&](auto & session_ptr)
{
session_ptr->no_delay(true);
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
// 可以用session_ptr这个会话启动一个定时器,这个定时器是在这个session_ptr会话的数据收
// 发线程中执行的,这对于连接状态的判断或其它需求很有用(尤其在UDP这种无连接的协议中,有
// 时需要在数据处理过程中使用一个定时器来延时做某些操作,而且这个定时器还需要和数据处理
// 在同一个线程中安全触发)
//session_ptr->start_timer(1, std::chrono::seconds(1), []() {});
}).bind_disconnect([&](auto & session_ptr)
{
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
});
server.start("0.0.0.0", "8080");
// 按\n自动拆包(可以指定任意字符)
//server.start("0.0.0.0", "8080", '\n');
// 按\r\n自动拆包(可以指定任意字符串)
//server.start("0.0.0.0", "8080", "\r\n");
// 按自定义规则自动拆包(match_role请参考example代码)(用于对用户自定义的协议拆包)
// 对自定义协议拆包时,match_role如何使用的详细说明请看:https://blog.csdn.net/zhllxt/article/details/104772948
//server.start("0.0.0.0", "8080", match_role('#'));
// 每次接收固定的100字节
//server.start("0.0.0.0", "8080", asio::transfer_exactly(100));
// 数据报模式的TCP,无论发送多长的数据,双方接收的一定是相应长度的整包数据
//server.start("0.0.0.0", "8080", asio2::use_dgram);
```
##### 客户端:
```c++
asio2::tcp_client client;
// 客户端在断开时默认会自动重连
// 禁止自动重连
//client.auto_reconnect(false);
// 启用自动重连 默认在断开连接后延时1秒就会开始重连
//client.auto_reconnect(true);
// 启用自动重连 并设置自定义的延时
client.auto_reconnect(true, std::chrono::seconds(3));
client.bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n", client.local_address().c_str(), client.local_port());
// 如果连接成功 就可以调用异步发送函数发送数据了
if (!asio2::get_last_error())
client.async_send("<abcdefghijklmnopqrstovuxyz0123456789>");
// 如果在通信线程中调用同步发送函数会退化为异步调用(这里的bind_connect的回调函数就位于通信线程中)
// client.send("abc");
}).bind_disconnect([]()
{
printf("disconnect : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_recv([&](std::string_view sv)
{
printf("recv : %zu %.*s\n", sv.size(), (int)sv.size(), sv.data());
client.async_send(sv);
})
//// 绑定全局函数
//.bind_recv(on_recv)
//// 绑定成员函数(具体请查看example代码)
//.bind_recv(std::bind(&listener::on_recv, &lis, std::placeholders::_1))
//// 按lis对象的引用来绑定成员函数(具体请查看example代码)
//.bind_recv(&listener::on_recv, lis)
//// 按lis对象的指针来绑定成员函数(具体请查看example代码)
//.bind_recv(&listener::on_recv, &lis)
;
// 异步连接服务端
//client.async_start("0.0.0.0", "8080");
// 同步连接服务端
client.start("0.0.0.0", "8080");
// 连接成功后,可以调用发送函数(这里是主线程不在通信线程中)
// 同步发送和异步发送可以混用,是线程安全的(一定会在A发送完之后才会发送B)
std::size_t bytes_sent = client.send("abc");
// 同步发送函数的返回值为发送的字节数 可以用get_last_error()查看是否发生错误
if(asio2::get_last_error())
{
printf("同步发送数据失败:%s\n", asio2::last_error_msg().data());
}
// 按\n自动拆包(可以指定任意字符)
//client.async_start("0.0.0.0", "8080", '\n');
// 按\r\n自动拆包(可以指定任意字符串)
//client.async_start("0.0.0.0", "8080", "\r\n");
// 按自定义规则自动拆包(match_role请参考example代码)(用于对用户自定义的协议拆包)
// 对自定义协议拆包时,match_role如何使用的详细说明请看:https://blog.csdn.net/zhllxt/article/details/104772948
//client.async_start("0.0.0.0", "8080", match_role);
// 每次接收固定的100字节
//client.async_start("0.0.0.0", "8080", asio::transfer_exactly(100));
// 数据报模式的TCP,无论发送多长的数据,双方接收的一定是相应长度的整包数据
//client.start("0.0.0.0", "8080", asio2::use_dgram);
// 发送时也可以指定use_future参数,然后通过返回值future来阻塞等待直到发送完成,发送结果的错误码和发送字节数
// 保存在返回值future中(注意,不能在通信线程中用future去等待,这会阻塞通信线程进而导致死锁)
// std::future<std::pair<asio::error_code, std::size_t>> future = client.async_send("abc", asio::use_future);
```
## UDP:
##### 服务端:
```c++
asio2::udp_server server;
// ... 绑定监听器(请查看example代码)
server.start("0.0.0.0", "8080"); // 常规UDP
//server.start("0.0.0.0", "8080", asio2::use_kcp); // 可靠UDP
```
##### 客户端:
```c++
asio2::udp_client client;
// ... 绑定监听器(请查看example代码)
client.start("0.0.0.0", "8080");
//client.async_start("0.0.0.0", "8080", asio2::use_kcp); // 可靠UDP
```
## RPC:
##### 服务端:
```c++
// 全局函数示例,当服务端的RPC函数被调用时,如果想知道是哪个客户端调用的,将这个RPC函数的第一
// 个参数设置为连接对象的智能指针即可(如果不关心是哪个客户端调用的,第一个参数可以不要),如下:
int add(std::shared_ptr<asio2::rpc_session>& session_ptr, int a, int b)
{
return a + b;
}
// rpc默认是按照"数据长度+数据内容"的格式来发送数据的,因此客户端可能会恶意组包,导致解析出的
// "数据长度"非常长,此时就会分配大量内存来接收完整数据包.避免此问题的办法就是是指定缓冲区最
// 大值,如果发送的数据超过缓冲区最大值,就会将该连接直接关闭.所有tcp udp http websocket,server
// client 等均支持这个功能.
asio2::rpc_server server(
512, // 接收缓冲区的初始大小
1024, // 接收缓冲区的最大大小
4 // 多少个并发线程
);
// ... 绑定监听器(请查看example代码)
// 绑定RPC全局函数
server.bind("add", add);
// 绑定RPC成员函数
server.bind("mul", &A::mul, a);
// 绑定lambda表达式
server.bind("cat", [&](const std::string& a, const std::string& b) { return a + b; });
// 绑定成员函数(按引用) a的定义请查看example代码
server.bind("get_user", &A::get_user, a);
// 绑定成员函数(按指针) a的定义请查看example代码
server.bind("del_user", &A::del_user, &a);
// 服务端也可以调用客户端的RPC函数(通过连接对象session_ptr)
session_ptr->async_call([](int v)
{
printf("sub : %d err : %d %s\n", v, asio2::last_error_val(), asio2::last_error_msg().c_str());
}, std::chrono::seconds(10), "sub", 15, 6);
//server.start("0.0.0.0", "8080");
```
##### 客户端:
```c++
asio2::rpc_client client;
// ... 绑定监听器(请查看example代码)
// 不仅server可以绑定RPC函数给client调用,同时client也可以绑定RPC函数给server调用。请参考example代码。
client.start("0.0.0.0", "8080");
// 同步调用RPC函数
int sum = client.call<int>(std::chrono::seconds(3), "add", 11, 2);
printf("sum : %d err : %d %s\n", sum, asio2::last_error_val(), asio2::last_error_msg().c_str());
// 异步调用RPC函数,
// 第一个参数是回调函数,当调用完成或超时会自动调用该回调函数
// 第二个参数是调用超时,可以不填,如果不填则使用默认超时
// 第三个参数是rpc函数名,之后的参数是rpc函数的参数
client.async_call([](int v)
{
// 如果超时或发生其它错误,可以通过asio2::get_last_error()等一系列函数获取错误信息
printf("sum : %d err : %d %s\n", v, asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "add", 10, 20);
// 上面的调用方式的参数位置很容易搞混,因此也支持链式调用,如下(其它示例请查看example):
client.timeout(std::chrono::seconds(5)).async_call("mul", 2.5, 2.5).response(
[](double v)
{
std::cout << "mul1 " << v << std::endl;
});
int sum = client.timeout(std::chrono::seconds(3)).call<int>("add", 11, 32);
// 返回值为用户自定义数据类型(user类型的定义请查看example代码)
user u = client.call<user>("get_user");
printf("%s %d ", u.name.c_str(), u.age);
for (auto &[k, v] : u.purview)
{
printf("%d %s ", k, v.c_str());
}
printf("\n");
u.name = "hanmeimei";
u.age = ((int)time(nullptr)) % 100;
u.purview = { {10,"get"},{20,"set"} };
// 如果RPC函数的返回值为void,则用户回调函数参数为空
client.async_call([]()
{
}, "del_user", std::move(u));
// 只调用rpc函数,不需要返回结果
client.async_call("del_user", std::move(u));
```
## HTTP:
##### 服务端:
```c++
// http 请求拦截器
struct aop_log
{
bool before(http::request& req, http::response& rep)
{
asio2::detail::ignore_unused(rep);
printf("aop_log before %s\n", req.method_string().data());
// 返回true则后续的拦截器会接着调用,返回false则后续的拦截器不会被调用
return true;
}
bool after(std::shared_ptr<asio2::http_session>& session_ptr, http::request& req, http::response& rep)
{
asio2::detail::ignore_unused(session_ptr, req, rep);
printf("aop_log after\n");
return true;
}
};
struct aop_check
{
bool before(std::shared_ptr<asio2::http_session>& session_ptr, http::request& req, http::response& rep)
{
asio2::detail::ignore_unused(session_ptr, req, rep);
printf("aop_check before\n");
return true;
}
bool after(http::request& req, http::response& rep)
{
asio2::detail::ignore_unused(req, rep);
printf("aop_check after\n");
return true;
}
};
asio2::http_server server;
server.bind<http::verb::get, http::verb::post>("/index.*", [](http::request& req, http::response& rep)
{
std::cout << req.path() << std::endl;
std::cout << req.query() << std::endl;
rep.fill_file("../../../index.html");
rep.chunked(true);
}, aop_log{});
server.bind<http::verb::get>("/del_user",
[](std::shared_ptr<asio2::http_session>& session_ptr, http::request& req, http::response& rep)
{
// 回调函数的第一个参数可以是会话指针session_ptr(这个参数也可以不要)
printf("del_user ip : %s\n", session_ptr->remote_address().data());
// fill_page函数用给定的错误代码构造一个简单的标准错误页,<html>...</html>这样
rep.fill_page(http::status::ok, "del_user successed.");
}, aop_check{});
server.bind<http::verb::get>("/api/user/*", [](http::request& req, http::response& rep)
{
rep.fill_text("the user name is hanmeimei, .....");
}, aop_log{}, aop_check{});
server.bind<http::verb::get>("/defer", [](http::request& req, http::response& rep)
{
// 使用defer让http响应延迟发送,defer的智能指针销毁时,才会自动发送response
std::shared_ptr<http::response_defer> rep_defer = rep.defer();
std::thread([rep_defer, &rep]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
auto newrep = asio2::http_client::execute("http://www.baidu.com");
rep = std::move(newrep);
}).detach();
}, aop_log{}, aop_check{});
// 对websocket的支持
server.bind("/ws", websocket::listener<asio2::http_session>{}.
on("message", [](std::shared_ptr<asio2::http_session>& session_ptr, std::string_view data)
{
printf("ws msg : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}).on("open", [](std::shared_ptr<asio2::http_session>& session_ptr)
{
printf("ws open\n");
// 打印websocket的http请求头
std::cout << session_ptr->request() << std::endl;
// 如何给websocket响应头填充额外信息
session_ptr->ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::response_type& rep)
{
rep.set(http::field::authorization, " http-server-coro");
}));
}).on("close", [](std::shared_ptr<asio2::http_session>& session_ptr)
{
printf("ws close\n");
}));
server.bind_not_found([](http::request& req, http::response& rep)
{
// fill_page函数可以构造一个简单的标准错误页
rep.fill_page(http::status::not_found);
});
```
##### 客户端:
```c++
// 1. http下载大文件并直接保存
// The file is in this directory: /asio2/example/bin/x64/QQ9.6.7.28807.exe
asio2::https_client::download(
"https://dldir1.qq.com/qqfile/qq/PCQQ9.6.7/QQ9.6.7.28807.exe",
"QQ9.6.7.28807.exe");
// 2. http下载大文件并循环调用回调函数,可在回调函数中写入文件,可实现进度条之类功能
std::fstream hugefile("CentOS-7-x86_64-DVD-2009.iso", std::ios::out | std::ios::binary | std::ios::trunc);
asio2::https_client::download(asio::ssl::context{ asio::ssl::context::tlsv13 },
"https://mirrors.tuna.tsinghua.edu.cn/centos/7.9.2009/isos/x86_64/CentOS-7-x86_64-DVD-2009.iso",
//[](auto& header) // http header callback. this param is optional. the body callback is required.
//{
// std::cout << header << std::endl;
//},
[&hugefile](std::string_view chunk) // http body callback.
{
hugefile.write(chunk.data(), chunk.size());
}
);
hugefile.close();
// 通过URL字符串生成一个http请求对象
auto req1 = http::make_request("http://www.baidu.com/get_user?name=abc");
// 通过URL字符串直接请求某个网址,返回结果在rep1中
auto rep1 = asio2::http_client::execute("http://www.baidu.com/get_user?name=abc");
// 通过asio2::get_last_error()判断是否发生错误
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep1 << std::endl; // 打印http请求结果
// 通过http协议字符串生成一个http请求对象
auto req2 = http::make_request("GET / HTTP/1.1\r\nHost: 192.168.0.1\r\n\r\n");
// 通过请求对象发送http请求
auto rep2 = asio2::http_client::execute("www.baidu.com", "80", req2, std::chrono::seconds(3));
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep2 << std::endl;
std::stringstream ss;
ss << rep2;
std::string result = ss.str(); // 通过这种方式将http请求结果转换为字符串
// 获取url中的path部分的值
auto path = asio2::http::url_to_path("/get_user?name=abc");
std::cout << path << std::endl;
// 获取url中的query部分的值
auto query = asio2::http::url_to_query("/get_user?name=abc");
std::cout << query << std::endl;
std::cout << std::endl;
auto rep3 = asio2::http_client::execute("www.baidu.com", "80", "/api/get_user?name=abc");
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep3 << std::endl;
// URL编解码
std::string en = http::url_encode(R"(http://www.baidu.com/json={"qeury":"name like '%abc%'","id":1})");
std::cout << en << std::endl;
std::string de = http::url_decode(en);
std::cout << de << std::endl;
// 其它的更多用法请查看example示例代码
```
##### 其它的HTTP使用方式以及WEBSOCKET使用方式请参考example代码
## ICMP:
```c++
asio2::ping ping;
ping.timeout(std::chrono::seconds(3)) // 设置ping超时 默认3秒
.interval(std::chrono::seconds(1)) // 设置ping间隔 默认1秒
.bind_recv([](asio2::icmp_rep& rep)
{
if (rep.is_timeout())
std::cout << "request timed out" << std::endl;
else
std::cout << rep.total_length() - rep.header_length()
<< " bytes from " << rep.source_address()
<< ": icmp_seq=" << rep.sequence_number()
<< ", ttl=" << rep.time_to_live()
<< ", time=" << rep.milliseconds() << "ms"
<< std::endl;
}).start("192.168.127.12");
```
```c++
// 直接发送icmp包并同步获取网络延迟的时长
std::cout << asio2::ping::execute("www.baidu.com").milliseconds() << std::endl;
```
## SSL:
##### TCP/HTTP/WEBSOCKET均支持SSL功能(需要在config.hpp中将#define ASIO2_USE_SSL宏定义放开)
```c++
asio2::tcps_server server;
// 设置证书模式
// 如果是 verify_peer | verify_fail_if_no_peer_cert 则客户端必须要使用证书否则握手失败
// 如果是 verify_peer 或者是 verify_fail_if_no_peer_cert 则客户端用不用证书都可以
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// 从内存字符串加载SSL证书(具体请查看example代码) 字符串的具体定义请查看example代码
server.set_cert_buffer(ca_crt, server_crt, server_key, "server"); // use memory string for cert
server.set_dh_buffer(dh);
// 从文件加载SSL证书(注意编译后把example/cert目录下的证书拷贝到exe目录下 否则会提示加载证书失败)
server.set_cert_file("ca.crt", "server.crt", "server.key", "server"); // use file for cert
server.set_dh_file("dh1024.pem");
// 如何制作自己的证书:
// 1. 生成服务端私有密钥
// openssl genrsa -des3 -out server.key 1024
// 2. 生成服务端证书请求文件
// openssl req -new -key server.key -out server.csr -config openssl.cnf
// 3. 生成客户端私有密钥
// openssl genrsa -des3 -out client.key 1024
// 4. 生成客户端证书请求文件
// openssl req -new -key client.key -out client.csr -config openssl.cnf
// 5. 生成CA私有密钥
// openssl genrsa -des3 -out ca.key 2048
// 6. 生成CA证书文件
// openssl req -new -x509 -key ca.key -out ca.crt -days 3650 -config openssl.cnf
// 7. 生成服务端证书
// openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key -config openssl.cnf
// 8. 生成客户端证书
// openssl ca -in client.csr -out client.crt -cert ca.crt -keyfile ca.key -config openssl.cnf
// 9. 生成dh文件
// openssl dhparam -out dh1024.pem 1024
// 说明:openssl是个exe文件,在tool/openssl/x64/bin目录下 openssl.cnf在tool/openssl/x64/ssl目录下
// 生成证书过程中的其它细节百度搜索即可找到相关说明
```
##### TCP/HTTP/WEBSOCKET服务端、客户端等SSL功能请到example代码中查看。
## 串口:
```c++
std::string_view device = "COM1"; // windows
//std::string_view device = "/dev/ttyS0"; // linux
std::string_view baud_rate = "9600";
asio2::serial_port sp;
sp.bind_init([&]()
{
// 设置串口参数
sp.socket().set_option(asio::serial_port::flow_control(asio::serial_port::flow_control::type::none));
sp.socket().set_option(asio::serial_port::parity(asio::serial_port::parity::type::none));
sp.socket().set_option(asio::serial_port::stop_bits(asio::serial_port::stop_bits::type::one));
sp.socket().set_option(asio::serial_port::character_size(8));
}).bind_recv([&](std::string_view sv)
{
printf("recv : %zu %.*s\n", sv.size(), (int)sv.size(), sv.data());
// 接收串口数据
std::string s;
uint8_t len = uint8_t(10 + (std::rand() % 20));
s += '<';
for (uint8_t i = 0; i < len; i++)
{
s += (char)((std::rand() % 26) + 'a');
}
s += '>';
sp.async_send(s, []() {});
});
// 没有指定如何解析串口数据,需要用户自己去解析串口数据
//sp.start(device, baud_rate);
// 按照单个字符'>'作为数据分隔符自动解析串口数据
sp.start(device, baud_rate, '>');
// 按照字符串"\r\n"作为数据分隔符自动解析串口数据
//sp.start(device, baud_rate, "\r\n");
// 按照用户自定义的协议自动解析,关于match_role如何使用请参考tcp部分说明
//sp.start(device, baud_rate, match_role);
//sp.start(device, baud_rate, asio::transfer_at_least(1));
//sp.start(device, baud_rate, asio::transfer_exactly(10));
```
## 其它:
##### 定时器
```c++
// 框架中提供了定时器功能,使用非常简单,如下(更多示例请参考example/timer/timer.cpp):
asio2::timer timer;
// 参数1表示定时器ID,参数2表示定时器间隔,参数3为定时器回调函数
timer.start_timer(1, std::chrono::seconds(1), [&]()
{
printf("timer 1\n");
if (true) // 满足某个条件时关闭定时器,当然也可以在其它任意地方关闭定时器
timer.stop_timer(1);
});
// 执行5次的定时器,定时器id是字符串"id2",定时器间隔是2000毫秒
timer.start_timer("id2", 2000, 5, []()
{
printf("timer id2, loop 5 times\n");
});
// 首次执行会延时5000毫秒的定时器,定时器id是5,定时器间隔是1000毫秒
timer.start_timer(5, std::chrono::milliseconds(1000), std::chrono::milliseconds(5000), []()
{
printf("timer 5, loop infinite, delay 5 seconds\n");
});
// 所有的server,client,session等都继承了timer,所以server,client,session也可以使用定时器功能.
```
##### 手动触发的事件
```c++
asio2::tcp_client client;
// 投递一个异步条件事件,除非这个事件被主动触发,否则永远不会执行
std::shared_ptr<asio2::condition_event> event_ptr = client.post_condition_event([]()
{
// do something.
});
client.bind_recv([&](std::string_view data)
{
// 比如达到某个条件
if (data == "some_condition")
{
// 触发事件让事件开始执行
event_ptr->notify();
}
});
```
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_RECV_OP_HPP__
#define __ASIO2_HTTP_RECV_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/external/asio.hpp>
#include <asio2/external/beast.hpp>
#include <asio2/base/error.hpp>
#include <asio2/http/detail/http_util.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class http_recv_op
{
public:
using body_type = typename args_t::body_t;
using buffer_type = typename args_t::buffer_t;
/**
* @brief constructor
*/
http_recv_op() noexcept {}
/**
* @brief destructor
*/
~http_recv_op() = default;
protected:
template<typename C>
void _http_session_post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (derive.is_http())
{
// Make the request empty before reading,
// otherwise the operation behavior is undefined.
derive.req_.reset();
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_recv_counter_.load() == 0);
derive.post_recv_counter_++;
#endif
derive.reading_ = true;
// Read a request
http::async_read(derive.stream(), derive.buffer().base(), derive.req_,
make_allocator(derive.rallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(const error_code & ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
derive.reading_ = false;
derive._handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}));
}
else
{
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_recv_counter_.load() == 0);
derive.post_recv_counter_++;
#endif
derive.reading_ = true;
// Read a message into our buffer
derive.ws_stream().async_read(derive.buffer().base(),
make_allocator(derive.rallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(const error_code & ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
derive.reading_ = false;
derive._handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}));
}
}
template<typename C>
void _http_client_post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
// Make the request empty before reading,
// otherwise the operation behavior is undefined.
derive.rep_.reset();
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_recv_counter_.load() == 0);
derive.post_recv_counter_++;
#endif
derive.reading_ = true;
// Receive the HTTP response
http::async_read(derive.stream(), derive.buffer().base(), derive.rep_,
make_allocator(derive.rallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(const error_code & ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
derive.reading_ = false;
derive._handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}));
}
template<typename C>
void _http_post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
if (!derive.is_started())
{
if (derive.state() == state_t::started)
{
derive._do_disconnect(asio2::get_last_error(), std::move(this_ptr));
}
return;
}
if constexpr (args_t::is_session)
{
derive._http_session_post_recv(std::move(this_ptr), std::move(ecs));
}
else
{
derive._http_client_post_recv(std::move(this_ptr), std::move(ecs));
}
}
template<typename C>
void _http_session_handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
detail::ignore_unused(ec, bytes_recvd);
derived_t& derive = static_cast<derived_t&>(*this);
if (derive.is_http())
{
std::string_view target = derive.req_.target();
http::parses::http_parser_parse_url(
target.data(), target.size(), 0, std::addressof(derive.req_.url_.parser()));
derive.rep_.result(http::status::unknown);
derive.rep_.keep_alive(derive.req_.keep_alive());
if (derive._check_upgrade(this_ptr, ecs))
return;
derive._fire_recv(this_ptr, ecs);
// note : can't read write the variable of "req_" after _fire_recv, it maybe
// cause crash, eg :
// user called response.defer() in the recv callback, and pass the defer_ptr
// into another thread, then code run to here, at this time, the "req_" maybe
// read write in two thread : this thread and "another thread".
// note : can't call "_do_disconnect" at here, beacuse if user has called
// response.defer() in the recv callback, this session maybe closed before
// the response is sent to the client.
//if (derive.req_.need_eof() || !derive.req_.keep_alive())
//{
// derive._do_disconnect(asio::error::operation_aborted, derive.selfptr());
// return;
//}
}
else
{
derive.req_.ws_frame_type_ = websocket::frame::message;
derive.req_.ws_frame_data_ = { reinterpret_cast<std::string_view::const_pointer>(
derive.buffer().data().data()), bytes_recvd };
derive._fire_recv(this_ptr, ecs);
derive.buffer().consume(derive.buffer().size());
derive._post_recv(std::move(this_ptr), std::move(ecs));
}
}
template<typename C>
void _http_client_handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
detail::ignore_unused(ec, bytes_recvd);
derived_t& derive = static_cast<derived_t&>(*this);
derive._fire_recv(this_ptr, ecs);
derive._post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
void _http_handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
set_last_error(ec);
if (!derive.is_started())
{
if (derive.state() == state_t::started)
{
ASIO2_LOG_INFOR("_http_handle_recv with closed socket: {} {}", ec.value(), ec.message());
derive._do_disconnect(ec, this_ptr);
}
derive._stop_readend_timer(std::move(this_ptr));
return;
}
if (!ec)
{
// every times recv data,we update the last alive time.
derive.update_alive_time();
if constexpr (args_t::is_session)
{
derive._http_session_handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}
else
{
derive._http_client_handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}
}
else
{
ASIO2_LOG_DEBUG("_http_handle_recv with error: {} {}", ec.value(), ec.message());
// This means they closed the connection
//if (ec == http::error::end_of_stream)
derive._do_disconnect(ec, this_ptr);
derive._stop_readend_timer(std::move(this_ptr));
}
// If an error occurs then no new asynchronous operations are started. This
// means that all shared_ptr references to the connection object will
// disappear and the object will be destroyed automatically after this
// handler returns. The connection class's destructor closes the socket.
}
protected:
};
}
#endif // !__ASIO2_HTTP_RECV_OP_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_WS_SERVER_HPP__
#define __ASIO2_WS_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/http/ws_session.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
template<class derived_t, class session_t>
class ws_server_impl_t : public tcp_server_impl_t<derived_t, session_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
public:
using super = tcp_server_impl_t<derived_t, session_t>;
using self = ws_server_impl_t <derived_t, session_t>;
using session_type = session_t;
public:
/**
* @brief constructor
*/
template<class ...Args>
explicit ws_server_impl_t(Args&&... args)
: super(std::forward<Args>(args)...)
{
}
/**
* @brief destructor
*/
~ws_server_impl_t()
{
this->stop();
}
/**
* @brief start the server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param service - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
bool start(String&& host, StrOrInt&& service, Args&&... args)
{
return this->derived()._do_start(
std::forward<String>(host), std::forward<StrOrInt>(service),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
public:
/**
* @brief bind websocket upgrade listener
* @param fun - a user defined callback function.
* Function signature : void(std::shared_ptr<asio2::ws_session>& session_ptr)
*/
template<class F, class ...C>
inline derived_t & bind_upgrade(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::upgrade, observer_t<std::shared_ptr<session_t>&>
(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
};
}
namespace asio2
{
template<class derived_t, class session_t>
using ws_server_impl_t = detail::ws_server_impl_t<derived_t, session_t>;
template<class session_t>
class ws_server_t : public detail::ws_server_impl_t<ws_server_t<session_t>, session_t>
{
public:
using detail::ws_server_impl_t<ws_server_t<session_t>, session_t>::ws_server_impl_t;
};
using ws_server = ws_server_t<ws_session>;
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
template<class session_t>
class ws_rate_server_t : public asio2::ws_server_impl_t<ws_rate_server_t<session_t>, session_t>
{
public:
using asio2::ws_server_impl_t<ws_rate_server_t<session_t>, session_t>::ws_server_impl_t;
};
using ws_rate_server = ws_rate_server_t<ws_rate_session>;
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_WS_SERVER_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_SSL_CONTEXT_COMPONENT_HPP__
#define __ASIO2_SSL_CONTEXT_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <string>
#include <string_view>
#include <asio2/base/error.hpp>
#include <asio2/base/log.hpp>
namespace asio2::detail
{
// we must pass the "args_t" to this base class.
// can't use derived_t::args_type to get the args_t, beacuse this base class
// is inited before the derived class, the derived_t::args_type has not been
// defined in this base class.
template<class derived_t, class args_t>
class ssl_context_cp : public asio::ssl::context
{
public:
template<typename = void>
ssl_context_cp(asio::ssl::context::method method)
: asio::ssl::context(method)
{
// default_workarounds : SSL_OP_ALL
// All of the above bug workarounds.
// It is usually safe to use SSL_OP_ALL to enable the bug workaround options if
// compatibility with somewhat broken implementations is desired.
// single_dh_use : SSL_OP_SINGLE_DH_USE
// Always create a new key when using temporary / ephemeral
// DH parameters(see ssl_ctx_set_tmp_dh_callback(3)).
// This option must be used to prevent small subgroup attacks,
// when the DH parameters were not generated using "strong"
// primes(e.g.when using DSA - parameters, see dhparam(1)).
// If "strong" primes were used, it is not strictly necessary
// to generate a new DH key during each handshake but it is
// also recommended.
// SSL_OP_SINGLE_DH_USE should therefore be enabled whenever
// temporary / ephemeral DH parameters are used.
if constexpr (args_t::is_server)
{
// set default options
this->set_options(
asio::ssl::context::default_workarounds |
asio::ssl::context::no_sslv2 |
asio::ssl::context::no_sslv3 |
asio::ssl::context::single_dh_use
);
}
else
{
std::ignore = true;
}
}
~ssl_context_cp() = default;
/**
*
* >> openssl create your certificates and sign them
* ------------------------------------------------------------------------------------------------
* // 1. Generate Server private key
* openssl genrsa -des3 -out server.key 1024
* // 2. Generate Server Certificate Signing Request(CSR)
* openssl req -new -key server.key -out server.csr -config openssl.cnf
* // 3. Generate Client private key
* openssl genrsa -des3 -out client.key 1024
* // 4. Generate Client Certificate Signing Request(CSR)
* openssl req -new -key client.key -out client.csr -config openssl.cnf
* // 5. Generate CA private key
* openssl genrsa -des3 -out ca.key 2048
* // 6. Generate CA Certificate file
* openssl req -new -x509 -key ca.key -out ca.crt -days 3650 -config openssl.cnf
* // 7. Generate Server Certificate file
* openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key -config openssl.cnf
* // 8. Generate Client Certificate file
* openssl ca -in client.csr -out client.crt -cert ca.crt -keyfile ca.key -config openssl.cnf
* // 9. Generate dhparam file
* openssl dhparam -out dh1024.pem 1024
*
*/
/**
* server set_verify_mode :
* "verify_peer", ca_cert_buffer can be empty.
* Whether the client has a certificate or not is ok.
* "verify_fail_if_no_peer_cert", ca_cert_buffer can be empty.
* Whether the client has a certificate or not is ok.
* "verify_peer | verify_fail_if_no_peer_cert", ca_cert_buffer cannot be empty.
* Client must use certificate, otherwise handshake will be failed.
* client set_verify_mode :
* "verify_peer", ca_cert_buffer cannot be empty.
* "verify_none", ca_cert_buffer can be empty.
* private_cert_buffer,private_key_buffer,private_password always cannot be empty.
*/
template<typename = void>
inline derived_t& set_cert_buffer(
std::string_view ca_cert_buffer,
std::string_view private_cert_buffer,
std::string_view private_key_buffer,
std::string_view private_password
) noexcept
{
error_code ec{};
do
{
this->set_password_callback([password = std::string{ private_password }]
(std::size_t max_length, asio::ssl::context_base::password_purpose purpose)->std::string
{
detail::ignore_unused(max_length, purpose);
return password;
}, ec);
if (ec)
break;
ASIO2_ASSERT(!private_cert_buffer.empty() && !private_key_buffer.empty());
this->use_certificate(asio::buffer(private_cert_buffer), asio::ssl::context::pem, ec);
if (ec)
break;
this->use_private_key(asio::buffer(private_key_buffer), asio::ssl::context::pem, ec);
if (ec)
break;
if (!ca_cert_buffer.empty())
{
this->add_certificate_authority(asio::buffer(ca_cert_buffer), ec);
if (ec)
break;
}
} while (false);
set_last_error(ec);
return (static_cast<derived_t&>(*this));
}
/**
* server set_verify_mode :
* "verify_peer", ca_cert_buffer can be empty.
* Whether the client has a certificate or not is ok.
* "verify_fail_if_no_peer_cert", ca_cert_buffer can be empty.
* Whether the client has a certificate or not is ok.
* "verify_peer | verify_fail_if_no_peer_cert", ca_cert_buffer cannot be empty.
* Client must use certificate, otherwise handshake will be failed.
* client set_verify_mode :
* "verify_peer", ca_cert_buffer cannot be empty.
* "verify_none", ca_cert_buffer can be empty.
* private_cert_buffer,private_key_buffer,private_password always cannot be empty.
*/
template<typename = void>
inline derived_t& set_cert_file(
const std::string& ca_cert_file,
const std::string& private_cert_file,
const std::string& private_key_file,
const std::string& private_password
) noexcept
{
error_code ec{};
do
{
this->set_password_callback([password = private_password]
(std::size_t max_length, asio::ssl::context_base::password_purpose purpose)->std::string
{
detail::ignore_unused(max_length, purpose);
return password;
}, ec);
if (ec)
break;
ASIO2_ASSERT(!private_cert_file.empty() && !private_key_file.empty());
this->use_certificate_chain_file(private_cert_file, ec);
if (ec)
break;
this->use_private_key_file(private_key_file, asio::ssl::context::pem, ec);
if (ec)
break;
if (!ca_cert_file.empty())
{
this->load_verify_file(ca_cert_file, ec);
if (ec)
break;
}
} while (false);
set_last_error(ec);
return (static_cast<derived_t&>(*this));
}
/**
* BIO_new_mem_buf -> SSL_CTX_set_tmp_dh
*/
inline derived_t& set_dh_buffer(std::string_view dh_buffer) noexcept
{
error_code ec{};
if (!dh_buffer.empty())
this->use_tmp_dh(asio::buffer(dh_buffer), ec);
set_last_error(ec);
return (static_cast<derived_t&>(*this));
}
/**
* BIO_new_file -> SSL_CTX_set_tmp_dh
*/
inline derived_t& set_dh_file(const std::string& dh_file) noexcept
{
error_code ec{};
if (!dh_file.empty())
this->use_tmp_dh_file(dh_file, ec);
set_last_error(ec);
return (static_cast<derived_t&>(*this));
}
protected:
};
}
#endif // !__ASIO2_SSL_CONTEXT_COMPONENT_HPP__
#endif
<file_sep>#include <asio2/udp/udp_server.hpp>
decltype(std::chrono::steady_clock::now()) time1 = std::chrono::steady_clock::now();
decltype(std::chrono::steady_clock::now()) time2 = std::chrono::steady_clock::now();
std::size_t recvd_bytes = 0;
bool first = true;
int main()
{
asio2::udp_server server(1500, 1500);
server.bind_recv([&](std::shared_ptr<asio2::udp_session>& session_ptr, std::string_view data)
{
if (first)
{
first = false;
time1 = std::chrono::steady_clock::now();
time2 = std::chrono::steady_clock::now();
}
recvd_bytes += data.size();
decltype(std::chrono::steady_clock::now()) time3 = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time2).count();
if (ms > 1)
{
time2 = time3;
ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time1).count();
double speed = (double)recvd_bytes / (double)ms / double(1024) / double(1024);
printf("%.1lf MByte/Sec\n", speed);
}
session_ptr->async_send(asio::buffer(data)); // no allocate memory
//session_ptr->async_send(data); // allocate memory
});
server.start("0.0.0.0", "8116");
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_INVOKER_HPP__
#define __ASIO2_MQTT_INVOKER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/log.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
#include <asio2/mqtt/detail/mqtt_subscription_map.hpp>
#include <asio2/mqtt/detail/mqtt_shared_target.hpp>
#include <asio2/mqtt/detail/mqtt_retained_message.hpp>
#include <asio2/mqtt/detail/mqtt_message_router.hpp>
#include <asio2/mqtt/message.hpp>
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/core/type_name.hpp>)
#include <boost/core/type_name.hpp>
#else
#include <asio2/bho/core/type_name.hpp>
#endif
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class caller_t, class args_t>
class mqtt_invoker_t
{
friend caller_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
protected:
struct dummy {};
public:
using self = mqtt_invoker_t<caller_t, args_t>;
using handler_type = std::function<
void(error_code&, std::shared_ptr<caller_t>&, caller_t*, std::string_view&)>;
/**
* @brief constructor
*/
mqtt_invoker_t() noexcept : mqtt_handlers_() {}
/**
* @brief destructor
*/
~mqtt_invoker_t() = default;
/**
* @brief bind connect listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::v4::connect& msg, mqtt::v4::connack& rep) or v3 or v5
* or : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::message& msg, mqtt::message& rep)
* client : Don't need
*/
template<class F, class ...C>
inline self& on_connect(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::connect, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind connack listener
* @param fun - a user defined callback function.
* @li Function signature : server : Don't need
* client : void(mqtt::v4::connack& msg) or v3 or v5
* or : void(mqtt::message& msg)
*/
template<class F, class ...C>
inline self& on_connack(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::connack, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind publish listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::v4::publish& msg, mqtt::v4::puback rep) or v3 or v5
* or : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::message& msg, mqtt::message rep)
* client : void(mqtt::v4::publish& msg, mqtt::v4::puback rep) or v3 or v5
* or : void(mqtt::message& msg, mqtt::message rep)
*/
template<class F, class ...C>
inline self& on_publish(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::publish, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind puback listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr, mqtt::v4::puback& msg) or v3 or v5
* or : void(std::shared_ptr<mqtt_session>& session_ptr, mqtt::message& msg)
* client : void(mqtt::v4::puback& puback) or v3 or v5
* or : void(mqtt::message& msg)
*/
template<class F, class ...C>
inline self& on_puback(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::puback, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind pubrec listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::v4::pubrec& msg, mqtt::v4::pubrel& rep) or v3 or v5
* or : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::message& msg, mqtt::message& rep)
* client : void(mqtt::v4::pubrec& msg, mqtt::v4::pubrel& rep) or v3 or v5
* or : void(mqtt::message& msg, mqtt::message& rep)
*/
template<class F, class ...C>
inline self& on_pubrec(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::pubrec, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind pubrel listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::v4::pubrel& msg, mqtt::v4::pubcomp& rep) or v3 or v5
* or : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::message& msg, mqtt::message& rep)
* client : void(mqtt::v4::pubrel& msg, mqtt::v4::pubcomp& rep) or v3 or v5
* or : void(mqtt::message& msg, mqtt::message& rep)
*/
template<class F, class ...C>
inline self& on_pubrel(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::pubrel, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind pubcomp listener
* @param fun - a user defined callback function.
* @li Function signature : server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::v4::pubcomp& msg) or v3 or v5
* or : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::message& msg)
* client : void(mqtt::v4::pubcomp& msg) or v3 or v5
* or : void(mqtt::message& msg)
*/
template<class F, class ...C>
inline self& on_pubcomp(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::pubcomp, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind subscribe listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::v4::subscribe& msg, mqtt::v4::suback& rep) or v3 or v5
* or : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::message& msg, mqtt::message& rep)
* client : Don't need
*/
template<class F, class ...C>
inline self& on_subscribe(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::subscribe, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind suback listener
* @param fun - a user defined callback function.
* @li Function signature : server : Don't need
* client : void(mqtt::v4::suback& msg) or v3 or v5
* or : void(mqtt::message& msg)
*/
template<class F, class ...C>
inline self& on_suback(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::suback, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind unsubscribe listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::v4::unsubscribe& msg, mqtt::v4::unsuback& rep) or v3 or v5
* server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::message& msg, mqtt::message& rep)
* client : Don't need
*/
template<class F, class ...C>
inline self& on_unsubscribe(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::unsubscribe, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind unsuback listener
* @param fun - a user defined callback function.
* @li Function signature : server : Don't need
* client : void(mqtt::v4::unsuback& msg) or v3 or v5
* or : void(mqtt::message& msg)
*/
template<class F, class ...C>
inline self& on_unsuback(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::unsuback, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind pingreq listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::v4::pingreq& msg, mqtt::v4::pingresp& rep) or v3 or v5
* or : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::message& msg, mqtt::message& rep)
* client : Don't need
*/
template<class F, class ...C>
inline self& on_pingreq(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::pingreq, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind pingresp listener
* @param fun - a user defined callback function.
* @li Function signature : server : Don't need
* client : void(mqtt::v4::pingresp& msg) or v3 or v5
* or : void(mqtt::message& msg)
*/
template<class F, class ...C>
inline self& on_pingresp(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::pingresp, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind disconnect listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr, mqtt::v4::disconnect& msg) or v3 or v5
* or : void(std::shared_ptr<mqtt_session>& session_ptr, mqtt::message& msg)
* client : void(mqtt::v4::disconnect& msg) or v3 or v5
* or : void(mqtt::message& msg)
*/
template<class F, class ...C>
inline self& on_disconnect(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::disconnect, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief bind auth listener
* @param fun - a user defined callback function.
* @li Function signature :
* server : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::v5::auth& msg, mqtt::v5::connack& rep)
* or : void(std::shared_ptr<mqtt_session>& session_ptr,
* mqtt::message& msg, mqtt::message& rep)
* client : void(mqtt::v5::auth& msg, mqtt::v5::auth& rep)
* or : void(mqtt::message& msg, mqtt::message& rep)
*/
template<class F, class ...C>
inline self& on_auth(F&& fun, C&&... obj)
{
this->_bind(mqtt::control_packet_type::auth, std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
protected:
template<class F>
inline void _bind(mqtt::control_packet_type type, F f)
{
this->_do_bind(type, std::move(f), ((dummy*)nullptr));
}
template<class F, class C>
inline void _bind(mqtt::control_packet_type type, F f, C& c)
{
this->_do_bind(type, std::move(f), std::addressof(c));
}
template<class F, class C>
inline void _bind(mqtt::control_packet_type type, F f, C* c)
{
this->_do_bind(type, std::move(f), c);
}
template<class F, class C>
inline void _do_bind(mqtt::control_packet_type type, F f, C* c)
{
asio2::unique_locker g(this->mqtt_invoker_mutex_);
this->mqtt_handlers_[detail::to_underlying(type)] = std::make_shared<handler_type>(std::bind(
&self::template _proxy<F, C>,
this, std::move(f), c,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
}
template<class F, class C>
inline void _proxy(F& f, C* c, error_code& ec,
std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, std::string_view& data)
{
using fun_traits_type = function_traits<F>;
_argc_proxy<fun_traits_type::argc>(f, c, ec, caller_ptr, caller, data);
}
template<class F, class C, class M>
inline void _do_argc_1_proxy(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, M& msg)
{
using fun_traits_type = function_traits<F>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
using message_type = arg0_type;
if constexpr (std::is_same_v<message_type, mqtt::message>)
{
ec.clear();
this->_do_client_no_response(f, c, ec, caller_ptr, caller, msg, msg);
}
else
{
message_type* pmsg = std::get_if<message_type>(std::addressof(msg.variant()));
if (pmsg)
{
ec.clear();
this->_do_client_no_response(f, c, ec, caller_ptr, caller, msg, *pmsg);
}
else
{
this->_do_no_match_callback(f, ec, caller_ptr, caller, pmsg);
}
}
}
// Argc == 1 : must be client, the callback signature : void (mqtt::xxx_message&)
template<std::size_t Argc, class F, class C>
typename std::enable_if_t<Argc == 1>
inline _argc_proxy(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, std::string_view& data)
{
mqtt::data_to_message(caller->version(), data, [this, &f, &c, &ec, &caller_ptr, caller]
(auto msg) mutable
{
if (msg.empty() || asio2::get_last_error())
{
this->_do_malformed_packet(f, ec ? ec : asio2::get_last_error(), caller_ptr, caller);
return;
}
this->_do_argc_1_proxy(f, c, ec, caller_ptr, caller, msg);
});
}
template<class F, class C, class M>
inline void _do_argc_2_proxy_server(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, M& msg)
{
using fun_traits_type = function_traits<F>;
using message_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<1>::type>>;
if constexpr (std::is_same_v<message_type, mqtt::message>)
{
ec.clear();
this->_do_server_no_response(f, c, ec, caller_ptr, caller, msg, msg);
}
else
{
message_type* pmsg = std::get_if<message_type>(std::addressof(msg.variant()));
if (pmsg)
{
ec.clear();
this->_do_server_no_response(f, c, ec, caller_ptr, caller, msg, *pmsg);
}
else
{
this->_do_no_match_callback(f, ec, caller_ptr, caller, pmsg);
}
}
}
template<class F, class C>
inline void _argc_2_proxy_server(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, std::string_view& data)
{
mqtt::data_to_message(caller->version(), data, [this, &f, &c, &ec, &caller_ptr, caller]
(auto msg) mutable
{
if (msg.empty() || asio2::get_last_error())
{
this->_do_malformed_packet(f, ec ? ec : asio2::get_last_error(), caller_ptr, caller);
return;
}
this->_do_argc_2_proxy_server(f, c, ec, caller_ptr, caller, msg);
});
}
template<class F, class C, class M>
inline void _do_argc_2_proxy_client(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, M& msg)
{
using fun_traits_type = function_traits<F>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
using message_type = arg0_type;
using response_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<1>::type>>;
if constexpr (std::is_same_v<message_type, mqtt::message>)
{
ec.clear();
this->_do_client_with_response(
f, c, ec, caller_ptr, caller, msg, msg, response_type{});
}
else
{
message_type* pmsg = std::get_if<message_type>(std::addressof(msg.variant()));
if (pmsg)
{
ec.clear();
this->_do_client_with_response(
f, c, ec, caller_ptr, caller, msg, *pmsg, response_type{});
}
else
{
this->_do_no_match_callback(f, ec, caller_ptr, caller, pmsg);
}
}
}
template<class F, class C>
inline void _argc_2_proxy_client(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, std::string_view& data)
{
mqtt::data_to_message(caller->version(), data, [this, &f, &c, &ec, &caller_ptr, caller]
(auto msg) mutable
{
if (msg.empty() || asio2::get_last_error())
{
this->_do_malformed_packet(f, ec ? ec : asio2::get_last_error(), caller_ptr, caller);
return;
}
this->_do_argc_2_proxy_client(f, c, ec, caller_ptr, caller, msg);
});
}
// Argc == 2 : client or server
// if client, the callback signature : void (mqtt::xxx_message& message, mqtt::xxx_message& response)
// if server, the callback signature : void (std::shared_ptr<xxx_session>& session, mqtt::xxx_message& message)
template<std::size_t Argc, class F, class C>
typename std::enable_if_t<Argc == 2>
inline _argc_proxy(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, std::string_view& data)
{
using fun_traits_type = function_traits<F>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
// must be server
if constexpr (std::is_same_v<std::shared_ptr<caller_t>, arg0_type>)
{
this->_argc_2_proxy_server(f, c, ec, caller_ptr, caller, data);
}
// must be client
else
{
this->_argc_2_proxy_client(f, c, ec, caller_ptr, caller, data);
}
}
template<class F, class C, class M>
inline void _do_argc_3_proxy(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, M& msg)
{
using fun_traits_type = function_traits<F>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
static_assert(std::is_same_v<std::shared_ptr<caller_t>, arg0_type>);
using message_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<1>::type>>;
using response_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<2>::type>>;
if constexpr (std::is_same_v<message_type, mqtt::message>)
{
ec.clear();
this->_do_server_with_response(
f, c, ec, caller_ptr, caller, msg, msg, response_type{});
}
else
{
message_type* pmsg = std::get_if<message_type>(std::addressof(msg.variant()));
if (pmsg)
{
ec.clear();
this->_do_server_with_response(
f, c, ec, caller_ptr, caller, msg, *pmsg, response_type{});
}
else
{
this->_do_no_match_callback(f, ec, caller_ptr, caller, pmsg);
}
}
}
// Argc == 3 : must be server, the callback signature :
// void (std::shared_ptr<xxx_session>&, mqtt::xxx_message& message, mqtt::xxx_message& response)
template<std::size_t Argc, class F, class C>
typename std::enable_if_t<Argc == 3>
inline _argc_proxy(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, std::string_view& data)
{
mqtt::data_to_message(caller->version(), data, [this, &f, &c, &ec, &caller_ptr, caller]
(auto msg) mutable
{
if (msg.empty() || asio2::get_last_error())
{
this->_do_malformed_packet(f, ec ? ec : asio2::get_last_error(), caller_ptr, caller);
return;
}
this->_do_argc_3_proxy(f, c, ec, caller_ptr, caller, msg);
});
}
template<class F>
inline void _do_malformed_packet(F& f,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller)
{
detail::ignore_unused(f);
if (!ec)
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
this->_handle_mqtt_error(ec, caller_ptr, caller);
}
template<class F, class M>
inline void _do_no_match_callback(F& f,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, M* pmsg)
{
detail::ignore_unused(f, pmsg);
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/core/type_name.hpp>)
ASIO2_LOG_INFOR("The user callback function signature do not match : {}({} ...)"
, boost::core::type_name<detail::remove_cvref_t<F>>()
, boost::core::type_name<detail::remove_cvref_t<M>>()
);
#else
ASIO2_LOG_INFOR("The user callback function signature do not match : {}({} ...)"
, bho::core::type_name<detail::remove_cvref_t<F>>()
, bho::core::type_name<detail::remove_cvref_t<M>>()
);
#endif
//ASIO2_ASSERT(false &&
// "The parameters of the user callback function do not match."
// " Check that the parameters of your callback function are of the correct type");
if (!ec)
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
this->_handle_mqtt_error(ec, caller_ptr, caller);
}
template<typename F, typename C, class Message>
inline void _do_client_no_response(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg)
{
caller->_before_user_callback(ec, caller_ptr, caller, om, msg);
if (ec)
return this->_handle_mqtt_error(ec, caller_ptr, caller);
this->_invoke_user_callback(f, c, msg);
caller->_match_router(om);
caller->_after_user_callback(ec, caller_ptr, caller, om, msg);
this->_handle_mqtt_error(ec, caller_ptr, caller);
}
template<typename F, typename C, class Message>
inline void _do_server_no_response(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg)
{
caller->_before_user_callback(ec, caller_ptr, caller, om, msg);
if (ec)
return this->_handle_mqtt_error(ec, caller_ptr, caller);
this->_invoke_user_callback(f, c, caller_ptr, msg);
caller->_after_user_callback(ec, caller_ptr, caller, om, msg);
this->_handle_mqtt_error(ec, caller_ptr, caller);
}
template<typename F, typename C, class Message, class Response>
inline void _do_client_with_response(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response rep)
{
this->_init_response(ec, caller_ptr, caller, msg, rep);
caller->_before_user_callback(ec, caller_ptr, caller, om, msg, rep);
if (ec)
return this->_handle_mqtt_error(ec, caller_ptr, caller);
this->_invoke_user_callback(f, c, msg, rep);
caller->_after_user_callback(ec, caller_ptr, caller, om, msg, rep);
this->_send_mqtt_response(ec, caller_ptr, caller, msg, std::move(rep));
this->_handle_mqtt_error(ec, caller_ptr, caller);
}
template<typename F, typename C, class Message, class Response>
inline void _do_server_with_response(F& f, C* c,
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response rep)
{
this->_init_response(ec, caller_ptr, caller, msg, rep);
caller->_before_user_callback(ec, caller_ptr, caller, om, msg, rep);
if (ec)
return this->_handle_mqtt_error(ec, caller_ptr, caller);
this->_invoke_user_callback(f, c, caller_ptr, msg, rep);
caller->_after_user_callback(ec, caller_ptr, caller, om, msg, rep);
this->_send_mqtt_response(ec, caller_ptr, caller, msg, std::move(rep));
this->_handle_mqtt_error(ec, caller_ptr, caller);
}
template<typename F, typename C, typename... Args>
inline void _invoke_user_callback(F& f, C* c, Args&&... args)
{
detail::ignore_unused(c);
if constexpr (std::is_same_v<detail::remove_cvref_t<C>, dummy>)
f(std::forward<Args>(args)...);
else
(c->*f)(std::forward<Args>(args)...);
}
template<class Message, class Response>
typename std::enable_if_t<std::is_same_v<typename detail::remove_cvref_t<Message>, mqtt::message>>
inline _init_response(error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if constexpr (std::is_same_v<response_type, mqtt::message>)
{
if constexpr (std::is_same_v<message_type, mqtt::message>)
{
std::visit([this, &ec, &caller_ptr, &caller, &rep](auto& pm) mutable
{
this->_init_response(ec, caller_ptr, caller, pm, rep);
}, msg.variant());
}
else
{
std::ignore = true;
}
}
else
{
std::ignore = true;
}
}
template<class Message, class Response>
inline void _init_connect_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
mqtt::version ver = caller->version();
if /**/ (ver == mqtt::version::v3)
{
rep = mqtt::v3::connack{};
}
else if (ver == mqtt::version::v4)
{
rep = mqtt::v4::connack{};
}
else if (ver == mqtt::version::v5)
{
rep = mqtt::v5::connack{};
}
}
template<class Message, class Response>
inline void _init_publish_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
mqtt::version ver = caller->version();
if /**/ (ver == mqtt::version::v3)
{
switch (msg.qos())
{
// the qos 0 publish messgae don't need response, here just a placeholder,
// if has't set the rep to a msg, the _before_user_callback_impl can't be
// called correctly.
case mqtt::qos_type::at_most_once : rep = mqtt::v3::puback{}; break;
case mqtt::qos_type::at_least_once: rep = mqtt::v3::puback{}; break;
case mqtt::qos_type::exactly_once : rep = mqtt::v3::pubrec{}; break;
default:break;
}
}
else if (ver == mqtt::version::v4)
{
switch (msg.qos())
{
// the qos 0 publish messgae don't need response, here just a placeholder,
// if has't set the rep to a msg, the _before_user_callback_impl can't be
// called correctly.
case mqtt::qos_type::at_most_once : rep = mqtt::v4::puback{}; break;
case mqtt::qos_type::at_least_once: rep = mqtt::v4::puback{}; break;
case mqtt::qos_type::exactly_once : rep = mqtt::v4::pubrec{}; break;
default:break;
}
}
else if (ver == mqtt::version::v5)
{
switch (msg.qos())
{
// the qos 0 publish messgae don't need response, here just a placeholder,
// if has't set the rep to a msg, the _before_user_callback_impl can't be
// called correctly.
case mqtt::qos_type::at_most_once : rep = mqtt::v5::puback{}; break;
case mqtt::qos_type::at_least_once: rep = mqtt::v5::puback{}; break;
case mqtt::qos_type::exactly_once : rep = mqtt::v5::pubrec{}; break;
default:break;
}
}
}
template<class Message, class Response>
inline void _init_pubrec_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
mqtt::version ver = caller->version();
if /**/ (ver == mqtt::version::v3)
{
rep = mqtt::v3::pubrel{};
}
else if (ver == mqtt::version::v4)
{
rep = mqtt::v4::pubrel{};
}
else if (ver == mqtt::version::v5)
{
rep = mqtt::v5::pubrel{};
}
}
template<class Message, class Response>
inline void _init_pubrel_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
mqtt::version ver = caller->version();
if /**/ (ver == mqtt::version::v3)
{
rep = mqtt::v3::pubcomp{};
}
else if (ver == mqtt::version::v4)
{
rep = mqtt::v4::pubcomp{};
}
else if (ver == mqtt::version::v5)
{
rep = mqtt::v5::pubcomp{};
}
}
template<class Message, class Response>
inline void _init_subscribe_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
mqtt::version ver = caller->version();
if /**/ (ver == mqtt::version::v3)
{
rep = mqtt::v3::suback{};
}
else if (ver == mqtt::version::v4)
{
rep = mqtt::v4::suback{};
}
else if (ver == mqtt::version::v5)
{
rep = mqtt::v5::suback{};
}
}
template<class Message, class Response>
inline void _init_unsubscribe_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
mqtt::version ver = caller->version();
if /**/ (ver == mqtt::version::v3)
{
rep = mqtt::v3::unsuback{};
}
else if (ver == mqtt::version::v4)
{
rep = mqtt::v4::unsuback{};
}
else if (ver == mqtt::version::v5)
{
rep = mqtt::v5::unsuback{};
}
}
template<class Message, class Response>
inline void _init_pingreq_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
mqtt::version ver = caller->version();
if /**/ (ver == mqtt::version::v3)
{
rep = mqtt::v3::pingresp{};
}
else if (ver == mqtt::version::v4)
{
rep = mqtt::v4::pingresp{};
}
else if (ver == mqtt::version::v5)
{
rep = mqtt::v5::pingresp{};
}
}
template<class Message, class Response>
inline void _init_auth_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
mqtt::version ver = caller->version();
if /**/ (ver == mqtt::version::v3)
{
rep = mqtt::v3::connack{};
}
else if (ver == mqtt::version::v4)
{
rep = mqtt::v4::connack{};
}
else if (ver == mqtt::version::v5)
{
rep = mqtt::v5::auth{};
}
}
template<class Message, class Response>
typename std::enable_if_t<mqtt::is_rawmsg<typename detail::remove_cvref_t<Message>>()>
inline _init_response(error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if constexpr (std::is_same_v<response_type, mqtt::message>)
{
if /**/ constexpr (
std::is_same_v<message_type, mqtt::v3::connect> ||
std::is_same_v<message_type, mqtt::v4::connect> ||
std::is_same_v<message_type, mqtt::v5::connect>)
{
this->_init_connect_response(ec, caller_ptr, caller, msg, rep);
}
else if constexpr (
std::is_same_v<message_type, mqtt::v3::publish> ||
std::is_same_v<message_type, mqtt::v4::publish> ||
std::is_same_v<message_type, mqtt::v5::publish>)
{
this->_init_publish_response(ec, caller_ptr, caller, msg, rep);
}
else if constexpr (
std::is_same_v<message_type, mqtt::v3::pubrec> ||
std::is_same_v<message_type, mqtt::v4::pubrec> ||
std::is_same_v<message_type, mqtt::v5::pubrec>)
{
this->_init_pubrec_response(ec, caller_ptr, caller, msg, rep);
}
else if constexpr (
std::is_same_v<message_type, mqtt::v3::pubrel> ||
std::is_same_v<message_type, mqtt::v4::pubrel> ||
std::is_same_v<message_type, mqtt::v5::pubrel>)
{
this->_init_pubrel_response(ec, caller_ptr, caller, msg, rep);
}
else if constexpr (
std::is_same_v<message_type, mqtt::v3::subscribe> ||
std::is_same_v<message_type, mqtt::v4::subscribe> ||
std::is_same_v<message_type, mqtt::v5::subscribe>)
{
this->_init_subscribe_response(ec, caller_ptr, caller, msg, rep);
}
else if constexpr (
std::is_same_v<message_type, mqtt::v3::unsubscribe> ||
std::is_same_v<message_type, mqtt::v4::unsubscribe> ||
std::is_same_v<message_type, mqtt::v5::unsubscribe>)
{
this->_init_unsubscribe_response(ec, caller_ptr, caller, msg, rep);
}
else if constexpr (
std::is_same_v<message_type, mqtt::v3::pingreq> ||
std::is_same_v<message_type, mqtt::v4::pingreq> ||
std::is_same_v<message_type, mqtt::v5::pingreq>)
{
this->_init_pingreq_response(ec, caller_ptr, caller, msg, rep);
}
else if constexpr (
std::is_same_v<message_type, mqtt::v5::auth>)
{
this->_init_auth_response(ec, caller_ptr, caller, msg, rep);
}
else
{
std::ignore = true;
}
}
else
{
std::ignore = true;
}
}
template<class Message, class Response>
inline void _send_mqtt_message_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
Message& msg, Response&& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if (rep.empty())
return;
bool sendflag = true;
std::visit([&sendflag](auto& rep) mutable { sendflag = rep.get_send_flag(); }, rep.variant());
if (sendflag == false)
return;
// can't use async_send, beacuse the caller maybe not started yet
caller->push_event([caller_ptr, caller, id = caller->life_id(), rep = std::forward<Response>(rep)]
(event_queue_guard<caller_t> g) mutable
{
detail::ignore_unused(caller_ptr);
if (id != caller->life_id())
{
set_last_error(asio::error::operation_aborted);
return;
}
std::visit([caller, g = std::move(g)](auto& pr) mutable
{
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/core/type_name.hpp>)
ASIO2_LOG_DEBUG("mqtt send {}", boost::core::type_name<decltype(pr)>());
#else
ASIO2_LOG_DEBUG("mqtt send {}", bho::core::type_name<decltype(pr)>());
#endif
caller->_do_send(pr, [g = std::move(g)](const error_code&, std::size_t) mutable {});
}, rep.variant());
});
}
template<class Message, class Response>
inline void _send_mqtt_packet_response(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
Message& msg, Response&& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if (rep.get_send_flag() == false)
return;
// can't use async_send, beacuse the caller maybe not started yet
caller->push_event([caller_ptr, caller, id = caller->life_id(), rep = std::forward<Response>(rep)]
(event_queue_guard<caller_t> g) mutable
{
detail::ignore_unused(caller_ptr);
if (id != caller->life_id())
{
set_last_error(asio::error::operation_aborted);
return;
}
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/core/type_name.hpp>)
ASIO2_LOG_DEBUG("mqtt send {}", boost::core::type_name<decltype(rep)>());
#else
ASIO2_LOG_DEBUG("mqtt send {}", bho::core::type_name<decltype(rep)>());
#endif
caller->_do_send(rep, [g = std::move(g)](const error_code&, std::size_t) mutable {});
});
}
template<class Message, class Response>
inline void _send_mqtt_response(error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
Message& msg, Response&& rep)
{
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if constexpr (std::is_same_v<response_type, mqtt::message>)
{
this->_send_mqtt_message_response(ec, caller_ptr, caller, msg, std::forward<Response>(rep));
}
else
{
this->_send_mqtt_packet_response(ec, caller_ptr, caller, msg, std::forward<Response>(rep));
}
}
inline void _call_mqtt_handler(mqtt::control_packet_type type, error_code& ec,
std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, std::string_view& data)
{
ASIO2_ASSERT(caller->io().running_in_this_thread());
std::shared_ptr<handler_type> p;
{
asio2::shared_locker g(this->mqtt_invoker_mutex_);
if (detail::to_underlying(type) < this->mqtt_handlers_.size())
{
p = this->mqtt_handlers_[detail::to_underlying(type)];
}
}
if (p && (*p))
{
(*p)(ec, caller_ptr, caller, data);
}
else
{
// Should't run to here.
ASIO2_ASSERT(false);
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
this->_handle_mqtt_error(ec, caller_ptr, caller);
return;
}
}
template<class CallerT = caller_t>
inline void _handle_mqtt_error(error_code& ec, std::shared_ptr<CallerT>& caller_ptr, CallerT* caller)
{
if constexpr (CallerT::is_client())
{
return;
}
else
{
if (!ec)
return;
// post a async event to disconnect, don't call _do_disconnect directly,
// otherwise the client's bind_disconnect callback maybe can't be called.
asio::post(caller->io().context(), make_allocator(caller->wallocator(),
[ec, caller_ptr, caller]() mutable
{
if (caller->state() == state_t::started)
{
caller->_do_disconnect(ec, std::move(caller_ptr));
}
}));
}
}
inline std::shared_ptr<handler_type> _find_mqtt_handler(mqtt::control_packet_type type)
{
asio2::shared_locker g(this->mqtt_invoker_mutex_);
if (detail::to_underlying(type) < this->mqtt_handlers_.size())
{
std::shared_ptr<handler_type> p = mqtt_handlers_[detail::to_underlying(type)];
if (p && (*p))
return p;
}
return nullptr;
}
protected:
/// use rwlock to make thread safe
mutable asio2::shared_mutexer mqtt_invoker_mutex_;
// magic_enum has bug: maybe return 0 under wsl ubuntu
std::array<std::shared_ptr<handler_type>, detail::to_underlying(mqtt::control_packet_type::auth) + 1>
mqtt_handlers_ ASIO2_GUARDED_BY(mqtt_invoker_mutex_);
};
}
#endif // !__ASIO2_MQTT_INVOKER_HPP__
<file_sep>#include <asio2/asio2.hpp>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/tcp/tcp_client.hpp>
int main()
{
asio2::timer timer;
// 1 - timer id
// 1000 - timer inteval, 1000 milliseconds
timer.start_timer(1, 1000, [&]()
{
printf("timer 1, loop infinite\n");
timer.reset_timer_interval(1, 2000);
// or:
// timer.reset_timer_interval(1, std::chrono::milliseconds(2000));
});
// "id2"- timer id, this timer id is a string
// 2000 - timer inteval, 2000 milliseconds
// 1 - timer repeat times
timer.start_timer("id2", 2000, 1, []()
{
printf("timer id2, loop once\n");
});
// 3 - timer id
// 3000 - timer inteval, 3000 milliseconds
timer.start_timer(3, std::chrono::milliseconds(3000), []()
{
printf("timer 3, loop infinite\n");
});
// 4 - timer id
// 4000 - timer inteval, 4000 milliseconds
// 4 - timer repeat times
timer.start_timer(4, std::chrono::milliseconds(4000), 4, []()
{
printf("timer 4, loop 4 times\n");
});
// 5 - timer id
// std::chrono::milliseconds(1000) - timer inteval, 1000 milliseconds
// std::chrono::milliseconds(5000) - timer delay for first execute, 5000 milliseconds
timer.start_timer(5, std::chrono::milliseconds(1000), std::chrono::seconds(5), []()
{
printf("timer 5, loop infinite, delay 5 seconds\n");
});
// 6 - timer id
// std::chrono::milliseconds(1000) - timer inteval, 1000 milliseconds
// 6 - timer repeat times
// std::chrono::milliseconds(6000) - timer delay for first execute, 6000 milliseconds
timer.start_timer(6, std::chrono::seconds(1), 6, std::chrono::milliseconds(6000), []()
{
printf("timer 6, loop 6 times, delay 6 seconds\n");
});
// Start an asynchronous task with delay
timer.post([&]()
{
ASIO2_ASSERT(timer.io().running_in_this_thread());
printf("execute some task after 3 seconds for timer\n");
}, std::chrono::seconds(3));
//---------------------------------------------------------------------------------------------
{
std::shared_ptr<asio2::timer> timer_ptr = std::make_shared<asio2::timer>();
timer_ptr->start_timer("timer_ptr1", 1000, []()
{
printf("timer_ptr1, loop infinite\n");
});
// Note :
// if the timer is create as "std::shared_ptr<asio2::timer>", not "asio2::timer", you must
// call the "timer::stop()" function manually, otherwise it maybe cause crash.
// all the "server, client" need do the same like this.
timer_ptr->stop();
}
//---------------------------------------------------------------------------------------------
asio2::tcp_server server;
// test timer
server.start_timer(1, std::chrono::seconds(1), [&]()
{
ASIO2_ASSERT(server.io().running_in_this_thread());
printf("execute timer for tcp server \n");
});
// Start an asynchronous task with delay
server.post([&]()
{
ASIO2_ASSERT(server.io().running_in_this_thread());
printf("execute some task after 3 seconds\n");
}, std::chrono::seconds(3));
// Start a synchronization task
server.dispatch([&]()
{
ASIO2_ASSERT(server.io().running_in_this_thread());
printf("execute some task in server's io_context thread\n");
});
server.bind_connect([&](auto & session_ptr)
{
session_ptr->post([session_ptr]()
{
printf("execute some task after 3 seconds, session key : %zu\n", session_ptr->hash_key());
}, std::chrono::seconds(3));
session_ptr->start_timer(1, 1000, 5, [session_ptr]()
{
printf("execute timer for 5 times, session key : %zu\n", session_ptr->hash_key());
});
});
server.start("127.0.0.1", 3990);
//---------------------------------------------------------------------------------------------
asio2::tcp_client client;
std::shared_ptr<asio2::condition_event> evt_ptr = client.post_condition_event([&]()
{
ASIO2_ASSERT(client.io().running_in_this_thread());
printf("execute manual event for tcp client \n");
});
// test timer
client.start_timer(1, std::chrono::seconds(1), 10, [&, evt_ptr]()
{
ASIO2_ASSERT(client.io().running_in_this_thread());
printf("execute timer 10 times for tcp client \n");
static int counter = 0;
if (counter++ > 5)
{
client.stop_timer(1);
evt_ptr->notify();
}
});
// Start an asynchronous task with delay
client.post([&]()
{
ASIO2_ASSERT(client.io().running_in_this_thread());
printf("execute some task immediately for tcp client\n");
});
// Start a synchronization task
client.dispatch([&]()
{
ASIO2_ASSERT(client.io().running_in_this_thread());
printf("execute some task in client's io_context thread\n");
});
client.start("127.0.0.1", 3990);
while (std::getchar() != '\n');
return 0;
}
<file_sep>#ifndef BHO_CONFIG_HELPER_MACROS_HPP_INCLUDED
#define BHO_CONFIG_HELPER_MACROS_HPP_INCLUDED
// Copyright 2001 <NAME>.
// Copyright 2017 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// BHO_STRINGIZE(X)
// BHO_JOIN(X, Y)
//
// Note that this header is C compatible.
//
// Helper macro BHO_STRINGIZE:
// Converts the parameter X to a string after macro replacement
// on X has been performed.
//
#define BHO_STRINGIZE(X) BHO_DO_STRINGIZE(X)
#define BHO_DO_STRINGIZE(X) #X
//
// Helper macro BHO_JOIN:
// The following piece of macro magic joins the two
// arguments together, even when one of the arguments is
// itself a macro (see 16.3.1 in C++ standard). The key
// is that macro expansion of macro arguments does not
// occur in BHO_DO_JOIN2 but does in BHO_DO_JOIN.
//
#define BHO_JOIN(X, Y) BHO_DO_JOIN(X, Y)
#define BHO_DO_JOIN(X, Y) BHO_DO_JOIN2(X,Y)
#define BHO_DO_JOIN2(X, Y) X##Y
#endif // BHO_CONFIG_HELPER_MACROS_HPP_INCLUDED
<file_sep>## Modify the code to be compatible with the UE4 "check" macro
##### Modify file /fmt/ranges.h
```c++
// change the function "check(...)" to "(check)(...)"
// line 81,109
/// tuple_size and tuple_element check.
template <typename T> class is_tuple_like_ {
template <typename U>
static auto (check)(U* p) -> decltype(std::tuple_size<U>::value, int());
template <typename> static void (check)(...);
public:
static FMT_CONSTEXPR_DECL const bool value =
!std::is_void<decltype(check<T>(nullptr))>::value;
};
```
##### Modify file /beast/http/detail/type_traits.hpp
```c++
// change the function "check(...)" to "(check)(...)"
// line 35
template<class T>
class is_header_impl
{
template<bool b, class F>
static std::true_type (check)(
header<b, F> const*);
static std::false_type (check)(...);
public:
using type = decltype((check)((T*)0));
};
```
##### Modify file /beast/http/basic_parser.hpp
```c++
// change the body and header limit to no limit.
// line 71
std::uint64_t body_limit_ = (std::numeric_limits<std::uint64_t>::max)();
//default_body_limit(is_request{}); // max payload body
// line 78
std::uint32_t header_limit_ = 1 * 1024 * 1024; // max header size
```
##### Modify file /beast/http/basic_file_body.hpp
```c++
// to support copyable
```
##### Modify file /beast/core/impl/basic_stream.hpp
```c++
// line 107
// in function: impl_type::on_timer::operator()(error_code ec)
// beacuase the ec param maybe zero when the timer callback is
// called even if the timer cancel function has called already,
// then the timer will never exited.
// add this code:
if (!sp->socket.is_open())
return;
```
## Modify the code to be compatible with the mysql "IS_NUM" macro
##### Modify file /asio2/http/detail/http_parser.h
```c++
// Append "HTTP_" before all macro definitions.
```
##### Modify file /spdlog/spdlog.h
```c++
// Add header only define.
#ifndef ASIO2_DISABLE_AUTO_HEADER_ONLY
#ifndef SPDLOG_HEADER_ONLY
#define SPDLOG_HEADER_ONLY
#endif
#endif
```
##### Modify file /fmt/format.h
```c++
// Add header only define.
#ifndef ASIO2_DISABLE_AUTO_HEADER_ONLY
#ifndef FMT_HEADER_ONLY
#define FMT_HEADER_ONLY
#endif
#endif
```
##### Modify file /cereal/details/static_object.hpp
```c++
// Add No CEREAL_DLL_EXPORT define.
#if defined(_MSC_VER) && !defined(__clang__)
#if defined(ASIO2_ENABLE_CEREAL_DLL_EXPORT)
# define CEREAL_DLL_EXPORT __declspec(dllexport)
#else
# define CEREAL_DLL_EXPORT
#endif
# define CEREAL_USED
#else // clang or gcc
#if defined(ASIO2_ENABLE_CEREAL_DLL_EXPORT)
# define CEREAL_DLL_EXPORT __attribute__ ((visibility("default")))
#else
# define CEREAL_DLL_EXPORT
#endif
# define CEREAL_USED __attribute__ ((__used__))
#endif
```
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_VERSION_HPP__
#define __ASIO2_VERSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
/** @def ASIO2_API_VERSION
Identifies the API version of asio2.
This is a simple integer that is incremented by one every
time a set of code changes is merged to the develop branch.
*/
// ASIO2_VERSION / 100 is the major version
// ASIO2_VERSION % 100 is the minor version
#define ASIO2_VERSION 207 // 2.7
#endif // !__ASIO2_VERSION_HPP__
<file_sep>#ifndef BHO_MP11_DETAIL_MP_COPY_IF_HPP_INCLUDED
#define BHO_MP11_DETAIL_MP_COPY_IF_HPP_INCLUDED
// Copyright 2015-2019 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/mp11/utility.hpp>
#include <asio2/bho/mp11/detail/mp_list.hpp>
#include <asio2/bho/mp11/detail/mp_append.hpp>
#include <asio2/bho/mp11/detail/config.hpp>
namespace bho
{
namespace mp11
{
// mp_copy_if<L, P>
namespace detail
{
template<class L, template<class...> class P> struct mp_copy_if_impl
{
};
template<template<class...> class L, class... T, template<class...> class P> struct mp_copy_if_impl<L<T...>, P>
{
#if BHO_MP11_WORKAROUND( BHO_MP11_MSVC, < 1920 )
template<class U> struct _f { using type = mp_if<P<U>, mp_list<U>, mp_list<>>; };
using type = mp_append<L<>, typename _f<T>::type...>;
#else
template<class U> using _f = mp_if<P<U>, mp_list<U>, mp_list<>>;
using type = mp_append<L<>, _f<T>...>;
#endif
};
} // namespace detail
template<class L, template<class...> class P> using mp_copy_if = typename detail::mp_copy_if_impl<L, P>::type;
template<class L, class Q> using mp_copy_if_q = mp_copy_if<L, Q::template fn>;
} // namespace mp11
} // namespace bho
#endif // #ifndef BHO_MP11_DETAIL_MP_COPY_IF_HPP_INCLUDED
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_CACHE_HPP__
#define __ASIO2_HTTP_CACHE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <map>
#include <unordered_map>
#include <type_traits>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::http
#else
namespace boost::beast::http
#endif
{
struct enable_cache_t {};
constexpr static enable_cache_t enable_cache;
template<bool isRequest, class Body, class Fields = fields>
inline bool is_cache_enabled(http::message<isRequest, Body, Fields>& msg)
{
if constexpr (isRequest)
{
if (msg.method() == http::verb::get)
{
return true;
}
return false;
}
else
{
return true;
}
}
}
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class caller_t, class args_t, class MessageT>
class basic_http_cache_t
{
friend caller_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
protected:
struct cache_node
{
std::chrono::steady_clock::time_point alive;
MessageT msg;
cache_node(std::chrono::steady_clock::time_point t, MessageT m)
: alive(t), msg(std::move(m))
{
}
inline void update_alive_time() noexcept
{
alive = std::chrono::steady_clock::now();
}
};
public:
using self = basic_http_cache_t<caller_t, args_t, MessageT>;
/**
* @brief constructor
*/
basic_http_cache_t()
{
}
/**
* @brief destructor
*/
~basic_http_cache_t() = default;
/**
* @brief Add a element into the cache.
*/
template<class StringT>
inline cache_node* emplace(StringT&& url, MessageT msg)
{
asio2::unique_locker guard(this->http_cache_mutex_);
if (this->http_cache_map_.size() >= http_caches_max_count_)
return nullptr;
// can't use insert_or_assign, it maybe cause the msg was changed in multithread, and
// other thread are using the msg at this time.
return std::addressof(this->http_cache_map_.emplace(
detail::to_string(std::forward<StringT>(url)),
cache_node{ std::chrono::steady_clock::now(), std::move(msg) }).first->second);
}
/**
* @brief Checks if the cache has no elements.
*/
inline bool empty() const noexcept
{
asio2::shared_locker guard(this->http_cache_mutex_);
return this->http_cache_map_.empty();
}
/**
* @brief Finds the cache with key equivalent to url.
*/
template<class StringT>
inline cache_node* find(const StringT& url)
{
asio2::shared_locker guard(this->http_cache_mutex_);
if (this->http_cache_map_.empty())
return nullptr;
// If rehashing occurs due to the insertion, all iterators are invalidated.
// Otherwise iterators are not affected. References are not invalidated.
if constexpr (std::is_same_v<StringT, std::string>)
{
if (auto it = this->http_cache_map_.find(url); it != this->http_cache_map_.end())
return std::addressof(it->second);
}
else
{
std::string str = detail::to_string(url);
if (auto it = this->http_cache_map_.find(str); it != this->http_cache_map_.end())
return std::addressof(it->second);
}
return nullptr;
}
/**
* @brief Set the max number of elements in the container.
*/
inline self& set_cache_max_count(std::size_t count) noexcept
{
this->http_caches_max_count_ = count;
return (*this);
}
/**
* @brief Get the max number of elements in the container.
*/
inline std::size_t get_cache_max_count() const noexcept
{
return this->http_caches_max_count_;
}
/**
* @brief Get the current number of elements in the container.
*/
inline std::size_t get_cache_count() const noexcept
{
asio2::shared_locker guard(this->http_cache_mutex_);
return this->http_cache_map_.size();
}
/**
* @brief Requests the removal of expired elements.
*/
inline self& shrink_to_fit()
{
asio2::unique_locker guard(this->http_cache_mutex_);
if (this->http_cache_map_.size() < http_caches_max_count_)
return (*this);
std::multimap<std::chrono::steady_clock::duration::rep, const std::string*> mms;
for (auto& [url, node] : this->http_cache_map_)
{
mms.emplace(node.alive.time_since_epoch().count(), std::addressof(url));
}
std::size_t i = 0, n = mms.size() / 3;
for (auto& [t, purl] : mms)
{
detail::ignore_unused(t);
if (++i > n)
break;
this->http_cache_map_.erase(*purl);
}
return (*this);
}
/**
* @brief Erases all elements from the container.
*/
inline self& clear() noexcept
{
asio2::unique_locker guard(this->http_cache_mutex_);
this->http_cache_map_.clear();
return (*this);
}
protected:
mutable asio2::shared_mutexer http_cache_mutex_;
std::unordered_map<std::string, cache_node> http_cache_map_ ASIO2_GUARDED_BY(http_cache_mutex_);
std::size_t http_caches_max_count_ = 100000;
};
template<class caller_t, class args_t>
using http_cache_t = basic_http_cache_t<caller_t, args_t, http::response<http::flex_body>>;
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTP_CACHE_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_PING_HPP__
#define __ASIO2_PING_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <queue>
#include <any>
#include <future>
#include <tuple>
#include <asio2/base/iopool.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/object.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/base/impl/thread_id_cp.hpp>
#include <asio2/base/impl/user_data_cp.hpp>
#include <asio2/base/impl/socket_cp.hpp>
#include <asio2/base/impl/user_timer_cp.hpp>
#include <asio2/base/impl/post_cp.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
#include <asio2/base/impl/condition_event_cp.hpp>
#include <asio2/icmp/detail/icmp_header.hpp>
#include <asio2/icmp/detail/ipv4_header.hpp>
#include <asio2/icmp/detail/ipv6_header.hpp>
namespace asio2
{
class icmp_rep : public detail::ipv4_header, /*public detail::ipv6_header,*/ public detail::icmp_header
{
public:
std::chrono::steady_clock::duration lag{ std::chrono::steady_clock::duration(-1) };
inline bool is_timeout() noexcept { return (this->lag.count() == -1); }
inline auto get_milliseconds() noexcept
{
return this->lag.count() == -1 ? -1 :
std::chrono::duration_cast<std::chrono::milliseconds>(this->lag).count();
}
inline auto milliseconds() noexcept
{
return this->get_milliseconds();
}
detail::ipv4_header& base_ipv4() noexcept { return static_cast<detail::ipv4_header&>(*this); }
//detail::ipv6_header& base_ipv6() noexcept { return static_cast<detail::ipv6_header&>(*this); }
detail::icmp_header& base_icmp() noexcept { return static_cast<detail::icmp_header&>(*this); }
protected:
};
}
namespace asio2::detail
{
struct template_args_icmp
{
using socket_t = asio::ip::icmp::socket;
using buffer_t = asio::streambuf;
static constexpr std::size_t allocator_storage_size = 256;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
template<class derived_t, class args_t = template_args_icmp>
class ping_impl_t
: public object_t <derived_t >
, public iopool_cp <derived_t, args_t>
, public thread_id_cp <derived_t, args_t>
, public user_data_cp <derived_t, args_t>
, public user_timer_cp <derived_t, args_t>
, public post_cp <derived_t, args_t>
, public condition_event_cp<derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
public:
using super = object_t <derived_t >;
using self = ping_impl_t<derived_t, args_t>;
using iopoolcp = iopool_cp<derived_t, args_t>;
using args_type = args_t;
using socket_type = typename args_t::socket_t;
using buffer_type = typename args_t::buffer_t;
/**
* @brief constructor
* @param send_count - Total number of echo packets you want to send,
* send_count equals -1 for infinite send,
* Other parameters should use default values.
*/
explicit ping_impl_t(
std::size_t send_count = -1,
std::size_t init_buf_size = 64 * 1024, // We prepare the buffer to receive up to 64KB.
std::size_t max_buf_size = max_buffer_size,
std::size_t concurrency = 1
)
: super()
, iopool_cp <derived_t, args_t>(concurrency)
, user_data_cp <derived_t, args_t>()
, user_timer_cp <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp <derived_t, args_t>()
, socket_ (iopoolcp::_get_io(0).context())
, rallocator_()
, wallocator_()
, listener_ ()
, io_ (iopoolcp::_get_io(0))
, buffer_ (init_buf_size, max_buf_size)
, timer_ (iopoolcp::_get_io(0).context())
, ncount_ (send_count)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit ping_impl_t(
std::size_t send_count,
std::size_t init_buf_size,
std::size_t max_buf_size,
Scheduler&& scheduler
)
: super()
, iopool_cp <derived_t, args_t>(std::forward<Scheduler>(scheduler))
, user_data_cp <derived_t, args_t>()
, user_timer_cp <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp <derived_t, args_t>()
, socket_ (iopoolcp::_get_io(0).context())
, rallocator_()
, wallocator_()
, listener_ ()
, io_ (iopoolcp::_get_io(0))
, buffer_ (init_buf_size, max_buf_size)
, timer_ (iopoolcp::_get_io(0).context())
, ncount_ (send_count)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit ping_impl_t(Scheduler&& scheduler)
: ping_impl_t(std::size_t(-1), 64 * 1024, max_buffer_size, std::forward<Scheduler>(scheduler))
{
}
/**
* @brief destructor
*/
~ping_impl_t()
{
this->stop();
}
/**
* @brief start
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string. example : "192.168.3.11" or "www.google.com"
*/
template<typename String>
inline bool start(String&& host)
{
return this->derived()._do_start(std::forward<String>(host));
}
/**
* @brief stop
*/
inline void stop()
{
if (this->is_iopool_stopped())
return;
derived_t& derive = this->derived();
derive.io().unregobj(&derive);
derive.dispatch([&derive]() mutable
{
derive._do_stop(asio::error::operation_aborted, derive.selfptr());
});
this->stop_iopool();
}
/**
* @brief check whether the client is started
*/
inline bool is_started()
{
return (this->state_ == state_t::started && this->socket().is_open());
}
/**
* @brief check whether the client is stopped
*/
inline bool is_stopped()
{
return (this->state_ == state_t::stopped && !this->socket().is_open());
}
public:
/**
* @brief sync ping the host, and return the response directly.
* if some error occurs, call asio2::get_last_error(); to get the error info.
*/
template<class Rep, class Period>
static inline icmp_rep execute(
std::string_view host, std::chrono::duration<Rep, Period> timeout, std::string body)
{
icmp_rep rep;
// First assign default value timed_out to last error
set_last_error(asio::error::timed_out);
// The io_context is required for all I/O
asio::io_context ioc;
// These objects perform our I/O
asio::ip::icmp::resolver resolver{ ioc };
asio::ip::icmp::socket socket{ ioc };
asio::streambuf request_buffer;
asio::streambuf reply_buffer;
std::ostream os(std::addressof(request_buffer));
std::istream is(std::addressof(reply_buffer));
icmp_header echo_request;
unsigned short id = static_cast<unsigned short>(0);
unsigned short sequence_number = static_cast<unsigned short>(0);
decltype(std::chrono::steady_clock::now()) time_sent;
// Look up the domain name
resolver.async_resolve(host, "",
[&](const error_code& ec1, const asio::ip::icmp::resolver::results_type& endpoints) mutable
{
if (ec1) { set_last_error(ec1); return; }
for (auto& dest : endpoints)
{
struct socket_guard
{
socket_guard(
asio::ip::icmp::socket& s,
const asio::ip::basic_resolver_entry<asio::ip::icmp>& d
) : socket(s), dest(d)
{
error_code ec_ignore{};
socket.cancel(ec_ignore);
socket.close(ec_ignore);
socket.open(dest.endpoint().protocol());
}
~socket_guard()
{
error_code ec_ignore{};
// Gracefully close the socket
socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec_ignore);
socket.cancel(ec_ignore);
socket.close(ec_ignore);
}
asio::ip::icmp::socket& socket;
const asio::ip::basic_resolver_entry<asio::ip::icmp>& dest;
};
std::unique_ptr<socket_guard> guarder = std::make_unique<socket_guard>(socket, dest);
// Create an ICMP header for an echo request.
echo_request.type(icmp_header::echo_request);
echo_request.code(0);
id = (unsigned short)(std::size_t(guarder.get()));
echo_request.identifier(id);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
sequence_number = static_cast<unsigned short>(ms % (std::numeric_limits<unsigned short>::max)());
echo_request.sequence_number(sequence_number);
compute_checksum(echo_request, body.begin(), body.end());
// Encode the request packet.
os << echo_request << body;
// Send the request.
time_sent = std::chrono::steady_clock::now();
socket.async_send_to(request_buffer.data(), dest, [&, guarder = std::move(guarder)]
(const error_code& ec2, std::size_t) mutable
{
if (ec2) { set_last_error(ec2); return; }
// Discard any data already in the buffer.
reply_buffer.consume(reply_buffer.size());
std::size_t length = sizeof(ipv4_header) + sizeof(icmp_header) + body.size();
// Wait for a reply. We prepare the buffer to receive up to 64KB.
socket.async_receive(reply_buffer.prepare(length), [&, guarder = std::move(guarder)]
(const error_code& ec3, std::size_t bytes_recvd) mutable
{
set_last_error(ec3);
// The actual number of bytes received is committed to the buffer so that we
// can extract it using a std::istream object.
reply_buffer.commit(bytes_recvd);
// Decode the reply packet.
ipv4_header& ipv4_hdr = rep.base_ipv4();
icmp_header& icmp_hdr = rep.base_icmp();
is >> ipv4_hdr >> icmp_hdr;
ASIO2_ASSERT(ipv4_hdr.total_length() == bytes_recvd);
// We can receive all ICMP packets received by the host, so we need to
// filter out only the echo replies that match the our identifier and
// expected sequence number.
if (is && icmp_hdr.type() == icmp_header::echo_reply
&& icmp_hdr.identifier() == id
&& icmp_hdr.sequence_number() == sequence_number)
{
// Print out some information about the reply packet.
rep.lag = std::chrono::steady_clock::now() - time_sent;
}
});
});
break;
}
});
// timedout run
ioc.run_for(timeout);
error_code ec_ignore{};
// Gracefully close the socket
socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec_ignore);
socket.cancel(ec_ignore);
socket.close(ec_ignore);
return rep;
}
/**
* @brief sync ping the host, and return the response directly.
* if some error occurs, call asio2::get_last_error(); to get the error info.
*/
template<class Rep, class Period>
static inline icmp_rep execute(std::string_view host, std::chrono::duration<Rep, Period> timeout)
{
return derived_t::execute(host, timeout, R"("Hello!" from Asio ping.)");
}
/**
* @brief sync ping the host, and return the response directly.
* if some error occurs, call asio2::get_last_error(); to get the error info.
*/
static inline icmp_rep execute(std::string_view host)
{
return derived_t::execute(host, std::chrono::milliseconds(icmp_execute_timeout), R"("Hello!" from Asio ping.)");
}
public:
/**
* @brief bind recv listener
* @param fun - a user defined callback function.
* @li void on_recv(asio2::icmp_rep& rep){...}
* or a lumbda function like this :
* [&](asio2::icmp_rep& rep){...}
*/
template<class F, class ...C>
inline derived_t & bind_recv(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::recv,
observer_t<icmp_rep&>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind init listener,we should set socket options at here
* @param fun - a user defined callback function.
* @li This notification is called after the socket is opened.
* You can set the socket option in this notification.
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_init(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::init,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind start listener
* @param fun - a user defined callback function.
* @li This notification is called after the server starts up, whether successful or unsuccessful
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_start(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::start,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind stop listener
* @param fun - a user defined callback function.
* @li This notification is called before the server is ready to stop
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_stop(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::stop,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
public:
/**
* @brief get the socket object refrence
*/
inline socket_type & socket() noexcept { return this->socket_; }
/**
* @brief get the socket object refrence
*/
inline const socket_type & socket() const noexcept { return this->socket_; }
/**
* @brief get the stream object refrence
*/
inline socket_type & stream() noexcept { return this->socket_; }
/**
* @brief get the stream object refrence
*/
inline const socket_type & stream() const noexcept { return this->socket_; }
public:
/**
* @brief set icmp protocol identifier
*/
template<class Integer>
inline derived_t & set_identifier(Integer id) noexcept
{
this->identifier_ = (unsigned short)(std::size_t(id));
return (this->derived());
}
/**
* @brief get icmp protocol identifier
*/
inline unsigned short get_identifier() noexcept
{
return this->identifier_;
}
/**
* @brief set reply timeout duration value
*/
template<class Rep, class Period>
inline derived_t & set_timeout(std::chrono::duration<Rep, Period> duration) noexcept
{
this->timeout_ = duration;
return (this->derived());
}
/**
* @brief set reply timeout duration value, same as set_timeout
*/
template<class Rep, class Period>
inline derived_t & timeout(std::chrono::duration<Rep, Period> duration) noexcept
{
return this->set_timeout(std::move(duration));
}
/**
* @brief get reply timeout duration value
*/
inline std::chrono::steady_clock::duration get_timeout() noexcept
{
return this->timeout_;
}
/**
* @brief get reply timeout duration value, same as get_timeout
*/
inline std::chrono::steady_clock::duration timeout() noexcept
{
return this->get_timeout();
}
/**
* @brief set send interval duration value
*/
template<class Rep, class Period>
inline derived_t & set_interval(std::chrono::duration<Rep, Period> duration) noexcept
{
this->interval_ = duration;
return (this->derived());
}
/**
* @brief set send interval duration value, same as set_interval
*/
template<class Rep, class Period>
inline derived_t & interval(std::chrono::duration<Rep, Period> duration) noexcept
{
return this->set_interval(std::move(duration));
}
/**
* @brief get send interval duration value
*/
inline std::chrono::steady_clock::duration get_interval() noexcept
{
return this->interval_;
}
/**
* @brief get send interval duration value, same as get_interval
*/
inline std::chrono::steady_clock::duration interval() noexcept
{
return this->interval_;
}
/**
* @brief set icmp payload body
* This function is the same as the "payload()" function
*/
inline derived_t & set_body(std::string_view body)
{
this->body_ = body;
if (this->body_.size() > 65500)
this->body_.resize(65500);
return (this->derived());
}
/**
* @brief set icmp payload body, same as set_body
* This function is the same as the "payload()" function
*/
inline derived_t & body(std::string_view body)
{
return this->set_body(std::move(body));
}
/**
* @brief set icmp payload body
* This function is the same as the "body()" function
*/
inline derived_t & set_payload(std::string_view body)
{
return this->derived().body(std::move(body));
}
/**
* @brief set icmp payload body, same as set_payload
* This function is the same as the "body()" function
*/
inline derived_t & payload(std::string_view body)
{
return this->set_payload(std::move(body));
}
/**
* @brief get the resolved host ip
*/
inline std::string get_host_ip() { return this->destination_.address().to_string(); }
/**
* @brief get the resolved host ip, same as get_host_ip
*/
inline std::string host_ip() { return this->get_host_ip(); }
/**
* @brief Set the total number of echo packets you want to send
*/
inline derived_t & set_ncount(std::size_t send_count) noexcept
{
this->ncount_ = send_count;
return (this->derived());
}
/**
* @brief Set the total number of echo packets you want to send, same as set_ncount
*/
inline derived_t & ncount(std::size_t send_count) noexcept
{
return this->set_ncount(send_count);
}
/**
* @brief Get the total number of echo packets has sent, same as get_total_send
*/
inline std::size_t total_send() noexcept { return this->total_send_; }
/**
* @brief Get the total number of reply packets has recved, same as get_total_recv
*/
inline std::size_t total_recv() noexcept { return this->total_recv_; }
/**
* @brief Get the total number of echo packets has sent
*/
inline std::size_t get_total_send() noexcept { return this->total_send_; }
/**
* @brief Get the total number of reply packets has recved
*/
inline std::size_t get_total_recv() noexcept { return this->total_recv_; }
/**
* @brief Get the packet loss probability (loss rate)
*/
inline double get_plp() noexcept
{
if (this->total_send_ == static_cast<std::size_t>(0))
return 0.0;
return (((double)(total_send_ - total_recv_)) / (double)total_send_ * 100.0);
}
/**
* @brief Get the packet loss probability (loss rate), same as get_plp
*/
inline double plp() noexcept
{
return this->get_plp();
}
/**
* @brief Get the average duration of elapsed when recved reply packets
*/
inline std::chrono::steady_clock::duration get_avg_lag() noexcept
{
if (this->total_recv_ == static_cast<std::size_t>(0))
return std::chrono::steady_clock::duration(0);
return std::chrono::steady_clock::duration(
long((double)this->total_time_.count() / (double)this->total_recv_));
}
/**
* @brief Get the average duration of elapsed when recved reply packets, same as get_avg_lag
*/
inline std::chrono::steady_clock::duration avg_lag() noexcept
{
return this->get_avg_lag();
}
protected:
template<typename String>
bool _do_start(String&& host)
{
derived_t& derive = this->derived();
// if log is enabled, init the log first, otherwise when "Too many open files" error occurs,
// the log file will be created failed too.
#if defined(ASIO2_ENABLE_LOG)
asio2::detail::get_logger();
#endif
this->start_iopool();
if (!this->is_iopool_started())
{
set_last_error(asio::error::operation_aborted);
return false;
}
asio::dispatch(derive.io().context(), [&derive, this_ptr = derive.selfptr()]() mutable
{
detail::ignore_unused(this_ptr);
// init the running thread id
derive.io().init_thread_id();
});
// use promise to get the result of async accept
std::promise<error_code> promise;
std::future<error_code> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[promise = std::move(promise)]() mutable
{
promise.set_value(get_last_error());
}
};
derive.post(
[this, this_ptr = derive.selfptr(), host = std::forward<String>(host), pg = std::move(pg)]
() mutable
{
derived_t& derive = this->derived();
state_t expected = state_t::stopped;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
// if the state is not stopped, set the last error to already_started
set_last_error(asio::error::already_started);
return;
}
error_code ec, ec_ignore;
derive.io().regobj(&derive);
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_called_ = false;
#endif
expected = state_t::starting;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
ASIO2_ASSERT(false);
derive._handle_start(asio::error::operation_aborted, std::move(this_ptr));
return;
}
this->seq_ = 0;
this->total_send_ = 0;
this->total_recv_ = 0;
this->total_time_ = std::chrono::steady_clock::duration{ 0 };
asio::ip::icmp::resolver resolver(this->io().context());
auto results = resolver.resolve(host, "", ec);
if (ec)
{
derive._handle_start(ec, std::move(this_ptr));
return;
}
if (results.empty())
{
derive._handle_start(asio::error::host_not_found, std::move(this_ptr));
return;
}
this->destination_ = *results.begin();
this->socket().cancel(ec_ignore);
this->socket().close(ec_ignore);
this->socket().open(this->destination_.protocol(), ec);
if (ec)
{
derive._handle_start(ec, std::move(this_ptr));
return;
}
clear_last_error();
derive._fire_init();
derive._handle_start(ec, std::move(this_ptr));
});
if (!derive.io().running_in_this_thread())
{
set_last_error(future.get());
return static_cast<bool>(!get_last_error());
}
else
{
set_last_error(asio::error::in_progress);
}
// if the state is stopped , the return value is "is_started()".
// if the state is stopping, the return value is false, the last error is already_started
// if the state is starting, the return value is false, the last error is already_started
// if the state is started , the return value is true , the last error is already_started
return derive.is_started();
}
void _handle_start(error_code ec, std::shared_ptr<derived_t> this_ptr)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
// Whether the startup succeeds or fails, always call fire_start notification
state_t expected = state_t::starting;
if (!ec)
if (!this->state_.compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
set_last_error(ec);
this->derived()._fire_start();
expected = state_t::started;
if (!ec)
if (!this->state_.compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
if (ec)
{
this->derived()._do_stop(ec, std::move(this_ptr));
return;
}
this->buffer_.consume(this->buffer_.size());
this->derived()._post_send(this_ptr);
this->derived()._post_recv(std::move(this_ptr));
}
inline void _do_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
state_t expected = state_t::starting;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
return this->derived()._post_stop(ec, std::move(this_ptr), expected);
expected = state_t::started;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
return this->derived()._post_stop(ec, std::move(this_ptr), expected);
}
inline void _post_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state)
{
// asio don't allow operate the same socket in multi thread,
// if you close socket in one thread and another thread is
// calling socket's async_... function,it will crash.so we
// must care for operate the socket.when need close the
// socket ,we use the io_context to post a event,make sure the
// socket's close operation is in the same thread.
asio::dispatch(this->io().context(), make_allocator(this->derived().wallocator(),
[this, ec, this_ptr = std::move(this_ptr), old_state]() mutable
{
detail::ignore_unused(old_state);
set_last_error(ec);
state_t expected = state_t::stopping;
if (this->state_.compare_exchange_strong(expected, state_t::stopped))
{
this->derived()._fire_stop();
// call CRTP polymorphic stop
this->derived()._handle_stop(ec, std::move(this_ptr));
}
else
{
ASIO2_ASSERT(false);
}
}));
}
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
detail::ignore_unused(ec, this_ptr);
error_code ec_ignore{};
// close user custom timers
this->_dispatch_stop_all_timers();
// close all posted timed tasks
this->_dispatch_stop_all_timed_events();
// close all async_events
this->notify_all_condition_events();
detail::cancel_timer(this->timer_);
this->socket().cancel(ec_ignore);
// Call close,otherwise the _handle_recv will never return
this->socket().close(ec_ignore);
// clear recv buffer
this->buffer().consume(this->buffer().size());
// destroy user data, maybe the user data is self shared_ptr,
// if don't destroy it, will cause loop refrence.
this->user_data_.reset();
}
void _post_send(std::shared_ptr<derived_t> this_ptr)
{
// if ncount_ is equal to max, infinite send
if (this->ncount_ != std::size_t(-1))
{
if (this->total_send_ >= this->ncount_)
{
this->derived()._do_stop(asio::error::eof, std::move(this_ptr));
return;
}
}
// Create an ICMP header for an echo request.
icmp_header req;
req.type(icmp_header::echo_request);
req.code(0);
req.identifier(this->identifier_);
req.sequence_number(++seq_);
compute_checksum(req, this->body_.begin(), this->body_.end());
// Encode the request packet.
asio::streambuf buffer;
std::ostream os(std::addressof(buffer));
os << req << this->body_;
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->derived().post_send_counter_.load() == 0);
this->derived().post_send_counter_++;
#endif
// Send the request.
error_code ec;
this->time_sent_ = std::chrono::steady_clock::now();
this->socket().send_to(buffer.data(), this->destination_, 0, ec);
set_last_error(ec);
if (!ec)
this->total_send_++;
#if defined(_DEBUG) || defined(DEBUG)
this->derived().post_send_counter_--;
#endif
// Wait up to five seconds for a reply.
this->replies_ = 0;
if (this->is_started())
{
this->timer_.expires_after(this->timeout_);
this->timer_.async_wait(
[this, this_ptr = std::move(this_ptr)](const error_code & ec) mutable
{
this->derived()._handle_timer(ec, std::move(this_ptr));
});
}
}
void _handle_timer(const error_code & ec, std::shared_ptr<derived_t> this_ptr)
{
detail::ignore_unused(ec);
set_last_error(ec);
if (this->replies_ == 0)
{
this->rep_.lag = std::chrono::steady_clock::duration(-1);
if (!ec && this->is_started())
{
this->derived()._fire_recv(this->rep_);
}
}
// Requests must be sent no less than one second apart.
if (this->is_started())
{
this->timer_.expires_after(this->interval_);
this->timer_.async_wait(
[this, this_ptr = std::move(this_ptr)](const error_code & ec) mutable
{
detail::ignore_unused(ec);
this->derived()._post_send(std::move(this_ptr));
});
}
}
void _post_recv(std::shared_ptr<derived_t> this_ptr)
{
if (!this->is_started())
{
if (this->derived().state() == state_t::started)
{
this->derived()._do_stop(asio2::get_last_error(), std::move(this_ptr));
}
return;
}
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->derived().post_recv_counter_.load() == 0);
this->derived().post_recv_counter_++;
#endif
// Wait for a reply. We prepare the buffer to receive up to 64KB.
this->socket().async_receive(this->buffer_.prepare(this->buffer_.pre_size()),
make_allocator(this->rallocator_,
[this, this_ptr = std::move(this_ptr)]
(const error_code& ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
this->derived().post_recv_counter_--;
#endif
this->derived()._handle_recv(ec, bytes_recvd, std::move(this_ptr));
}));
}
void _handle_recv(const error_code& ec, std::size_t bytes_recvd, std::shared_ptr<derived_t> this_ptr)
{
set_last_error(ec);
if (!this->is_started())
{
if (this->derived().state() == state_t::started)
{
this->derived()._do_stop(ec, std::move(this_ptr));
}
return;
}
if (ec == asio::error::operation_aborted)
{
this->derived()._do_stop(ec, std::move(this_ptr));
return;
}
if (ec && bytes_recvd == 0)
{
this->derived()._do_stop(ec, std::move(this_ptr));
return;
}
// The actual number of bytes received is committed to the buffer so that we
// can extract it using a std::istream object.
this->buffer_.commit(bytes_recvd);
// Decode the reply packet.
std::istream is(std::addressof(this->buffer_));
ipv4_header& ipv4_hdr = this->rep_.base_ipv4();
icmp_header& icmp_hdr = this->rep_.base_icmp();
is >> ipv4_hdr >> icmp_hdr;
ASIO2_ASSERT(ipv4_hdr.total_length() == bytes_recvd);
// We can receive all ICMP packets received by the host, so we need to
// filter out only the echo replies that match the our identifier and
// expected sequence number.
if (is
&& icmp_hdr.type() == icmp_header::echo_reply
&& icmp_hdr.identifier() == this->identifier_
&& icmp_hdr.sequence_number() == this->seq_)
{
// If this is the first reply, interrupt the five second timeout.
if (this->replies_++ == 0)
{
detail::cancel_timer(this->timer_);
}
this->total_recv_++;
this->rep_.lag = std::chrono::steady_clock::now() - this->time_sent_;
this->total_time_ += this->rep_.lag;
this->derived()._fire_recv(this->rep_);
}
// Discard any data already in the buffer.
this->buffer_.consume(this->buffer_.size());
this->derived()._post_recv(std::move(this_ptr));
}
inline void _fire_init()
{
// the _fire_init must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(!get_last_error());
this->listener_.notify(event_type::init);
}
inline void _fire_start()
{
// the _fire_start must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_stop_called_ == false);
#endif
this->listener_.notify(event_type::start);
}
inline void _fire_stop()
{
// the _fire_stop must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_called_ = true;
#endif
this->listener_.notify(event_type::stop);
}
inline void _fire_recv(icmp_rep& rep)
{
this->listener_.notify(event_type::recv, rep);
}
public:
/**
* @brief get the buffer object refrence
*/
inline buffer_wrap<buffer_type> & buffer() noexcept { return this->buffer_; }
/**
* @brief get the io object refrence
*/
inline io_t & io() noexcept { return this->io_; }
protected:
/**
* @brief get the recv/read allocator object refrence
*/
inline auto & rallocator() noexcept { return this->rallocator_; }
/**
* @brief get the timer/post allocator object refrence
*/
inline auto & wallocator() noexcept { return this->wallocator_; }
inline listener_t & listener() noexcept { return this->listener_; }
inline std::atomic<state_t> & state () noexcept { return this->state_; }
protected:
/// socket
socket_type socket_;
/// The memory to use for handler-based custom memory allocation. used fo recv/read.
handler_memory<std::true_type , assizer<args_t>> rallocator_;
/// The memory to use for handler-based custom memory allocation. used fo timer/post.
handler_memory<std::false_type, assizer<args_t>> wallocator_;
/// listener
listener_t listener_;
/// The io_context wrapper used to handle the accept event.
io_t & io_;
/// buffer
buffer_wrap<buffer_type> buffer_;
/// state
std::atomic<state_t> state_ = state_t::stopped;
asio::steady_timer timer_;
std::string body_{ R"("Hello!" from Asio ping.)" };
unsigned short seq_ = 0;
std::size_t replies_ = 0;
icmp_rep rep_;
asio::ip::icmp::endpoint destination_;
unsigned short identifier_ = (unsigned short)(std::size_t(this));
std::size_t ncount_ { std::size_t(-1) };
std::size_t total_send_{ 0 };
std::size_t total_recv_{ 0 };
std::chrono::steady_clock::duration total_time_{ 0 };
std::chrono::steady_clock::duration timeout_ = std::chrono::milliseconds(icmp_execute_timeout);
std::chrono::steady_clock::duration interval_ = std::chrono::milliseconds(1000);
std::chrono::steady_clock::time_point time_sent_;
#if defined(_DEBUG) || defined(DEBUG)
bool is_stop_called_ = false;
std::atomic<int> post_send_counter_ = 0;
std::atomic<int> post_recv_counter_ = 0;
#endif
};
}
namespace asio2
{
template<class derived_t>
class ping_t : public detail::ping_impl_t<derived_t, detail::template_args_icmp>
{
public:
using detail::ping_impl_t<derived_t, detail::template_args_icmp>::ping_impl_t;
};
/**
* @brief constructor Parameter description
* @param send_count - Total number of echo packets you want to send,
* send_count equals -1 for infinite send,
* Other parameters should use default values.
* If this object is created as a shared_ptr like std::shared_ptr<asio2::ping> ping;
* you must call the ping->stop() manual when exit, otherwise maybe cause memory leaks.
*/
class ping : public ping_t<ping>
{
public:
using ping_t<ping>::ping_t;
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_PING_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_SSL_STREAM_COMPONENT_HPP__
#define __ASIO2_SSL_STREAM_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/ecs.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class ssl_stream_cp
{
public:
using ssl_socket_type = typename args_t::socket_t;
using ssl_stream_type = asio::ssl::stream<ssl_socket_type&>;
using ssl_handshake_type = typename asio::ssl::stream_base::handshake_type;
ssl_stream_cp(io_t& ssl_io, asio::ssl::context& ctx, ssl_handshake_type type) noexcept
: ssl_ctx_(ctx)
, ssl_type_(type)
{
detail::ignore_unused(ssl_io);
}
~ssl_stream_cp() = default;
/**
* @brief get the ssl socket object refrence
*/
inline ssl_stream_type & ssl_stream() noexcept
{
ASIO2_ASSERT(bool(this->ssl_stream_));
return (*(this->ssl_stream_));
}
protected:
template<typename C>
inline void _ssl_init(std::shared_ptr<ecs_t<C>>& ecs, ssl_socket_type& socket, asio::ssl::context& ctx)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::ignore_unused(derive, ecs, socket, ctx);
if constexpr (args_t::is_client)
{
ASIO2_ASSERT(derive.io().running_in_this_thread());
}
else
{
ASIO2_ASSERT(derive.sessions().io().running_in_this_thread());
}
// Why put the initialization code of ssl stream here ?
// Why not put it in the constructor ?
// -----------------------------------------------------------------------
// Beacuse SSL_CTX_use_certificate_chain_file,SSL_CTX_use_PrivateKey and
// other SSL_CTX_... functions must be called before SSL_new, otherwise,
// those SSL_CTX_... function calls have no effect.
// When construct a tcps_client object, beacuse the tcps_client is derived
// from ssl_stream_cp, so the ssl_stream_cp's constructor will be called,
// but at this time, the SSL_CTX_... function has not been called.
this->ssl_stream_ = std::make_unique<ssl_stream_type>(socket, ctx);
}
template<typename C>
inline void _ssl_start(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, ssl_socket_type& socket,
asio::ssl::context& ctx) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::ignore_unused(derive, this_ptr, ecs, socket, ctx);
ASIO2_ASSERT(derive.io().running_in_this_thread());
}
template<typename DeferEvent>
inline void _ssl_stop(std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
if (!this->ssl_stream_)
return;
derive.disp_event([this, &derive, this_ptr = std::move(this_ptr), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
// must construct a new chain
defer_event chain(std::move(e), std::move(g));
struct SSL_clear_op
{
ssl_stream_type* s{};
// SSL_clear :
// Reset ssl to allow another connection. All settings (method, ciphers, BIOs) are kept.
// When the client auto reconnect, SSL_clear must be called,
// otherwise the SSL handshake will failed.
SSL_clear_op(ssl_stream_type* p) : s(p)
{
}
~SSL_clear_op()
{
if (s)
SSL_clear(s->native_handle());
}
};
// use "std::shared_ptr<SSL_clear_op>" to enusre that the SSL_clear(...) function is
// called after "socket.shutdown, socket.close, ssl_stream.async_shutdown".
std::shared_ptr<SSL_clear_op> SSL_clear_ptr =
std::make_shared<SSL_clear_op>(this->ssl_stream_.get());
// if the client socket is not closed forever,this async_shutdown
// callback also can't be called forever, so we use a timer to
// force close the socket,then the async_shutdown callback will
// be called.
std::shared_ptr<asio::steady_timer> timer =
std::make_shared<asio::steady_timer>(derive.io().context());
timer->expires_after(derive.get_disconnect_timeout());
timer->async_wait(
[this_ptr, chain = std::move(chain), SSL_clear_ptr]
(const error_code& ec) mutable
{
// note : lambda [chain = std::move(chain), SSL_clear_ptr]
// SSL_clear_ptr will destroyed first
// chain will destroyed second after SSL_clear_ptr.
detail::ignore_unused(this_ptr, chain, SSL_clear_ptr);
set_last_error(ec);
});
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
// https://stackoverflow.com/questions/52990455/boost-asio-ssl-stream-shutdownec-always-had-error-which-is-boostasiossl
error_code ec_ignore{};
derive.socket().cancel(ec_ignore);
ASIO2_LOG_DEBUG("ssl_stream_cp enter async_shutdown");
// when server call ssl stream sync shutdown first,if the client socket is
// not closed forever,then here shutdowm will blocking forever.
this->ssl_stream_->async_shutdown(
[&derive, p = std::move(this_ptr), timer = std::move(timer), clear_ptr = std::move(SSL_clear_ptr)]
(const error_code& ec) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
detail::ignore_unused(derive, p, clear_ptr);
ASIO2_LOG_DEBUG("ssl_stream_cp leave async_shutdown: {} {}", ec.value(), ec.message());
set_last_error(ec);
detail::cancel_timer(*timer);
});
}, chain.move_guard());
}
template<typename C, typename DeferEvent>
inline void _post_handshake(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(bool(this->ssl_stream_));
ASIO2_ASSERT(derive.io().running_in_this_thread());
// Used to chech whether the ssl handshake is timeout
std::shared_ptr<std::atomic_flag> flag_ptr = std::make_shared<std::atomic_flag>();
flag_ptr->clear();
std::shared_ptr<asio::steady_timer> timer =
std::make_shared<asio::steady_timer>(derive.io().context());
timer->expires_after(derive.get_connect_timeout());
timer->async_wait(
[&derive, this_ptr, flag_ptr](const error_code& ec) mutable
{
detail::ignore_unused(this_ptr);
// no errors indicating timed out
if (!ec)
{
flag_ptr->test_and_set();
error_code ec_ignore{};
if (derive.socket().is_open())
{
error_code oldec = get_last_error();
asio::socket_base::linger linger = derive.get_linger();
// the get_linger maybe change the last error value.
set_last_error(oldec);
// we close the socket, so the async_handshake will returned
// with operation_aborted.
if (!(linger.enabled() == true && linger.timeout() == 0))
{
derive.socket().shutdown(asio::socket_base::shutdown_both, ec_ignore);
}
}
derive.socket().cancel(ec_ignore);
derive.socket().close(ec_ignore);
}
});
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
this->ssl_stream_->async_handshake(this->ssl_type_, make_allocator(derive.wallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs),
flag_ptr = std::move(flag_ptr), timer = std::move(timer), chain = std::move(chain)]
(const error_code& ec) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
detail::cancel_timer(*timer);
if (flag_ptr->test_and_set())
derive._handle_handshake(asio::error::timed_out,
std::move(this_ptr), std::move(ecs), std::move(chain));
else
derive._handle_handshake(ec,
std::move(this_ptr), std::move(ecs), std::move(chain));
}));
}
template<typename C, typename DeferEvent>
inline void _session_handle_handshake(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
// Use "sessions().dispatch" to ensure that the _fire_accept function and the _fire_handshake
// function are fired in the same thread
derive.sessions().dispatch(
[&derive, ec, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
set_last_error(ec);
derive._fire_handshake(this_ptr);
if (ec)
{
ASIO2_LOG_DEBUG("ssl_stream_cp::handle_handshake {} {}", ec.value(), ec.message());
derive._do_disconnect(ec, std::move(this_ptr), std::move(chain));
return;
}
derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
});
}
template<typename C, typename DeferEvent>
inline void _client_handle_handshake(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
set_last_error(ec);
derive._fire_handshake(this_ptr);
derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename C, typename DeferEvent>
inline void _handle_handshake(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
if constexpr (args_t::is_session)
{
derive._session_handle_handshake(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
else
{
derive._client_handle_handshake(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
}
protected:
asio::ssl::context & ssl_ctx_;
ssl_handshake_type ssl_type_;
std::unique_ptr<ssl_stream_type> ssl_stream_;
};
}
#endif // !__ASIO2_SSL_STREAM_COMPONENT_HPP__
#endif
<file_sep>/*
Copyright 2019 <NAME>
(<EMAIL>)
Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_CORE_FIRST_SCALAR_HPP
#define BHO_CORE_FIRST_SCALAR_HPP
#include <asio2/bho/config.hpp>
#include <cstddef>
namespace bho {
namespace detail {
template<class T>
struct make_scalar {
typedef T type;
};
template<class T, std::size_t N>
struct make_scalar<T[N]> {
typedef typename make_scalar<T>::type type;
};
} /* detail */
template<class T>
BHO_CONSTEXPR inline T*
first_scalar(T* p) BHO_NOEXCEPT
{
return p;
}
template<class T, std::size_t N>
BHO_CONSTEXPR inline typename detail::make_scalar<T>::type*
first_scalar(T (*p)[N]) BHO_NOEXCEPT
{
return bho::first_scalar(&(*p)[0]);
}
} /* boost */
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_AOP_CONNACK_HPP__
#define __ASIO2_MQTT_AOP_CONNACK_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class caller_t, class args_t>
class mqtt_aop_connack
{
friend caller_t;
protected:
template<class Message, bool IsClient = args_t::is_client>
inline std::enable_if_t<!IsClient, void>
_before_connack_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
// if server recvd connack message, disconnect
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
}
template<class Message, bool IsClient = args_t::is_client>
inline std::enable_if_t<IsClient, void>
_before_connack_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
// if started already and recvd connack message again, disconnect
state_t expected = state_t::started;
if (caller->state_.compare_exchange_strong(expected, state_t::started))
{
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
return;
}
caller->connack_message_ = msg;
}
// must be client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::connack& msg)
{
if (_before_connack_callback(ec, caller_ptr, caller, om, msg); ec)
return;
switch(msg.reason_code())
{
case mqtt::v3::connect_reason_code::success : ec = mqtt::make_error_code(mqtt::error::success ); break;
case mqtt::v3::connect_reason_code::unacceptable_protocol_version : ec = mqtt::make_error_code(mqtt::error::unsupported_protocol_version); break;
case mqtt::v3::connect_reason_code::identifier_rejected : ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid ); break;
case mqtt::v3::connect_reason_code::server_unavailable : ec = mqtt::make_error_code(mqtt::error::server_unavailable ); break;
case mqtt::v3::connect_reason_code::bad_user_name_or_password : ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password ); break;
case mqtt::v3::connect_reason_code::not_authorized : ec = mqtt::make_error_code(mqtt::error::not_authorized ); break;
default : ec = mqtt::make_error_code(mqtt::error::malformed_packet ); break;
}
}
// must be client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::connack& msg)
{
if (_before_connack_callback(ec, caller_ptr, caller, om, msg); ec)
return;
switch(msg.reason_code())
{
case mqtt::v4::connect_reason_code::success : ec = mqtt::make_error_code(mqtt::error::success ); break;
case mqtt::v4::connect_reason_code::unacceptable_protocol_version : ec = mqtt::make_error_code(mqtt::error::unsupported_protocol_version); break;
case mqtt::v4::connect_reason_code::identifier_rejected : ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid ); break;
case mqtt::v4::connect_reason_code::server_unavailable : ec = mqtt::make_error_code(mqtt::error::server_unavailable ); break;
case mqtt::v4::connect_reason_code::bad_user_name_or_password : ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password ); break;
case mqtt::v4::connect_reason_code::not_authorized : ec = mqtt::make_error_code(mqtt::error::not_authorized ); break;
default : ec = mqtt::make_error_code(mqtt::error::malformed_packet ); break;
}
}
// must be client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::connack& msg)
{
if (_before_connack_callback(ec, caller_ptr, caller, om, msg); ec)
return;
ec = mqtt::make_error_code(static_cast<mqtt::error>(msg.reason_code()));
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::connack& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
// if already has error, return
if (ec)
return;
switch(msg.reason_code())
{
case mqtt::v3::connect_reason_code::success : ec = mqtt::make_error_code(mqtt::error::success ); break;
case mqtt::v3::connect_reason_code::unacceptable_protocol_version : ec = mqtt::make_error_code(mqtt::error::unsupported_protocol_version); break;
case mqtt::v3::connect_reason_code::identifier_rejected : ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid ); break;
case mqtt::v3::connect_reason_code::server_unavailable : ec = mqtt::make_error_code(mqtt::error::server_unavailable ); break;
case mqtt::v3::connect_reason_code::bad_user_name_or_password : ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password ); break;
case mqtt::v3::connect_reason_code::not_authorized : ec = mqtt::make_error_code(mqtt::error::not_authorized ); break;
default : ec = mqtt::make_error_code(mqtt::error::malformed_packet ); break;
}
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::connack& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
// if already has error, return
if (ec)
return;
switch(msg.reason_code())
{
case mqtt::v4::connect_reason_code::success : ec = mqtt::make_error_code(mqtt::error::success ); break;
case mqtt::v4::connect_reason_code::unacceptable_protocol_version : ec = mqtt::make_error_code(mqtt::error::unsupported_protocol_version); break;
case mqtt::v4::connect_reason_code::identifier_rejected : ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid ); break;
case mqtt::v4::connect_reason_code::server_unavailable : ec = mqtt::make_error_code(mqtt::error::server_unavailable ); break;
case mqtt::v4::connect_reason_code::bad_user_name_or_password : ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password ); break;
case mqtt::v4::connect_reason_code::not_authorized : ec = mqtt::make_error_code(mqtt::error::not_authorized ); break;
default : ec = mqtt::make_error_code(mqtt::error::malformed_packet ); break;
}
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::connack& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
// if already has error, return
if (ec)
return;
ec = mqtt::make_error_code(static_cast<mqtt::error>(msg.reason_code()));
}
};
}
#endif // !__ASIO2_MQTT_AOP_CONNACK_HPP__
<file_sep>#include "unit_test.hpp"
#include <asio2/util/aes.hpp>
#include <asio2/util/base64.hpp>
void aes_test()
{
std::string src = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// ecb
{
std::string password = "<PASSWORD>";
std::string base64 = "<KEY>;
asio2::aes aes1(password);
aes1.mode(asio2::aes::mode_t::ecb);
std::string en = aes1.encrypt(src);
std::string de = aes1.decrypt(en);
ASIO2_CHECK(asio2::base64_encode(en) == base64);
ASIO2_CHECK(src == de);
}
{
std::string password = "<PASSWORD>";
std::string base64 = "pMY2AU58ga73<KEY>/hKs5/<KEY>3yBQ==";
asio2::aes aes1(password);
aes1.mode(asio2::aes::mode_t::ecb);
std::string en = aes1.encrypt(src);
std::string de = aes1.decrypt(en);
ASIO2_CHECK(asio2::base64_encode(en) == base64);
ASIO2_CHECK(src == de);
}
{
std::string password = "<PASSWORD>23456789123456";
std::string base64 = "<KEY>;
asio2::aes aes1(password);
aes1.mode(asio2::aes::mode_t::ecb);
std::string en = aes1.encrypt(src);
std::string de = aes1.decrypt(en);
ASIO2_CHECK(asio2::base64_encode(en) == base64);
ASIO2_CHECK(src == de);
}
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
std::string str;
{
int len = 500 + std::rand() % (500);
for (int i = 0; i < len; i++)
{
str += (char)(std::rand() % 255);
}
// the last character should not be '\0'
str += (char)((std::rand() % 26) + 'a');
}
{
std::string password;
int len = std::rand() % (40);
for (int i = 0; i < len; i++)
{
password += (char)(std::rand() % 255);
}
asio2::aes aes1(password, asio2::aes::mode_t::ecb);
std::string en = aes1.encrypt(str);
std::string de = aes1.decrypt(en);
ASIO2_CHECK(str == de);
}
// the cbc,ctr maybe has some problem
//{
// std::string password;
// int len = std::rand() % (40);
// for (int i = 0; i < len; i++)
// {
// password += (char)(std::rand() % 255);
// }
// asio2::aes aes1(password, asio2::aes::mode_t::cbc);
// std::string en = aes1.encrypt(str);
// std::string de = aes1.decrypt(en);
// ASIO2_CHECK(str == de);
//}
//{
// std::string password;
// int len = std::rand() % (40);
// for (int i = 0; i < len; i++)
// {
// password += (char)(std::rand() % 255);
// }
// asio2::aes aes1(password, asio2::aes::mode_t::ctr);
// std::string en = aes1.encrypt(str);
// std::string de = aes1.decrypt(en);
// ASIO2_CHECK(str == de);
//}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"aes",
ASIO2_TEST_CASE(aes_test)
)
<file_sep>/*
Copyright <NAME> 2012-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_BSD_FREE_H
#define BHO_PREDEF_OS_BSD_FREE_H
#include <asio2/bho/predef/os/bsd.h>
/* tag::reference[]
= `BHO_OS_BSD_FREE`
http://en.wikipedia.org/wiki/Freebsd[FreeBSD] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__FreeBSD__+` | {predef_detection}
| `+__FreeBSD_version+` | V.R.P
|===
*/ // end::reference[]
#define BHO_OS_BSD_FREE BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__FreeBSD__) \
)
# ifndef BHO_OS_BSD_AVAILABLE
# undef BHO_OS_BSD
# define BHO_OS_BSD BHO_VERSION_NUMBER_AVAILABLE
# define BHO_OS_BSD_AVAILABLE
# endif
# undef BHO_OS_BSD_FREE
# include <sys/param.h>
# if defined(__FreeBSD_version)
# if __FreeBSD_version == 491000
# define BHO_OS_BSD_FREE \
BHO_VERSION_NUMBER(4, 10, 0)
# elif __FreeBSD_version == 492000
# define BHO_OS_BSD_FREE \
BHO_VERSION_NUMBER(4, 11, 0)
# elif __FreeBSD_version < 500000
# define BHO_OS_BSD_FREE \
BHO_PREDEF_MAKE_10_VRPPPP(__FreeBSD_version)
# else
# define BHO_OS_BSD_FREE \
BHO_PREDEF_MAKE_10_VVRRPPP(__FreeBSD_version)
# endif
# else
# define BHO_OS_BSD_FREE BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_OS_BSD_FREE
# define BHO_OS_BSD_FREE_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_BSD_FREE_NAME "Free BSD"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_BSD_FREE,BHO_OS_BSD_FREE_NAME)
<file_sep>#ifndef ASIO2_USE_SSL
#define ASIO2_USE_SSL
#endif
#include "unit_test.hpp"
#include <asio2/asio2.hpp>
#include <asio2/external/fmt.hpp>
std::string_view server_key = R"(
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,32DBC28981A12AF1
<KEY>
)";
std::string_view server_crt = R"(
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 1 (0x1)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=AU, ST=HENAN, L=ZHENGZHOU, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=37792738@qq.com
Validity
Not Before: Nov 26 08:21:41 2021 GMT
Not After : Nov 24 08:21:41 2031 GMT
Subject: C=AU, ST=HENAN, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=37792738@qq.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (1024 bit)
Modulus:
00:c4:ba:4e:5f:22:45:ac:74:8f:5a:c3:06:4b:b4:
a6:22:be:68:7b:99:bf:44:02:66:69:09:ec:2c:7a:
68:c9:a9:0a:b2:f4:ed:69:6b:ad:29:59:b7:a6:ff:
69:df:f6:e5:45:44:d7:70:a7:40:84:d6:19:dd:c4:
36:27:86:1d:6d:79:e0:91:e5:77:79:49:28:4f:06:
7f:31:70:8b:ec:c2:58:9c:f4:14:1d:29:bb:2c:5a:
82:c2:b5:ca:de:eb:cb:a8:34:fc:7b:eb:48:76:44:
ed:29:a1:7d:99:3c:ad:a9:3d:8c:8d:ef:12:ef:d5:
fc00:e968:6179::de52:7100:a9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
9B:D5:B6:0E:47:C3:A7:B6:DA:84:3B:F0:CE:D1:50:D3:8F:4F:0A:8A
X509v3 Authority Key Identifier:
keyid:61:74:1F:7E:B1:0E:0D:F9:46:DD:6A:97:85:72:DE:1A:7D:A2:34:65
Signature Algorithm: sha256WithRSAEncryption
b6:1e:bb:f7:fa:c5:9f:07:6e:36:9d:2e:7d:39:8e:a1:ed:f1:
65:a0:0c:e4:bb:6d:bc:eb:58:d5:1d:c2:03:57:8a:41:0a:f1:
81:0f:87:38:c4:56:83:c3:9d:dc:f3:47:88:c8:a7:ba:69:f9:
bb:45:1f:73:48:96:f9:d7:fc:da:73:f9:17:5f:2f:94:19:83:
27:4b:b0:3e:19:29:71:a2:fc:db:d2:5f:6e:4f:e5:f1:d8:35:
55:f8:d9:db:75:dc:fe:11:e0:9f:70:6e:a8:26:2a:ca:7e:25:
08:e1:d5:d8:e3:0b:10:48:c6:ae:c5:b4:7b:15:20:87:97:20:
31:ee:e1:6f:d7:be:41:5d:2a:22:b0:36:16:1d:7a:70:bc:1b:
d3:89:94:ae:33:66:0c:cd:39:95:9e:69:30:37:05:bb:62:cd:
3f:dd:2b:bb:72:16:48:75:91:33:33:ae:b7:d7:2d:bd:ce:66:
f3:6b:69:81:fa:0d:aa:0e:5a:09:9d:24:54:ac:21:9b:14:43:
44:12:56:8b:cc:13:b5:3b:5a:ba:4e:7b:81:42:1e:38:61:ff:
a0:a7:01:2f:0b:67:77:90:48:bb:8a:52:62:69:76:3c:a8:a1:
d6:13:1e:27:f6:02:58:ae:91:4b:9d:37:4e:31:55:73:18:4e:
d0:61:54:3b
-----BEGIN CERTIFICATE-----
<KEY>
-----END CERTIFICATE-----
)";
std::string_view ca_crt = R"(
-----BEGIN CERTIFICATE-----
MIID0DCCArigAwIBAgIJ<KEY>0<KEY>
-----END CERTIFICATE-----
)";
std::string_view dh = R"(
-----BEGIN DH PARAMETERS-----
MIGHAoGB<KEY>
-----END DH PARAMETERS-----
)";
std::string_view client_key = R"(
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,967AA0B1DF77C592
<KEY>
)";
std::string_view client_crt = R"(
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 2 (0x2)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=AU, ST=HENAN, L=ZHENGZHOU, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=<EMAIL>
Validity
Not Before: Nov 26 09:04:13 2021 GMT
Not After : Nov 24 09:04:13 2031 GMT
Subject: C=AU, ST=HENAN, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=<EMAIL>
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (1024 bit)
Modulus:
00:be:94:6f:5b:ae:20:a8:73:25:3f:a8:4d:92:5a:
fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:10:e9:ad:e5:06:41:5a:
f6:eb:58:9a:22:6b:5c:ac:04:03:c5:09:2a:3d:84:
d9:34:25:42:76:f8:e6:c7:64:cd:5d:ce:ee:03:54:
da:af:dd:da:f2:b4:93:72:3f:26:d6:57:ea:18:ec:
9c:c8:20:bc:1a:a1:f9:e0:f5:64:67:9d:61:b8:f6:
87:a4:d3:36:01:24:b4:e7:00:c3:54:82:bd:7f:22:
48:40:df:43:8c:26:83:aa:b3:68:5d:e9:a1:fe:7c:
fc00:e968:6179::de52:7100:25
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
50:C7:26:F5:62:F6:B7:24:3C:1C:5C:58:96:08:59:94:A5:7A:A1:22
X509v3 Authority Key Identifier:
keyid:61:74:1F:7E:B1:0E:0D:F9:46:DD:6A:97:85:72:DE:1A:7D:A2:34:65
Signature Algorithm: sha256WithRSAEncryption
39:c1:66:e0:1a:68:2a:bc:6e:56:a0:a4:18:53:ac:2e:49:03:
d3:df:e0:7d:4e:51:4c:0b:fb:f9:1d:ae:a5:b8:16:b1:b6:23:
db:62:33:25:72:14:99:e1:3a:1a:52:d2:f4:51:74:ef:df:04:
91:34:4f:e6:57:c2:d6:41:60:05:d5:65:09:6c:44:14:e6:29:
b8:fc00:db20:35b:7399::5:99:24:eb:a8:76:18:88:14:84:
83:ee:33:a3:5c:05:9a:3c:e3:f0:35:e3:52:a2:4e:aa:39:07:
41:43:10:3f:cb:03:a2:48:a9:90:ef:5a:53:3b:5b:c7:4d:bb:
76:05:70:eb:a7:15:22:ad:b5:ed:3b:74:58:71:c0:53:90:44:
92:81:8b:62:62:2f:3a:96:66:ee:18:53:d4:4c:5e:d6:29:f4:
4c:18:2c:7a:79:96:38:d7:cf:51:e4:3b:72:9f:9c:be:7f:2e:
05:8a:06:18:61:62:d5:9c:cc:31:a7:4c:d9:94:bd:d3:b4:22:
b8:42:d2:6f:99:7a:72:43:b3:a9:03:e2:36:6d:6b:28:4f:f8:
c5:b5:1b:2b:1d:e9:34:8f:66:0a:13:58:d5:28:38:03:22:bc:
37:27:ed:c7:b3:c7:80:63:25:d7:fc:38:ad:ac:f9:aa:5b:07:
15:df:56:17
-----BEGIN CERTIFICATE-----
<KEY>
-----END CERTIFICATE-----
)";
void start_stop_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
// test tcps stop then start in non io_context thread
{
asio2::tcps_server server;
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcps_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
int& num = session_ptr->get_user_data<int&>();
num++;
session_ptr->async_send(data);
});
server.bind_connect([&](auto & session_ptr)
{
session_ptr->set_user_data(0);
});
bool server_start_ret = server.start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
bool flag = false;
std::vector<std::shared_ptr<asio2::tcps_client>> clients;
std::atomic<int> client_connect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcps_client>());
asio2::tcps_client& client = *iter;
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_connect([&]()
{
client.set_user_data(0);
if (!asio2::get_last_error())
{
client_connect_counter++;
if (flag)
{
client.async_send("01234567890123456789012345678901234567890123456789");
}
}
});
client.bind_disconnect([&]()
{
client_connect_counter--;
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
int& num = client.get_user_data<int&>();
num++;
if (num == 11)
return;
client.async_send(data);
});
bool client_start_ret = client.async_start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
// wait all client's bind connect has called.
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_connect_counter, client_connect_counter == std::size_t(test_client_count));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
flag = true;
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->stop();
ASIO2_CHECK(p->is_stopped());
p->start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(p->is_started());
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_connect_counter, client_connect_counter == std::size_t(test_client_count));
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
for (int num = p->get_user_data<int>(); num < 11; num = p->get_user_data<int>())
{
ASIO2_TEST_WAIT_CHECK();
}
int num = p->get_user_data<int>();
ASIO2_CHECK_VALUE(num, num == 11);
}
flag = true;
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->post([p]()
{
p->stop();
});
}
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
while (!p->is_stopped())
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->stop();
ASIO2_CHECK(p->is_stopped());
p->start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(p->is_started());
p->stop();
ASIO2_CHECK(p->is_stopped());
p->start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(p->is_started());
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_connect_counter, client_connect_counter == std::size_t(test_client_count));
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
for (int num = p->get_user_data<int>(); num < 11; num = p->get_user_data<int>())
{
ASIO2_TEST_WAIT_CHECK();
}
int num = p->get_user_data<int>();
ASIO2_CHECK_VALUE(num, num == 11);
}
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->stop();
ASIO2_CHECK(p->is_stopped());
p->stop();
ASIO2_CHECK(p->is_stopped());
p->start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(p->is_started());
p->start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(p->is_started());
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_connect_counter, client_connect_counter == std::size_t(test_client_count));
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
for (int num = p->get_user_data<int>(); num < 11; num = p->get_user_data<int>())
{
ASIO2_TEST_WAIT_CHECK();
}
int num = p->get_user_data<int>();
ASIO2_CHECK_VALUE(num, num == 11);
}
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->stop();
ASIO2_CHECK(p->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
}
// test tcps stop then start in io_context thread
{
asio2::tcps_server server;
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcps_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
int& num = session_ptr->get_user_data<int&>();
num++;
ASIO2_CHECK(std::stoi(std::string(data.substr(0, data.find(',')))) == num);
session_ptr->async_send(data);
});
server.bind_connect([&](auto & session_ptr)
{
session_ptr->set_user_data(0);
});
bool server_start_ret = server.start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
bool flag = false;
std::vector<std::shared_ptr<asio2::tcps_client>> clients;
std::atomic<int> client_connect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcps_client>());
asio2::tcps_client& client = *iter;
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_connect([&]()
{
client.set_user_data(0);
if (!asio2::get_last_error())
{
client_connect_counter++;
if (flag)
{
client.async_send("1,a");
}
}
});
client.bind_disconnect([&]()
{
client_connect_counter--;
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
int& num = client.get_user_data<int&>();
num++;
ASIO2_CHECK(std::stoi(std::string(data.substr(0, data.find(',')))) == num);
if (num == 11)
return;
std::string str;
str += std::to_string(num + 1);
str += ",";
for (int i = 0; i < num + 1; i++)
str += "a";
client.async_send(std::move(str));
});
bool client_start_ret = client.async_start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
// wait all client's bind connect has called.
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_connect_counter, client_connect_counter == std::size_t(test_client_count));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
flag = true;
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->post([p]()
{
p->stop();
p->start("127.0.0.1", 18042, asio2::use_dgram);
});
}
// wait all client's stop and start has called.
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->post([]() {}, asio::use_future).wait();
p->post_queued_event([]() {}, asio::use_future).wait();
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_connect_counter, client_connect_counter == std::size_t(test_client_count));
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
for (int num = p->get_user_data<int>(); num < 11; num = p->get_user_data<int>())
{
ASIO2_TEST_WAIT_CHECK();
}
int num = p->get_user_data<int>();
ASIO2_CHECK_VALUE(num, num == 11);
}
flag = true;
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->post([p]()
{
p->stop();
});
}
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
while (!p->is_stopped())
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->post([p]()
{
p->stop();
p->start("127.0.0.1", 18042, asio2::use_dgram);
p->stop();
p->start("127.0.0.1", 18042, asio2::use_dgram);
});
}
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
// wait all client's stop and start has called.
p->post([]() {}, asio::use_future).wait();
// wait all client's stop and start event has called.
// otherwise the get user data maybe failed, beacuse after the first start, the while
// loop maybe true and breaked, when code run to the get user data, at this time, the
// second stop is called, so the user data is empty.
p->post_queued_event([]() {}, asio::use_future).wait();
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_connect_counter, client_connect_counter == std::size_t(test_client_count));
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
for (int num = p->get_user_data<int>(); num < 11; num = p->get_user_data<int>())
{
ASIO2_TEST_WAIT_CHECK();
}
int num = p->get_user_data<int>();
ASIO2_CHECK_VALUE(num, num == 11);
}
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
// @see /asio2/base/iopool.hpp ~iopool()
p->post([p]()
{
p->stop();
});
}
server.stop();
ASIO2_CHECK(server.is_stopped());
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->stop();
ASIO2_CHECK(p->is_stopped());
}
}
// test tcps stop then start in io_context thread and non io_context thread
{
asio2::tcps_server server;
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcps_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
int& num = session_ptr->get_user_data<int&>();
num++;
ASIO2_CHECK(std::stoi(std::string(data.substr(0, data.find(',')))) == num);
session_ptr->async_send(data);
});
server.bind_connect([&](auto & session_ptr)
{
session_ptr->set_user_data(0);
});
bool server_start_ret = server.start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
std::vector<std::shared_ptr<asio2::tcps_client>> clients;
std::atomic<int> client_connect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcps_client>());
asio2::tcps_client& client = *iter;
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_connect([&]()
{
client.set_user_data(0);
if (!asio2::get_last_error())
{
client_connect_counter++;
client.async_send("1,a");
}
});
client.bind_disconnect([&]()
{
client_connect_counter--;
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
int& num = client.get_user_data<int&>();
num++;
ASIO2_CHECK(std::stoi(std::string(data.substr(0, data.find(',')))) == num);
if (num == 11)
return;
std::string str;
str += std::to_string(num + 1);
str += ",";
for (int i = 0; i < num + 1; i++)
str += "a";
client.async_send(std::move(str));
});
bool client_start_ret = client.async_start("127.0.0.1", 18042, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
// wait all client's bind connect has called.
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_connect_counter, client_connect_counter == std::size_t(test_client_count));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->start_timer("id1", std::chrono::nanoseconds(1), 1, [p]()
{
p->stop();
p->start("127.0.0.1", 18042, asio2::use_dgram);
});
}
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::tcps_client> p = clients[i];
p->stop();
ASIO2_CHECK(p->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"start_stop",
ASIO2_TEST_CASE(start_stop_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_AOP_PUBREL_HPP__
#define __ASIO2_MQTT_AOP_PUBREL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class caller_t, class args_t>
class mqtt_aop_pubrel
{
friend caller_t;
protected:
// server or client
template<class Message, class Response>
inline void _before_pubrel_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
rep.packet_id(msg.packet_id());
// PUBCOMP Reason Code
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901154
if constexpr (std::is_same_v<response_type, mqtt::v5::pubcomp>)
{
rep.reason_code(detail::to_underlying(mqtt::error::success));
}
else
{
std::ignore = true;
}
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::pubrel& msg, asio2::mqtt::v3::pubcomp& rep)
{
if (_before_pubrel_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::pubrel& msg, asio2::mqtt::v4::pubcomp& rep)
{
if (_before_pubrel_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::pubrel& msg, asio2::mqtt::v5::pubcomp& rep)
{
if (_before_pubrel_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::pubrel& msg, asio2::mqtt::v3::pubcomp& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::pubrel& msg, asio2::mqtt::v4::pubcomp& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::pubrel& msg, asio2::mqtt::v5::pubcomp& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
};
}
#endif // !__ASIO2_MQTT_AOP_PUBREL_HPP__
<file_sep>#include "unit_test.hpp"
#include <asio2/util/event_dispatcher.hpp>
#include <iostream>
void event_dispatcher_test_basic()
{
std::cout << std::endl << "event_dispatcher tutorial 1, basic" << std::endl;
// The namespace is asio2
// The first template parameter int is the event type,
// the event type can be any type such as std::string, int, etc.
// The second is the prototype of the listener.
asio2::event_dispatcher<int, void ()> dispatcher;
std::vector<asio2::event_dispatcher<int, void()>::listener_type> listeners;
ASIO2_CHECK(dispatcher.get_listener_count() == 0);
// Add a listener. As the type of dispatcher,
// here 3 and 5 is the event type,
// []() {} is the listener.
// Lambda is not required, any function or std::function
// or whatever function object with the required prototype is fine.
int f31 = -1;
auto listener = dispatcher.append_listener(3, [&]()
{
f31 = 1;
});
ASIO2_CHECK(dispatcher.get_listener_count() == 1);
listeners.emplace_back(listener);
ASIO2_CHECK(dispatcher.has_any_listener(3));
dispatcher.remove_listener(listeners.front());
ASIO2_CHECK(dispatcher.get_listener_count() == 0);
ASIO2_CHECK(!dispatcher.has_any_listener(3));
// listener has been removed, so the listener will be append at the tail
listener = dispatcher.insert_listener(3, []() {}, listener);
ASIO2_CHECK(listener);
ASIO2_CHECK(dispatcher.get_listener_count(3) == 1);
listener = dispatcher.find_listener_if(3, [](auto& listener_ptr) { return (listener_ptr->get_event_type() == 30); });
ASIO2_CHECK(!listener);
// the listener is empty, so remove listener will be failed.
ASIO2_CHECK(!dispatcher.remove_listener(listener));
listener = dispatcher.find_listener_if(3, [](auto& listener_ptr) { return (listener_ptr->get_event_type() == 3); });
ASIO2_CHECK(listener);
dispatcher.remove_listener(listener);
ASIO2_CHECK(!listener);
ASIO2_CHECK(dispatcher.get_listener_count(3) == 0);
listener = dispatcher.find_listener_if(3, [](auto& listener_ptr) { return (listener_ptr->get_event_type() == 3); });
ASIO2_CHECK(!listener);
int f32 = -1;
listener = dispatcher.append_listener(3, [&]()
{
f32 = 1;
});
ASIO2_CHECK(dispatcher.has_any_listener(3));
ASIO2_CHECK(dispatcher.get_listener_count() == 1);
ASIO2_CHECK(dispatcher.get_listener_count(3) == 1);
// the event_type 30 is not equal to the "listener->evt", so this insert will failed.
#if !defined(DEBUG) && !defined(_DEBUG)
listener = dispatcher.insert_listener(30, []() {}, listener);
ASIO2_CHECK(!listener);
#endif
int f51 = -1;
dispatcher.append_listener(5, [&]()
{
f51 = 1;
});
ASIO2_CHECK(dispatcher.get_listener_count() == 2);
ASIO2_CHECK(dispatcher.get_listener_count(5) == 1);
int f52 = -1;
dispatcher.append_listener(5, [&]()
{
f52 = 1;
});
ASIO2_CHECK(dispatcher.get_listener_count() == 3);
ASIO2_CHECK(dispatcher.get_listener_count(5) == 2);
auto liss1 = dispatcher.append_listener({ 6,7 }, [&]()
{
});
ASIO2_CHECK(dispatcher.get_listener_count(6) == 1);
ASIO2_CHECK(dispatcher.get_listener_count(7) == 1);
listeners.insert(listeners.end(), liss1.begin(), liss1.end());
ASIO2_CHECK(dispatcher.get_listener_count() == 5);
auto liss2 = dispatcher.prepend_listener({ 8,9 }, [&]()
{
});
ASIO2_CHECK(dispatcher.get_listener_count(8) == 1);
ASIO2_CHECK(dispatcher.get_listener_count(9) == 1);
listeners.insert(listeners.end(), liss2.begin(), liss2.end());
ASIO2_CHECK(dispatcher.get_listener_count() == 7);
dispatcher.insert_listener(3, []() {}, listener);
ASIO2_CHECK(dispatcher.get_listener_count(3) == 2);
ASIO2_CHECK(dispatcher.get_listener_count() == 8);
auto* listener_list = dispatcher.find_listeners(5);
ASIO2_CHECK(listener_list != nullptr);
ASIO2_CHECK(listener_list->size() == 2);
for (auto it = listener_list->begin(); it != listener_list->end(); ++it)
{
ASIO2_CHECK(it->get_event_type() == 5);
}
for (auto it = listener_list->cbegin(); it != listener_list->cend(); ++it)
{
ASIO2_CHECK(it->get_event_type() == 5);
}
ASIO2_CHECK(dispatcher.get_listener_count() == 8);
// Dispatch the events, the first argument is always the event type.
dispatcher.dispatch(3);
dispatcher.dispatch(5);
ASIO2_CHECK(f31 == -1);
ASIO2_CHECK(f32 == 1);
ASIO2_CHECK(f51 == 1);
ASIO2_CHECK(f52 == 1);
dispatcher.clear_listeners();
ASIO2_CHECK(dispatcher.get_listener_count() == 0);
}
void event_dispatcher_test_listener_with_parameters()
{
std::cout << std::endl << "event_dispatcher tutorial 2, listener with parameters" << std::endl;
// The listener has two parameters.
asio2::event_dispatcher<int, void (const std::string &, const bool)> dispatcher;
int f31 = -1;
dispatcher.append_listener(3, [&](const std::string & s, const bool b)
{
f31 = 1;
ASIO2_CHECK(s == "Hello" && b == true);
});
// The listener prototype doesn't need to be exactly same as the dispatcher.
// It would be find as long as the arguments is compatible with the dispatcher.
int f51 = -1;
dispatcher.append_listener(5, [&](std::string s, int b)
{
f51 = 1;
ASIO2_CHECK(s == "World" && b == false);
});
int f52 = -1;
dispatcher.append_listener(5, [&](const std::string & s, const bool b)
{
f52 = 1;
ASIO2_CHECK(s == "World" && b == false);
});
// Dispatch the events, the first argument is always the event type.
dispatcher.dispatch(3, "Hello", true);
dispatcher.dispatch(5, "World", false);
ASIO2_CHECK(f31 == 1);
ASIO2_CHECK(f51 == 1);
ASIO2_CHECK(f52 == 1);
}
void event_dispatcher_test_customized_event_struct()
{
std::cout << std::endl << "event_dispatcher tutorial 3, customized event struct" << std::endl;
// Define an Event to hold all parameters.
struct my_event
{
int type;
std::string message;
int param;
};
// Define policies to let the dispatcher knows how to
// extract the event type.
struct my_event_policy
{
static int get_event(const my_event & e, bool /*b*/)
{
return e.type;
}
};
// Pass my_event_policy as the third template argument of event_dispatcher.
// Note: the first template argument is the event type type int, not my_event.
asio2::event_dispatcher<int, void(const my_event&, bool), my_event_policy> dispatcher;
// Add a listener.
// Note: the first argument is the event type of type int, not my_event.
int f = -1;
dispatcher.append_listener(3, [&](const my_event & e, bool b)
{
f = 1;
ASIO2_CHECK(e.type == 3);
ASIO2_CHECK(e.message == "Hello world");
ASIO2_CHECK(e.param == 38);
ASIO2_CHECK(b == true);
});
// Dispatch the event.
// The first argument is Event.
dispatcher.dispatch(my_event { 3, "Hello world", 38 }, true);
ASIO2_CHECK(f == 1);
}
struct Tutor4MyEvent
{
Tutor4MyEvent() : type(0), canceled(false)
{
}
explicit Tutor4MyEvent(const int type)
: type(type), canceled(false)
{
}
int type;
mutable bool canceled;
};
struct Tutor4MyEventPolicy
{
// E is Tutor4MyEvent and get_event doesn't need to be template.
// We make it template to show get_event can be templated member.
template <typename E>
static int get_event(const E & e)
{
return e.type;
}
// E is Tutor4MyEvent and can_continue_invoking doesn't need to be template.
// We make it template to show can_continue_invoking can be templated member.
template <typename E>
static bool can_continue_invoking(const E & e)
{
return ! e.canceled;
}
using thread_t = asio2::dispatcheres::single_thread;
using user_data_t = std::size_t;
};
void event_dispatcher_test_event_canceling()
{
std::cout << std::endl << "event_dispatcher tutorial 4, event canceling" << std::endl;
asio2::event_dispatcher<int, void (const Tutor4MyEvent &), Tutor4MyEventPolicy> dispatcher;
int f31 = -1;
dispatcher.append_listener(3, [&](const Tutor4MyEvent & e)
{
f31 = 1;
ASIO2_CHECK(e.type == 3);
e.canceled = true;
});
int f32 = -1;
auto listener = dispatcher.append_listener(3, [&](const Tutor4MyEvent & /*e*/)
{
f32 = 1;
});
listener.lock()->set_user_data(200);
ASIO2_CHECK(listener.lock()->get_user_data() == 200);
int f33 = -1;
dispatcher.insert_listener(3,
[&](const Tutor4MyEvent & /*e*/)
{
f33 = 1;
},
[](auto& listener_ptr)
{
return listener_ptr->get_user_data() == 0;
});
ASIO2_CHECK(dispatcher.get_listener_count(3) == 3);
ASIO2_CHECK(dispatcher.get_listener_count() == 3);
dispatcher.dispatch(Tutor4MyEvent(3));
ASIO2_CHECK(f31 == 1);
ASIO2_CHECK(f32 == -1);
ASIO2_CHECK(f33 == 1);
}
void event_dispatcher_test_event_filter()
{
std::cout << std::endl << "event_dispatcher tutorial 5, event filter" << std::endl;
struct MyPolicy
{
using mixins_t = asio2::dispatcheres::mixin_list<asio2::dispatcheres::mixin_filter>;
};
asio2::event_dispatcher<int, void (int e, int i, std::string), MyPolicy> dispatcher;
std::vector<int> v;
int f3 = -1;
dispatcher.append_listener(3, [&](const int e, const int i, const std::string & s)
{
f3 = 1;
v.emplace_back(304);
ASIO2_CHECK(e == 3 && i == 38 && s == "Hi");
});
int f5 = -1;
dispatcher.append_listener(5, [&](const int /*e*/, const int /*i*/, const std::string & /*s*/)
{
f5 = 1;
v.emplace_back(-2);
});
ASIO2_CHECK(dispatcher.get_listener_count() == 2);
ASIO2_CHECK(dispatcher.get_filter_count() == 0);
// Add three event filters.
// The first filter modifies the input arguments to other values, then the subsequence filters
// and listeners will see the modified values.
dispatcher.append_filter([&](const int e, int & i, std::string & s) -> bool
{
ASIO2_CHECK(e == 3 || e == 5);
if (e == 3)
{
v.emplace_back(301);
ASIO2_CHECK(e == 3 && i == 1 && s == "Hello");
}
else
{
v.emplace_back(501);
ASIO2_CHECK(e == 5 && i == 2 && s == "World");
}
i = 38;
s = "Hi";
ASIO2_CHECK(i == 38 && s == "Hi");
return true;
});
ASIO2_CHECK(dispatcher.get_filter_count() == 1);
std::vector<asio2::event_dispatcher<int, void(int e, int i, std::string), MyPolicy>::filter_type> filters;
// The second filter filters out all event of 5. So no listeners on event 5 can be triggered.
// The third filter is not invoked on event 5 also.
auto filter = dispatcher.append_filter([&](const int , int & e, std::string & ) -> bool
{
// can't run to here
v.emplace_back(-1);
if(e == 5)
{
return false;
}
return true;
});
ASIO2_CHECK(dispatcher.get_filter_count() == 2);
filters.emplace_back(filter);
dispatcher.remove_filter(filter);
ASIO2_CHECK(dispatcher.get_filter_count() == 1);
dispatcher.remove_filter(filter);
ASIO2_CHECK(dispatcher.get_filter_count() == 1);
dispatcher.append_filter([&](const int e, int & i, std::string & s) -> bool
{
ASIO2_CHECK(e == 3 || e == 5);
if (e == 3)
{
v.emplace_back(302);
ASIO2_CHECK(e == 3 && i == 38 && s == "Hi");
}
else
{
v.emplace_back(502);
ASIO2_CHECK(e == 5 && i == 38 && s == "Hi");
}
if(e == 5)
{
return false;
}
return true;
});
// The third filter just prints the input arguments.
dispatcher.append_filter([&](const int e, int & i, std::string & s) -> bool
{
ASIO2_CHECK(e == 3);
v.emplace_back(303);
ASIO2_CHECK(e == 3 && i == 38 && s == "Hi");
return true;
});
ASIO2_CHECK(dispatcher.get_filter_count() == 3);
// Dispatch the events, the first argument is always the event type.
dispatcher.dispatch(3, 1, "Hello");
dispatcher.dispatch(5, 2, "World");
ASIO2_CHECK(f3 == 1);
ASIO2_CHECK(f5 == -1);
ASIO2_CHECK(v.size() == 6);
ASIO2_CHECK(v[0] == 301);
ASIO2_CHECK(v[1] == 302);
ASIO2_CHECK(v[2] == 303);
ASIO2_CHECK(v[3] == 304);
ASIO2_CHECK(v[4] == 501);
ASIO2_CHECK(v[5] == 502);
dispatcher.clear_filters();
ASIO2_CHECK(dispatcher.get_filter_count() == 0);
}
void event_dispatcher_test_name()
{
std::cout << std::endl << "event_dispatcher tutorial 6, listener name" << std::endl;
asio2::event_dispatcher<int, void ()> dispatcher;
std::vector<asio2::event_dispatcher<int, void()>::listener_type> listeners;
ASIO2_CHECK(dispatcher.get_listener_count() == 0);
int f31 = -1;
auto listener = dispatcher.append_listener("e31", 3, [&]()
{
f31 = 1;
});
ASIO2_CHECK(dispatcher.get_listener_count("e31") == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e31", 3) == 1);
ASIO2_CHECK(dispatcher.get_listener_count() == 1);
listeners.emplace_back(listener);
ASIO2_CHECK(dispatcher.has_any_listener(3));
dispatcher.remove_listener(listeners.front());
ASIO2_CHECK(dispatcher.get_listener_count("e31") == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e31", 3) == 0);
ASIO2_CHECK(dispatcher.get_listener_count() == 0);
ASIO2_CHECK(!dispatcher.has_any_listener(3));
// listener has been removed, so the listener will be append at the tail
listener = dispatcher.insert_listener("e32", 3, []() {}, listener);
ASIO2_CHECK(listener);
ASIO2_CHECK(dispatcher.get_listener_count(3) == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e31") == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e31", 3) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e32") == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e32", 3) == 1);
dispatcher.remove_listener(listener);
ASIO2_CHECK(!listener);
ASIO2_CHECK(dispatcher.get_listener_count(3) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e31") == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e31", 3) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e32") == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e32", 3) == 0);
int f32 = -1;
listener = dispatcher.append_listener("e32", 3, [&]()
{
f32 = 1;
});
ASIO2_CHECK(dispatcher.has_any_listener(3));
ASIO2_CHECK(dispatcher.get_listener_count() == 1);
ASIO2_CHECK(dispatcher.get_listener_count(3) == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e32") == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e32", 3) == 1);
dispatcher.append_listener("e32", 5, [&]()
{
});
ASIO2_CHECK(dispatcher.get_listener_count("e32") == 2);
ASIO2_CHECK(dispatcher.get_listener_count("e32", 3) == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e32", 5) == 1);
dispatcher.remove_listener("e32", 5);
ASIO2_CHECK(dispatcher.get_listener_count("e32") == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e32", 3) == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e32", 5) == 0);
int f51 = -1;
dispatcher.append_listener("e51", 5, [&]()
{
f51 = 1;
});
ASIO2_CHECK(dispatcher.get_listener_count() == 2);
ASIO2_CHECK(dispatcher.get_listener_count(5) == 1);
int f52 = -1;
dispatcher.append_listener("e52", 5, [&]()
{
f52 = 1;
});
ASIO2_CHECK(dispatcher.get_listener_count() == 3);
ASIO2_CHECK(dispatcher.get_listener_count(5) == 2);
auto liss1 = dispatcher.append_listener("e67", { 6,7 }, [&]()
{
});
ASIO2_CHECK(dispatcher.get_listener_count(6) == 1);
ASIO2_CHECK(dispatcher.get_listener_count(7) == 1);
listeners.insert(listeners.end(), liss1.begin(), liss1.end());
ASIO2_CHECK(dispatcher.get_listener_count() == 5);
auto liss2 = dispatcher.prepend_listener("e89", { 8,9 }, [&]()
{
});
ASIO2_CHECK(dispatcher.get_listener_count(8) == 1);
ASIO2_CHECK(dispatcher.get_listener_count(9) == 1);
listeners.insert(listeners.end(), liss2.begin(), liss2.end());
ASIO2_CHECK(dispatcher.get_listener_count() == 7);
dispatcher.insert_listener(3, []() {}, listener);
ASIO2_CHECK(dispatcher.get_listener_count(3) == 2);
ASIO2_CHECK(dispatcher.get_listener_count() == 8);
auto* listener_list = dispatcher.find_listeners(5);
ASIO2_CHECK(listener_list != nullptr);
ASIO2_CHECK(listener_list->size() == 2);
for (auto it = listener_list->begin(); it != listener_list->end(); ++it)
{
ASIO2_CHECK(it->get_event_type() == 5);
}
for (auto it = listener_list->cbegin(); it != listener_list->cend(); ++it)
{
ASIO2_CHECK(it->get_event_type() == 5);
}
ASIO2_CHECK(dispatcher.get_listener_count("e51") == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e51", 3) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e51", 5) == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e52") == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e52", 3) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e52", 5) == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e67") == 2);
ASIO2_CHECK(dispatcher.get_listener_count("e67", 3) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e67", 5) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e67", 6) == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e67", 7) == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e89") == 2);
ASIO2_CHECK(dispatcher.get_listener_count("e89", 3) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e89", 5) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e89", 6) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e89", 7) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e89", 8) == 1);
ASIO2_CHECK(dispatcher.get_listener_count("e89", 9) == 1);
ASIO2_CHECK(dispatcher.get_listener_count() == 8);
ASIO2_CHECK(dispatcher.remove_listener("e89"));
ASIO2_CHECK(dispatcher.get_listener_count("e89") == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e89", 3) == 0);
ASIO2_CHECK(dispatcher.get_listener_count("e89", 5) == 0);
// Dispatch the events, the first argument is always the event type.
dispatcher.dispatch(3);
dispatcher.dispatch(5);
ASIO2_CHECK(f31 == -1);
ASIO2_CHECK(f32 == 1);
ASIO2_CHECK(f51 == 1);
ASIO2_CHECK(f52 == 1);
dispatcher.clear_listeners();
ASIO2_CHECK(dispatcher.get_listener_count() == 0);
}
class ipacket
{
public:
ipacket()
{
}
virtual ~ipacket()
{
}
virtual const char * get_packet_type() = 0;
};
class mem_packet : public ipacket
{
public:
mem_packet(std::string m) : message(std::move(m))
{
}
virtual ~mem_packet()
{
}
virtual const char * get_packet_type() { return "mp"; }
std::string message;
};
void event_dispatcher_test_move()
{
std::cout << std::endl << "event_dispatcher tutorial 6, move" << std::endl;
struct my_policy
{
static std::string_view get_event(const std::shared_ptr<ipacket> & e)
{
return e->get_packet_type();
}
};
asio2::event_dispatcher<std::string_view, void(const std::shared_ptr<ipacket>&), my_policy> dispatcher;
int f = -1;
dispatcher.append_listener("mp", [&](const std::shared_ptr<ipacket>& e)
{
f = 1;
ASIO2_CHECK(std::string_view{ "mp" } == e->get_packet_type());
mem_packet* p = dynamic_cast<mem_packet*>(e.get());
ASIO2_CHECK(p->message == "Hello world");
});
std::shared_ptr<mem_packet> e = std::make_shared<mem_packet>("Hello world");
dispatcher.dispatch(std::move(e));
ASIO2_CHECK(f == 1);
}
#include <asio2/util/uuid.hpp>
void event_dispatcher_test_bench()
{
struct policy
{
//using thread_t = asio2::dispatcheres::single_thread;
};
asio2::event_dispatcher<std::string_view, void(std::string_view), policy> dispatcher;
std::vector<std::string> vs;
std::size_t sum = 0;
int count = 100;
int loop = 10000000;
#if defined(DEBUG) || defined(_DEBUG)
loop /= 100;
#endif
vs.reserve(count);
asio2::uuid u1;
for (int i = 0; i < count; i++)
{
std::string s = u1.short_uuid(8);
vs.emplace_back(s);
}
for (auto& s : vs)
{
dispatcher.append_listener(s, [&sum](std::string_view sr) { sum += std::size_t(sr.data()); });
}
{
sum = 0;
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < loop; i++)
{
std::string& s = vs[i % vs.size()];
dispatcher.dispatch(s, s);
}
auto t2 = std::chrono::high_resolution_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
std::cout << sum << " dispatcher : " << ms << std::endl;
}
{
sum = 0;
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < loop; i++)
{
std::string& s = vs[i % vs.size()];
for (auto& sr : vs)
{
if (std::strcmp(s.data(), sr.data()) == 0)
{
sum += std::size_t(sr.data());
break;
}
}
}
auto t2 = std::chrono::high_resolution_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
std::cout << sum << " strcmp : " << ms << std::endl;
}
}
ASIO2_TEST_SUITE
(
"event_dispatcher",
ASIO2_TEST_CASE(event_dispatcher_test_basic)
ASIO2_TEST_CASE(event_dispatcher_test_listener_with_parameters)
ASIO2_TEST_CASE(event_dispatcher_test_customized_event_struct)
ASIO2_TEST_CASE(event_dispatcher_test_event_canceling)
ASIO2_TEST_CASE(event_dispatcher_test_event_filter)
ASIO2_TEST_CASE(event_dispatcher_test_name)
ASIO2_TEST_CASE(event_dispatcher_test_move)
ASIO2_TEST_CASE(event_dispatcher_test_bench)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* chinese :
* english : http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_PROTOCOL_V3_HPP__
#define __ASIO2_MQTT_PROTOCOL_V3_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/mqtt/core.hpp>
namespace asio2::mqtt::v3
{
static constexpr std::uint8_t version_number = asio2::detail::to_underlying(mqtt::version::v3);
enum class connect_reason_code : std::uint8_t
{
/* 0 0x00 Connection Accepted : */ success = 0,
/* 1 0x01 Connection Refused : */ unacceptable_protocol_version = 1,
/* 2 0x02 Connection Refused : */ identifier_rejected = 2,
/* 3 0x03 Connection Refused : */ server_unavailable = 3,
/* 4 0x04 Connection Refused : */ bad_user_name_or_password = 4,
/* 5 0x05 Connection Refused : */ not_authorized = 5,
/* 6 - 255 Reserved for future use */
};
/**
* CONNECT - Client requests a connection to a server
*
* When a TCP/IP socket connection is established from a client to a server, a protocol level
* session must be created using a CONNECT flow.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#connect
*/
class connect : public fixed_header<version_number>
{
public:
connect() : fixed_header(control_packet_type::connect)
{
update_remain_length();
}
connect(utf8_string::value_type clientid) : fixed_header(control_packet_type::connect)
{
client_id(std::move(clientid));
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline connect& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
protocol_name_ .serialize(buffer);
protocol_version_ .serialize(buffer);
connect_flags_.byte .serialize(buffer);
keep_alive_ .serialize(buffer);
client_id_ .serialize(buffer);
if (will_topic_ ) will_topic_ ->serialize(buffer);
if (will_payload_) will_payload_->serialize(buffer);
if (username_ ) username_ ->serialize(buffer);
if (password_ ) password_ ->serialize(buffer);
return (*this);
}
inline connect& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
protocol_name_ .deserialize(data);
protocol_version_ .deserialize(data);
connect_flags_.byte .deserialize(data);
keep_alive_ .deserialize(data);
client_id_ .deserialize(data);
if (has_will())
{
utf8_string will_topic{};
will_topic.deserialize(data);
will_topic_ = std::move(will_topic);
binary_data will_payload{};
will_payload.deserialize(data);
will_payload_ = std::move(will_payload);
}
if (has_username())
{
utf8_string username{};
username.deserialize(data);
username_ = std::move(username);
}
if (has_password())
{
binary_data password{};
password.deserialize(data);
password_ = std::move(password);
}
update_remain_length();
return (*this);
}
inline std::uint8_t protocol_version() { return (protocol_version_ ); }
inline bool clean_start () { return (connect_flags_.bits.clean_session); }
inline bool clean_session () { return (connect_flags_.bits.clean_session); }
inline bool has_will () { return (connect_flags_.bits.will_flag ); }
inline qos_type will_qos () { return static_cast<qos_type>(connect_flags_.bits.will_qos ); }
inline bool will_retain () { return (connect_flags_.bits.will_retain ); }
inline bool has_password () { return (connect_flags_.bits.password_flag); }
inline bool has_username () { return (connect_flags_.bits.username_flag); }
inline connect& clean_start (bool v) { connect_flags_.bits.clean_session = v; return (*this); }
inline connect& clean_session (bool v) { connect_flags_.bits.clean_session = v; return (*this); }
inline two_byte_integer::value_type keep_alive () { return keep_alive_ ; }
inline utf8_string::view_type client_id () { return client_id_ .data_view(); }
inline utf8_string::view_type will_topic () { return will_topic_ ? will_topic_ ->data_view() : ""; }
inline binary_data::view_type will_payload () { return will_payload_ ? will_payload_->data_view() : ""; }
inline utf8_string::view_type username () { return username_ ? username_ ->data_view() : ""; }
inline binary_data::view_type password () { return password_ ? password_ ->data_view() : ""; }
inline connect& keep_alive(two_byte_integer::value_type v)
{
keep_alive_ = std::move(v);
return (*this);
}
inline connect& client_id(utf8_string::value_type v)
{
client_id_ = std::move(v);
update_remain_length();
return (*this);
}
inline connect& username(utf8_string::value_type v)
{
username_ = std::move(v);
connect_flags_.bits.username_flag = true;
update_remain_length();
return (*this);
}
inline connect& password(binary_data::value_type v)
{
password_ = <PASSWORD>(v);
connect_flags_.bits.password_flag = true;
update_remain_length();
return (*this);
}
template<class String1, class String2, class QosOrInt>
inline connect& will_attributes(String1&& topic, String2&& payload,
QosOrInt qos = qos_type::at_most_once, bool retain = false)
{
will_topic_ = std::forward<String1>(topic);
will_payload_ = std::forward<String2>(payload);
connect_flags_.bits.will_flag = true;
connect_flags_.bits.will_qos = static_cast<std::uint8_t>(qos);
connect_flags_.bits.will_retain = retain;
update_remain_length();
return (*this);
}
inline bool has_will () const noexcept { return will_topic_.has_value(); }
inline bool has_username () const noexcept { return username_ .has_value(); }
inline bool has_password () const noexcept { return password_ .has_value(); }
inline connect& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ protocol_name_ .required_size()
+ protocol_version_ .required_size()
+ connect_flags_.byte .required_size()
+ keep_alive_ .required_size()
+ client_id_ .required_size()
+ (will_topic_ ? will_topic_ ->required_size() : 0)
+ (will_payload_ ? will_payload_->required_size() : 0)
+ (username_ ? username_ ->required_size() : 0)
+ (password_ ? password_ ->required_size() : 0)
);
return (*this);
}
protected:
// The protocol name is present in the variable header of a MQTT CONNECT message.
// This field is a UTF-encoded string that represents the protocol name MQIsdp, capitalized as shown.
utf8_string protocol_name_{ "MQIsdp" };
// The protocol version is present in the variable header of a CONNECT message.
// The value of the Protocol version field for the current version of the protocol, 3 (0x03)
one_byte_integer protocol_version_{ 0x03 };
union
{
one_byte_integer byte{ 0 }; // all connect flags
#if ASIO2_ENDIAN_BIG_BYTE
struct
{
bool username_flag : 1; // User Name Flag
bool password_flag : 1; // <PASSWORD> Flag
bool will_retain : 1; // will retain setting
std::uint8_t will_qos : 2; // will QoS value
bool will_flag : 1; // will flag
bool clean_session : 1; // Clean Session flag
std::uint8_t reserved : 1; // unused
} bits;
#else
struct
{
std::uint8_t reserved : 1; // unused
bool clean_session : 1; // Clean Session flag
bool will_flag : 1; // will flag
std::uint8_t will_qos : 2; // will QoS value
bool will_retain : 1; // will retain setting
bool password_flag : 1; // Password Flag
bool username_flag : 1; // User Name Flag
} bits;
#endif
} connect_flags_{}; // connect flags byte
// The Keep Alive is a time interval measured in seconds. Expressed as a 16-bit word
// Default to 60 seconds
two_byte_integer keep_alive_ { 60 };
// The Client Identifier (ClientID) identifies the Client to the Server.
// Each Client connecting to the Server has a unique ClientID.
utf8_string client_id_ {};
// If the Will Flag is set to 1, the Will Topic is the next field in the Payload.
std::optional<utf8_string> will_topic_ {};
// If the Will Flag is set to 1 the Will Payload is the next field in the Payload.
std::optional<binary_data> will_payload_{};
// If the User Name Flag is set to 1, the User Name is the next field in the Payload.
std::optional<utf8_string> username_ {};
// If the Password Flag is set to 1, the Password is the next field in the Payload.
std::optional<binary_data> password_ {};
};
/**
* CONNACK - Acknowledge connection request
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#connack
*/
class connack : public fixed_header<version_number>
{
public:
connack() : fixed_header(control_packet_type::connack)
{
update_remain_length();
}
explicit connack(std::uint8_t reason_code)
: fixed_header(control_packet_type::connack)
, reason_code_(reason_code)
{
update_remain_length();
}
explicit connack(connect_reason_code reason_code)
: fixed_header(control_packet_type::connack)
, reason_code_(asio2::detail::to_underlying(reason_code))
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline connack& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
connack_flags_.byte.serialize(buffer);
reason_code_ .serialize(buffer);
return (*this);
}
inline connack& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
connack_flags_.byte.deserialize(data);
reason_code_ .deserialize(data);
update_remain_length();
return (*this);
}
inline bool session_present() { return connack_flags_.bits.session_present; }
inline connect_reason_code reason_code () { return static_cast<connect_reason_code>(reason_code_.value()); }
inline connack & session_present(bool v) { connack_flags_.bits.session_present = v; return (*this); }
inline connack & reason_code (std::uint8_t v) { reason_code_ = v; return (*this); }
inline connack & reason_code(connect_reason_code v)
{ reason_code_ = asio2::detail::to_underlying(v); return (*this); }
inline connack& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ connack_flags_.byte.required_size()
+ reason_code_ .required_size()
);
return (*this);
}
protected:
// Topic Name Compression Response
// byte 1 Reserved values. Not used.
//one_byte_integer reserved_ { 0 };
// Here we use the connection flags to replace the "reserved_"
union
{
one_byte_integer byte{ 0 }; // all connack flags
#if ASIO2_ENDIAN_BIG_BYTE
struct
{
std::uint8_t reserved : 7;
bool session_present : 1; // session found on the server?
} bits;
#else
struct
{
bool session_present : 1; // session found on the server?
std::uint8_t reserved : 7;
} bits;
#endif
} connack_flags_{}; // connack flags
// Connect Return Code
// byte 2 Return Code
one_byte_integer reason_code_{ 0 };
};
/**
* PUBLISH - Publish message
*
* A PUBLISH message is sent by a client to a server for distribution to interested subscribers.
* Each PUBLISH message is associated with a topic name (also known as the Subject or Channel).
* This is a hierarchical name space that defines a taxonomy of information sources for which
* subscribers can register an interest. A message that is published to a specific topic name
* is delivered to connected subscribers for that topic.
* If a client subscribes to one or more topics, any message published to those topics are sent
* by the server to the client as a PUBLISH message.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#publish
*/
class publish : public fixed_header<version_number>
{
public:
publish() : fixed_header(control_packet_type::publish)
{
update_remain_length();
}
template<class String1, class String2, class QosOrInt, std::enable_if_t<
asio2::detail::is_character_string_v<String1>, int> = 0>
explicit publish(String1&& topic_name, String2&& payload, QosOrInt qos,
bool dup = false, bool retain = false)
: fixed_header(control_packet_type::publish)
, topic_name_ (std::forward<String1>(topic_name))
, payload_ (std::forward<String2>(payload ))
{
type_and_flags_.bits.dup = dup;
type_and_flags_.bits.qos = static_cast<std::uint8_t>(qos);
type_and_flags_.bits.retain = retain;
update_remain_length();
}
template<class String1, class String2, class QosOrInt, std::enable_if_t<
asio2::detail::is_character_string_v<String1>, int> = 0>
explicit publish(std::uint16_t pid, String1&& topic_name, String2&& payload, QosOrInt qos,
bool dup = false, bool retain = false)
: fixed_header(control_packet_type::publish)
, topic_name_ (std::forward<String1>(topic_name))
, packet_id_ (pid)
, payload_ (std::forward<String2>(payload ))
{
type_and_flags_.bits.dup = dup;
type_and_flags_.bits.qos = static_cast<std::uint8_t>(qos);
type_and_flags_.bits.retain = retain;
ASIO2_ASSERT(type_and_flags_.bits.qos > std::uint8_t(0));
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline publish& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
// The Packet Identifier field is only present in PUBLISH packets where the QoS level is 1 or 2.
// A PUBLISH packet MUST NOT contain a Packet Identifier if its QoS value is set to 0
if ((type_and_flags_.bits.qos == std::uint8_t(0) && packet_id_.has_value()) ||
(type_and_flags_.bits.qos > std::uint8_t(0) && !packet_id_.has_value()))
{
ASIO2_ASSERT(false);
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
}
topic_name_.serialize(buffer);
if (type_and_flags_.bits.qos > std::uint8_t(0) && packet_id_.has_value())
{
packet_id_->serialize(buffer);
}
payload_.serialize(buffer);
return (*this);
}
inline publish& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
topic_name_.deserialize(data);
if (type_and_flags_.bits.qos == 1 || type_and_flags_.bits.qos == 2)
{
two_byte_integer packet_id{};
packet_id.deserialize(data);
packet_id_ = packet_id;
}
payload_ .deserialize(data);
update_remain_length();
return (*this);
}
inline bool dup () { return (type_and_flags_.bits.dup ); }
inline qos_type qos () { return static_cast<qos_type>(type_and_flags_.bits.qos ); }
inline bool retain() { return (type_and_flags_.bits.retain); }
inline publish & dup (bool v) { type_and_flags_.bits.dup = v; return (*this); }
template<class QosOrInt>
inline publish & qos (QosOrInt v) { type_and_flags_.bits.qos = static_cast<std::uint8_t>(v); return (*this); }
inline publish & retain(bool v) { type_and_flags_.bits.retain = v; return (*this); }
inline utf8_string::view_type topic_name() { return topic_name_.data_view(); }
inline two_byte_integer::value_type packet_id () { return packet_id_ ? packet_id_->value() : 0; }
inline application_message::view_type payload () { return payload_ .data_view(); }
inline publish & packet_id (std::uint16_t v) { packet_id_ = v ; return (*this); }
template<class String>
inline publish & topic_name(String&& v) { topic_name_ = std::forward<String>(v); update_remain_length(); return (*this); }
template<class String>
inline publish & payload (String&& v) { payload_ = std::forward<String>(v); update_remain_length(); return (*this); }
inline bool has_packet_id() const noexcept { return packet_id_.has_value(); }
inline publish& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ topic_name_.required_size()
+ (packet_id_ ? packet_id_->required_size() : 0)
+ payload_ .required_size()
);
return (*this);
}
protected:
// The Topic Name identifies the information channel to which Payload data is published.
utf8_string topic_name_{};
// The Packet Identifier field is only present in PUBLISH packets where the QoS level is 1 or 2.
// a Two Byte Integer Packet Identifier.
std::optional<two_byte_integer> packet_id_ {};
// The Payload contains the Application Message that is being published.
// The content and format of the data is application specific.
// The length of the Payload can be calculated by subtracting the length of the Variable Header
// from the Remaining Length field that is in the Fixed Header.
// It is valid for a PUBLISH packet to contain a zero length Payload.
application_message payload_ {};
};
/**
* PUBACK - Publish acknowledgement
*
* A PUBACK message is the response to a PUBLISH message with QoS level 1.
* A PUBACK message is sent by a server in response to a PUBLISH message from a publishing client,
* and by a subscriber in response to a PUBLISH message from the server.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#puback
*/
class puback : public fixed_header<version_number>
{
public:
puback() : fixed_header(control_packet_type::puback)
{
update_remain_length();
}
explicit puback(std::uint16_t packet_id)
: fixed_header(control_packet_type::puback)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline puback& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline puback& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline puback & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline puback& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// Contains the Message Identifier (Message ID) for the PUBLISH message that is being acknowledged.
two_byte_integer packet_id_ {};
};
/**
* PUBREC - Assured publish received (part 1)
*
* A PUBREC message is the response to a PUBLISH message with QoS level 2.
* It is the second message of the QoS level 2 protocol flow.
* A PUBREC message is sent by the server in response to a PUBLISH message from a publishing client,
* or by a subscriber in response to a PUBLISH message from the server.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#pubrec
*/
class pubrec : public fixed_header<version_number>
{
public:
pubrec() : fixed_header(control_packet_type::pubrec)
{
update_remain_length();
}
explicit pubrec(std::uint16_t packet_id)
: fixed_header(control_packet_type::pubrec)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pubrec& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline pubrec& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline pubrec & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline pubrec& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the Message ID for the acknowledged PUBLISH.
two_byte_integer packet_id_ {};
};
/**
* PUBREL - Assured Publish Release (part 2)
*
* A PUBREL message is the response either from a publisher to a PUBREC message from the server,
* or from the server to a PUBREC message from a subscriber.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#pubrel
*/
class pubrel : public fixed_header<version_number>
{
public:
pubrel() : fixed_header(control_packet_type::pubrel)
{
// PUBREL messages use QoS level 1 as an acknowledgement is expected in the form of a PUBCOMP.
// Retries are handled in the same way as PUBLISH messages.
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
explicit pubrel(std::uint16_t packet_id)
: fixed_header(control_packet_type::pubrel)
, packet_id_ (packet_id)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pubrel& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline pubrel& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline pubrel & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline pubrel& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the same Message ID as the PUBREC message that is being acknowledged.
two_byte_integer packet_id_ {};
};
/**
* PUBCOMP - Assured publish complete (part 3)
*
* This message is either the response from the server to a PUBREL message from a publisher,
* or the response from a subscriber to a PUBREL message from the server.
* It is the fourth and last message in the QoS 2 protocol flow.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#pubcomp
*/
class pubcomp : public fixed_header<version_number>
{
public:
pubcomp() : fixed_header(control_packet_type::pubcomp)
{
update_remain_length();
}
explicit pubcomp(std::uint16_t packet_id)
: fixed_header(control_packet_type::pubcomp)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pubcomp& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline pubcomp& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline pubcomp & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline pubcomp& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the same Message ID as the acknowledged PUBREL message.
two_byte_integer packet_id_ {};
};
/**
* SUBSCRIBE - Subscribe to named topics
*
* The SUBSCRIBE message allows a client to register an interest in one or more topic names with the server.
* Messages published to these topics are delivered from the server to the client as PUBLISH messages.
* The SUBSCRIBE message also specifies the QoS level at which the subscriber wants to receive published messages.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#subscribe
*/
class subscribe : public fixed_header<version_number>
{
public:
subscribe() : fixed_header(control_packet_type::subscribe)
{
// SUBSCRIBE messages use QoS level 1 to acknowledge multiple subscription requests.
// The corresponding SUBACK message is identified by matching the Message ID.
// Retries are handled in the same way as PUBLISH messages.
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
explicit subscribe(std::uint16_t packet_id)
: fixed_header(control_packet_type::subscribe)
, packet_id_ (packet_id)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline subscribe& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
subscriptions_.serialize(buffer);
return (*this);
}
inline subscribe& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
subscriptions_.deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline subscriptions_set& subscriptions() { return subscriptions_ ; }
inline subscribe & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Subscriptions>
inline subscribe& add_subscriptions(Subscriptions&&... Subscripts)
{
subscriptions_.add(std::forward<Subscriptions>(Subscripts)...);
update_remain_length();
return (*this);
}
inline subscribe& erase_subscription(std::string_view topic_filter)
{
subscriptions_.erase(topic_filter);
update_remain_length();
return (*this);
}
inline subscribe& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ subscriptions_.required_size()
);
return (*this);
}
protected:
// The variable header contains a Message ID because a SUBSCRIBE message has a QoS level of 1.
two_byte_integer packet_id_ {};
// The payload of a SUBSCRIBE message contains a list of topic names to which the client wants
// to subscribe, and the QoS level at which the client wants to receive the messages. The strings
// are UTF-encoded, and the QoS level occupies 2 bits of a single byte. The topic strings may
// contain special Topic wildcard characters to represent a set of topics.
subscriptions_set subscriptions_{};
};
/**
* SUBACK - Subscription acknowledgement
*
* A SUBACK message is sent by the server to the client to confirm receipt of a SUBSCRIBE message.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#suback
*/
class suback : public fixed_header<version_number>
{
public:
suback() : fixed_header(control_packet_type::suback)
{
update_remain_length();
}
explicit suback(std::uint16_t packet_id)
: fixed_header(control_packet_type::suback)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline suback& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
reason_codes_ .serialize(buffer);
return (*this);
}
inline suback& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
reason_codes_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value(); }
inline one_byte_integer_set & reason_codes () { return reason_codes_ ; }
inline suback & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Integers>
inline suback& add_reason_codes(Integers... Ints)
{
reason_codes_.add(static_cast<one_byte_integer::value_type>(Ints)...);
update_remain_length();
return (*this);
}
inline suback& erase_reason_code(std::size_t index)
{
reason_codes_.erase(index);
update_remain_length();
return (*this);
}
inline suback& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ reason_codes_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the Message ID for the SUBSCRIBE message that is being acknowledged.
two_byte_integer packet_id_ {};
// The payload contains a vector of granted QoS levels. Each level corresponds to a topic name
// in the corresponding SUBSCRIBE message. The order of QoS levels in the SUBACK message matches
// the order of topic name and Requested QoS pairs in the SUBSCRIBE message. The Message ID in the
// variable header enables you to match SUBACK messages with the corresponding SUBSCRIBE messages.
one_byte_integer_set reason_codes_{};
};
/**
* UNSUBSCRIBE - Unsubscribe from named topics
*
* An UNSUBSCRIBE message is sent by the client to the server to unsubscribe from named topics.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#unsubscribe
*/
class unsubscribe : public fixed_header<version_number>
{
public:
unsubscribe() : fixed_header(control_packet_type::unsubscribe)
{
// UNSUBSCRIBE messages use QoS level 1 to acknowledge multiple unsubscribe requests.
// The corresponding UNSUBACK message is identified by the Message ID. Retries are
// handled in the same way as PUBLISH messages.
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
template<class... Strings>
explicit unsubscribe(std::uint16_t packet_id, Strings&&... topic_filters)
: fixed_header (control_packet_type::unsubscribe)
, packet_id_ (packet_id)
, topic_filters_(std::forward<Strings>(topic_filters)...)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline unsubscribe& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
topic_filters_.serialize(buffer);
return (*this);
}
inline unsubscribe& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
topic_filters_.deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline utf8_string_set & topic_filters() { return topic_filters_ ; }
inline unsubscribe & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Strings>
inline unsubscribe& add_topic_filters(Strings&&... Strs)
{
topic_filters_.add(std::forward<Strings>(Strs)...);
update_remain_length();
return (*this);
}
inline unsubscribe& erase_topic_filter(std::string_view topic_filter)
{
topic_filters_.erase(topic_filter);
update_remain_length();
return (*this);
}
inline unsubscribe& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ topic_filters_.required_size()
);
return (*this);
}
protected:
// The variable header contains a Message ID because an UNSUBSCRIBE message has a QoS level of 1.
two_byte_integer packet_id_ {};
// The client unsubscribes from the list of topics named in the payload.
// The strings are UTF-encoded and are packed contiguously.
// Topic names in a UNSUBSCRIBE message are not compressed.
utf8_string_set topic_filters_{};
};
/**
* UNSUBACK - Unsubscribe acknowledgment
*
* The UNSUBACK message is sent by the server to the client to confirm receipt of an UNSUBSCRIBE message.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#unsuback
*/
class unsuback : public fixed_header<version_number>
{
public:
unsuback() : fixed_header(control_packet_type::unsuback)
{
update_remain_length();
}
explicit unsuback(std::uint16_t packet_id)
: fixed_header(control_packet_type::unsuback)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline unsuback& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline unsuback& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline unsuback & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline unsuback& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the Message ID for the UNSUBSCRIBE message that is being acknowledged.
two_byte_integer packet_id_ {};
// The UNSUBACK Packet has no payload.
};
/**
* PINGREQ - PING request
*
* The PINGREQ message is an "are you alive?" message that is sent from a connected client to the server.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#pingreq
*/
class pingreq : public fixed_header<version_number>
{
public:
pingreq() : fixed_header(control_packet_type::pingreq)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pingreq& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
return (*this);
}
inline pingreq& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
update_remain_length();
return (*this);
}
inline pingreq& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
);
return (*this);
}
protected:
// The PINGREQ packet has no Variable Header.
// The PINGREQ packet has no Payload.
};
/**
* PINGRESP - PING response
*
* A PINGRESP message is the response sent by a server to a PINGREQ message and means "yes I am alive".
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#pingresp
*/
class pingresp : public fixed_header<version_number>
{
public:
pingresp() : fixed_header(control_packet_type::pingresp)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pingresp& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
return (*this);
}
inline pingresp& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
update_remain_length();
return (*this);
}
inline pingresp& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
);
return (*this);
}
protected:
// The PINGRESP packet has no Variable Header.
// The PINGRESP packet has no Payload.
};
/**
* DISCONNECT - Disconnect notification
*
* The DISCONNECT message is sent from the client to the server to indicate that it is about to close
* its TCP/IP connection. This allows for a clean disconnection, rather than just dropping the line.
* If the client had connected with the clean session flag set, then all previously maintained
* information about the client will be discarded.
* A server should not rely on the client to close the TCP/IP connection after receiving a DISCONNECT.
*
* http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#disconnect
*/
class disconnect : public fixed_header<version_number>
{
public:
disconnect() : fixed_header(control_packet_type::disconnect)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline disconnect& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
return (*this);
}
inline disconnect& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
update_remain_length();
return (*this);
}
inline disconnect& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
);
return (*this);
}
protected:
// There is no variable header.
// There is no payload.
};
}
namespace asio2::mqtt
{
template<typename = void>
inline constexpr std::string_view to_string(v3::connect_reason_code v)
{
using namespace std::string_view_literals;
switch(v)
{
case v3::connect_reason_code::success : return "Connection accepted"sv;
case v3::connect_reason_code::unacceptable_protocol_version : return "The Server does not support the level of the MQTT protocol requested by the Client"sv;
case v3::connect_reason_code::identifier_rejected : return "The Client identifier is correct UTF-8 but not allowed by the Server"sv;
case v3::connect_reason_code::server_unavailable : return "The Network Connection has been made but the MQTT service is unavailable"sv;
case v3::connect_reason_code::bad_user_name_or_password : return "The data in the user name or password is malformed"sv;
case v3::connect_reason_code::not_authorized : return "The Client is not authorized to connect"sv;
default:
ASIO2_ASSERT(false);
break;
}
return "unknown"sv;
}
template<typename message_type>
inline constexpr bool is_v3_message()
{
using type = asio2::detail::remove_cvref_t<message_type>;
if constexpr (
std::is_same_v<type, mqtt::v3::connect > ||
std::is_same_v<type, mqtt::v3::connack > ||
std::is_same_v<type, mqtt::v3::publish > ||
std::is_same_v<type, mqtt::v3::puback > ||
std::is_same_v<type, mqtt::v3::pubrec > ||
std::is_same_v<type, mqtt::v3::pubrel > ||
std::is_same_v<type, mqtt::v3::pubcomp > ||
std::is_same_v<type, mqtt::v3::subscribe > ||
std::is_same_v<type, mqtt::v3::suback > ||
std::is_same_v<type, mqtt::v3::unsubscribe > ||
std::is_same_v<type, mqtt::v3::unsuback > ||
std::is_same_v<type, mqtt::v3::pingreq > ||
std::is_same_v<type, mqtt::v3::pingresp > ||
std::is_same_v<type, mqtt::v3::disconnect > )
{
return true;
}
else
{
return false;
}
}
}
#endif // !__ASIO2_MQTT_PROTOCOL_V3_HPP__
<file_sep>// (C) Copyright <NAME> 2010
//
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// compiler setup for IBM XL C/C++ for Linux (Little Endian) based on clang.
#define BHO_HAS_PRAGMA_ONCE
// Detecting `-fms-extension` compiler flag assuming that _MSC_VER defined when that flag is used.
#if defined (_MSC_VER) && (__clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 4))
# define BHO_HAS_PRAGMA_DETECT_MISMATCH
#endif
// When compiling with clang before __has_extension was defined,
// even if one writes 'defined(__has_extension) && __has_extension(xxx)',
// clang reports a compiler error. So the only workaround found is:
#ifndef __has_extension
#define __has_extension __has_feature
#endif
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif
#if !__has_feature(cxx_exceptions) && !defined(BHO_NO_EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
#endif
#if !__has_feature(cxx_rtti) && !defined(BHO_NO_RTTI)
# define BHO_NO_RTTI
#endif
#if !__has_feature(cxx_rtti) && !defined(BHO_NO_TYPEID)
# define BHO_NO_TYPEID
#endif
#if defined(__int64) && !defined(__GNUC__)
# define BHO_HAS_MS_INT64
#endif
#define BHO_HAS_NRVO
// Branch prediction hints
#if defined(__has_builtin)
#if __has_builtin(__builtin_expect)
#define BHO_LIKELY(x) __builtin_expect(x, 1)
#define BHO_UNLIKELY(x) __builtin_expect(x, 0)
#endif
#endif
// Clang supports "long long" in all compilation modes.
#define BHO_HAS_LONG_LONG
//
// Dynamic shared object (DSO) and dynamic-link library (DLL) support
//
#if !defined(_WIN32) && !defined(__WIN32__) && !defined(WIN32)
# define BHO_SYMBOL_EXPORT __attribute__((__visibility__("default")))
# define BHO_SYMBOL_IMPORT
# define BHO_SYMBOL_VISIBLE __attribute__((__visibility__("default")))
#endif
//
// The BHO_FALLTHROUGH macro can be used to annotate implicit fall-through
// between switch labels.
//
#if __cplusplus >= 201103L && defined(__has_warning)
# if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough")
# define BHO_FALLTHROUGH [[clang::fallthrough]]
# endif
#endif
#if !__has_feature(cxx_auto_type)
# define BHO_NO_CXX11_AUTO_DECLARATIONS
# define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#endif
//
// Currently clang on Windows using VC++ RTL does not support C++11's char16_t or char32_t
//
#if defined(_MSC_VER) || !(defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L)
# define BHO_NO_CXX11_CHAR16_T
# define BHO_NO_CXX11_CHAR32_T
#endif
#if !__has_feature(cxx_constexpr)
# define BHO_NO_CXX11_CONSTEXPR
#endif
#if !__has_feature(cxx_decltype)
# define BHO_NO_CXX11_DECLTYPE
#endif
#if !__has_feature(cxx_decltype_incomplete_return_types)
# define BHO_NO_CXX11_DECLTYPE_N3276
#endif
#if !__has_feature(cxx_defaulted_functions)
# define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#endif
#if !__has_feature(cxx_deleted_functions)
# define BHO_NO_CXX11_DELETED_FUNCTIONS
#endif
#if !__has_feature(cxx_explicit_conversions)
# define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#endif
#if !__has_feature(cxx_default_function_template_args)
# define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#endif
#if !__has_feature(cxx_generalized_initializers)
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
#endif
#if !__has_feature(cxx_lambdas)
# define BHO_NO_CXX11_LAMBDAS
#endif
#if !__has_feature(cxx_local_type_template_args)
# define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#endif
#if !__has_feature(cxx_noexcept)
# define BHO_NO_CXX11_NOEXCEPT
#endif
#if !__has_feature(cxx_nullptr)
# define BHO_NO_CXX11_NULLPTR
#endif
#if !__has_feature(cxx_range_for)
# define BHO_NO_CXX11_RANGE_BASED_FOR
#endif
#if !__has_feature(cxx_raw_string_literals)
# define BHO_NO_CXX11_RAW_LITERALS
#endif
#if !__has_feature(cxx_reference_qualified_functions)
# define BHO_NO_CXX11_REF_QUALIFIERS
#endif
#if !__has_feature(cxx_generalized_initializers)
# define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#endif
#if !__has_feature(cxx_rvalue_references)
# define BHO_NO_CXX11_RVALUE_REFERENCES
#endif
#if !__has_feature(cxx_strong_enums)
# define BHO_NO_CXX11_SCOPED_ENUMS
#endif
#if !__has_feature(cxx_static_assert)
# define BHO_NO_CXX11_STATIC_ASSERT
#endif
#if !__has_feature(cxx_alias_templates)
# define BHO_NO_CXX11_TEMPLATE_ALIASES
#endif
#if !__has_feature(cxx_unicode_literals)
# define BHO_NO_CXX11_UNICODE_LITERALS
#endif
#if !__has_feature(cxx_variadic_templates)
# define BHO_NO_CXX11_VARIADIC_TEMPLATES
#endif
#if !__has_feature(cxx_user_literals)
# define BHO_NO_CXX11_USER_DEFINED_LITERALS
#endif
#if !__has_feature(cxx_alignas)
# define BHO_NO_CXX11_ALIGNAS
#endif
#if !__has_feature(cxx_trailing_return)
# define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#endif
#if !__has_feature(cxx_inline_namespaces)
# define BHO_NO_CXX11_INLINE_NAMESPACES
#endif
#if !__has_feature(cxx_override_control)
# define BHO_NO_CXX11_FINAL
# define BHO_NO_CXX11_OVERRIDE
#endif
#if !__has_feature(cxx_unrestricted_unions)
# define BHO_NO_CXX11_UNRESTRICTED_UNION
#endif
#if !(__has_feature(__cxx_binary_literals__) || __has_extension(__cxx_binary_literals__))
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !__has_feature(__cxx_decltype_auto__)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if !__has_feature(__cxx_aggregate_nsdmi__)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !__has_feature(__cxx_init_captures__)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !__has_feature(__cxx_generic_lambdas__)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
// clang < 3.5 has a defect with dependent type, like following.
//
// template <class T>
// constexpr typename enable_if<pred<T> >::type foo(T &)
// { } // error: no return statement in constexpr function
//
// This issue also affects C++11 mode, but C++11 constexpr requires return stmt.
// Therefore we don't care such case.
//
// Note that we can't check Clang version directly as the numbering system changes depending who's
// creating the Clang release (see https://github.com/boostorg/config/pull/39#issuecomment-59927873)
// so instead verify that we have a feature that was introduced at the same time as working C++14
// constexpr (generic lambda's in this case):
//
#if !__has_feature(__cxx_generic_lambdas__) || !__has_feature(__cxx_relaxed_constexpr__)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !__has_feature(__cxx_return_type_deduction__)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !__has_feature(__cxx_variable_templates__)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
// Clang 3.9+ in c++1z
#if !__has_cpp_attribute(fallthrough) || __cplusplus < 201406L
# define BHO_NO_CXX17_INLINE_VARIABLES
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !__has_feature(cxx_thread_local)
# define BHO_NO_CXX11_THREAD_LOCAL
#endif
#if __cplusplus < 201400
// All versions with __cplusplus above this value seem to support this:
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
// Unused attribute:
#if defined(__GNUC__) && (__GNUC__ >= 4)
# define BHO_ATTRIBUTE_UNUSED __attribute__((unused))
#endif
// Type aliasing hint.
#if __has_attribute(__may_alias__)
# define BHO_MAY_ALIAS __attribute__((__may_alias__))
#endif
#ifndef BHO_COMPILER
# define BHO_COMPILER "Clang version " __clang_version__
#endif
// Macro used to identify the Clang compiler.
#define BHO_CLANG 1
#define BHO_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001 - 2002.
// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2002.
// (C) Copyright <NAME> 2002 - 2003.
// (C) Copyright <NAME> 2002 - 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
//
// Microsoft Visual C++ compiler setup:
//
// We need to be careful with the checks in this file, as contrary
// to popular belief there are versions with _MSC_VER with the final
// digit non-zero (mainly the MIPS cross compiler).
//
// So we either test _MSC_VER >= XXXX or else _MSC_VER < XXXX.
// No other comparisons (==, >, or <=) are safe.
//
#define BHO_MSVC _MSC_VER
//
// Helper macro BHO_MSVC_FULL_VER for use in Boost code:
//
#if _MSC_FULL_VER > 100000000
# define BHO_MSVC_FULL_VER _MSC_FULL_VER
#else
# define BHO_MSVC_FULL_VER (_MSC_FULL_VER * 10)
#endif
// Attempt to suppress VC6 warnings about the length of decorated names (obsolete):
#pragma warning( disable : 4503 ) // warning: decorated name length exceeded
#define BHO_HAS_PRAGMA_ONCE
//
// versions check:
// we don't support Visual C++ prior to version 7.1:
#if _MSC_VER < 1310
# error "Compiler not supported or configured - please reconfigure"
#endif
// VS2005 (VC8) docs: __assume has been in Visual C++ for multiple releases
#define BHO_UNREACHABLE_RETURN(x) __assume(0);
#if _MSC_FULL_VER < 180020827
# define BHO_NO_FENV_H
#endif
#if _MSC_VER < 1400
// although a conforming signature for swprint exists in VC7.1
// it appears not to actually work:
# define BHO_NO_SWPRINTF
// Our extern template tests also fail for this compiler:
# define BHO_NO_CXX11_EXTERN_TEMPLATE
// Variadic macros do not exist for VC7.1 and lower
# define BHO_NO_CXX11_VARIADIC_MACROS
# define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#endif
#if _MSC_VER < 1500 // 140X == VC++ 8.0
# define BHO_NO_MEMBER_TEMPLATE_FRIENDS
#endif
#if _MSC_VER < 1600 // 150X == VC++ 9.0
// A bug in VC9:
# define BHO_NO_ADL_BARRIER
#endif
#ifndef _NATIVE_WCHAR_T_DEFINED
# define BHO_NO_INTRINSIC_WCHAR_T
#endif
//
// check for exception handling support:
#if !defined(_CPPUNWIND) && !defined(BHO_NO_EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
#endif
//
// __int64 support:
//
#define BHO_HAS_MS_INT64
#if defined(_MSC_EXTENSIONS) || (_MSC_VER >= 1400)
# define BHO_HAS_LONG_LONG
#else
# define BHO_NO_LONG_LONG
#endif
#if (_MSC_VER >= 1400) && !defined(_DEBUG)
# define BHO_HAS_NRVO
#endif
#if _MSC_VER >= 1600 // 160X == VC++ 10.0
# define BHO_HAS_PRAGMA_DETECT_MISMATCH
#endif
//
// disable Win32 API's if compiler extensions are
// turned off:
//
#if !defined(_MSC_EXTENSIONS) && !defined(BHO_DISABLE_WIN32)
# define BHO_DISABLE_WIN32
#endif
#if !defined(_CPPRTTI) && !defined(BHO_NO_RTTI)
# define BHO_NO_RTTI
#endif
//
// TR1 features:
//
#if (_MSC_VER >= 1700) && defined(_HAS_CXX17) && (_HAS_CXX17 > 0)
// # define BHO_HAS_TR1_HASH // don't know if this is true yet.
// # define BHO_HAS_TR1_TYPE_TRAITS // don't know if this is true yet.
# define BHO_HAS_TR1_UNORDERED_MAP
# define BHO_HAS_TR1_UNORDERED_SET
#endif
//
// C++0x features
//
// See above for BHO_NO_LONG_LONG
// C++ features supported by VC++ 10 (aka 2010)
//
#if _MSC_VER < 1600
# define BHO_NO_CXX11_AUTO_DECLARATIONS
# define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
# define BHO_NO_CXX11_LAMBDAS
# define BHO_NO_CXX11_RVALUE_REFERENCES
# define BHO_NO_CXX11_STATIC_ASSERT
# define BHO_NO_CXX11_NULLPTR
# define BHO_NO_CXX11_DECLTYPE
#endif // _MSC_VER < 1600
#if _MSC_VER >= 1600
# define BHO_HAS_STDINT_H
#endif
// C++11 features supported by VC++ 11 (aka 2012)
//
#if _MSC_VER < 1700
# define BHO_NO_CXX11_FINAL
# define BHO_NO_CXX11_RANGE_BASED_FOR
# define BHO_NO_CXX11_SCOPED_ENUMS
# define BHO_NO_CXX11_OVERRIDE
#endif // _MSC_VER < 1700
// C++11 features supported by VC++ 12 (aka 2013).
//
#if _MSC_FULL_VER < 180020827
# define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
# define BHO_NO_CXX11_DELETED_FUNCTIONS
# define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
# define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
# define BHO_NO_CXX11_RAW_LITERALS
# define BHO_NO_CXX11_TEMPLATE_ALIASES
# define BHO_NO_CXX11_TRAILING_RESULT_TYPES
# define BHO_NO_CXX11_VARIADIC_TEMPLATES
# define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
# define BHO_NO_CXX11_DECLTYPE_N3276
#endif
#if _MSC_FULL_VER >= 180020827
#define BHO_HAS_EXPM1
#define BHO_HAS_LOG1P
#endif
// C++11 features supported by VC++ 14 (aka 2015)
//
#if (_MSC_FULL_VER < 190023026)
# define BHO_NO_CXX11_NOEXCEPT
# define BHO_NO_CXX11_DEFAULTED_MOVES
# define BHO_NO_CXX11_REF_QUALIFIERS
# define BHO_NO_CXX11_USER_DEFINED_LITERALS
# define BHO_NO_CXX11_ALIGNAS
# define BHO_NO_CXX11_INLINE_NAMESPACES
# define BHO_NO_CXX11_CHAR16_T
# define BHO_NO_CXX11_CHAR32_T
# define BHO_NO_CXX11_UNICODE_LITERALS
# define BHO_NO_CXX14_DECLTYPE_AUTO
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
# define BHO_NO_CXX14_BINARY_LITERALS
# define BHO_NO_CXX14_GENERIC_LAMBDAS
# define BHO_NO_CXX14_DIGIT_SEPARATORS
# define BHO_NO_CXX11_THREAD_LOCAL
# define BHO_NO_CXX11_UNRESTRICTED_UNION
#endif
// C++11 features supported by VC++ 14 update 3 (aka 2015)
//
#if (_MSC_FULL_VER < 190024210)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
# define BHO_NO_SFINAE_EXPR
# define BHO_NO_CXX11_CONSTEXPR
#endif
// C++14 features supported by VC++ 14.1 (Visual Studio 2017)
//
#if (_MSC_VER < 1910)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
// C++17 features supported by VC++ 14.1 (Visual Studio 2017) Update 3
//
#if (_MSC_VER < 1911) || (_MSVC_LANG < 201703)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
# define BHO_NO_CXX17_IF_CONSTEXPR
// Let the defaults handle these now:
//# define BHO_NO_CXX17_HDR_OPTIONAL
//# define BHO_NO_CXX17_HDR_STRING_VIEW
#endif
// MSVC including version 14 has not yet completely
// implemented value-initialization, as is reported:
// "VC++ does not value-initialize members of derived classes without
// user-declared constructor", reported in 2009 by <NAME>:
// https://connect.microsoft.com/VisualStudio/feedback/details/484295
// "Presence of copy constructor breaks member class initialization",
// reported in 2009 by <NAME>:
// https://connect.microsoft.com/VisualStudio/feedback/details/499606
// "Value-initialization in new-expression", reported in 2005 by
// <NAME> (MetaCommunications Engineering):
// https://connect.microsoft.com/VisualStudio/feedback/details/100744
// Reported again by <NAME> in 2015 for VC14:
// https://connect.microsoft.com/VisualStudio/feedback/details/1582233/c-subobjects-still-not-value-initialized-correctly
// See also: http://www.boost.org/libs/utility/value_init.htm#compiler_issues
// (<NAME>, LKEB, May 2010)
// Still present in VC15.5, Dec 2017.
#define BHO_NO_COMPLETE_VALUE_INITIALIZATION
//
// C++ 11:
//
// This is supported with /permissive- for 15.5 onwards, unfortunately we appear to have no way to tell
// if this is in effect or not, in any case nothing in Boost is currently using this, so we'll just go
// on defining it for now:
//
#if (_MSC_FULL_VER < 193030705) || (_MSVC_LANG < 202004)
# define BHO_NO_TWO_PHASE_NAME_LOOKUP
#endif
#if (_MSC_VER < 1912) || (_MSVC_LANG < 201402)
// Supported from msvc-15.5 onwards:
#define BHO_NO_CXX11_SFINAE_EXPR
#endif
#if (_MSC_VER < 1915) || (_MSVC_LANG < 201402)
// C++ 14:
// Still gives internal compiler error for msvc-15.5:
# define BHO_NO_CXX14_CONSTEXPR
#endif
// C++ 17:
#if (_MSC_VER < 1912) || (_MSVC_LANG < 201703)
#define BHO_NO_CXX17_INLINE_VARIABLES
#define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
//
// Things that don't work in clr mode:
//
#ifdef _M_CEE
#ifndef BHO_NO_CXX11_THREAD_LOCAL
# define BHO_NO_CXX11_THREAD_LOCAL
#endif
#ifndef BHO_NO_SFINAE_EXPR
# define BHO_NO_SFINAE_EXPR
#endif
#ifndef BHO_NO_CXX11_REF_QUALIFIERS
# define BHO_NO_CXX11_REF_QUALIFIERS
#endif
#endif
#ifdef _M_CEE_PURE
#ifndef BHO_NO_CXX11_CONSTEXPR
# define BHO_NO_CXX11_CONSTEXPR
#endif
#endif
//
// prefix and suffix headers:
//
#ifndef BHO_ABI_PREFIX
# define BHO_ABI_PREFIX "asio2/bho/config/abi/msvc_prefix.hpp"
#endif
#ifndef BHO_ABI_SUFFIX
# define BHO_ABI_SUFFIX "asio2/bho/config/abi/msvc_suffix.hpp"
#endif
//
// Approximate compiler conformance version
//
#ifdef _MSVC_LANG
# define BHO_CXX_VERSION _MSVC_LANG
#elif defined(_HAS_CXX17)
# define BHO_CXX_VERSION 201703L
#elif BHO_MSVC >= 1916
# define BHO_CXX_VERSION 201402L
#endif
#ifndef BHO_COMPILER
// TODO:
// these things are mostly bogus. 1200 means version 12.0 of the compiler. The
// artificial versions assigned to them only refer to the versions of some IDE
// these compilers have been shipped with, and even that is not all of it. Some
// were shipped with freely downloadable SDKs, others as crosscompilers in eVC.
// IOW, you can't use these 'versions' in any sensible way. Sorry.
# if defined(UNDER_CE)
# if _MSC_VER < 1400
// Note: I'm not aware of any CE compiler with version 13xx
# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown EVC++ compiler version - please run the configure tests and report the results"
# else
# pragma message("boost: Unknown EVC++ compiler version - please run the configure tests and report the results")
# endif
# elif _MSC_VER < 1500
# define BHO_COMPILER_VERSION evc8
# elif _MSC_VER < 1600
# define BHO_COMPILER_VERSION evc9
# elif _MSC_VER < 1700
# define BHO_COMPILER_VERSION evc10
# elif _MSC_VER < 1800
# define BHO_COMPILER_VERSION evc11
# elif _MSC_VER < 1900
# define BHO_COMPILER_VERSION evc12
# elif _MSC_VER < 2000
# define BHO_COMPILER_VERSION evc14
# else
# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown EVC++ compiler version - please run the configure tests and report the results"
# else
# pragma message("boost: Unknown EVC++ compiler version - please run the configure tests and report the results")
# endif
# endif
# else
# if _MSC_VER < 1200
// Note: Versions up to 10.0 aren't supported.
# define BHO_COMPILER_VERSION 5.0
# elif _MSC_VER < 1300
# define BHO_COMPILER_VERSION 6.0
# elif _MSC_VER < 1310
# define BHO_COMPILER_VERSION 7.0
# elif _MSC_VER < 1400
# define BHO_COMPILER_VERSION 7.1
# elif _MSC_VER < 1500
# define BHO_COMPILER_VERSION 8.0
# elif _MSC_VER < 1600
# define BHO_COMPILER_VERSION 9.0
# elif _MSC_VER < 1700
# define BHO_COMPILER_VERSION 10.0
# elif _MSC_VER < 1800
# define BHO_COMPILER_VERSION 11.0
# elif _MSC_VER < 1900
# define BHO_COMPILER_VERSION 12.0
# elif _MSC_VER < 1910
# define BHO_COMPILER_VERSION 14.0
# elif _MSC_VER < 1920
# define BHO_COMPILER_VERSION 14.1
# elif _MSC_VER < 1930
# define BHO_COMPILER_VERSION 14.2
# else
# define BHO_COMPILER_VERSION _MSC_VER
# endif
# endif
# define BHO_COMPILER "Microsoft Visual C++ version " BHO_STRINGIZE(BHO_COMPILER_VERSION)
#endif
#include <asio2/bho/config/pragma_message.hpp>
//
// last known and checked version is 19.20.27508 (VC++ 2019 RC3):
#if (_MSC_VER > 1920)
# if defined(BHO_ASSERT_CONFIG)
# error "Boost.Config is older than your current compiler version."
# elif !defined(BHO_CONFIG_SUPPRESS_OUTDATED_MESSAGE)
//
// Disabled as of March 2018 - the pace of VS releases is hard to keep up with
// and in any case, we have relatively few defect macros defined now.
// BHO_PRAGMA_MESSAGE("Info: Boost.Config is older than your compiler version - probably nothing bad will happen - but you may wish to look for an updated Boost version. Define BHO_CONFIG_SUPPRESS_OUTDATED_MESSAGE to suppress this message.")
# endif
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_TCP_RECV_OP_HPP__
#define __ASIO2_TCP_RECV_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/ecs.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class tcp_recv_op
{
protected:
template<class, class = std::void_t<>>
struct has_member_dgram : std::false_type {};
template<class T>
struct has_member_dgram<T, std::void_t<decltype(T::dgram_)>> : std::true_type {};
public:
/**
* @brief constructor
*/
tcp_recv_op() noexcept {}
/**
* @brief destructor
*/
~tcp_recv_op() = default;
protected:
/**
* @brief Pre process the data before recv callback was called.
* You can overload this function in a derived class to implement additional
* processing of the data. eg: decrypt data with a custom encryption algorithm.
*/
inline std::string_view data_filter_before_recv(std::string_view data)
{
return data;
}
protected:
template<typename C>
void _tcp_post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
using condition_lowest_type = typename ecs_t<C>::condition_lowest_type;
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
if (!derive.is_started())
{
if (derive.state() == state_t::started)
{
derive._do_disconnect(asio2::get_last_error(), std::move(this_ptr));
}
return;
}
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_recv_counter_.load() == 0);
derive.post_recv_counter_++;
#endif
derive.reading_ = true;
ecs_t<C>& e = *ecs;
if constexpr (
std::is_same_v<condition_lowest_type, asio::detail::transfer_all_t> ||
std::is_same_v<condition_lowest_type, asio::detail::transfer_at_least_t> ||
std::is_same_v<condition_lowest_type, asio::detail::transfer_exactly_t> ||
std::is_same_v<condition_lowest_type, asio2::detail::hook_buffer_t>)
{
asio::async_read(derive.stream(), derive.buffer().base(), e.get_condition().lowest(),
make_allocator(derive.rallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(const error_code& ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
derive.reading_ = false;
derive._handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}));
}
else
{
asio::async_read_until(derive.stream(), derive.buffer().base(), e.get_condition().lowest(),
make_allocator(derive.rallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(const error_code& ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
derive.reading_ = false;
derive._handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}));
}
}
template<typename C>
void _tcp_dgram_fire_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
detail::ignore_unused(ec);
derived_t& derive = static_cast<derived_t&>(*this);
const std::uint8_t* buffer = static_cast<const std::uint8_t*>(derive.buffer().data().data());
if /**/ (std::uint8_t(buffer[0]) < std::uint8_t(254))
{
derive._fire_recv(this_ptr, ecs, std::string_view(reinterpret_cast<
std::string_view::const_pointer>(buffer + 1), bytes_recvd - 1));
}
else if (std::uint8_t(buffer[0]) == std::uint8_t(254))
{
derive._fire_recv(this_ptr, ecs, std::string_view(reinterpret_cast<
std::string_view::const_pointer>(buffer + 1 + 2), bytes_recvd - 1 - 2));
}
else
{
ASIO2_ASSERT(std::uint8_t(buffer[0]) == std::uint8_t(255));
derive._fire_recv(this_ptr, ecs, std::string_view(reinterpret_cast<
std::string_view::const_pointer>(buffer + 1 + 8), bytes_recvd - 1 - 8));
}
}
template<typename C>
void _tcp_handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
using condition_lowest_type = typename ecs_t<C>::condition_lowest_type;
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
set_last_error(ec);
// bytes_recvd : The number of bytes in the streambuf's get area up to and including the delimiter.
// After testing, it is found that even if the "ec" is 0, the socket may have been closed already,
// the stop function of the base class has been called already, and the member variable resources
// have been destroyed already, so we need check the "derive.is_started()" to ensure that the user
// maybe read write the member variable resources in the recv callback, and it will cause crash.
// the code can't be like this:
//if (!ec && derive.is_started())
//{
// _fire_recv(...);
// _post_recv(...);
//}
//else
//{
// // after call client.stop, and user call client.start again, when code run to here, the state
// // maybe changed to starting by the client.start, if we call _do_disconnect at here, the state
// // is changed to stopping again, this will break the client.start processing.
// _do_disconnect(...);
//}
if (!derive.is_started())
{
if (derive.state() == state_t::started)
{
ASIO2_LOG_INFOR("_tcp_handle_recv with closed socket: {} {}", ec.value(), ec.message());
derive._do_disconnect(ec, this_ptr);
}
derive._stop_readend_timer(std::move(this_ptr));
return;
}
if (!ec)
{
// every times recv data,we update the last alive time.
derive.update_alive_time();
if constexpr (std::is_same_v<condition_lowest_type, use_dgram_t>)
{
if constexpr (has_member_dgram<derived_t>::value)
{
if (bytes_recvd == 0)
{
derive._do_disconnect(asio::error::no_data, this_ptr);
derive._stop_readend_timer(std::move(this_ptr));
return;
}
}
else
{
ASIO2_ASSERT(false);
}
derive._tcp_dgram_fire_recv(ec, bytes_recvd, this_ptr, ecs);
}
else
{
if constexpr (!std::is_same_v<condition_lowest_type, asio2::detail::hook_buffer_t>)
{
derive._fire_recv(this_ptr, ecs, std::string_view(reinterpret_cast<
std::string_view::const_pointer>(derive.buffer().data().data()), bytes_recvd));
}
else
{
derive._fire_recv(this_ptr, ecs, std::string_view(reinterpret_cast<
std::string_view::const_pointer>(derive.buffer().data().data()),
derive.buffer().size()));
}
}
if constexpr (!std::is_same_v<condition_lowest_type, asio2::detail::hook_buffer_t>)
{
derive.buffer().consume(bytes_recvd);
}
else
{
std::ignore = true;
}
derive._post_recv(std::move(this_ptr), std::move(ecs));
}
else
{
ASIO2_LOG_DEBUG("_tcp_handle_recv with error: {} {}", ec.value(), ec.message());
if (ec == asio::error::eof)
{
// /beast/http/impl/read.hpp
//if (ec == net::error::eof)
//{
// BHO_ASSERT(bytes_transferred == 0);
// ...
//}
ASIO2_ASSERT(bytes_recvd == 0);
if (bytes_recvd)
{
// http://www.purecpp.cn/detail?id=2303
ASIO2_LOG_INFOR("_tcp_handle_recv with eof: {}", bytes_recvd);
}
}
derive._do_disconnect(ec, this_ptr);
derive._stop_readend_timer(std::move(this_ptr));
}
// If an error occurs then no new asynchronous operations are started. This
// means that all shared_ptr references to the connection object will
// disappear and the object will be destroyed automatically after this
// handler returns. The connection class's destructor closes the socket.
}
protected:
};
}
#endif // !__ASIO2_TCP_RECV_OP_HPP__
<file_sep>/*
Copyright <NAME> 2021
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_E2K_H
#define BHO_PREDEF_ARCHITECTURE_E2K_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_E2K`
https://en.wikipedia.org/wiki/Elbrus_2000[E2K] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__e2k__+` | {predef_detection}
| `+__e2k__+` | V.0.0
|===
*/ // end::reference[]
#define BHO_ARCH_E2K BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__e2k__)
# undef BHO_ARCH_E2K
# if !defined(BHO_ARCH_E2K) && defined(__iset__)
# define BHO_ARCH_E2K BHO_VERSION_NUMBER(__iset__,0,0)
# endif
# if !defined(BHO_ARCH_E2K)
# define BHO_ARCH_E2K BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_E2K
# define BHO_ARCH_E2K_AVAILABLE
#endif
#if BHO_ARCH_E2K
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_E2K_NAME "E2K"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_E2K,BHO_ARCH_E2K_NAME)
<file_sep>// Copyright (c) 2016-2021 <NAME>
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BHO_PFR_DETAIL_SIZE_T_HPP
#define BHO_PFR_DETAIL_SIZE_T_HPP
#pragma once
namespace bho { namespace pfr { namespace detail {
///////////////////// General utility stuff
template <std::size_t Index>
using size_t_ = std::integral_constant<std::size_t, Index >;
}}} // namespace bho::pfr::detail
#endif // BHO_PFR_DETAIL_SIZE_T_HPP
<file_sep>// Copyright 2021 <NAME>
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt)
#if !defined(__APPLE__)
# define BHO_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
#else
# define BHO_CLANG_REPORTED_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
// https://en.wikipedia.org/wiki/Xcode#Toolchain_versions
# if BHO_CLANG_REPORTED_VERSION >= 130000
# define BHO_CLANG_VERSION 120000
# elif BHO_CLANG_REPORTED_VERSION >= 120005
# define BHO_CLANG_VERSION 110100
# elif BHO_CLANG_REPORTED_VERSION >= 120000
# define BHO_CLANG_VERSION 100000
# elif BHO_CLANG_REPORTED_VERSION >= 110003
# define BHO_CLANG_VERSION 90000
# elif BHO_CLANG_REPORTED_VERSION >= 110000
# define BHO_CLANG_VERSION 80000
# elif BHO_CLANG_REPORTED_VERSION >= 100001
# define BHO_CLANG_VERSION 70000
# elif BHO_CLANG_REPORTED_VERSION >= 100000
# define BHO_CLANG_VERSION 60001
# elif BHO_CLANG_REPORTED_VERSION >= 90100
# define BHO_CLANG_VERSION 50002
# elif BHO_CLANG_REPORTED_VERSION >= 90000
# define BHO_CLANG_VERSION 40000
# elif BHO_CLANG_REPORTED_VERSION >= 80000
# define BHO_CLANG_VERSION 30900
# elif BHO_CLANG_REPORTED_VERSION >= 70300
# define BHO_CLANG_VERSION 30800
# elif BHO_CLANG_REPORTED_VERSION >= 70000
# define BHO_CLANG_VERSION 30700
# elif BHO_CLANG_REPORTED_VERSION >= 60100
# define BHO_CLANG_VERSION 30600
# elif BHO_CLANG_REPORTED_VERSION >= 60000
# define BHO_CLANG_VERSION 30500
# elif BHO_CLANG_REPORTED_VERSION >= 50100
# define BHO_CLANG_VERSION 30400
# elif BHO_CLANG_REPORTED_VERSION >= 50000
# define BHO_CLANG_VERSION 30300
# elif BHO_CLANG_REPORTED_VERSION >= 40200
# define BHO_CLANG_VERSION 30200
# elif BHO_CLANG_REPORTED_VERSION >= 30100
# define BHO_CLANG_VERSION 30100
# elif BHO_CLANG_REPORTED_VERSION >= 20100
# define BHO_CLANG_VERSION 30000
# else
# define BHO_CLANG_VERSION 20900
# endif
# undef BHO_CLANG_REPORTED_VERSION
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_IBM_H
#define BHO_PREDEF_COMPILER_IBM_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_IBM`
http://en.wikipedia.org/wiki/VisualAge[IBM XL C/{CPP}] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__IBMCPP__+` | {predef_detection}
| `+__xlC__+` | {predef_detection}
| `+__xlc__+` | {predef_detection}
| `+__COMPILER_VER__+` | V.R.P
| `+__xlC__+` | V.R.P
| `+__xlc__+` | V.R.P
| `+__IBMCPP__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_IBM BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__IBMCPP__) || defined(__xlC__) || defined(__xlc__)
# if !defined(BHO_COMP_IBM_DETECTION) && defined(__COMPILER_VER__)
# define BHO_COMP_IBM_DETECTION BHO_PREDEF_MAKE_0X_VRRPPPP(__COMPILER_VER__)
# endif
# if !defined(BHO_COMP_IBM_DETECTION) && defined(__xlC__)
# define BHO_COMP_IBM_DETECTION BHO_PREDEF_MAKE_0X_VVRR(__xlC__)
# endif
# if !defined(BHO_COMP_IBM_DETECTION) && defined(__xlc__)
# define BHO_COMP_IBM_DETECTION BHO_PREDEF_MAKE_0X_VVRR(__xlc__)
# endif
# if !defined(BHO_COMP_IBM_DETECTION)
# define BHO_COMP_IBM_DETECTION BHO_PREDEF_MAKE_10_VRP(__IBMCPP__)
# endif
#endif
#ifdef BHO_COMP_IBM_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_IBM_EMULATED BHO_COMP_IBM_DETECTION
# else
# undef BHO_COMP_IBM
# define BHO_COMP_IBM BHO_COMP_IBM_DETECTION
# endif
# define BHO_COMP_IBM_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_IBM_NAME "IBM XL C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_IBM,BHO_COMP_IBM_NAME)
#ifdef BHO_COMP_IBM_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_IBM_EMULATED,BHO_COMP_IBM_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* chinese : http://blog.mcxiaoke.com/mqtt/protocol/MQTT-3.1.1-CN.html
* english : http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_PROTOCOL_V4_HPP__
#define __ASIO2_MQTT_PROTOCOL_V4_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/mqtt/core.hpp>
namespace asio2::mqtt::v4
{
static constexpr std::uint8_t version_number = asio2::detail::to_underlying(mqtt::version::v4);
enum class connect_reason_code : std::uint8_t
{
/* 0 0x00 Connection Accepted : */ success = 0,
/* 1 0x01 Connection Refused : */ unacceptable_protocol_version = 1,
/* 2 0x02 Connection Refused : */ identifier_rejected = 2,
/* 3 0x03 Connection Refused : */ server_unavailable = 3,
/* 4 0x04 Connection Refused : */ bad_user_name_or_password = 4,
/* 5 0x05 Connection Refused : */ not_authorized = 5,
/* 6 - 255 Reserved for future use */
};
/**
* CONNECT - Client requests a connection to a Server
*
* After a Network Connection is established by a Client to a Server, the first packet sent from the
* Client to the Server MUST be a CONNECT packet [MQTT-3.1.0-1].
*
* A Client can only send the CONNECT Packet once over a Network Connection. The Server MUST process
* a second CONNECT Packet sent from a Client as a protocol violation and disconnect the Client
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028
*/
class connect : public fixed_header<version_number>
{
public:
connect() : fixed_header(control_packet_type::connect)
{
update_remain_length();
}
connect(utf8_string::value_type clientid) : fixed_header(control_packet_type::connect)
{
client_id(std::move(clientid));
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline connect& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
protocol_name_ .serialize(buffer);
protocol_version_ .serialize(buffer);
connect_flags_.byte .serialize(buffer);
keep_alive_ .serialize(buffer);
client_id_ .serialize(buffer);
if (will_topic_ ) will_topic_ ->serialize(buffer);
if (will_payload_) will_payload_->serialize(buffer);
if (username_ ) username_ ->serialize(buffer);
if (password_ ) password_ ->serialize(buffer);
return (*this);
}
inline connect& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
protocol_name_ .deserialize(data);
protocol_version_ .deserialize(data);
connect_flags_.byte .deserialize(data);
keep_alive_ .deserialize(data);
client_id_ .deserialize(data);
if (has_will())
{
utf8_string will_topic{};
will_topic.deserialize(data);
will_topic_ = std::move(will_topic);
binary_data will_payload{};
will_payload.deserialize(data);
will_payload_ = std::move(will_payload);
}
if (has_username())
{
utf8_string username{};
username.deserialize(data);
username_ = std::move(username);
}
if (has_password())
{
binary_data password{};
password.deserialize(data);
password_ = std::move(password);
}
update_remain_length();
return (*this);
}
inline std::uint8_t protocol_version() { return (protocol_version_ ); }
inline bool clean_start () { return (connect_flags_.bits.clean_session); }
inline bool clean_session () { return (connect_flags_.bits.clean_session); }
inline bool has_will () { return (connect_flags_.bits.will_flag ); }
inline qos_type will_qos () { return static_cast<qos_type>(connect_flags_.bits.will_qos ); }
inline bool will_retain () { return (connect_flags_.bits.will_retain ); }
inline bool has_password () { return (connect_flags_.bits.password_flag); }
inline bool has_username () { return (connect_flags_.bits.username_flag); }
inline connect& clean_start (bool v) { connect_flags_.bits.clean_session = v; return (*this); }
inline connect& clean_session (bool v) { connect_flags_.bits.clean_session = v; return (*this); }
inline two_byte_integer::value_type keep_alive () { return keep_alive_ ; }
inline utf8_string::view_type client_id () { return client_id_ .data_view(); }
inline utf8_string::view_type will_topic () { return will_topic_ ? will_topic_ ->data_view() : ""; }
inline binary_data::view_type will_payload () { return will_payload_ ? will_payload_->data_view() : ""; }
inline utf8_string::view_type username () { return username_ ? username_ ->data_view() : ""; }
inline binary_data::view_type password () { return password_ ? password_ ->data_view() : ""; }
inline connect& keep_alive(two_byte_integer::value_type v)
{
keep_alive_ = std::move(v);
return (*this);
}
inline connect& client_id(utf8_string::value_type v)
{
client_id_ = std::move(v);
update_remain_length();
return (*this);
}
inline connect& username(utf8_string::value_type v)
{
username_ = std::move(v);
connect_flags_.bits.username_flag = true;
update_remain_length();
return (*this);
}
inline connect& password(binary_data::value_type v)
{
password_ = std::move(v);
connect_flags_.bits.password_flag = true;
update_remain_length();
return (*this);
}
template<class String1, class String2, class QosOrInt>
inline connect& will_attributes(String1&& topic, String2&& payload,
QosOrInt qos = qos_type::at_most_once, bool retain = false)
{
will_topic_ = std::forward<String1>(topic);
will_payload_ = std::forward<String2>(payload);
connect_flags_.bits.will_flag = true;
connect_flags_.bits.will_qos = static_cast<std::uint8_t>(qos);
connect_flags_.bits.will_retain = retain;
update_remain_length();
return (*this);
}
inline bool has_will () const noexcept { return will_topic_.has_value(); }
inline bool has_username () const noexcept { return username_ .has_value(); }
inline bool has_password () const noexcept { return password_ .has_value(); }
inline connect& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ protocol_name_ .required_size()
+ protocol_version_ .required_size()
+ connect_flags_.byte .required_size()
+ keep_alive_ .required_size()
+ client_id_ .required_size()
+ (will_topic_ ? will_topic_ ->required_size() : 0)
+ (will_payload_ ? will_payload_->required_size() : 0)
+ (username_ ? username_ ->required_size() : 0)
+ (password_ ? password_ ->required_size() : 0)
);
return (*this);
}
protected:
// The Protocol Name is a UTF-8 Encoded String that represents the protocol name "MQTT".
// The string, its offset and length will not be changed by future versions of the MQTT specification.
utf8_string protocol_name_{ "MQTT" };
// The 8 bit unsigned value that represents the revision level of the protocol used by the Client.
// The value of the Protocol Level field for the version 3.1.1 of the protocol is 4 (0x04).
one_byte_integer protocol_version_{ 0x04 };
union
{
one_byte_integer byte{ 0 }; // all connect flags
#if ASIO2_ENDIAN_BIG_BYTE
struct
{
bool username_flag : 1; // User Name Flag
bool password_flag : 1; // Password Flag
bool will_retain : 1; // will retain setting
std::uint8_t will_qos : 2; // will QoS value
bool will_flag : 1; // will flag
bool clean_session : 1; // Clean Session flag
std::uint8_t reserved : 1; // unused
} bits;
#else
struct
{
std::uint8_t reserved : 1; // unused
bool clean_session : 1; // Clean Session flag
bool will_flag : 1; // will flag
std::uint8_t will_qos : 2; // will QoS value
bool will_retain : 1; // will retain setting
bool password_flag : 1; // Password Flag
bool username_flag : 1; // User Name Flag
} bits;
#endif
} connect_flags_{}; // connect flags byte
// The Keep Alive is a time interval measured in seconds. Expressed as a 16-bit word
// Default to 60 seconds
two_byte_integer keep_alive_ { 60 };
// The Client Identifier (ClientID) identifies the Client to the Server.
// Each Client connecting to the Server has a unique ClientID.
utf8_string client_id_ {};
// If the Will Flag is set to 1, the Will Topic is the next field in the Payload.
std::optional<utf8_string> will_topic_ {};
// If the Will Flag is set to 1 the Will Payload is the next field in the Payload.
std::optional<binary_data> will_payload_{};
// If the User Name Flag is set to 1, the User Name is the next field in the Payload.
std::optional<utf8_string> username_ {};
// If the Password Flag is set to 1, the Password is the next field in the Payload.
std::optional<binary_data> password_ {};
};
/**
* CONNACK - Acknowledge connection request
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033
*/
class connack : public fixed_header<version_number>
{
public:
connack() : fixed_header(control_packet_type::connack)
{
update_remain_length();
}
explicit connack(bool session_present, std::uint8_t reason_code)
: fixed_header(control_packet_type::connack)
, reason_code_(reason_code)
{
connack_flags_.bits.session_present = session_present;
update_remain_length();
}
explicit connack(bool session_present, connect_reason_code reason_code)
: fixed_header(control_packet_type::connack)
, reason_code_(asio2::detail::to_underlying(reason_code))
{
connack_flags_.bits.session_present = session_present;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline connack& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
connack_flags_.byte .serialize(buffer);
reason_code_ .serialize(buffer);
return (*this);
}
inline connack& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
connack_flags_.byte .deserialize(data);
reason_code_ .deserialize(data);
update_remain_length();
return (*this);
}
inline bool session_present() { return connack_flags_.bits.session_present; }
inline connect_reason_code reason_code () { return static_cast<connect_reason_code>(reason_code_.value()); }
inline connack & session_present(bool v) { connack_flags_.bits.session_present = v; return (*this); }
inline connack & reason_code (std::uint8_t v) { reason_code_ = v; return (*this); }
inline connack & reason_code (connect_reason_code v)
{ reason_code_ = asio2::detail::to_underlying(v); return (*this); }
inline connack& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ connack_flags_.byte .required_size()
+ reason_code_ .required_size()
);
return (*this);
}
protected:
union
{
one_byte_integer byte{ 0 }; // all connack flags
#if ASIO2_ENDIAN_BIG_BYTE
struct
{
std::uint8_t reserved : 7;
bool session_present : 1; // session found on the server?
} bits;
#else
struct
{
bool session_present : 1; // session found on the server?
std::uint8_t reserved : 7;
} bits;
#endif
} connack_flags_{}; // connack flags
// Byte 2 in the Variable Header is the Connect Reason Code.
one_byte_integer reason_code_{ 0 };
};
/**
* PUBLISH - Publish message
*
* A PUBLISH packet is sent from a Client to a Server or from a Server to a Client to transport an Application Message.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718037
*/
class publish : public fixed_header<version_number>
{
public:
publish() : fixed_header(control_packet_type::publish)
{
update_remain_length();
}
template<class String1, class String2, class QosOrInt, std::enable_if_t<
asio2::detail::is_character_string_v<String1>, int> = 0>
explicit publish(String1&& topic_name, String2&& payload, QosOrInt qos,
bool dup = false, bool retain = false)
: fixed_header(control_packet_type::publish)
, topic_name_ (std::forward<String1>(topic_name))
, payload_ (std::forward<String2>(payload ))
{
type_and_flags_.bits.dup = dup;
type_and_flags_.bits.qos = static_cast<std::uint8_t>(qos);
type_and_flags_.bits.retain = retain;
update_remain_length();
}
template<class String1, class String2, class QosOrInt, std::enable_if_t<
asio2::detail::is_character_string_v<String1>, int> = 0>
explicit publish(std::uint16_t pid, String1&& topic_name, String2&& payload, QosOrInt qos,
bool dup = false, bool retain = false)
: fixed_header(control_packet_type::publish)
, topic_name_ (std::forward<String1>(topic_name))
, packet_id_ (pid)
, payload_ (std::forward<String2>(payload ))
{
type_and_flags_.bits.dup = dup;
type_and_flags_.bits.qos = static_cast<std::uint8_t>(qos);
type_and_flags_.bits.retain = retain;
ASIO2_ASSERT(type_and_flags_.bits.qos > std::uint8_t(0));
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline publish& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
// The Packet Identifier field is only present in PUBLISH packets where the QoS level is 1 or 2.
// A PUBLISH packet MUST NOT contain a Packet Identifier if its QoS value is set to 0
if ((type_and_flags_.bits.qos == std::uint8_t(0) && packet_id_.has_value()) ||
(type_and_flags_.bits.qos > std::uint8_t(0) && !packet_id_.has_value()))
{
ASIO2_ASSERT(false);
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
}
topic_name_.serialize(buffer);
if (type_and_flags_.bits.qos > std::uint8_t(0) && packet_id_.has_value())
{
packet_id_->serialize(buffer);
}
payload_.serialize(buffer);
return (*this);
}
inline publish& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
topic_name_.deserialize(data);
// A PUBLISH Packet MUST NOT contain a Packet Identifier if its QoS value is set to 0 [MQTT-2.3.1-5].
if (type_and_flags_.bits.qos == 1 || type_and_flags_.bits.qos == 2)
{
two_byte_integer packet_id{};
packet_id.deserialize(data);
packet_id_ = packet_id;
}
payload_ .deserialize(data);
update_remain_length();
return (*this);
}
inline bool dup () { return (type_and_flags_.bits.dup ); }
inline qos_type qos () { return static_cast<qos_type>(type_and_flags_.bits.qos ); }
inline bool retain() { return (type_and_flags_.bits.retain); }
inline publish & dup (bool v) { type_and_flags_.bits.dup = v; return (*this); }
template<class QosOrInt>
inline publish & qos (QosOrInt v) { type_and_flags_.bits.qos = static_cast<std::uint8_t>(v); return (*this); }
inline publish & retain(bool v) { type_and_flags_.bits.retain = v; return (*this); }
inline utf8_string::view_type topic_name() { return topic_name_.data_view(); }
inline two_byte_integer::value_type packet_id () { return packet_id_ ? packet_id_->value() : 0; }
inline application_message::view_type payload () { return payload_.data_view() ; }
inline publish & packet_id (std::uint16_t v) { packet_id_ = v ; return (*this); }
template<class String>
inline publish & topic_name(String&& v) { topic_name_ = std::forward<String>(v); update_remain_length(); return (*this); }
template<class String>
inline publish & payload (String&& v) { payload_ = std::forward<String>(v); update_remain_length(); return (*this); }
inline bool has_packet_id() const noexcept { return packet_id_.has_value(); }
inline publish& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ topic_name_.required_size()
+ (packet_id_ ? packet_id_->required_size() : 0)
+ payload_ .required_size()
);
return (*this);
}
protected:
// The Topic Name identifies the information channel to which Payload data is published.
utf8_string topic_name_{};
// The Packet Identifier field is only present in PUBLISH packets where the QoS level is 1 or 2.
// a Two Byte Integer Packet Identifier.
std::optional<two_byte_integer> packet_id_ {};
// The Payload contains the Application Message that is being published.
// The content and format of the data is application specific.
// The length of the Payload can be calculated by subtracting the length of the Variable Header
// from the Remaining Length field that is in the Fixed Header.
// It is valid for a PUBLISH packet to contain a zero length Payload.
application_message payload_ {};
};
/**
* PUBACK - Publish acknowledgement
*
* A PUBACK Packet is the response to a PUBLISH Packet with QoS level 1.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718043
*/
class puback : public fixed_header<version_number>
{
public:
puback() : fixed_header(control_packet_type::puback)
{
update_remain_length();
}
explicit puback(std::uint16_t packet_id)
: fixed_header(control_packet_type::puback)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline puback& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline puback& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline puback & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline puback& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// This contains the Packet Identifier from the PUBLISH Packet that is being acknowledged.
two_byte_integer packet_id_ {};
};
/**
* PUBREC - Publish received (QoS 2 publish received, part 1)
*
* A PUBREC Packet is the response to a PUBLISH Packet with QoS 2.
* It is the second packet of the QoS 2 protocol exchange.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718048
*/
class pubrec : public fixed_header<version_number>
{
public:
pubrec() : fixed_header(control_packet_type::pubrec)
{
update_remain_length();
}
explicit pubrec(std::uint16_t packet_id)
: fixed_header(control_packet_type::pubrec)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pubrec& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline pubrec& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline pubrec & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline pubrec& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the Packet Identifier from the PUBLISH Packet that is being acknowledged.
two_byte_integer packet_id_ {};
};
/**
* PUBREL - Publish release (QoS 2 publish received, part 2)
*
* A PUBREL Packet is the response to a PUBREC Packet.
* It is the third packet of the QoS 2 protocol exchange.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718053
*/
class pubrel : public fixed_header<version_number>
{
public:
pubrel() : fixed_header(control_packet_type::pubrel)
{
// Bits 3,2,1 and 0 of the Fixed Header in the PUBREL packet are reserved and MUST be
// set to 0,0,1 and 0 respectively.
// The Server MUST treat any other value as malformed and close the Network Connection [MQTT-3.6.1-1].
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
explicit pubrel(std::uint16_t packet_id)
: fixed_header(control_packet_type::pubrel)
, packet_id_ (packet_id)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pubrel& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline pubrel& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline pubrel & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline pubrel& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the same Packet Identifier as the PUBREC Packet that is being acknowledged.
two_byte_integer packet_id_ {};
};
/**
* PUBCOMP - Publish complete (QoS 2 publish received, part 3)
*
* The PUBCOMP Packet is the response to a PUBREL Packet.
* It is the fourth and final packet of the QoS 2 protocol exchange.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718058
*/
class pubcomp : public fixed_header<version_number>
{
public:
pubcomp() : fixed_header(control_packet_type::pubcomp)
{
update_remain_length();
}
explicit pubcomp(std::uint16_t packet_id)
: fixed_header(control_packet_type::pubcomp)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pubcomp& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline pubcomp& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline pubcomp & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline pubcomp& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the same Packet Identifier as the PUBREL Packet that is being acknowledged.
two_byte_integer packet_id_ {};
};
/**
* SUBSCRIBE - Subscribe to topics
*
* The SUBSCRIBE Packet is sent from the Client to the Server to create one or more Subscriptions.
* Each Subscription registers a Client's interest in one or more Topics.
* The Server sends PUBLISH Packets to the Client in order to forward Application Messages that were
* published to Topics that match these Subscriptions.
* The SUBSCRIBE Packet also specifies (for each Subscription) the maximum QoS with which the Server
* can send Application Messages to the Client.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718063
*/
class subscribe : public fixed_header<version_number>
{
public:
subscribe() : fixed_header(control_packet_type::subscribe)
{
// Bits 3,2,1 and 0 of the fixed header of the SUBSCRIBE Control Packet are reserved and MUST be
// set to 0,0,1 and 0 respectively. The Server MUST treat any other value as malformed and close
// the Network Connection [MQTT-3.8.1-1].
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
explicit subscribe(std::uint16_t packet_id)
: fixed_header(control_packet_type::subscribe)
, packet_id_ (packet_id)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline subscribe& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
subscriptions_.serialize(buffer);
return (*this);
}
inline subscribe& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
subscriptions_.deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline subscriptions_set& subscriptions() { return subscriptions_ ; }
inline subscribe & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Subscriptions>
inline subscribe& add_subscriptions(Subscriptions&&... Subscripts)
{
subscriptions_.add(std::forward<Subscriptions>(Subscripts)...);
update_remain_length();
return (*this);
}
inline subscribe& erase_subscription(std::string_view topic_filter)
{
subscriptions_.erase(topic_filter);
update_remain_length();
return (*this);
}
inline subscribe& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ subscriptions_.required_size()
);
return (*this);
}
protected:
// The variable header contains a Packet Identifier.
two_byte_integer packet_id_ {};
// The payload of a SUBSCRIBE Packet contains a list of Topic Filters indicating the Topics
// to which the Client wants to subscribe. The Topic Filters in a SUBSCRIBE packet payload
// MUST be UTF-8 encoded strings as defined in Section 1.5.3 [MQTT-3.8.3-1]. A Server SHOULD
// support Topic filters that contain the wildcard characters defined in Section 4.7.1. If
// it chooses not to support topic filters that contain wildcard characters it MUST reject
// any Subscription request whose filter contains them [MQTT-3.8.3-2]. Each filter is
// followed by a byte called the Requested QoS. This gives the maximum QoS level at which
// the Server can send Application Messages to the Client.
subscriptions_set subscriptions_{};
};
/**
* SUBACK - Subscribe acknowledgement
*
* A SUBACK Packet is sent by the Server to the Client to confirm receipt and processing of a SUBSCRIBE Packet.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718068
*/
class suback : public fixed_header<version_number>
{
public:
suback() : fixed_header(control_packet_type::suback)
{
update_remain_length();
}
explicit suback(std::uint16_t packet_id)
: fixed_header(control_packet_type::suback)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline suback& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
reason_codes_ .serialize(buffer);
return (*this);
}
inline suback& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
reason_codes_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline one_byte_integer_set & reason_codes () { return reason_codes_ ; }
inline suback & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Integers>
inline suback& add_reason_codes(Integers... Ints)
{
reason_codes_.add(static_cast<one_byte_integer::value_type>(Ints)...);
update_remain_length();
return (*this);
}
inline suback& erase_reason_code(std::size_t index)
{
reason_codes_.erase(index);
update_remain_length();
return (*this);
}
inline suback& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ reason_codes_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the Packet Identifier from the SUBSCRIBE Packet that is being acknowledged.
two_byte_integer packet_id_ {};
// The payload contains a list of return codes. Each return code corresponds to a Topic Filter
// in the SUBSCRIBE Packet being acknowledged. The order of return codes in the SUBACK Packet
// MUST match the order of Topic Filters in the SUBSCRIBE Packet [MQTT-3.9.3-1].
one_byte_integer_set reason_codes_{};
};
/**
* UNSUBSCRIBE - Unsubscribe from topics
*
* An UNSUBSCRIBE Packet is sent by the Client to the Server, to unsubscribe from topics.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718072
*/
class unsubscribe : public fixed_header<version_number>
{
public:
unsubscribe() : fixed_header(control_packet_type::unsubscribe)
{
// Bits 3,2,1 and 0 of the Fixed Header of the UNSUBSCRIBE packet are reserved and MUST
// be set to 0,0,1 and 0 respectively. The Server MUST treat any other value as malformed
// and close the Network Connection [MQTT-3.10.1-1].
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
template<class... Strings>
explicit unsubscribe(std::uint16_t packet_id, Strings&&... topic_filters)
: fixed_header (control_packet_type::unsubscribe)
, packet_id_ (packet_id)
, topic_filters_(std::forward<Strings>(topic_filters)...)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline unsubscribe& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
topic_filters_.serialize(buffer);
return (*this);
}
inline unsubscribe& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
topic_filters_.deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline utf8_string_set & topic_filters() { return topic_filters_ ; }
inline unsubscribe & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Strings>
inline unsubscribe& add_topic_filters(Strings&&... Strs)
{
topic_filters_.add(std::forward<Strings>(Strs)...);
update_remain_length();
return (*this);
}
inline unsubscribe& erase_topic_filter(std::string_view topic_filter)
{
topic_filters_.erase(topic_filter);
update_remain_length();
return (*this);
}
inline unsubscribe& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ topic_filters_.required_size()
);
return (*this);
}
protected:
// The variable header contains a Packet Identifier.
two_byte_integer packet_id_ {};
// The payload for the UNSUBSCRIBE Packet contains the list of Topic Filters that the Client
// wishes to unsubscribe from. The Topic Filters in an UNSUBSCRIBE packet MUST be UTF-8
// encoded strings as defined in Section 1.5.3, packed contiguously [MQTT-3.10.3-1].
// The Payload of an UNSUBSCRIBE packet MUST contain at least one Topic Filter.An UNSUBSCRIBE
// packet with no payload is a protocol violation[MQTT - 3.10.3 - 2].See section 4.8 for
// information about handling errors.
utf8_string_set topic_filters_{};
};
/**
* UNSUBACK - Unsubscribe acknowledgement
*
* The UNSUBACK packet is sent by the Server to the Client to confirm receipt of an UNSUBSCRIBE packet.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718077
*/
class unsuback : public fixed_header<version_number>
{
public:
unsuback() : fixed_header(control_packet_type::unsuback)
{
update_remain_length();
}
explicit unsuback(std::uint16_t packet_id)
: fixed_header(control_packet_type::unsuback)
, packet_id_ (packet_id)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline unsuback& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
return (*this);
}
inline unsuback& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline unsuback & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline unsuback& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
);
return (*this);
}
protected:
// The variable header contains the Packet Identifier of the UNSUBSCRIBE Packet that is being acknowledged.
two_byte_integer packet_id_ {};
// The UNSUBACK Packet has no payload.
};
/**
* PINGREQ - PING request
*
* The PINGREQ packet is sent from a Client to the Server.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718081
*/
class pingreq : public fixed_header<version_number>
{
public:
pingreq() : fixed_header(control_packet_type::pingreq)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pingreq& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
return (*this);
}
inline pingreq& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
update_remain_length();
return (*this);
}
inline pingreq& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
);
return (*this);
}
protected:
// The PINGREQ packet has no Variable Header.
// The PINGREQ packet has no Payload.
};
/**
* PINGRESP - PING response
*
* A PINGRESP Packet is sent by the Server to the Client in response to a PINGREQ packet.
* It indicates that the Server is alive.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718086
*/
class pingresp : public fixed_header<version_number>
{
public:
pingresp() : fixed_header(control_packet_type::pingresp)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pingresp& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
return (*this);
}
inline pingresp& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
update_remain_length();
return (*this);
}
inline pingresp& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
);
return (*this);
}
protected:
// The PINGRESP packet has no Variable Header.
// The PINGRESP packet has no Payload.
};
/**
* DISCONNECT - Disconnect notification
*
* The DISCONNECT Packet is the final Control Packet sent from the Client to the Server.
* It indicates that the Client is disconnecting cleanly.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718090
*/
class disconnect : public fixed_header<version_number>
{
public:
disconnect() : fixed_header(control_packet_type::disconnect)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline disconnect& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
return (*this);
}
inline disconnect& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
update_remain_length();
return (*this);
}
inline disconnect& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
);
return (*this);
}
protected:
// The DISCONNECT Packet has no variable header.
// The DISCONNECT Packet has no payload.
};
}
namespace asio2::mqtt
{
template<typename = void>
inline constexpr std::string_view to_string(v4::connect_reason_code v)
{
using namespace std::string_view_literals;
switch(v)
{
case v4::connect_reason_code::success : return "Connection accepted"sv;
case v4::connect_reason_code::unacceptable_protocol_version : return "The Server does not support the level of the MQTT protocol requested by the Client"sv;
case v4::connect_reason_code::identifier_rejected : return "The Client identifier is correct UTF-8 but not allowed by the Server"sv;
case v4::connect_reason_code::server_unavailable : return "The Network Connection has been made but the MQTT service is unavailable"sv;
case v4::connect_reason_code::bad_user_name_or_password : return "The data in the user name or password is malformed"sv;
case v4::connect_reason_code::not_authorized : return "The Client is not authorized to connect"sv;
default:
ASIO2_ASSERT(false);
break;
}
return "unknown"sv;
}
template<typename message_type>
inline constexpr bool is_v4_message()
{
using type = asio2::detail::remove_cvref_t<message_type>;
if constexpr (
std::is_same_v<type, mqtt::v4::connect > ||
std::is_same_v<type, mqtt::v4::connack > ||
std::is_same_v<type, mqtt::v4::publish > ||
std::is_same_v<type, mqtt::v4::puback > ||
std::is_same_v<type, mqtt::v4::pubrec > ||
std::is_same_v<type, mqtt::v4::pubrel > ||
std::is_same_v<type, mqtt::v4::pubcomp > ||
std::is_same_v<type, mqtt::v4::subscribe > ||
std::is_same_v<type, mqtt::v4::suback > ||
std::is_same_v<type, mqtt::v4::unsubscribe > ||
std::is_same_v<type, mqtt::v4::unsuback > ||
std::is_same_v<type, mqtt::v4::pingreq > ||
std::is_same_v<type, mqtt::v4::pingresp > ||
std::is_same_v<type, mqtt::v4::disconnect > )
{
return true;
}
else
{
return false;
}
}
}
#endif // !__ASIO2_MQTT_PROTOCOL_V4_HPP__
<file_sep>#ifndef BHO_ENDIAN_DETAIL_IS_TRIVIALLY_COPYABLE_HPP_INCLUDED
#define BHO_ENDIAN_DETAIL_IS_TRIVIALLY_COPYABLE_HPP_INCLUDED
// Copyright 2019 <NAME>
//
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/config.hpp>
#include <type_traits>
#if !defined(BHO_NO_CXX11_HDR_TYPE_TRAITS)
# include <type_traits>
#endif
namespace bho
{
namespace endian
{
namespace detail
{
#if !defined(BHO_NO_CXX11_HDR_TYPE_TRAITS)
using std::is_trivially_copyable;
#else
template<class T> struct is_trivially_copyable: std::integral_constant<bool,
std::is_trivially_copyable<T>::value && std::is_trivially_assignable<T>::value && std::is_trivially_destructible<T>::value> {};
#endif
} // namespace detail
} // namespace endian
} // namespace bho
#endif // BHO_ENDIAN_DETAIL_IS_TRIVIALLY_COPYABLE_HPP_INCLUDED
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_MODENA_H
#define BHO_PREDEF_LIBRARY_STD_MODENA_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_MSIPL`
http://modena.us/[Modena Software Lib++] Standard {CPP} Library.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `MSIPL_COMPILE_H` | {predef_detection}
| `+__MSIPL_COMPILE_H+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_LIB_STD_MSIPL BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(MSIPL_COMPILE_H) || defined(__MSIPL_COMPILE_H)
# undef BHO_LIB_STD_MSIPL
# define BHO_LIB_STD_MSIPL BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_LIB_STD_MSIPL
# define BHO_LIB_STD_MSIPL_AVAILABLE
#endif
#define BHO_LIB_STD_MSIPL_NAME "Modena Software Lib++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_MSIPL,BHO_LIB_STD_MSIPL_NAME)
<file_sep>#include "unit_test.hpp"
#include <asio2/config.hpp>
#ifndef ASIO2_ENABLE_LOG
#define ASIO2_ENABLE_LOG
#endif
#include <asio2/asio2.hpp>
void shared_iopool_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
asio2::iopool iopool(4);
// iopool must start first, othwise the server.start will blocked forever.
iopool.start();
ASIO2_CHECK(iopool.stopped() == false);
ASIO2_CHECK(std::addressof(iopool.get()) != nullptr);
ASIO2_CHECK(std::addressof(iopool.get_context()) != nullptr);
ASIO2_CHECK(iopool.running_in_threads() == false);
ASIO2_CHECK(iopool.running_in_thread(0) == false);
ASIO2_CHECK(iopool.running_in_thread(1) == false);
ASIO2_CHECK(iopool.running_in_thread(2) == false);
ASIO2_CHECK(iopool.running_in_thread(3) == false);
ASIO2_CHECK(iopool.size() == 4);
ASIO2_CHECK(iopool.get_thread_id(0) != std::this_thread::get_id());
ASIO2_CHECK(iopool.get_thread_id(1) != std::this_thread::get_id());
ASIO2_CHECK(iopool.get_thread_id(2) != std::this_thread::get_id());
ASIO2_CHECK(iopool.get_thread_id(3) != std::this_thread::get_id());
ASIO2_CHECK(iopool.next(30) != 30);
iopool.wait_for(std::chrono::milliseconds(10));
iopool.wait_until(std::chrono::steady_clock::now() + std::chrono::milliseconds(10));
ASIO2_CHECK(loop < loops);
if (loop > loops)
{
iopool.wait_signal(SIGINT);
}
iopool.post([]() {});
iopool.post(0, []() {});
iopool.post(1, []() {});
iopool.post(2, []() {});
iopool.post(3, []() {});
std::vector<std::shared_ptr<std::thread>> threads;
//// --------------------------------------------------------------------------------
// compile test, just for test the constructor sfinae
asio2::tcp_server _server1(1024);
asio2::tcp_server _server2(1024, 65535);
asio2::tcp_server _server3(1024, 65535, 4);
asio2::tcp_server _server5(1024, 65535, std::vector{ &iopool.get(0), &iopool.get(1) });
asio2::tcp_server _server6(1024, 65535, std::list { &iopool.get(0), &iopool.get(1) });
asio2::rpc_server _server7(1024, 65535, &iopool.get(0));
asio2::http_server _server8(1024, 65535, iopool.get(0));
asio2::udp_server _servera(std::vector<asio2::io_t*>{ &iopool.get(0), &iopool.get(1) });
asio2::ws_server _serverb(std::list <asio2::io_t*>{ &iopool.get(0), &iopool.get(1) });
asio2::tcp_server _serverc(&iopool.get(0));
asio2::tcp_server _serverd( iopool.get(0));
asio2::tcp_server _servere( iopool);
ASIO2_CHECK(_server5.iopool().stopped() == true);
ASIO2_CHECK(std::addressof(_server5.iopool().get(10)) != nullptr);
ASIO2_CHECK(_server5.iopool().size() == 2);
ASIO2_CHECK(_server5.iopool().running_in_threads() == false);
asio2::tcp_client _client1(1024);
asio2::tcp_client _client2(1024, 65535);
asio2::tcp_client _client3(1024, 65535, 4);
asio2::tcp_client _client5(1024, 65535, std::vector{ &iopool.get(0) });
asio2::tcp_client _client6(1024, 65535, std::list { &iopool.get(0) });
asio2::tcp_client _client7(1024, 65535, &iopool.get(0));
asio2::tcp_client _client8(1024, 65535, iopool.get(0));
asio2::http_client _clienta(std::vector<asio2::io_t*>{ &iopool.get(0) });
asio2::ws_client _clientb(std::list <asio2::io_t*>{ &iopool.get(0) });
asio2::udp_client _clientc(&iopool.get(0));
asio2::rpc_client _clientd( iopool.get(0));
asio2::serial_port _sp1 ( iopool.get(1));
asio2::udp_cast _cast1(&iopool.get(2));
asio2::ping _ping1(&iopool.get(3));
//// --------------------------------------------------------------------------------
int index = std::rand() % iopool.size();
#define iothread_check \
[&iopool, index]() \
{ \
ASIO2_CHECK(iopool.running_in_thread(index)); \
}
#define iothreads_check \
[&iopool]() \
{ \
ASIO2_CHECK(iopool.running_in_threads()); \
}
//// --------------------------------------------------------------------------------
#undef ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR
#define timer_check \
[&iopool, index]() \
{ \
ASIO2_CHECK(iopool.running_in_thread(index)); \
ASIO2_CHECK(!asio2::get_last_error()); \
}
asio2::timer t1(iopool.get(index));
t1.start_timer("3011", std::chrono::milliseconds(10), timer_check);
t1.start_timer("3012", std::chrono::milliseconds(10), std::chrono::milliseconds(10), timer_check);
t1.start_timer("3013", std::chrono::milliseconds(10), 3, timer_check);
t1.start_timer("3014", std::chrono::milliseconds(10), 3, std::chrono::milliseconds(10), timer_check);
t1.post([&t1, &iopool, index]()
{
t1.start_timer("3021", std::chrono::milliseconds(10), timer_check);
t1.start_timer("3022", std::chrono::milliseconds(10), std::chrono::milliseconds(10), timer_check);
t1.start_timer("3023", std::chrono::milliseconds(10), 3, timer_check);
t1.start_timer("3024", std::chrono::milliseconds(10), 3, std::chrono::milliseconds(10), timer_check);
});
std::thread([&t1, &iopool, index]()
{
t1.start_timer(3031, std::chrono::milliseconds(10), timer_check);
t1.start_timer(3032, std::chrono::milliseconds(10), std::chrono::milliseconds(10), timer_check);
t1.start_timer(3033, std::chrono::milliseconds(10), 3, timer_check);
t1.start_timer(3034, std::chrono::milliseconds(10), 3, std::chrono::milliseconds(10), timer_check);
t1.post([&t1, &iopool, index]()
{
t1.start_timer(3041, std::chrono::milliseconds(10), timer_check);
t1.start_timer(3042, std::chrono::milliseconds(10), std::chrono::milliseconds(10), timer_check);
t1.start_timer(3043, std::chrono::milliseconds(10), 3, timer_check);
t1.start_timer(3044, std::chrono::milliseconds(10), 3, std::chrono::milliseconds(10), timer_check);
});
}).join();
//// --------------------------------------------------------------------------------
index = std::rand() % iopool.size();
asio2::udp_cast cast1(iopool.get(index));
cast1.start_timer(1, std::chrono::seconds(1), timer_check);
auto ptr = cast1.post_condition_event(iothread_check);
cast1.post(iothread_check, std::chrono::milliseconds(std::rand() % 50));
threads.emplace_back(std::make_shared<std::thread>([ptr]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(50 + std::rand() % 2));
ptr->notify();
}));
std::this_thread::sleep_for(std::chrono::milliseconds(2 + std::rand() % 5));
ptr->notify();
cast1.start("0.0.0.0", 4444);
std::this_thread::sleep_for(std::chrono::milliseconds(2 + std::rand() % 5));
cast1.stop();
cast1.start_timer(1, std::chrono::seconds(1), timer_check);
cast1.post(iothread_check, std::chrono::milliseconds(std::rand() % 50));
ptr = cast1.post_condition_event(iothread_check);
threads.emplace_back(std::make_shared<std::thread>([ptr]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(50 + std::rand() % 2));
ptr->notify();
}));
ptr.reset();
ptr = cast1.post_condition_event(iothread_check);
//-----------------------------------------------------------------------------------
index = 0;
asio2::tcp_server server(std::vector<asio2::io_t*>{
&iopool.get(0), &iopool.get(1), &iopool.get(2), &iopool.get(3) });
server.wait_for(std::chrono::milliseconds(10));
server.wait_until(std::chrono::steady_clock::now() + std::chrono::milliseconds(10));
ASIO2_CHECK(loop < loops);
if (loop > loops)
{
server.wait_signal(SIGINT);
server.wait_stop();
}
// the server's io_context must be the user passed io_context.
for (std::size_t i = 0; i < server.iopool().size(); i++)
{
[[maybe_unused]] asio::io_context& ioc1 = iopool.get(i).context();
[[maybe_unused]] asio::io_context& ioc2 = server.iopool().get(i).context();
ASIO2_CHECK(&ioc1 == &ioc2);
}
server.start_timer(1, std::chrono::seconds(1), timer_check); // test timer
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view sv)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
iothreads_check();
session_ptr->async_send(sv);
}).bind_connect([&](auto & session_ptr)
{
ASIO2_CHECK(iopool.running_in_thread(0));
session_ptr->start_timer(2, std::chrono::seconds(1), iothreads_check); // test timer
}).bind_disconnect([&](auto & session_ptr)
{
asio2::ignore_unused(session_ptr);
ASIO2_CHECK(iopool.running_in_thread(0));
}).bind_start([&]()
{
ASIO2_CHECK(iopool.running_in_thread(0));
}).bind_stop([&]()
{
ASIO2_CHECK(iopool.running_in_thread(0));
});
server.start("127.0.0.1", 39001);
//-----------------------------------------------------------------------------------
index = std::rand() % iopool.size();
// if you create a object and it will destroyed before iopool.stop(), you must create
// the object as shared_ptr<asio2::tcp_client>, can't be asio2::tcp_client.
{
std::shared_ptr<asio2::tcp_client> tcp_client = std::make_shared<asio2::tcp_client>(iopool.get(index));
tcp_client->start("127.0.0.1", 39001);
tcp_client->async_send("i love you", iothread_check);
//tcp_client->stop();
std::this_thread::sleep_for(std::chrono::milliseconds(2 + std::rand() % 2));
}
asio2::tcp_client client(iopool.get(index));
client.auto_reconnect(true, std::chrono::milliseconds(1000));
client.start_timer(1, std::chrono::seconds(1), timer_check); // test timer
client.bind_connect([&, index]()
{
ASIO2_CHECK(iopool.running_in_thread(index));
std::string str(std::size_t(100 + (std::rand() % 300)), char(std::rand() % 255));
client.async_send(std::move(str), iothread_check);
}).bind_disconnect([&]()
{
ASIO2_CHECK(iopool.running_in_thread(index));
}).bind_recv([&, index](std::string_view sv)
{
ASIO2_CHECK(iopool.running_in_thread(index));
client.async_send(sv, iothread_check);
});
client.async_start("127.0.0.1", 39001);
std::this_thread::sleep_for(std::chrono::milliseconds(20 + std::rand() % 10));
cast1.stop();
client.stop();
server.stop();
t1.stop();
iopool.stop();
ASIO2_CHECK(client.is_stopped());
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK(cast1 .is_stopped());
ASIO2_CHECK(iopool.stopped());
//// --------------------------------------------------------------------------------
// iopool must start first, othwise the server.start will blocked forever.
iopool.start();
t1.post([&t1]()
{
t1.start_timer(1, std::chrono::seconds(1), []() {});
});
cast1.start_timer(1, std::chrono::seconds(1), []() {});
ptr = cast1.post_condition_event([]() {});
cast1.post([]()
{
}, std::chrono::milliseconds(std::rand() % 50));
threads.emplace_back(std::make_shared<std::thread>([ptr]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(10 + std::rand() % 10));
ptr->notify();
}));
std::this_thread::sleep_for(std::chrono::milliseconds(2 + std::rand() % 2));
ptr->notify();
cast1.start("0.0.0.0", 4444);
std::this_thread::sleep_for(std::chrono::milliseconds(10 + std::rand() % 10));
cast1.stop();
cast1.start_timer(1, std::chrono::seconds(1), []() {});
cast1.post([]()
{
}, std::chrono::milliseconds(std::rand() % 50));
ptr = cast1.post_condition_event([]() {});
threads.emplace_back(std::make_shared<std::thread>([ptr]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(10 + std::rand() % 10));
ptr->notify();
}));
ptr.reset();
ptr = cast1.post_condition_event([]() {});
cast1.start("0.0.0.0", 4444);
//-----------------------------------------------------------------------------------
// the server's io_context must be the user passed io_context.
for (std::size_t i = 0; i < server.iopool().size(); i++)
{
[[maybe_unused]] asio::io_context& ioc1 = iopool.get(i).context();
[[maybe_unused]] asio::io_context& ioc2 = server.iopool().get(i).context();
ASIO2_CHECK(&ioc1 == &ioc2);
}
server.bind_recv([&](std::shared_ptr<asio2::tcp_session>& session_ptr, std::string_view s)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
session_ptr->async_send(s);
}).bind_connect([&](std::shared_ptr<asio2::tcp_session>&)
{
ASIO2_CHECK(iopool.running_in_thread(0));
}).bind_disconnect([&](std::shared_ptr<asio2::tcp_session>&)
{
ASIO2_CHECK(iopool.running_in_thread(0));
}).bind_start([&]()
{
ASIO2_CHECK(iopool.running_in_thread(0));
}).bind_stop([&]()
{
ASIO2_CHECK(iopool.running_in_thread(0));
});
server.start("127.0.0.1", 39001);
//-----------------------------------------------------------------------------------
client.start_timer(1, std::chrono::seconds(1), []() {}); // test timer
client.bind_connect([&]()
{
std::string s(std::size_t(100 + (std::rand() % 300)), char(std::rand() % 255));
client.async_send(std::move(s));
}).bind_disconnect([&]()
{
}).bind_recv([&](std::string_view sv)
{
client.async_send(sv);
});
client.async_start("127.0.0.1", 39001);
std::this_thread::sleep_for(std::chrono::milliseconds(20 + std::rand() % 80));
//cast1.stop();
//client.stop();
//server.stop();
//t1.stop();
// the iopool.stop will cal all "server,client,timer,serial_port,ping" objects stop();
iopool.stop();
ASIO2_CHECK(client.is_stopped());
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK(cast1 .is_stopped());
ASIO2_CHECK(iopool.stopped());
for (auto& thread : threads)
{
//thread->join();
thread->detach();
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"shared_iopool",
ASIO2_TEST_CASE(shared_iopool_test)
)
<file_sep># 1. Install Android NDK (my installed version is android-ndk-r22b)
# 2. Open cmd.exe, enter this directory(\asio2\example\ndk\jni\), run "ndk-build"
# all arm64-v8a armeabi-v7a x86 x86_64
# APP_ABI := arm64-v8a
APP_PLATFORM := android-16
APP_STL += c++_static
APP_CPPFLAGS += -fexceptions -frtti
APP_CPPFLAGS +=-std=c++17
APP_OPTIM := release
<file_sep>#include <asio2/tcp/tcp_client.hpp>
class clt_listener
{
public:
void on_connect(asio2::tcp_client& client)
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n", client.local_address().c_str(), client.local_port());
std::string str;
int len = 128 + std::rand() % (300);
for (int i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
str += "\r\n";
client.async_send(std::move(str));
}
void on_disconnect()
{
printf("disconnect : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}
void on_recv(asio2::tcp_client& client, std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
std::string str;
int len = 128 + std::rand() % (300);
for (int i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
str += "\r\n";
// this is just a demo to show :
// even if we force one packet data to be sent twice,
// but the server must recvd whole packet once
client.async_send(str.substr(0, str.size() / 2));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
client.async_send(str.substr(str.size() / 2));
// of course you can sent the whole data once
//client.async_send(std::move(str));
}
};
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8025";
asio2::tcp_client client;
clt_listener listener;
// bind member function
client
.bind_disconnect(&clt_listener::on_disconnect, listener)
.bind_connect (&clt_listener::on_connect , listener, std::ref(client)) // not use std::bind
.bind_recv (&clt_listener::on_recv , listener, std::ref(client)); // not use std::bind
// Split data with a single character
//client.start(host, port, '\n');
// Split data with string
client.start(host, port, "\r\n");
while (std::getchar() != '\n');
return 0;
}
<file_sep>#ifndef ASIO2_USE_SSL
#define ASIO2_USE_SSL
#endif
#ifndef ASIO2_INCLUDE_RATE_LIMIT
#define ASIO2_INCLUDE_RATE_LIMIT
#endif
#ifndef ASIO2_USE_WEBSOCKET_RPC
#define ASIO2_USE_WEBSOCKET_RPC
#endif
#include "unit_test.hpp"
#include <asio2/asio2.hpp>
#include <asio2/external/fmt.hpp>
std::string_view server_key = R"(
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,32DBC28981A12AF1
<KEY>
-----END RSA PRIVATE KEY-----
)";
std::string_view server_crt = R"(
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 1 (0x1)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=AU, ST=HENAN, L=ZHENGZHOU, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=<EMAIL>@<EMAIL>
Validity
Not Before: Nov 26 08:21:41 2021 GMT
Not After : Nov 24 08:21:41 2031 GMT
Subject: C=AU, ST=HENAN, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=37792738@qq.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (1024 bit)
Modulus:
00:c4:ba:4e:5f:22:45:ac:74:8f:5a:c3:06:4b:b4:
a6:22:be:68:7b:99:bf:44:02:66:69:09:ec:2c:7a:
68:c9:a9:0a:b2:f4:ed:69:6b:ad:29:59:b7:a6:ff:
69:df:f6:e5:45:44:d7:70:a7:40:84:d6:19:dd:c4:
36:27:86:1d:6d:79:e0:91:e5:77:79:49:28:4f:06:
7f:31:70:8b:ec:c2:58:9c:f4:14:1d:29:bb:2c:5a:
82:c2:b5:ca:de:eb:cb:a8:34:fc:7b:eb:48:76:44:
ed:29:a1:7d:99:3c:ad:a9:3d:8c:8d:ef:12:ef:d5:
fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:a9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
9B:D5:B6:0E:47:C3:A7:B6:DA:84:3B:F0:CE:D1:50:D3:8F:4F:0A:8A
X509v3 Authority Key Identifier:
keyid:61:74:1F:7E:B1:0E:0D:F9:46:DD:6A:97:85:72:DE:1A:7D:A2:34:65
Signature Algorithm: sha256WithRSAEncryption
b6:1e:bb:f7:fa:c5:9f:07:6e:36:9d:2e:7d:39:8e:a1:ed:f1:
65:a0:0c:e4:bb:6d:bc:eb:58:d5:1d:c2:03:57:8a:41:0a:f1:
81:0f:87:38:c4:56:83:c3:9d:dc:f3:47:88:c8:a7:ba:69:f9:
bb:45:1f:73:48:96:f9:d7:fc:da:73:f9:17:5f:2f:94:19:83:
27:4b:b0:3e:19:29:71:a2:fc:db:d2:5f:6e:4f:e5:f1:d8:35:
55:f8:d9:db:75:dc:fe:11:e0:9f:70:6e:a8:26:2a:ca:7e:25:
08:e1:d5:d8:e3:0b:10:48:c6:ae:c5:b4:7b:15:20:87:97:20:
31:ee:e1:6f:d7:be:41:5d:2a:22:b0:36:16:1d:7a:70:bc:1b:
d3:89:94:ae:33:66:0c:cd:39:95:9e:69:30:37:05:bb:62:cd:
3f:dd:2b:bb:72:16:48:75:91:33:33:ae:b7:d7:2d:bd:ce:66:
f3:6b:69:81:fa:0d:aa:0e:5a:09:9d:24:54:ac:21:9b:14:43:
44:12:56:8b:cc:13:b5:3b:5a:ba:4e:7b:81:42:1e:38:61:ff:
a0:a7:01:2f:0b:67:77:90:48:bb:8a:52:62:69:76:3c:a8:a1:
d6:13:1e:27:f6:02:58:ae:91:4b:9d:37:4e:31:55:73:18:4e:
d0:61:54:3b
-----BEGIN CERTIFICATE-----
<KEY>04xVXMYTtBhVDs=
-----END CERTIFICATE-----
)";
std::string_view ca_crt = R"(
-----BEGIN CERTIFICATE-----
<KEY>
-----END CERTIFICATE-----
)";
std::string_view dh = R"(
-----BEGIN DH PARAMETERS-----
<KEY>DTZxIWkwr09JD7c
J5fipXRE8kFry0Nk9lL96seMYoER32zw6y2tXgUeksVrjOkGuheTAgEC
-----END DH PARAMETERS-----
)";
std::string_view client_key = R"(
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,967AA0B1DF77C592
<KEY>
)";
std::string_view client_crt = R"(
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 2 (0x2)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=AU, ST=HENAN, L=ZHENGZHOU, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=<EMAIL>
Validity
Not Before: Nov 26 09:04:13 2021 GMT
Not After : Nov 24 09:04:13 2031 GMT
Subject: C=AU, ST=HENAN, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=<EMAIL>
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (1024 bit)
Modulus:
00:be:94:6f:5b:ae:20:a8:73:25:3f:a8:4d:92:5a:
5b:8b:64:4d:7b:53:2c:fb:10:e9:ad:e5:06:41:5a:
f6:eb:58:9a:22:6b:5c:ac:04:03:c5:09:2a:3d:84:
fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:64:cd:5d:ce:ee:03:54:
da:af:dd:da:f2:b4:93:72:3f:26:d6:57:ea:18:ec:
9c:c8:20:bc:1a:a1:f9:e0:f5:64:67:9d:61:b8:f6:
87:a4:d3:36:01:24:b4:e7:00:c3:54:82:bd:7f:22:
48:40:df:43:8c:26:83:aa:b3:68:5d:e9:a1:fe:7c:
fc00:e968:6179::de52:7100:25
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
fc00:db20:35b:7399::5:3C:1C:5C:58:96:08:59:94:A5:7A:A1:22
X509v3 Authority Key Identifier:
keyid:61:74:1F:7E:B1:0E:0D:F9:46:DD:6A:97:85:72:DE:1A:7D:A2:34:65
Signature Algorithm: sha256WithRSAEncryption
39:c1:66:e0:1a:68:2a:bc:6e:56:a0:a4:18:53:ac:2e:49:03:
d3:df:e0:7d:4e:51:4c:0b:fb:f9:1d:ae:a5:b8:16:b1:b6:23:
db:62:33:25:72:14:99:e1:3a:1a:52:d2:f4:51:74:ef:df:04:
fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:60:05:d5:65:09:6c:44:14:e6:29:
b8:51:03:e0:bd:33:c3:9d:da:99:24:eb:a8:76:18:88:14:84:
83:ee:33:a3:5c:05:9a:3c:e3:f0:35:e3:52:a2:4e:aa:39:07:
fc00:db20:35b:7399::5:a9:90:ef:5a:53:3b:5b:c7:4d:bb:
76:05:70:eb:a7:15:22:ad:b5:ed:3b:74:58:71:c0:53:90:44:
fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:66:ee:18:53:d4:4c:5e:d6:29:f4:
4c:18:2c:7a:79:96:38:d7:cf:51:e4:3b:72:9f:9c:be:7f:2e:
05:8a:06:18:61:62:d5:9c:cc:31:a7:4c:d9:94:bd:d3:b4:22:
b8:42:d2:6f:99:7a:72:43:b3:a9:03:e2:36:6d:6b:28:4f:f8:
c5:b5:1b:2b:1d:e9:34:8f:66:0a:13:58:d5:28:38:03:22:bc:
37:27:ed:c7:b3:c7:80:63:25:d7:fc:38:ad:ac:f9:aa:5b:07:
15:df:56:17
-----BEGIN CERTIFICATE-----
<KEY>
-----END CERTIFICATE-----
)";
void rate_limit_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
// tcp
{
asio2::tcp_rate_server server;
server.bind_connect([](std::shared_ptr<asio2::tcp_rate_session>& session_ptr)
{
// set the send rate
session_ptr->socket().rate_policy().write_limit(256);
// set the recv rate
session_ptr->socket().rate_policy().read_limit(256);
}).bind_recv([](auto& session_ptr, std::string_view data)
{
ASIO2_CHECK(data.size() <= 256);
session_ptr->async_send(data);
});
server.start("0.0.0.0", 18102);
asio2::tcp_rate_client client;
client.bind_connect([&client]()
{
// set the send rate
client.socket().rate_policy().write_limit(512);
client.socket().rate_policy().read_limit(512);
ASIO2_CHECK(!asio2::get_last_error());
if (!asio2::get_last_error())
{
std::string str;
for (int i = 0; i < 1024; i++)
{
str += '0' + std::rand() % 64;
}
client.async_send(str);
}
}).bind_recv([&client](std::string_view data)
{
ASIO2_CHECK_VALUE(data.size(), data.size() <= 512);
client.async_send(data);
});
client.start("127.0.0.1", 18102);
std::thread([&client]()
{
// note: if you set the rate in the other thread which is not the io_context
// thread, you should use post function to make the operation is executed in
// the io_context thread, otherwise it is not thread safety.
client.post([&client]()
{
// set the recv rate
client.socket().rate_policy().read_limit(512);
});
}).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
// tcps
{
asio2::tcps_rate_server server;
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
server.bind_connect([](std::shared_ptr<asio2::tcps_rate_session>& session_ptr)
{
// set the send rate
session_ptr->socket().rate_policy().write_limit(256);
// set the recv rate
session_ptr->socket().rate_policy().read_limit(256);
}).bind_recv([](auto& session_ptr, std::string_view data)
{
session_ptr->async_send(data);
ASIO2_CHECK(data.size() <= 256);
});
server.start("0.0.0.0", 18102);
asio2::tcps_rate_client client;
client.set_connect_timeout(std::chrono::seconds(10));
client.auto_reconnect(true, std::chrono::seconds(3));
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
client.bind_connect([&client]()
{
// set the send rate
client.socket().rate_policy().write_limit(512);
ASIO2_CHECK(!asio2::get_last_error());
if (!asio2::get_last_error())
{
std::string str;
// when used ssl, if the message size greate than the read limit,
// maybe cause some problem.
for (int i = 0; i < 32; i++)
{
str += '0' + std::rand() % 64;
}
client.async_send(str);
}
}).bind_recv([&client](std::string_view data)
{
client.async_send(data);
ASIO2_CHECK(data.size() <= 256);
});
client.start("127.0.0.1", 18102);
std::thread([&client]()
{
// note: if you set the rate in the other thread which is not the io_context
// thread, you should use post function to make the operation is executed in
// the io_context thread, otherwise it is not thread safety.
client.post([&client]()
{
// set the recv rate
client.socket().rate_policy().read_limit(512);
});
}).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
// rpc
{
asio2::rpc_rate_server server;
server.bind_connect([](std::shared_ptr<asio2::rpc_rate_session>& session_ptr)
{
// set the send rate
session_ptr->socket().rate_policy().write_limit(256);
// set the recv rate
session_ptr->socket().rate_policy().read_limit(256);
}).bind_recv([](auto& session_ptr, std::string_view data)
{
asio2::ignore_unused(session_ptr, data);
});
server.bind("echo", [](std::string str)
{
auto session = asio2::get_current_caller<std::shared_ptr<asio2::rpc_rate_session>>();
session->async_call("echo", str);
return str;
});
server.start("0.0.0.0", 18102);
// "fn" should be declared before "client", beacuse when the client destroying, the client
// async_call's response callback maybe still be invoked, so if the "fn" is declared after
// "client", when "fn" is called in the response callback, the "fn" maybe destroyed already.
// of course, you can call "client.stop" manual to avoid this problem.
std::function<void()> fn;
asio2::rpc_rate_client client;
client.bind("echo", [](std::string str)
{
return str;
});
client.bind_connect([&client, &fn]()
{
// set the send rate
client.socket().rate_policy().write_limit(512);
ASIO2_CHECK(!asio2::get_last_error());
if (!asio2::get_last_error())
{
fn = [&client, &fn]()
{
std::string str;
for (int i = 0; i < 300; i++)
{
str += '0' + std::rand() % 64;
}
client.async_call("echo", str).response([str, &fn](std::string s)
{
if (!asio2::get_last_error())
{
ASIO2_CHECK(s == str);
fn();
}
});
};
fn();
}
}).bind_recv([](std::string_view data)
{
asio2::ignore_unused(data);
});
client.start("127.0.0.1", 18102);
std::thread([&client]()
{
// note: if you set the rate in the other thread which is not the io_context
// thread, you should use post function to make the operation is executed in
// the io_context thread, otherwise it is not thread safety.
client.post([&client]()
{
// set the recv rate
client.socket().rate_policy().read_limit(512);
});
}).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
// rpcs
{
asio2::rpcs_rate_server server;
server.bind_connect([](std::shared_ptr<asio2::rpcs_rate_session>& session_ptr)
{
// set the send rate
session_ptr->socket().rate_policy().write_limit(256);
// set the recv rate
session_ptr->socket().rate_policy().read_limit(256);
}).bind_recv([](auto& session_ptr, std::string_view data)
{
asio2::ignore_unused(session_ptr, data);
});
server.bind("echo", [](std::string str)
{
auto session = asio2::get_current_caller<std::shared_ptr<asio2::rpcs_rate_session>>();
session->async_call("echo", str);
return str;
});
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
server.start("0.0.0.0", 18102);
// "fn" should be declared before "client", beacuse when the client destroying, the client
// async_call's response callback maybe still be invoked, so if the "fn" is declared after
// "client", when "fn" is called in the response callback, the "fn" maybe destroyed already.
// of course, you can call "client.stop" manual to avoid this problem.
std::function<void()> fn;
asio2::rpcs_rate_client client;
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
client.bind("echo", [](std::string str)
{
return str;
});
client.bind_connect([&client, &fn]()
{
// set the send rate
client.socket().rate_policy().write_limit(512);
ASIO2_CHECK(!asio2::get_last_error());
if (!asio2::get_last_error())
{
fn = [&client, &fn]()
{
std::string str;
for (int i = 0; i < 32; i++)
{
str += '0' + std::rand() % 64;
}
client.async_call("echo", str).response([str, &fn](std::string s)
{
if (!asio2::get_last_error())
{
ASIO2_CHECK(s == str);
fn();
}
});
};
fn();
}
}).bind_recv([](std::string_view data)
{
asio2::ignore_unused(data);
});
client.start("127.0.0.1", 18102);
std::thread([&client]()
{
// note: if you set the rate in the other thread which is not the io_context
// thread, you should use post function to make the operation is executed in
// the io_context thread, otherwise it is not thread safety.
client.post([&client]()
{
// set the recv rate
client.socket().rate_policy().read_limit(512);
});
}).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
// http
{
asio2::http_rate_server server;
server.bind_connect([](std::shared_ptr<asio2::http_rate_session>& session_ptr)
{
// set the send rate
session_ptr->socket().rate_policy().write_limit(256);
// set the recv rate
session_ptr->socket().rate_policy().read_limit(256);
});
server.bind("*", [](http::web_request& req, http::web_response& rep)
{
rep.fill_text(req.target());
});
server.start("0.0.0.0", 18102);
asio2::http_rate_client client;
client.bind_connect([&client]()
{
// set the send rate
client.socket().rate_policy().write_limit(512);
ASIO2_CHECK(!asio2::get_last_error());
if (!asio2::get_last_error())
{
http::web_request req;
req.version(11);
req.method(http::verb::get);
req.target("/1");
req.set(http::field::host, "127.0.0.1");
client.async_send(req);
}
}).bind_recv([&client](http::web_request& req,http::web_response& rep)
{
ASIO2_CHECK(rep.body().text() == "/1");
req.version(11);
req.method(http::verb::get);
req.target("/1");
req.set(http::field::host, "127.0.0.1");
client.async_send(req);
});
client.start("127.0.0.1", 18102);
std::thread([&client]()
{
// note: if you set the rate in the other thread which is not the io_context
// thread, you should use post function to make the operation is executed in
// the io_context thread, otherwise it is not thread safety.
client.post([&client]()
{
// set the recv rate
client.socket().rate_policy().read_limit(512);
});
}).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
// https
{
asio2::https_rate_server server;
server.bind_connect([](std::shared_ptr<asio2::https_rate_session>& session_ptr)
{
// set the send rate
session_ptr->socket().rate_policy().write_limit(256);
// set the recv rate
session_ptr->socket().rate_policy().read_limit(256);
});
server.bind("*", [](http::web_request& req, http::web_response& rep)
{
rep.fill_text(req.target());
});
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
server.start("0.0.0.0", 18102);
asio2::https_rate_client client;
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
client.bind_connect([&client]()
{
// set the send rate
client.socket().rate_policy().write_limit(512);
ASIO2_CHECK(!asio2::get_last_error());
if (!asio2::get_last_error())
{
http::web_request req;
req.version(11);
req.method(http::verb::get);
req.target("/1");
req.set(http::field::host, "127.0.0.1");
client.async_send(req);
}
}).bind_recv([&client](http::web_request& req,http::web_response& rep)
{
ASIO2_CHECK(rep.body().text() == "/1");
req.version(11);
req.method(http::verb::get);
req.target("/1");
req.set(http::field::host, "127.0.0.1");
client.async_send(req);
});
client.start("127.0.0.1", 18102);
std::thread([&client]()
{
// note: if you set the rate in the other thread which is not the io_context
// thread, you should use post function to make the operation is executed in
// the io_context thread, otherwise it is not thread safety.
client.post([&client]()
{
// set the recv rate
client.socket().rate_policy().read_limit(512);
});
}).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
// websocket
{
asio2::ws_rate_server server;
server.bind_connect([](std::shared_ptr<asio2::ws_rate_session>& session_ptr)
{
// set the send rate
session_ptr->socket().rate_policy().write_limit(256);
// set the recv rate
session_ptr->socket().rate_policy().read_limit(256);
}).bind_recv([](auto& session_ptr, std::string_view data)
{
ASIO2_CHECK(data.size() == 1024);
session_ptr->async_send(data);
});
server.start("0.0.0.0", 18102);
asio2::ws_rate_client client;
client.bind_connect([&client]()
{
// set the send rate
client.socket().rate_policy().write_limit(512);
ASIO2_CHECK(!asio2::get_last_error());
if (!asio2::get_last_error())
{
std::string str;
for (int i = 0; i < 1024; i++)
{
str += '0' + std::rand() % 64;
}
client.async_send(str);
}
}).bind_recv([&client](std::string_view data)
{
ASIO2_CHECK(data.size() == 1024);
client.async_send(data);
});
client.start("127.0.0.1", 18102);
std::thread([&client]()
{
// note: if you set the rate in the other thread which is not the io_context
// thread, you should use post function to make the operation is executed in
// the io_context thread, otherwise it is not thread safety.
client.post([&client]()
{
// set the recv rate
client.socket().rate_policy().read_limit(512);
});
}).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
// ssl websocket
{
asio2::wss_rate_server server;
server.bind_connect([](std::shared_ptr<asio2::wss_rate_session>& session_ptr)
{
// set the send rate
session_ptr->socket().rate_policy().write_limit(256);
// set the recv rate
session_ptr->socket().rate_policy().read_limit(256);
}).bind_recv([](auto& session_ptr, std::string_view data)
{
ASIO2_CHECK(data.size() == 32);
session_ptr->async_send(data);
});
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
server.start("0.0.0.0", 18102);
asio2::wss_rate_client client;
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
client.bind_connect([&client]()
{
// set the send rate
client.socket().rate_policy().write_limit(512);
ASIO2_CHECK(!asio2::get_last_error());
if (!asio2::get_last_error())
{
std::string str;
for (int i = 0; i < 32; i++)
{
str += '0' + std::rand() % 64;
}
client.async_send(str);
}
}).bind_recv([&client](std::string_view data)
{
ASIO2_CHECK(data.size() == 32);
client.async_send(data);
});
client.start("127.0.0.1", 18102);
std::thread([&client]()
{
// note: if you set the rate in the other thread which is not the io_context
// thread, you should use post function to make the operation is executed in
// the io_context thread, otherwise it is not thread safety.
client.post([&client]()
{
// set the recv rate
client.socket().rate_policy().read_limit(512);
});
}).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"rate_limit",
ASIO2_TEST_CASE(rate_limit_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_HTTPS_EXECUTE_HPP__
#define __ASIO2_HTTPS_EXECUTE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/http/detail/http_util.hpp>
#include <asio2/http/detail/http_make.hpp>
#include <asio2/http/detail/http_traits.hpp>
#include <asio2/component/socks/socks5_client.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t, bool Enable = is_https_execute_download_enabled<args_t>::value()>
struct https_execute_impl_bridge;
template<class derived_t, class args_t>
struct https_execute_impl_bridge<derived_t, args_t, false>
{
};
template<class derived_t, class args_t>
struct https_execute_impl_bridge<derived_t, args_t, true>
{
protected:
template<typename String, typename StrOrInt, class Proxy, class Body, class Fields, class Buffer>
static void _execute_with_socks5(
asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
asio::ssl::stream<asio::ip::tcp::socket&>& stream,
http::parser<false, Body, typename Fields::allocator_type>& parser,
Buffer& buffer,
String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, Proxy&& proxy)
{
auto sk5 = detail::to_shared_ptr(std::forward<Proxy>(proxy));
std::string_view h{ sk5->host() };
std::string_view p{ sk5->port() };
// Look up the domain name
resolver.async_resolve(h, p, [&, s5 = std::move(sk5)]
(const error_code& ec1, const asio::ip::tcp::resolver::results_type& endpoints) mutable
{
if (ec1) { set_last_error(ec1); return; }
// Make the connection on the IP address we get from a lookup
asio::async_connect(socket, endpoints,
[&, s5 = std::move(s5)](const error_code& ec2, const asio::ip::tcp::endpoint&) mutable
{
if (ec2) { set_last_error(ec2); return; }
detail::socks5_client_connect_op
{
ioc,
detail::to_string(std::forward<String >(host)),
detail::to_string(std::forward<StrOrInt>(port)),
socket,
std::move(s5),
[&](error_code ecs5) mutable
{
if (ecs5) { set_last_error(ecs5); return; }
// https://github.com/djarek/certify
if (auto it = req.find(http::field::host); it != req.end())
{
std::string hostname(it->value());
SSL_set_tlsext_host_name(stream.native_handle(), hostname.data());
}
stream.async_handshake(asio::ssl::stream_base::client,
[&](const error_code& ec3) mutable
{
if (ec3) { set_last_error(ec3); return; }
http::async_write(stream, req, [&](const error_code& ec4, std::size_t) mutable
{
// can't use stream.shutdown(),in some case the shutdowm will blocking forever.
if (ec4) { set_last_error(ec4); stream.async_shutdown([](const error_code&) {}); return; }
// Then start asynchronous reading
http::async_read(stream, buffer, parser,
[&](const error_code& ec5, std::size_t) mutable
{
// Reading completed, assign the read the result to last error
// If the code does not execute into here, the last error
// is the default value timed_out.
set_last_error(ec5);
stream.async_shutdown([](const error_code&) mutable {});
});
});
});
}
};
});
});
}
template<typename String, typename StrOrInt, class Body, class Fields, class Buffer>
static void _execute_trivially(
asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
asio::ssl::stream<asio::ip::tcp::socket&>& stream,
http::parser<false, Body, typename Fields::allocator_type>& parser,
Buffer& buffer,
String&& host, StrOrInt&& port,
http::request<Body, Fields>& req)
{
detail::ignore_unused(ioc);
// Look up the domain name
resolver.async_resolve(std::forward<String>(host), detail::to_string(std::forward<StrOrInt>(port)),
[&](const error_code& ec1, const asio::ip::tcp::resolver::results_type& endpoints) mutable
{
if (ec1) { set_last_error(ec1); return; }
// Make the connection on the IP address we get from a lookup
asio::async_connect(socket, endpoints,
[&](const error_code& ec2, const asio::ip::tcp::endpoint&) mutable
{
if (ec2) { set_last_error(ec2); return; }
// https://github.com/djarek/certify
if (auto it = req.find(http::field::host); it != req.end())
{
std::string hostname(it->value());
SSL_set_tlsext_host_name(stream.native_handle(), hostname.data());
}
stream.async_handshake(asio::ssl::stream_base::client,
[&](const error_code& ec3) mutable
{
if (ec3) { set_last_error(ec3); return; }
http::async_write(stream, req, [&](const error_code& ec4, std::size_t) mutable
{
// can't use stream.shutdown(),in some case the shutdowm will blocking forever.
if (ec4) { set_last_error(ec4); stream.async_shutdown([](const error_code&) {}); return; }
// Then start asynchronous reading
http::async_read(stream, buffer, parser,
[&](const error_code& ec5, std::size_t) mutable
{
// Reading completed, assign the read the result to last error
// If the code does not execute into here, the last error
// is the default value timed_out.
set_last_error(ec5);
stream.async_shutdown([](const error_code&) mutable {});
});
});
});
});
});
}
template<typename String, typename StrOrInt, class Proxy, class Body, class Fields, class Buffer>
static void _execute_impl(
asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
asio::ssl::stream<asio::ip::tcp::socket&>& stream,
http::parser<false, Body, typename Fields::allocator_type>& parser,
Buffer& buffer,
String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, Proxy&& proxy)
{
// if has socks5 proxy
if constexpr (std::is_base_of_v<asio2::socks5::option_base,
typename detail::element_type_adapter<detail::remove_cvref_t<Proxy>>::type>)
{
derived_t::_execute_with_socks5(ioc, resolver, socket, stream, parser, buffer
, std::forward<String>(host), std::forward<StrOrInt>(port)
, req
, std::forward<Proxy>(proxy)
);
}
else
{
detail::ignore_unused(proxy);
derived_t::_execute_trivially(ioc, resolver, socket, stream, parser, buffer
, std::forward<String>(host), std::forward<StrOrInt>(port)
, req
);
}
}
public:
template<typename String, typename StrOrInt, class Rep, class Period, class Proxy,
class Body = http::string_body, class Fields = http::fields, class Buffer = beast::flat_buffer>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(const asio::ssl::context& ctx, String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
http::parser<false, Body, typename Fields::allocator_type> parser;
// First assign default value timed_out to last error
set_last_error(asio::error::timed_out);
// set default result to unknown
parser.get().result(http::status::unknown);
parser.eager(true);
// The io_context is required for all I/O
asio::io_context ioc;
// These objects perform our I/O
asio::ip::tcp::resolver resolver{ ioc };
asio::ip::tcp::socket socket{ ioc };
asio::ssl::stream<asio::ip::tcp::socket&> stream(socket, const_cast<asio::ssl::context&>(ctx));
// This buffer is used for reading and must be persisted
Buffer buffer;
// do work
derived_t::_execute_impl(ioc, resolver, socket, stream, parser, buffer
, std::forward<String>(host), std::forward<StrOrInt>(port)
, req
, std::forward<Proxy>(proxy)
);
// timedout run
ioc.run_for(timeout);
error_code ec_ignore{};
// Gracefully close the socket
socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec_ignore);
socket.cancel(ec_ignore);
socket.close(ec_ignore);
return parser.release();
}
// ----------------------------------------------------------------------------------------
template<typename String, typename StrOrInt, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(
const asio::ssl::context& ctx, String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, std::chrono::duration<Rep, Period> timeout)
{
return derived_t::execute(ctx, std::forward<String>(host), std::forward<StrOrInt>(port),
req, timeout, std::in_place);
}
template<typename String, typename StrOrInt,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(
const asio::ssl::context& ctx, String&& host, StrOrInt&& port,
http::request<Body, Fields>& req)
{
return derived_t::execute(ctx, std::forward<String>(host), std::forward<StrOrInt>(port),
req, std::chrono::milliseconds(http_execute_timeout), std::in_place);
}
// ----------------------------------------------------------------------------------------
template<typename String, typename StrOrInt, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, std::chrono::duration<Rep, Period> timeout)
{
return derived_t::execute(asio::ssl::context{ asio::ssl::context::sslv23 },
std::forward<String>(host), std::forward<StrOrInt>(port), req, timeout, std::in_place);
}
template<typename String, typename StrOrInt, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, http::request<Body, Fields>& req)
{
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
req, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
template<class Rep, class Period, class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(
const asio::ssl::context& ctx, http::web_request& req, std::chrono::duration<Rep, Period> timeout)
{
return derived_t::execute(ctx, req.url().host(), req.url().port(), req.base(), timeout, std::in_place);
}
template<class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(
const asio::ssl::context& ctx, http::web_request& req)
{
return derived_t::execute(ctx, req, std::chrono::milliseconds(http_execute_timeout));
}
template<class Rep, class Period, class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(
http::web_request& req, std::chrono::duration<Rep, Period> timeout)
{
return derived_t::execute(asio::ssl::context{ asio::ssl::context::sslv23 }, req, timeout);
}
template<class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(http::web_request& req)
{
return derived_t::execute(req, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Rep, class Period, class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(const asio::ssl::context& ctx, std::string_view url,
std::chrono::duration<Rep, Period> timeout)
{
http::web_request req = http::make_request(url);
if (get_last_error())
{
return http::response<Body, Fields>{ http::status::unknown, 11};
}
return derived_t::execute(ctx, req.host(), req.port(), req.base(), timeout, std::in_place);
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(const asio::ssl::context& ctx, std::string_view url)
{
return derived_t::execute(ctx, url, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Rep, class Period, class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(std::string_view url,
std::chrono::duration<Rep, Period> timeout)
{
return derived_t::execute(asio::ssl::context{ asio::ssl::context::sslv23 }, url, timeout);
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(std::string_view url)
{
return derived_t::execute(url, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(
const asio::ssl::context& ctx, String&& host, StrOrInt&& port,
std::string_view target, std::chrono::duration<Rep, Period> timeout)
{
http::web_request req = http::make_request(host, port, target);
if (get_last_error())
{
return http::response<Body, Fields>{ http::status::unknown, 11};
}
return derived_t::execute(ctx,
std::forward<String>(host), std::forward<StrOrInt>(port),
req.base(), timeout, std::in_place);
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(
const asio::ssl::context& ctx, String&& host, StrOrInt&& port,
std::string_view target)
{
return derived_t::execute(ctx,
std::forward<String>(host), std::forward<StrOrInt>(port),
target, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::can_convert_to_string_v<detail::remove_cvref_t<String>>,
http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, std::string_view target,
std::chrono::duration<Rep, Period> timeout)
{
return derived_t::execute(asio::ssl::context{ asio::ssl::context::sslv23 },
std::forward<String>(host), std::forward<StrOrInt>(port),
target, timeout);
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::can_convert_to_string_v<detail::remove_cvref_t<String>>,
http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, std::string_view target)
{
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
target, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
template<typename String, typename StrOrInt, class Proxy,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(
const asio::ssl::context& ctx, String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, Proxy&& proxy)
{
return derived_t::execute(ctx, std::forward<String>(host), std::forward<StrOrInt>(port),
req, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
}
// ----------------------------------------------------------------------------------------
template<typename String, typename StrOrInt, class Proxy, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
return derived_t::execute(asio::ssl::context{ asio::ssl::context::sslv23 },
std::forward<String>(host), std::forward<StrOrInt>(port),
req, timeout, std::forward<Proxy>(proxy));
}
template<typename String, typename StrOrInt, class Proxy,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, http::request<Body, Fields>& req, Proxy&& proxy)
{
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
req, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
}
// ----------------------------------------------------------------------------------------
template<class Proxy, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(
const asio::ssl::context& ctx, http::web_request& req,
std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
return derived_t::execute(ctx, req.url().host(), req.url().port(), req.base(), timeout,
std::forward<Proxy>(proxy));
}
template<class Proxy, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(const asio::ssl::context& ctx, http::web_request& req, Proxy&& proxy)
{
return derived_t::execute(ctx, req, std::chrono::milliseconds(http_execute_timeout),
std::forward<Proxy>(proxy));
}
template<class Proxy, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(
http::web_request& req, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
return derived_t::execute(asio::ssl::context{ asio::ssl::context::sslv23 }, req, timeout,
std::forward<Proxy>(proxy));
}
template<class Proxy, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(http::web_request& req, Proxy&& proxy)
{
return derived_t::execute(req, std::chrono::milliseconds(http_execute_timeout),
std::forward<Proxy>(proxy));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Proxy, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(
const asio::ssl::context& ctx, std::string_view url,
std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
http::web_request req = http::make_request(url);
if (get_last_error())
{
return http::response<Body, Fields>{ http::status::unknown, 11};
}
return derived_t::execute(ctx, req.host(), req.port(), req.base(), timeout, std::forward<Proxy>(proxy));
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Proxy, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(const asio::ssl::context& ctx, std::string_view url, Proxy&& proxy)
{
return derived_t::execute(ctx, url, std::chrono::milliseconds(http_execute_timeout),
std::forward<Proxy>(proxy));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Proxy, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(std::string_view url, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
return derived_t::execute(asio::ssl::context{ asio::ssl::context::sslv23 }, url, timeout,
std::forward<Proxy>(proxy));
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Proxy, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(std::string_view url, Proxy&& proxy)
{
return derived_t::execute(url, std::chrono::milliseconds(http_execute_timeout),
std::forward<Proxy>(proxy));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Proxy, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(
const asio::ssl::context& ctx, String&& host, StrOrInt&& port,
std::string_view target, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
http::web_request req = http::make_request(host, port, target);
if (get_last_error())
{
return http::response<Body, Fields>{ http::status::unknown, 11};
}
return derived_t::execute(ctx,
std::forward<String>(host), std::forward<StrOrInt>(port),
req.base(), timeout, std::forward<Proxy>(proxy));
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Proxy,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(
const asio::ssl::context& ctx, String&& host, StrOrInt&& port,
std::string_view target, Proxy&& proxy)
{
return derived_t::execute(ctx,
std::forward<String>(host), std::forward<StrOrInt>(port),
target, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Proxy, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, std::string_view target,
std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
return derived_t::execute(asio::ssl::context{ asio::ssl::context::sslv23 },
std::forward<String>(host), std::forward<StrOrInt>(port),
target, timeout, std::forward<Proxy>(proxy));
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Proxy,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, std::string_view target, Proxy&& proxy)
{
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
target, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
}
};
template<class derived_t, class args_t = void>
struct https_execute_impl : public https_execute_impl_bridge<derived_t, args_t> {};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTPS_EXECUTE_HPP__
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_CLIENT_HPP__
#define __ASIO2_HTTP_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <fstream>
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_client.hpp>
#include <asio2/http/http_execute.hpp>
#include <asio2/http/http_download.hpp>
#include <asio2/http/impl/http_send_op.hpp>
#include <asio2/http/impl/http_recv_op.hpp>
namespace asio2::detail
{
struct template_args_http_client : public template_args_tcp_client
{
using body_t = http::string_body;
using buffer_t = beast::flat_buffer;
using send_data_t = http::web_request&;
using recv_data_t = http::web_response&;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class derived_t, class args_t = template_args_http_client>
class http_client_impl_t
: public tcp_client_impl_t <derived_t, args_t>
, public http_send_op <derived_t, args_t>
, public http_recv_op <derived_t, args_t>
, public http_execute_impl <derived_t, args_t>
, public http_download_impl<derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using super = tcp_client_impl_t <derived_t, args_t>;
using self = http_client_impl_t<derived_t, args_t>;
using args_type = args_t;
using body_type = typename args_t::body_t;
using buffer_type = typename args_t::buffer_t;
using send_data_t = typename args_t::send_data_t;
using recv_data_t = typename args_t::recv_data_t;
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
template<class... Args>
explicit http_client_impl_t(Args&&... args)
: super(std::forward<Args>(args)...)
, http_send_op<derived_t, args_t>()
, req_()
, rep_()
{
}
/**
* @brief destructor
*/
~http_client_impl_t()
{
this->stop();
}
/**
* @brief start the client, blocking connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& port, Args&&... args)
{
if constexpr (ecs_helper::args_has_rdc<Args...>())
{
return this->derived().template _do_connect<false>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
else
{
asio2::rdc::option rdc_option
{
[](http::web_request &) { return 0; },
[](http::web_response&) { return 0; }
};
return this->derived().template _do_connect<false>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0', std::forward<Args>(args)..., std::move(rdc_option)));
}
}
/**
* @brief start the client, asynchronous connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool async_start(String&& host, StrOrInt&& port, Args&&... args)
{
if constexpr (ecs_helper::args_has_rdc<Args...>())
{
return this->derived().template _do_connect<true>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
else
{
asio2::rdc::option rdc_option
{
[](http::web_request &) { return 0; },
[](http::web_response&) { return 0; }
};
return this->derived().template _do_connect<true>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0', std::forward<Args>(args)..., std::move(rdc_option)));
}
}
public:
/**
* @brief get the request object, same as get_request
*/
inline const http::web_request & request() noexcept { return this->req_; }
/**
* @brief get the response object, same as get_response
*/
inline const http::web_response& response() noexcept { return this->rep_; }
/**
* @brief get the request object
*/
inline const http::web_request & get_request() noexcept { return this->req_; }
/**
* @brief get the response object
*/
inline const http::web_response& get_response() noexcept { return this->rep_; }
public:
/**
* @brief bind recv listener
* @param fun - a user defined callback function
* Function signature : void(http::web_request& req, http::web_response& rep)
*/
template<class F, class ...C>
inline derived_t & bind_recv(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::recv,
observer_t<http::web_request&, http::web_response&>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
if constexpr (
detail::is_template_instance_of_v<http::request, detail::remove_cvref_t<Data>> ||
detail::is_template_instance_of_v<detail::http_request_impl_t, detail::remove_cvref_t<Data>>)
{
this->req_ = std::move(data);
return this->derived()._http_send(this->req_, std::forward<Callback>(callback));
}
else
{
return this->derived()._http_send(data, std::forward<Callback>(callback));
}
}
template<class Data>
inline send_data_t _rdc_convert_to_send_data(Data& data)
{
return data;
}
template<class Invoker>
inline void _rdc_invoke_with_none(const error_code& ec, Invoker& invoker)
{
if (invoker)
invoker(ec, this->req_, this->rep_);
}
template<class Invoker>
inline void _rdc_invoke_with_recv(const error_code& ec, Invoker& invoker, recv_data_t data)
{
detail::ignore_unused(data);
if (invoker)
invoker(ec, this->req_, this->rep_);
}
template<class Invoker>
inline void _rdc_invoke_with_send(const error_code& ec, Invoker& invoker, send_data_t data)
{
if (invoker)
invoker(ec, data, this->rep_);
}
protected:
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._http_post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _handle_recv(
const error_code & ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._http_handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _fire_recv(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
this->listener_.notify(event_type::recv, this->req_, this->rep_);
this->derived()._rdc_handle_recv(this_ptr, ecs, this->rep_);
}
protected:
http::web_request req_;
http::web_response rep_;
};
}
namespace asio2
{
using http_client_args = detail::template_args_http_client;
template<class derived_t, class args_t>
using http_client_impl_t = detail::http_client_impl_t<derived_t, args_t>;
template<class derived_t>
class http_client_t : public detail::http_client_impl_t<derived_t, detail::template_args_http_client>
{
public:
using detail::http_client_impl_t<derived_t, detail::template_args_http_client>::http_client_impl_t;
};
class http_client : public http_client_t<http_client>
{
public:
using http_client_t<http_client>::http_client_t;
};
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct http_rate_client_args : public http_client_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
template<class derived_t>
class http_rate_client_t : public asio2::http_client_impl_t<derived_t, http_rate_client_args>
{
public:
using asio2::http_client_impl_t<derived_t, http_rate_client_args>::http_client_impl_t;
};
class http_rate_client : public asio2::http_rate_client_t<http_rate_client>
{
public:
using asio2::http_rate_client_t<http_rate_client>::http_rate_client_t;
};
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTP_CLIENT_HPP__
<file_sep>// Copyright <NAME> 2008
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// This file exists to turn off some overly-pedantic warning emitted
// by certain compilers. You should include this header only in:
//
// * A test case, before any other headers, or,
// * A library source file before any other headers.
//
// IT SHOULD NOT BE INCLUDED BY ANY BOOST HEADER.
//
// YOU SHOULD NOT INCLUDE IT IF YOU CAN REASONABLY FIX THE WARNING.
//
// The only warnings disabled here are those that are:
//
// * Quite unreasonably pedantic.
// * Generally only emitted by a single compiler.
// * Can't easily be fixed: for example if the vendors own std lib
// code emits these warnings!
//
// Note that THIS HEADER MUST NOT INCLUDE ANY OTHER HEADERS:
// not even std library ones! Doing so may turn the warning
// off too late to be of any use. For example the VC++ C4996
// warning can be emitted from <iosfwd> if that header is included
// before or by this one :-(
//
#ifndef BHO_CONFIG_WARNING_DISABLE_HPP
#define BHO_CONFIG_WARNING_DISABLE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
// Error 'function': was declared deprecated
// http://msdn2.microsoft.com/en-us/library/ttcz0bys(VS.80).aspx
// This error is emitted when you use some perfectly conforming
// std lib functions in a perfectly correct way, and also by
// some of Microsoft's own std lib code !
# pragma warning(disable:4996)
#endif
#if defined(__INTEL_COMPILER) || defined(__ICL)
// As above: gives warning when a "deprecated"
// std library function is encountered.
# pragma warning(disable:1786)
#endif
#endif // BHO_CONFIG_WARNING_DISABLE_HPP
<file_sep>#include "unit_test.hpp"
#include <iostream>
#include <asio2/external/pfr.hpp>
class actor
{
public:
actor(int index) : m_index(index)
{
}
virtual ~actor()
{
}
int m_index = 0;
};
class dog
: public actor
, public pfr::base_dynamic_creator<actor, dog, int, std::string, const char*>
{
public:
dog(int index, std::string name, const char* type)
: actor(index), m_name(std::move(name)), m_type(type)
{
}
virtual ~dog()
{
}
std::string m_name;
const char * m_type;
};
struct userinfo
{
F_BEGIN(userinfo);
F_FIELD(int, age);
F_FIELD(std::string, name);
F_END();
};
void reflection_test()
{
int i1 = 1;
actor* p1 = pfr::create_helper<actor>::create(
"dog", i1, std::string("dog1"), (const char*)"d1");
std::string dog2 = "dog2";
std::shared_ptr<actor> p2 = pfr::create_helper<std::shared_ptr<actor>>::create(
"dog", 2, dog2, (const char*)"d2");
const char* type3 = "d3";
std::unique_ptr<actor> p3 = pfr::create_helper<std::unique_ptr<actor>>::create(
"dog", 3, std::string("dog3"), type3);
std::string class_name = "dog";
actor* p4 = pfr::create_helper<actor*>::create(
class_name, 4, std::string("dog4"), (const char*)"d4");
ASIO2_CHECK(p1->m_index == 1);
ASIO2_CHECK(p2->m_index == 2);
ASIO2_CHECK(p3->m_index == 3);
ASIO2_CHECK(p4->m_index == 4);
dog* d1 = (dog*)p1;
dog* d2 = (dog*)p2.get();
dog* d3 = (dog*)p3.get();
dog* d4 = (dog*)p4;
ASIO2_CHECK(d1->m_name == "dog1" && std::string_view{ "d1" } == d1->m_type);
ASIO2_CHECK(d2->m_name == "dog2" && std::string_view{ "d2" } == d2->m_type);
ASIO2_CHECK(d3->m_name == "dog3" && std::string_view{ "d3" } == d3->m_type);
ASIO2_CHECK(d4->m_name == "dog4" && std::string_view{ "d4" } == d4->m_type);
userinfo u;
u.age = 101;
u.name = "hanmeimei";
ASIO2_CHECK(2 == u.get_field_count());
ASIO2_CHECK(u.get_class_name() == "userinfo");
int userage = -1;
std::string username;
int c = 0;
u.for_each_field([&](const char* name, auto& value) mutable
{
std::ignore = true;
if constexpr (std::is_integral_v<std::remove_reference_t<decltype(value)>>)
{
ASIO2_CHECK(std::string_view{ "age" } == name);
userage = value;
ASIO2_CHECK(value == 101);
ASIO2_CHECK(c == 0);
}
else
{
ASIO2_CHECK(std::string_view{ "name" } == name);
username = value;
ASIO2_CHECK(value == "hanmeimei");
ASIO2_CHECK(c == 1);
}
c++;
});
ASIO2_CHECK(c == 2);
ASIO2_CHECK(userage == u.age);
ASIO2_CHECK(username == u.name);
c = 0;
userinfo::for_each_field_name([&c](const char* name) mutable
{
if (c == 0)
{
ASIO2_CHECK(std::string_view{ "age" } == name);
}
else
{
ASIO2_CHECK(std::string_view{ "name" } == name);
}
c++;
});
ASIO2_CHECK(c == 2);
delete p1;
delete p4;
}
ASIO2_TEST_SUITE
(
"reflection",
ASIO2_TEST_CASE(reflection_test)
)
<file_sep>// (C) Copyright <NAME> 2014.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Haiku specific config options:
#define BHO_PLATFORM "Haiku"
#define BHO_HAS_UNISTD_H
#define BHO_HAS_STDINT_H
#ifndef BHO_DISABLE_THREADS
# define BHO_HAS_THREADS
#endif
#define BHO_NO_CXX11_HDR_TYPE_TRAITS
#define BHO_NO_CXX11_ATOMIC_SMART_PTR
#define BHO_NO_CXX11_STATIC_ASSERT
#define BHO_NO_CXX11_VARIADIC_MACROS
//
// thread API's not auto detected:
//
#define BHO_HAS_SCHED_YIELD
#define BHO_HAS_GETTIMEOFDAY
// boilerplate code:
#include <asio2/bho/config/detail/posix_features.hpp>
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* /Microsoft Visual Studio/2022/Enterprise/VC/Tools/MSVC/14.33.31629/include/codecvt
*
*/
#ifndef __ASIO2_CODECVT_HPP__
#define __ASIO2_CODECVT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdlib>
#include <locale>
#include <codecvt>
#include <asio2/external/predef.h>
#include <asio2/external/asio.hpp>
#include <asio2/util/string.hpp>
#if defined(ASIO2_OS_WINDOWS) || defined(__CYGWIN__)
# if __has_include(<Windows.h>)
# include <Windows.h>
# ifndef ASIO2_LOCALE_USE_WIN32_API
# define ASIO2_LOCALE_USE_WIN32_API
# endif
# endif
#endif
namespace asio2
{
using codecvt_base = std::codecvt_base;
template <class _Elem, class _Byte, class _Statype>
using codecvt = std::codecvt<_Elem, _Byte, _Statype>;
template <class _Elem, class _Byte, class _Statype>
using codecvt_byname = std::codecvt_byname<_Elem, _Byte, _Statype>;
namespace detail
{
inline constexpr int _Codecvt_Little_first = 1;
inline constexpr int _Codecvt_Big_first = 2;
template <class _CvtTy, class _Byte, class _Statype>
[[nodiscard]] int _Codecvt_do_length(
const _CvtTy& _Cvt, _Statype& _State, const _Byte* _First1, const _Byte* _Last1, std::size_t _Count) {
// return p - _First1, for the largest value p in [_First1, _Last1] such that _Cvt will successfully convert
// [_First1, p) to at most _Count wide characters
using _Elem = typename _CvtTy::intern_type;
const auto _Old_first1 = _First1;
while (_Count > 0 && _First1 != _Last1) { // convert another wide character
const _Byte* _Mid1;
_Elem* _Mid2;
_Elem _Ch;
// test result of single widechar conversion
const auto _Result = _Cvt._CvtTy::do_in(_State, _First1, _Last1, _Mid1, &_Ch, &_Ch + 1, _Mid2);
if (_Result != std::codecvt_base::ok) {
if (_Result == std::codecvt_base::noconv) {
_First1 += (std::min)(static_cast<std::size_t>(_Last1 - _First1), _Count);
}
break; // error, noconv, or partial
}
if (_Mid2 == &_Ch + 1) {
--_Count; // do_in converted an output character
}
_First1 = _Mid1;
}
return static_cast<int>((std::min)(_First1 - _Old_first1, std::ptrdiff_t{(std::numeric_limits<int>::max)()}));
}
}
enum codecvt_mode { consume_header = 4, generate_header = 2, little_endian = 1 };
template <
class _Elem,
class CharT = char,
unsigned long _Mymax = 0x10ffff,
asio2::codecvt_mode _Mymode = asio2::codecvt_mode{}>
class codecvt_utf8 : public std::codecvt<_Elem, CharT, std::mbstate_t> {
// facet for converting between _Elem and UTF-8 byte sequences
public:
using _Mybase = std::codecvt<_Elem, CharT, std::mbstate_t>;
using result = typename _Mybase::result;
using _Byte = CharT;
using intern_type = _Elem;
using extern_type = _Byte;
using state_type = std::mbstate_t;
explicit codecvt_utf8(std::size_t _Refs = 0) : _Mybase(_Refs) {}
~codecvt_utf8() noexcept override {}
protected:
result do_in(std::mbstate_t& _State, const _Byte* _First1, const _Byte* _Last1, const _Byte*& _Mid1,
_Elem* _First2, _Elem* _Last2, _Elem*& _Mid2) const override {
// convert bytes [_First1, _Last1) to [_First2, _Last2)
std::int8_t* _Pstate = reinterpret_cast<std::int8_t*>(&_State);
_Mid1 = _First1;
_Mid2 = _First2;
while (_Mid1 != _Last1 && _Mid2 != _Last2) { // convert a multibyte sequence
unsigned long _By = static_cast<std::make_unsigned_t<CharT>>(*_Mid1);
unsigned long _Ch;
int _Nextra;
if (_By < 0x80u) {
_Ch = _By;
_Nextra = 0;
} else if (_By < 0xc0u) { // 0x80-0xbf not first byte
++_Mid1;
return _Mybase::error;
} else if (_By < 0xe0u) {
_Ch = _By & 0x1f;
_Nextra = 1;
} else if (_By < 0xf0u) {
_Ch = _By & 0x0f;
_Nextra = 2;
} else if (_By < 0xf8u) {
_Ch = _By & 0x07;
_Nextra = 3;
} else {
_Ch = _By & 0x03;
_Nextra = _By < 0xfc ? 4 : 5;
}
if (_Nextra == 0) {
++_Mid1;
} else if (_Last1 - _Mid1 < _Nextra + 1) {
break; // not enough input
} else {
for (++_Mid1; 0 < _Nextra; --_Nextra, ++_Mid1) {
if ((_By = static_cast<std::make_unsigned_t<CharT>>(*_Mid1)) < 0x80u || 0xc0u <= _By) {
return _Mybase::error; // not continuation byte
} else {
_Ch = _Ch << 6 | (_By & 0x3f);
}
}
}
if (*_Pstate == 0) { // first time, maybe look for and consume header
*_Pstate = 1;
constexpr bool _Consuming = (_Mymode & consume_header) != 0;
if constexpr (_Consuming) {
if (_Ch == 0xfeff) { // drop header and retry
const result _Ans = do_in(_State, _Mid1, _Last1, _Mid1, _First2, _Last2, _Mid2);
if (_Ans == _Mybase::partial) { // roll back header determination
*_Pstate = 0;
_Mid1 = _First1;
}
return _Ans;
}
}
}
if (_Mymax < _Ch) {
return _Mybase::error; // code too large
}
*_Mid2++ = static_cast<_Elem>(_Ch);
}
return _First1 == _Mid1 ? _Mybase::partial : _Mybase::ok;
}
result do_out(std::mbstate_t& _State, const _Elem* _First1, const _Elem* _Last1, const _Elem*& _Mid1,
_Byte* _First2, _Byte* _Last2, _Byte*& _Mid2) const override {
// convert [_First1, _Last1) to bytes [_First2, _Last2)
std::int8_t* _Pstate = reinterpret_cast<std::int8_t*>(&_State);
_Mid1 = _First1;
_Mid2 = _First2;
while (_Mid1 != _Last1 && _Mid2 != _Last2) { // convert and put a widechar
_Byte _By;
int _Nextra;
unsigned long _Ch = static_cast<unsigned long>(*_Mid1);
if (_Mymax < _Ch) {
return _Mybase::error;
}
if (_Ch < 0x0080u) {
_By = static_cast<_Byte>(_Ch);
_Nextra = 0;
} else if (_Ch < 0x0800u) {
_By = static_cast<_Byte>(0xc0 | _Ch >> 6);
_Nextra = 1;
} else if (_Ch < 0x00010000u) {
_By = static_cast<_Byte>(0xe0 | _Ch >> 12);
_Nextra = 2;
} else if (_Ch < 0x00200000u) {
_By = static_cast<_Byte>(0xf0 | _Ch >> 18);
_Nextra = 3;
} else if (_Ch < 0x04000000u) {
_By = static_cast<_Byte>(0xf8 | _Ch >> 24);
_Nextra = 4;
} else {
_By = static_cast<_Byte>(0xfc | (_Ch >> 30 & 0x03));
_Nextra = 5;
}
if (*_Pstate == 0) { // first time, maybe generate header
*_Pstate = 1;
constexpr bool _Generating = (_Mymode & generate_header) != 0;
if constexpr (_Generating) {
if (_Last2 - _Mid2 < 3 + 1 + _Nextra) {
return _Mybase::partial; // not enough room for both
}
// prepend header
*_Mid2++ = '\xef';
*_Mid2++ = '\xbb';
*_Mid2++ = '\xbf';
}
}
if (_Last2 - _Mid2 < 1 + _Nextra) {
break; // not enough room for output
}
++_Mid1;
for (*_Mid2++ = _By; 0 < _Nextra;) {
*_Mid2++ = static_cast<_Byte>((_Ch >> 6 * --_Nextra & 0x3f) | 0x80);
}
}
return _First1 == _Mid1 ? _Mybase::partial : _Mybase::ok;
}
result do_unshift(std::mbstate_t&, _Byte* _First2, _Byte*, _Byte*& _Mid2) const override {
// generate bytes to return to default shift state
_Mid2 = _First2;
return _Mybase::noconv;
}
friend int detail::_Codecvt_do_length<>(const codecvt_utf8&, std::mbstate_t&, const _Byte*, const _Byte*, std::size_t);
int do_length(
std::mbstate_t& _State, const _Byte* _First1, const _Byte* _Last1, std::size_t _Count) const noexcept override {
return detail::_Codecvt_do_length(*this, _State, _First1, _Last1, _Count);
}
bool do_always_noconv() const noexcept override {
// return true if conversions never change input
return false;
}
int do_max_length() const noexcept override {
// return maximum length required for a conversion
if constexpr ((_Mymode & (consume_header | generate_header)) != 0) {
return 9;
} else {
return 6;
}
}
int do_encoding() const noexcept override {
// return length of code sequence (from codecvt)
if constexpr ((_Mymode & (consume_header | generate_header)) != 0) {
return -1; // -1 => state dependent
} else {
return 0; // 0 => varying length
}
}
};
template <
class _Elem,
class CharT = char,
unsigned long _Mymax = 0x10ffff,
asio2::codecvt_mode _Mymode = asio2::codecvt_mode{}>
class codecvt_utf16 : public std::codecvt<_Elem, CharT, std::mbstate_t> {
// facet for converting between _Elem and UTF-16 multibyte sequences
private:
enum { _Bytes_per_word = 2 };
public:
using _Mybase = std::codecvt<_Elem, CharT, std::mbstate_t>;
using result = typename _Mybase::result;
using _Byte = CharT;
using intern_type = _Elem;
using extern_type = _Byte;
using state_type = std::mbstate_t;
explicit codecvt_utf16(std::size_t _Refs = 0) : _Mybase(_Refs) {}
~codecvt_utf16() noexcept override {}
protected:
result do_in(std::mbstate_t& _State, const _Byte* _First1, const _Byte* _Last1, const _Byte*& _Mid1,
_Elem* _First2, _Elem* _Last2, _Elem*& _Mid2) const override {
// convert bytes [_First1, _Last1) to [_First2, _Last2)
std::int8_t* _Pstate = reinterpret_cast<std::int8_t*>(&_State);
_Mid1 = _First1;
_Mid2 = _First2;
while (_Bytes_per_word <= _Last1 - _Mid1 && _Mid2 != _Last2) { // convert a multibyte sequence
const auto _Ptr = reinterpret_cast<const std::make_unsigned_t<CharT>*>(_Mid1);
unsigned long _Ch;
unsigned short _Ch0;
unsigned short _Ch1;
if (*_Pstate == detail::_Codecvt_Little_first) {
_Ch0 = static_cast<unsigned short>(_Ptr[1] << 8 | _Ptr[0]);
} else if (*_Pstate == detail::_Codecvt_Big_first) {
_Ch0 = static_cast<unsigned short>(_Ptr[0] << 8 | _Ptr[1]);
} else { // no header seen yet, try preferred mode
constexpr bool _Prefer_LE = (_Mymode & little_endian) != 0;
constexpr std::int8_t _Default_endian = _Prefer_LE ? detail::_Codecvt_Little_first : detail::_Codecvt_Big_first;
if constexpr (_Prefer_LE) {
_Ch0 = static_cast<unsigned short>(_Ptr[1] << 8 | _Ptr[0]);
} else {
_Ch0 = static_cast<unsigned short>(_Ptr[0] << 8 | _Ptr[1]);
}
*_Pstate = _Default_endian;
constexpr bool _Consuming = (_Mymode & consume_header) != 0;
if constexpr (_Consuming) {
if (_Ch0 == 0xfffeu) {
*_Pstate = 3 - _Default_endian;
}
if (_Ch0 == 0xfffeu || _Ch0 == 0xfeffu) { // consume header, fixate on endianness, and retry
_Mid1 += _Bytes_per_word;
result _Ans = do_in(_State, _Mid1, _Last1, _Mid1, _First2, _Last2, _Mid2);
if (_Ans == _Mybase::partial) { // not enough bytes, roll back header
*_Pstate = 0;
_Mid1 = _First1;
}
return _Ans;
}
}
}
if (_Ch0 < 0xd800u || 0xdc00u <= _Ch0) { // one word, consume bytes
_Mid1 += _Bytes_per_word;
_Ch = _Ch0;
} else if (_Last1 - _Mid1 < 2 * _Bytes_per_word) {
break;
} else { // get second word
if (*_Pstate == detail::_Codecvt_Little_first) {
_Ch1 = static_cast<unsigned short>(_Ptr[3] << 8 | _Ptr[2]);
} else {
_Ch1 = static_cast<unsigned short>(_Ptr[2] << 8 | _Ptr[3]);
}
if (_Ch1 < 0xdc00u || 0xe000u <= _Ch1) {
return _Mybase::error;
}
_Mid1 += 2 * _Bytes_per_word;
_Ch = static_cast<unsigned long>(_Ch0 - 0xd800 + 0x0040) << 10 | (_Ch1 - 0xdc00);
}
if (_Mymax < _Ch) {
return _Mybase::error; // code too large
}
*_Mid2++ = static_cast<_Elem>(_Ch);
}
return _First1 == _Mid1 ? _Mybase::partial : _Mybase::ok;
}
result do_out(std::mbstate_t& _State, const _Elem* _First1, const _Elem* _Last1, const _Elem*& _Mid1,
_Byte* _First2, _Byte* _Last2, _Byte*& _Mid2) const override {
// convert [_First1, _Last1) to bytes [_First2, _Last2)
std::int8_t* _Pstate = reinterpret_cast<std::int8_t*>(&_State);
_Mid1 = _First1;
_Mid2 = _First2;
if (*_Pstate == 0) { // determine endianness once, maybe generate header
if constexpr ((_Mymode & little_endian) != 0) {
*_Pstate = detail::_Codecvt_Little_first;
} else {
*_Pstate = detail::_Codecvt_Big_first;
}
constexpr bool _Generating = (_Mymode & generate_header) != 0;
if constexpr (_Generating) {
if (_Last2 - _Mid2 < 3 * _Bytes_per_word) {
return _Mybase::partial; // not enough room for all
}
if (*_Pstate == detail::_Codecvt_Little_first) { // put header LS byte first
*_Mid2++ = '\xff';
*_Mid2++ = '\xfe';
} else { // put header MS byte first
*_Mid2++ = '\xfe';
*_Mid2++ = '\xff';
}
}
}
while (_Mid1 != _Last1 && _Bytes_per_word <= _Last2 - _Mid2) { // convert and put a widechar
bool _Extra = false;
unsigned long _Ch = static_cast<unsigned long>(*_Mid1++);
if ((_Mymax < 0x10ffffu ? _Mymax : 0x10ffffu) < _Ch) {
return _Mybase::error; // value too large
}
if (_Ch <= 0xffffu) { // one word, can't be code for first of two
if (0xd800u <= _Ch && _Ch < 0xdc00u) {
return _Mybase::error;
}
} else if (_Last2 - _Mid2 < 2 * _Bytes_per_word) { // not enough room for two-word output, back up
--_Mid1;
return _Mybase::partial;
} else {
_Extra = true;
}
if (*_Pstate == detail::_Codecvt_Little_first) {
if (_Extra) { // put a pair of words LS byte first
unsigned short _Ch0 =
static_cast<unsigned short>(0xd800 | (static_cast<unsigned short>(_Ch >> 10) - 0x0040));
*_Mid2++ = static_cast<_Byte>(_Ch0);
*_Mid2++ = static_cast<_Byte>(_Ch0 >> 8);
_Ch0 = static_cast<unsigned short>(0xdc00 | (static_cast<unsigned short>(_Ch) & 0x03ff));
*_Mid2++ = static_cast<_Byte>(_Ch0);
*_Mid2++ = static_cast<_Byte>(_Ch0 >> 8);
} else { // put a single word LS byte first
*_Mid2++ = static_cast<_Byte>(_Ch);
*_Mid2++ = static_cast<_Byte>(_Ch >> 8);
}
} else {
if (_Extra) { // put a pair of words MS byte first
unsigned short _Ch0 =
static_cast<unsigned short>(0xd800 | (static_cast<unsigned short>(_Ch >> 10) - 0x0040));
*_Mid2++ = static_cast<_Byte>(_Ch0 >> 8);
*_Mid2++ = static_cast<_Byte>(_Ch0);
_Ch0 = static_cast<unsigned short>(0xdc00 | (static_cast<unsigned short>(_Ch) & 0x03ff));
*_Mid2++ = static_cast<_Byte>(_Ch0 >> 8);
*_Mid2++ = static_cast<_Byte>(_Ch0);
} else { // put a single word MS byte first
*_Mid2++ = static_cast<_Byte>(_Ch >> 8);
*_Mid2++ = static_cast<_Byte>(_Ch);
}
}
}
return _First1 == _Mid1 ? _Mybase::partial : _Mybase::ok;
}
result do_unshift(std::mbstate_t&, _Byte* _First2, _Byte*, _Byte*& _Mid2) const override {
// generate bytes to return to default shift state
_Mid2 = _First2;
return _Mybase::noconv;
}
friend int detail::_Codecvt_do_length<>(const codecvt_utf16&, std::mbstate_t&, const _Byte*, const _Byte*, std::size_t);
int do_length(
std::mbstate_t& _State, const _Byte* _First1, const _Byte* _Last1, std::size_t _Count) const noexcept override {
return detail::_Codecvt_do_length(*this, _State, _First1, _Last1, _Count);
}
bool do_always_noconv() const noexcept override {
// return true if conversions never change input
return false;
}
int do_max_length() const noexcept override {
// return maximum length required for a conversion
if constexpr ((_Mymode & (consume_header | generate_header)) != 0) {
return 3 * _Bytes_per_word;
} else {
return 6 * _Bytes_per_word;
}
}
int do_encoding() const noexcept override {
// return length of code sequence (from codecvt)
if constexpr ((_Mymode & (consume_header | generate_header)) != 0) {
return -1; // -1 => state dependent
} else {
return 0; // 0 => varying length
}
}
};
template <
class _Elem,
class CharT = char,
unsigned long _Mymax = 0x10ffff,
asio2::codecvt_mode _Mymode = asio2::codecvt_mode{}>
class codecvt_utf8_utf16
: public std::codecvt<_Elem, CharT, std::mbstate_t> { // facet for converting between UTF-16 _Elem and UTF-8 byte sequences
public:
using _Mybase = std::codecvt<_Elem, CharT, std::mbstate_t>;
using result = typename _Mybase::result;
using _Byte = CharT;
using intern_type = _Elem;
using extern_type = _Byte;
using state_type = std::mbstate_t;
static_assert(sizeof(unsigned short) <= sizeof(state_type), "state_type too small");
explicit codecvt_utf8_utf16(std::size_t _Refs = 0) : _Mybase(_Refs) {}
~codecvt_utf8_utf16() noexcept override {}
protected:
result do_in(std::mbstate_t& _State, const _Byte* _First1, const _Byte* _Last1, const _Byte*& _Mid1,
_Elem* _First2, _Elem* _Last2, _Elem*& _Mid2) const override {
// convert bytes [_First1, _Last1) to [_First2, _Last2)
unsigned short* _Pstate = reinterpret_cast<unsigned short*>(&_State);
_Mid1 = _First1;
_Mid2 = _First2;
while (_Mid1 != _Last1 && _Mid2 != _Last2) { // convert a multibyte sequence
unsigned long _By = static_cast<std::make_unsigned_t<CharT>>(*_Mid1);
unsigned long _Ch;
int _Nextra;
int _Nskip;
if (*_Pstate > 1u) {
if (_By < 0x80u || 0xc0u <= _By) {
return _Mybase::error; // not continuation byte
}
// deliver second half of two-word value
++_Mid1;
*_Mid2++ = static_cast<_Elem>(*_Pstate | (_By & 0x3f));
*_Pstate = 1;
continue;
}
if (_By < 0x80u) {
_Ch = _By;
_Nextra = 0;
} else if (_By < 0xc0u) { // 0x80-0xbf not first byte
++_Mid1;
return _Mybase::error;
} else if (_By < 0xe0u) {
_Ch = _By & 0x1f;
_Nextra = 1;
} else if (_By < 0xf0u) {
_Ch = _By & 0x0f;
_Nextra = 2;
} else if (_By < 0xf8u) {
_Ch = _By & 0x07;
_Nextra = 3;
} else {
_Ch = _By & 0x03;
_Nextra = _By < 0xfc ? 4 : 5;
}
_Nskip = _Nextra < 3 ? 0 : 1; // leave a byte for 2nd word
_First1 = _Mid1; // roll back point
if (_Nextra == 0) {
++_Mid1;
} else if (_Last1 - _Mid1 < _Nextra + 1 - _Nskip) {
break; // not enough input
} else {
for (++_Mid1; _Nskip < _Nextra; --_Nextra, ++_Mid1) {
if ((_By = static_cast<std::make_unsigned_t<CharT>>(*_Mid1)) < 0x80u || 0xc0u <= _By) {
return _Mybase::error; // not continuation byte
}
_Ch = _Ch << 6 | (_By & 0x3f);
}
}
if (0 < _Nskip) {
_Ch <<= 6; // get last byte on next call
}
if ((_Mymax < 0x10ffffu ? _Mymax : 0x10ffffu) < _Ch) {
return _Mybase::error; // value too large
}
if (0xffffu < _Ch) { // deliver first half of two-word value, save second word
unsigned short _Ch0 = static_cast<unsigned short>(0xd800 | ((_Ch >> 10) - 0x0040));
*_Mid2++ = static_cast<_Elem>(_Ch0);
*_Pstate = static_cast<unsigned short>(0xdc00 | (_Ch & 0x03ff));
continue;
}
if (_Nskip != 0) {
if (_Mid1 == _Last1) { // not enough bytes, noncanonical value
_Mid1 = _First1;
break;
}
if ((_By = static_cast<std::make_unsigned_t<CharT>>(*_Mid1++)) < 0x80u || 0xc0u <= _By) {
return _Mybase::error; // not continuation byte
}
_Ch |= _By & 0x3f; // complete noncanonical value
}
if (*_Pstate == 0u) { // first time, maybe look for and consume header
*_Pstate = 1;
constexpr bool _Consuming = (_Mymode & consume_header) != 0;
if constexpr (_Consuming) {
if (_Ch == 0xfeffu) { // drop header and retry
result _Ans = do_in(_State, _Mid1, _Last1, _Mid1, _First2, _Last2, _Mid2);
if (_Ans == _Mybase::partial) { // roll back header determination
*_Pstate = 0;
_Mid1 = _First1;
}
return _Ans;
}
}
}
*_Mid2++ = static_cast<_Elem>(_Ch);
}
return _First1 == _Mid1 ? _Mybase::partial : _Mybase::ok;
}
result do_out(std::mbstate_t& _State, const _Elem* _First1, const _Elem* _Last1, const _Elem*& _Mid1,
_Byte* _First2, _Byte* _Last2, _Byte*& _Mid2) const override {
// convert [_First1, _Last1) to bytes [_First2, _Last2)
unsigned short* _Pstate = reinterpret_cast<unsigned short*>(&_State);
_Mid1 = _First1;
_Mid2 = _First2;
while (_Mid1 != _Last1 && _Mid2 != _Last2) { // convert and put a widechar
unsigned long _Ch;
unsigned short _Ch1 = static_cast<unsigned short>(*_Mid1);
bool _Save = false;
if (1u < *_Pstate) { // get saved MS 11 bits from *_Pstate
if (_Ch1 < 0xdc00u || 0xe000u <= _Ch1) {
return _Mybase::error; // bad second word
}
_Ch = static_cast<unsigned long>((*_Pstate << 10) | (_Ch1 - 0xdc00));
} else if (0xd800u <= _Ch1 && _Ch1 < 0xdc00u) { // get new first word
_Ch = static_cast<unsigned long>((_Ch1 - 0xd800 + 0x0040) << 10);
_Save = true; // put only first byte, rest with second word
} else {
_Ch = _Ch1; // not first word, just put it
}
_Byte _By;
int _Nextra;
if (_Ch < 0x0080u) {
_By = static_cast<_Byte>(_Ch);
_Nextra = 0;
} else if (_Ch < 0x0800u) {
_By = static_cast<_Byte>(0xc0 | _Ch >> 6);
_Nextra = 1;
} else if (_Ch < 0x10000u) {
_By = static_cast<_Byte>(0xe0 | _Ch >> 12);
_Nextra = 2;
} else {
_By = static_cast<_Byte>(0xf0 | _Ch >> 18);
_Nextra = 3;
}
int _Nput = _Nextra < 3 ? _Nextra + 1 : _Save ? 1 : 3;
if (_Last2 - _Mid2 < _Nput) {
break; // not enough room, even without header
}
if constexpr ((_Mymode & generate_header) != 0) { // header to put
if (*_Pstate == 0u) {
if (_Last2 - _Mid2 < 3 + _Nput) {
break; // not enough room for header + output
}
// prepend header
*_Mid2++ = '\xef';
*_Mid2++ = '\xbb';
*_Mid2++ = '\xbf';
}
}
++_Mid1;
if (_Save || _Nextra < 3) { // put first byte of sequence, if not already put
*_Mid2++ = _By;
--_Nput;
}
for (; 0 < _Nput; --_Nput) {
*_Mid2++ = static_cast<_Byte>((_Ch >> 6 * --_Nextra & 0x3f) | 0x80);
}
*_Pstate = static_cast<unsigned short>(_Save ? _Ch >> 10 : 1);
}
return _First1 == _Mid1 ? _Mybase::partial : _Mybase::ok;
}
result do_unshift(std::mbstate_t&, _Byte* _First2, _Byte*, _Byte*& _Mid2) const override {
// generate bytes to return to default shift state
_Mid2 = _First2;
return _Mybase::noconv;
}
friend int detail::_Codecvt_do_length<>(const codecvt_utf8_utf16&, std::mbstate_t&, const _Byte*, const _Byte*, std::size_t);
int do_length(
std::mbstate_t& _State, const _Byte* _First1, const _Byte* _Last1, std::size_t _Count) const noexcept override {
return detail::_Codecvt_do_length(*this, _State, _First1, _Last1, _Count);
}
bool do_always_noconv() const noexcept override {
// return true if conversions never change input
return false;
}
int do_max_length() const noexcept override {
// return maximum length required for a conversion
if constexpr ((_Mymode & consume_header) != 0) {
return 9; // header + max input
} else if constexpr ((_Mymode & generate_header) != 0) {
return 7; // header + max output
} else {
return 6; // 6-byte max input sequence, no 3-byte header
}
}
int do_encoding() const noexcept override {
// return length of code sequence (from codecvt)
return 0; // 0 => varying length
}
};
template <
class _Codecvt,
class _Elem = wchar_t,
class CharT = char,
class _Traits = std::char_traits<_Elem>>
class wbuffer_convert
: public std::basic_streambuf<_Elem, _Traits> { // stream buffer associated with a codecvt facet
private:
enum _Mode { _Unused, _Wrote, _Need, _Got, _Eof };
enum { _STRING_INC = 8 };
public:
using _Mysb = std::basic_streambuf<CharT>;
using _Byte_traits = std::char_traits<CharT>;
using int_type = typename _Traits::int_type;
using pos_type = typename _Traits::pos_type;
using off_type = typename _Traits::off_type;
using state_type = typename _Codecvt::state_type;
wbuffer_convert() : _State(), _Pcvt(new _Codecvt), _Mystrbuf(nullptr), _Status(_Unused), _Nback(0) {
// construct without buffer pointer
_Loc = std::locale(_Loc, const_cast<_Codecvt*>(_Pcvt));
}
explicit wbuffer_convert(_Mysb* _Strbuf)
: _State(), _Pcvt(new _Codecvt), _Mystrbuf(_Strbuf), _Status(_Unused), _Nback(0) {
// construct with byte stream buffer pointer
_Loc = std::locale(_Loc, const_cast<_Codecvt*>(_Pcvt));
}
wbuffer_convert(_Mysb* _Strbuf, const _Codecvt* _Pcvt_arg)
: _State(), _Pcvt(_Pcvt_arg), _Mystrbuf(_Strbuf), _Status(_Unused), _Nback(0) {
// construct with byte stream buffer pointer and codecvt
_Loc = std::locale(_Loc, const_cast<_Codecvt*>(_Pcvt));
}
wbuffer_convert(_Mysb* _Strbuf, const _Codecvt* _Pcvt_arg, state_type _State_arg)
: _State(_State_arg), _Pcvt(_Pcvt_arg), _Mystrbuf(_Strbuf), _Status(_Unused), _Nback(0) {
// construct with byte stream buffer pointer, codecvt, and state
_Loc = std::locale(_Loc, const_cast<_Codecvt*>(_Pcvt));
}
~wbuffer_convert() noexcept override {
while (_Status == _Wrote) { // put any trailing homing shift
if (_Str.size() < _STRING_INC) {
_Str.assign(_STRING_INC, '\0');
}
CharT* _Buf = &_Str[0];
CharT* _Dest;
switch (_Pcvt->unshift(_State, _Buf, _Buf + _Str.size(), _Dest)) { // test result of homing conversion
case _Codecvt::ok:
_Status = _Unused; // homed successfully
case _Codecvt::partial: // fall through
{ // put any generated bytes
ptrdiff_t _Count = _Dest - _Buf;
if (0 < _Count
&& _Byte_traits::eq_int_type(
_Byte_traits::eof(), static_cast<typename _Byte_traits::int_type>(_Mystrbuf->sputn(_Buf, _Count)))) {
return; // write failed
}
if (_Status == _Wrote && _Count == 0) {
_Str.append(_STRING_INC, '\0'); // try with more space
}
break;
}
case _Codecvt::noconv:
return; // nothing to do
default:
return; // conversion failed
}
}
}
[[nodiscard]] _Mysb* rdbuf() const {
return _Mystrbuf;
}
_Mysb* rdbuf(_Mysb* _Strbuf) { // set byte stream buffer pointer
_Mysb* _Oldstrbuf = _Mystrbuf;
_Mystrbuf = _Strbuf;
return _Oldstrbuf;
}
[[nodiscard]] state_type state() const {
return _State;
}
wbuffer_convert(const wbuffer_convert&) = delete;
wbuffer_convert& operator=(const wbuffer_convert&) = delete;
protected:
int_type overflow(int_type _Meta = _Traits::eof()) override { // put an element to stream
if (_Traits::eq_int_type(_Traits::eof(), _Meta)) {
return _Traits::not_eof(_Meta); // EOF, return success code
} else if (!_Mystrbuf || 0 < _Nback || (_Status != _Unused && _Status != _Wrote)) {
return _Traits::eof(); // no buffer or reading, fail
} else { // put using codecvt facet
const _Elem _Ch = _Traits::to_char_type(_Meta);
if (_Str.size() < _STRING_INC) {
_Str.assign(_STRING_INC, '\0');
}
for (_Status = _Wrote;;) {
CharT* _Buf = &_Str[0];
const _Elem* _Src;
CharT* _Dest;
// test result of converting one element
switch (_Pcvt->out(_State, &_Ch, &_Ch + 1, _Src, _Buf, _Buf + _Str.size(), _Dest)) {
case _Codecvt::partial:
case _Codecvt::ok:
{ // converted something, try to put it out
ptrdiff_t _Count = _Dest - _Buf;
if (0 < _Count
&& _Byte_traits::eq_int_type(_Byte_traits::eof(),
static_cast<typename _Byte_traits::int_type>(_Mystrbuf->sputn(_Buf, _Count)))) {
return _Traits::eof(); // write failed
}
if (_Src != &_Ch) {
return _Meta; // converted whole element
}
if (0 >= _Count) {
if (_Str.size() >= 4 * _STRING_INC) {
return _Traits::eof(); // conversion failed
}
_Str.append(_STRING_INC, '\0'); // try with more space
}
break;
}
case _Codecvt::noconv:
if (_Traits::eq_int_type(
_Traits::eof(), static_cast<int_type>(_Mystrbuf->sputn(reinterpret_cast<const char*>(&_Ch),
static_cast<std::streamsize>(sizeof(_Elem)))))) {
return _Traits::eof();
}
return _Meta; // put native byte order
default:
return _Traits::eof(); // conversion failed
}
}
}
}
int_type pbackfail(int_type _Meta = _Traits::eof()) override { // put an element back to stream
if (sizeof(_Myback) / sizeof(_Myback[0]) <= _Nback || _Status == _Wrote) {
return _Traits::eof(); // nowhere to put back
} else { // enough room, put it back
if (!_Traits::eq_int_type(_Traits::eof(), _Meta)) {
_Myback[_Nback] = _Traits::to_char_type(_Meta);
}
++_Nback;
if (_Status == _Unused) {
_Status = _Got;
}
return _Meta;
}
}
int_type underflow() override { // get an element from stream, but don't point past it
int_type _Meta;
if (0 >= _Nback) {
if (_Traits::eq_int_type(_Traits::eof(), _Meta = _Get_elem())) {
return _Meta; // _Get_elem failed, return EOF
}
_Myback[_Nback++] = _Traits::to_char_type(_Meta);
}
return _Traits::to_int_type(_Myback[_Nback - 1]);
}
int_type uflow() override { // get an element from stream, point past it
int_type _Meta;
if (0 >= _Nback) {
if (_Traits::eq_int_type(_Traits::eof(), _Meta = _Get_elem())) {
return _Meta; // _Get_elem failed, return EOF
}
_Myback[_Nback++] = _Traits::to_char_type(_Meta);
}
return _Traits::to_int_type(_Myback[--_Nback]);
}
pos_type seekoff(off_type, std::ios_base::seekdir,
std::ios_base::openmode = static_cast<std::ios_base::openmode>(std::ios_base::in | std::ios_base::out)) override {
return pos_type(-1); // always fail
}
pos_type seekpos(
pos_type, std::ios_base::openmode = static_cast<std::ios_base::openmode>(std::ios_base::in | std::ios_base::out)) override {
return pos_type(-1); // always fail
}
private:
int_type _Get_elem() { // compose an element from byte stream buffer
if (_Mystrbuf && _Status != _Wrote) { // got buffer, haven't written, try to compose an element
if (_Status != _Eof) {
if (_Str.empty()) {
_Status = _Need;
} else {
_Status = _Got;
}
}
while (_Status != _Eof) { // get using codecvt facet
CharT* _Buf = &_Str[0];
_Elem _Ch;
_Elem* _Dest;
const CharT* _Src;
int _Meta;
if (_Status == _Need) {
if (_Byte_traits::eq_int_type(_Byte_traits::eof(), _Meta = _Mystrbuf->sbumpc())) {
_Status = _Eof;
} else {
_Str.push_back(_Byte_traits::to_char_type(_Meta));
}
}
// test result of converting one element
switch (_Pcvt->in(_State, _Buf, _Buf + _Str.size(), _Src, &_Ch, &_Ch + 1, _Dest)) {
case _Codecvt::partial:
case _Codecvt::ok:
_Str.erase(0, static_cast<std::size_t>(_Src - _Buf)); // discard any used input
if (_Dest != &_Ch) {
return _Traits::to_int_type(_Ch);
}
break;
case _Codecvt::noconv:
if (_Str.size() < sizeof(_Elem)) {
break; // no conversion, but need more chars
}
std::memcpy(&_Ch, _Buf, sizeof(_Elem)); // copy raw bytes to element
_Str.erase(0, sizeof(_Elem));
return _Traits::to_int_type(_Ch); // return result
default:
_Status = _Eof; // conversion failed
break;
}
}
}
return _Traits::eof();
}
state_type _State; // code conversion state
const _Codecvt* _Pcvt; // the codecvt facet
_Mysb* _Mystrbuf; // pointer to stream buffer
_Mode _Status; // buffer read/write status
std::size_t _Nback; // number of elements in putback buffer
_Elem _Myback[8]; // putback buffer
std::basic_string<CharT> _Str; // unconsumed input bytes
std::locale _Loc; // manages reference to codecvt facet
};
template <
class _Codecvt,
class _Elem = wchar_t,
class CharT = char,
class _Walloc = std::allocator<_Elem>,
class _Balloc = std::allocator<CharT>>
class wstring_convert { // converts between _Elem (wide) and char (byte) strings
private:
enum { _BUF_INC = 8, _BUF_MAX = 16 };
void _Init(const _Codecvt* _Pcvt_arg = new _Codecvt) { // initialize the object
_State = state_type{};
_Pcvt = _Pcvt_arg;
_Loc = std::locale(_Loc, const_cast<_Codecvt*>(_Pcvt));
_Nconv = 0;
}
public:
using byte_string = std::basic_string<CharT, std::char_traits<CharT>, _Balloc>;
using wide_string = std::basic_string<_Elem, std::char_traits<_Elem>, _Walloc>;
using state_type = typename _Codecvt::state_type;
using int_type = typename wide_string::traits_type::int_type;
wstring_convert() : _Has_state(false), _Has_berr(false), _Has_werr(false) { // construct with no error strings
_Init();
}
explicit wstring_convert(const _Codecvt* _Pcvt_arg)
: _Has_state(false), _Has_berr(false), _Has_werr(false) { // construct with no error strings and codecvt
_Init(_Pcvt_arg);
}
wstring_convert(const _Codecvt* _Pcvt_arg, state_type _State_arg)
: _Has_state(true), _Has_berr(false), _Has_werr(false) { // construct with no error strings, codecvt, and state
_Init(_Pcvt_arg);
_State = _State_arg;
}
explicit wstring_convert(const byte_string& _Berr_arg)
: _Berr(_Berr_arg), _Has_state(false), _Has_berr(true), _Has_werr(false) { // construct with byte error string
_Init();
}
wstring_convert(const byte_string& _Berr_arg, const wide_string& _Werr_arg)
: _Berr(_Berr_arg), _Werr(_Werr_arg), _Has_state(false), _Has_berr(true),
_Has_werr(true) { // construct with byte and wide error strings
_Init();
}
virtual ~wstring_convert() noexcept {}
[[nodiscard]] std::size_t converted() const noexcept { // get conversion count
return _Nconv;
}
[[nodiscard]] state_type state() const {
return _State;
}
[[nodiscard]] wide_string from_bytes(CharT _Byte) { // convert a byte to a wide string
return from_bytes(&_Byte, &_Byte + 1);
}
[[nodiscard]] wide_string from_bytes(const CharT* _Ptr) { // convert a NTBS to a wide string
return from_bytes(_Ptr, _Ptr + std::strlen(_Ptr));
}
[[nodiscard]] wide_string from_bytes(const byte_string& _Bstr) { // convert a byte string to a wide string
const CharT* _Ptr = _Bstr.c_str();
return from_bytes(_Ptr, _Ptr + _Bstr.size());
}
[[nodiscard]] wide_string from_bytes(
const CharT* _First, const CharT* _Last) { // convert byte sequence [_First, _Last) to a wide string
wide_string _Wbuf;
wide_string _Wstr;
const CharT* _First_sav = _First;
if (!_Has_state) {
_State = state_type{}; // reset state if not remembered
}
_Wbuf.append(_BUF_INC, _Elem{});
for (_Nconv = 0; _First != _Last; _Nconv = static_cast<std::size_t>(_First - _First_sav)) {
// convert one or more bytes
_Elem* _Dest = &_Wbuf[0];
_Elem* _Dnext;
// test result of converting one or more bytes
switch (_Pcvt->in(_State, _First, _Last, _First, _Dest, _Dest + _Wbuf.size(), _Dnext)) {
case _Codecvt::partial:
case _Codecvt::ok:
if (_Dest < _Dnext) {
_Wstr.append(_Dest, static_cast<std::size_t>(_Dnext - _Dest));
} else if (_Wbuf.size() < _BUF_MAX) {
_Wbuf.append(_BUF_INC, _Elem{});
} else if (_Has_werr) {
return _Werr;
} else {
throw std::range_error("bad conversion");
}
break;
case _Codecvt::noconv:
for (; _First != _Last; ++_First) {
_Wstr.push_back(static_cast<_Elem>(static_cast<std::make_unsigned_t<CharT>>(*_First)));
}
break; // no conversion, just copy code values
default:
if (_Has_werr) {
return _Werr;
} else {
throw std::range_error("bad conversion");
}
}
}
return _Wstr;
}
[[nodiscard]] byte_string to_bytes(_Elem _Char) { // convert a widechar to a byte string
return to_bytes(&_Char, &_Char + 1);
}
[[nodiscard]] byte_string to_bytes(const _Elem* _Wptr) { // convert a NTWCS to a byte string
const _Elem* _Next = _Wptr;
while (*_Next != 0) {
++_Next;
}
return to_bytes(_Wptr, _Next);
}
[[nodiscard]] byte_string to_bytes(const wide_string& _Wstr) { // convert a wide string to a byte string
const _Elem* _Wptr = _Wstr.c_str();
return to_bytes(_Wptr, _Wptr + _Wstr.size());
}
[[nodiscard]] byte_string to_bytes(
const _Elem* _First, const _Elem* _Last) { // convert wide sequence [_First, _Last) to a byte string
byte_string _Bbuf;
byte_string _Bstr;
const _Elem* _First_sav = _First;
if (!_Has_state) {
_State = state_type{}; // reset state if not remembered
}
_Bbuf.append(_BUF_INC, '\0');
for (_Nconv = 0; _First != _Last; _Nconv = static_cast<std::size_t>(_First - _First_sav)) {
// convert one or more wide chars
CharT* _Dest = &_Bbuf[0];
CharT* _Dnext;
// test result of converting one or more wide chars
switch (_Pcvt->out(_State, _First, _Last, _First, _Dest, _Dest + _Bbuf.size(), _Dnext)) {
case _Codecvt::partial:
case _Codecvt::ok:
if (_Dest < _Dnext) {
_Bstr.append(_Dest, static_cast<std::size_t>(_Dnext - _Dest));
} else if (_Bbuf.size() < _BUF_MAX) {
_Bbuf.append(_BUF_INC, '\0');
} else if (_Has_berr) {
return _Berr;
} else {
throw std::range_error("bad conversion");
}
break;
case _Codecvt::noconv:
for (; _First != _Last; ++_First) {
_Bstr.push_back(static_cast<CharT>(static_cast<int_type>(*_First)));
}
break; // no conversion, just copy code values
default:
if (_Has_berr) {
return _Berr;
} else {
throw std::range_error("bad conversion");
}
}
}
return _Bstr;
}
wstring_convert(const wstring_convert&) = delete;
wstring_convert& operator=(const wstring_convert&) = delete;
private:
const _Codecvt* _Pcvt; // the codecvt facet
std::locale _Loc; // manages reference to codecvt facet
byte_string _Berr;
wide_string _Werr;
state_type _State; // the remembered state
bool _Has_state;
bool _Has_berr;
bool _Has_werr;
std::size_t _Nconv;
};
}
namespace asio2
{
/**
* @brief Return default system locale name in POSIX format.
*
* This function tries to detect the locale using, LC_CTYPE, LC_ALL and LANG environment
* variables in this order and if all of them unset, in POSIX platforms it returns "C"
*
* On Windows additionally to check the above environment variables, this function
* tries to creates locale name from ISO-339 and ISO-3199 country codes defined
* for user default locale.
* If use_utf8_on_windows is true it sets the encoding to UTF-8, otherwise, if system
* locale supports ANSI code-page it defines the ANSI encoding like windows-1252, otherwise it fall-backs
* to UTF-8 encoding if ANSI code-page is not available.
*
* /boost/libs/locale/src/boost/locale/util/default_locale.cpp
*/
inline std::string get_system_locale(bool use_utf8_on_windows = false)
{
char const *lang = 0;
if(!lang || !*lang)
lang = std::getenv("LC_CTYPE");
if(!lang || !*lang)
lang = std::getenv("LC_ALL");
if(!lang || !*lang)
lang = std::getenv("LANG");
#if !defined(BOOST_LOCALE_USE_WIN32_API) && !defined(BHO_LOCALE_USE_WIN32_API) && !defined(ASIO2_LOCALE_USE_WIN32_API)
(void)use_utf8_on_windows; // not relevant for non-windows
if(!lang || !*lang)
lang = "C";
return lang;
#else
if(lang && *lang) {
return lang;
}
char buf[10] = { 0 };
if(GetLocaleInfoA(LOCALE_USER_DEFAULT,LOCALE_SISO639LANGNAME,buf,sizeof(buf))==0)
return "C";
std::string lc_name = buf;
if(GetLocaleInfoA(LOCALE_USER_DEFAULT,LOCALE_SISO3166CTRYNAME,buf,sizeof(buf))!=0) {
lc_name += "_";
lc_name += buf;
}
if(!use_utf8_on_windows) {
if(GetLocaleInfoA(LOCALE_USER_DEFAULT,LOCALE_IDEFAULTANSICODEPAGE,buf,sizeof(buf))!=0) {
if(std::atoi(buf)==0)
lc_name+=".UTF-8";
else {
lc_name +=".windows-";
lc_name +=buf;
}
}
else {
lc_name += "UTF-8";
}
}
else {
lc_name += ".UTF-8";
}
return lc_name;
#endif
}
/**
* @brief Return default system locale name that can be used in codecvt.
*
*/
inline std::string get_codecvt_locale(bool use_utf8_on_windows = false)
{
char const *lang = 0;
if(!lang || !*lang)
lang = std::getenv("LC_CTYPE");
if(!lang || !*lang)
lang = std::getenv("LC_ALL");
if(!lang || !*lang)
lang = std::getenv("LANG");
#if !defined(BOOST_LOCALE_USE_WIN32_API) && !defined(BHO_LOCALE_USE_WIN32_API) && !defined(ASIO2_LOCALE_USE_WIN32_API)
(void)use_utf8_on_windows; // not relevant for non-windows
if(!lang || !*lang)
lang = "C";
return lang;
#else
if(lang && *lang) {
return lang;
}
char buf[10] = { 0 };
std::string lc_name;
if(!use_utf8_on_windows) {
if(GetLocaleInfoA(LOCALE_USER_DEFAULT,LOCALE_IDEFAULTANSICODEPAGE,buf,sizeof(buf))!=0) {
if(std::atoi(buf)==0)
lc_name+=".UTF-8";
else {
lc_name +=".";
lc_name +=buf;
}
}
else {
lc_name += "UTF-8";
}
}
else {
lc_name += ".UTF-8";
}
return lc_name;
#endif
}
/**
* @brief Converts gbk characters to utf8 characters.
* @param str - gbk characters
* @return Converted value as std::string.
*/
template<class StringT>
inline auto gbk_to_utf8(const StringT& str, const std::string& locale_name = "chs") noexcept
{
using CharT = typename detail::char_type<StringT>::type;
clear_last_error();
std::wstring w;
std::codecvt_byname<wchar_t, CharT, std::mbstate_t>* c = nullptr;
try
{
c = new std::codecvt_byname<wchar_t, CharT, std::mbstate_t>(locale_name);
}
catch (const std::exception&)
{
set_last_error(std::errc::invalid_argument);
return std::basic_string<CharT>{};
}
// gbk to widechar
{
auto sv = asio2::to_basic_string_view(str);
asio2::wstring_convert<std::codecvt_byname<wchar_t, CharT, std::mbstate_t>, wchar_t, CharT> conv(c);
try
{
w = conv.from_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
w = conv.from_bytes(sv.data(), sv.data() + sv.size());
}
}
// widechar to utf8
{
auto sv = asio2::to_basic_string_view(w);
asio2::wstring_convert<asio2::codecvt_utf8<wchar_t, CharT>, wchar_t, CharT> conv;
try
{
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
}
}
/**
* @brief Converts utf8 characters to gbk characters.
* @param str - gbk characters
* @return Converted value as std::string.
*/
template<class StringT>
inline auto utf8_to_gbk(const StringT& str, const std::string& locale_name = "chs") noexcept
{
using CharT = typename detail::char_type<StringT>::type;
clear_last_error();
std::wstring w;
std::codecvt_byname<wchar_t, char, std::mbstate_t>* c = nullptr;
try
{
c = new std::codecvt_byname<wchar_t, char, std::mbstate_t>(locale_name);
}
catch (const std::exception&)
{
set_last_error(std::errc::invalid_argument);
return std::string{};
}
// utf8 to widechar
{
auto sv = asio2::to_basic_string_view(str);
asio2::wstring_convert<asio2::codecvt_utf8<wchar_t, CharT>, wchar_t, CharT> conv;
try
{
w = conv.from_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
w = conv.from_bytes(sv.data(), sv.data() + sv.size());
}
}
// widechar to gbk
{
auto sv = asio2::to_basic_string_view(w);
asio2::wstring_convert<std::codecvt_byname<wchar_t, char, std::mbstate_t>> conv(c);
try
{
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
}
}
/**
* @brief Converts wide characters to multibyte characters.
* @param str - wide characters
* @param locale_name - locale name
* @return Converted value as std::string.
*/
template<class StringT>
inline std::string wcstombs(const StringT& str, const std::string& locale_name = asio2::get_codecvt_locale()) noexcept
{
clear_last_error();
auto sv = asio2::to_basic_string_view(str);
std::codecvt_byname<wchar_t, char, std::mbstate_t>* c = nullptr;
try
{
c = new std::codecvt_byname<wchar_t, char, std::mbstate_t>(locale_name);
}
catch (const std::exception&)
{
set_last_error(std::errc::invalid_argument);
return std::string{};
}
asio2::wstring_convert<std::codecvt_byname<wchar_t, char, std::mbstate_t>> conv(c);
try
{
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
}
/**
* @brief Converts multibyte characters to wide characters.
* @param str - wide characters
* @param locale_name - locale name
* @return Converted value as std::wstring.
*/
template<class StringT>
inline std::wstring mbstowcs(const StringT& str, const std::string& locale_name = asio2::get_codecvt_locale()) noexcept
{
clear_last_error();
auto sv = asio2::to_basic_string_view(str);
std::codecvt_byname<wchar_t, char, std::mbstate_t>* c = nullptr;
try
{
c = new std::codecvt_byname<wchar_t, char, std::mbstate_t>(locale_name);
}
catch (const std::exception&)
{
set_last_error(std::errc::invalid_argument);
return std::wstring{};
}
asio2::wstring_convert<std::codecvt_byname<wchar_t, char, std::mbstate_t>> conv(c);
try
{
return conv.from_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
return conv.from_bytes(sv.data(), sv.data() + sv.size());
}
}
/**
* @brief Converts utf8 characters to current default locale characters.
* @param str - utf8 characters
* @return Converted value as std::string.
*/
template<class StringT>
inline std::string utf8_to_locale(const StringT& str) noexcept
{
using CharT = typename detail::char_type<StringT>::type;
clear_last_error();
std::wstring w;
std::codecvt_byname<wchar_t, char, std::mbstate_t>* c = nullptr;
try
{
c = new std::codecvt_byname<wchar_t, char, std::mbstate_t>(asio2::get_codecvt_locale());
}
catch (const std::exception&)
{
set_last_error(std::errc::invalid_argument);
return std::string{};
}
// utf8 to widechar
{
auto sv = asio2::to_basic_string_view(str);
asio2::wstring_convert<asio2::codecvt_utf8<wchar_t, CharT>, wchar_t, CharT> conv;
try
{
w = conv.from_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
w = conv.from_bytes(sv.data(), sv.data() + sv.size());
}
}
// widechar to locale
{
auto sv = asio2::to_basic_string_view(w);
asio2::wstring_convert<std::codecvt_byname<wchar_t, char, std::mbstate_t>> conv(c);
try
{
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
}
}
/**
* @brief Converts current default locale characters to utf8 characters.
* @param str - current default locale characters
* @return Converted value as std::string.
*/
template<class StringT>
inline std::string locale_to_utf8(const StringT& str) noexcept
{
using CharT = typename detail::char_type<StringT>::type;
clear_last_error();
std::wstring w;
std::codecvt_byname<wchar_t, CharT, std::mbstate_t>* c = nullptr;
try
{
c = new std::codecvt_byname<wchar_t, CharT, std::mbstate_t>(asio2::get_codecvt_locale());
}
catch (const std::exception&)
{
set_last_error(std::errc::invalid_argument);
return std::string{};
}
// locale to widechar
{
auto sv = asio2::to_basic_string_view(str);
asio2::wstring_convert<std::codecvt_byname<wchar_t, CharT, std::mbstate_t>, wchar_t, CharT> conv(c);
try
{
w = conv.from_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
w = conv.from_bytes(sv.data(), sv.data() + sv.size());
}
}
// widechar to utf8
{
auto sv = asio2::to_basic_string_view(w);
asio2::wstring_convert<asio2::codecvt_utf8<wchar_t, CharT>, wchar_t, CharT> conv;
try
{
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
catch (const std::range_error&)
{
set_last_error(std::errc::result_out_of_range);
sv = sv.substr(0, conv.converted());
return conv.to_bytes(sv.data(), sv.data() + sv.size());
}
}
}
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_CODECVT_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_THREAD_ID_COMPONENT_HPP__
#define __ASIO2_THREAD_ID_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <thread>
#include <asio2/base/error.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t = void>
class thread_id_cp
{
public:
/**
* @brief constructor
*/
thread_id_cp() = default;
/**
* @brief destructor
*/
~thread_id_cp() = default;
thread_id_cp(thread_id_cp&&) noexcept = default;
thread_id_cp(thread_id_cp const&) = default;
thread_id_cp& operator=(thread_id_cp&&) noexcept = default;
thread_id_cp& operator=(thread_id_cp const&) = default;
public:
/**
* @brief Determine whether the object is running in the current thread.
*/
inline bool running_in_this_thread() const noexcept
{
derived_t& derive = const_cast<derived_t&>(static_cast<const derived_t&>(*this));
return (derive.io().get_thread_id() == std::this_thread::get_id());
}
/**
* @brief return the thread id of the current object running in.
*/
inline std::thread::id get_thread_id() const noexcept
{
derived_t& derive = const_cast<derived_t&>(static_cast<const derived_t&>(*this));
return derive.io().get_thread_id();
}
protected:
};
}
#endif // !__ASIO2_THREAD_ID_COMPONENT_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_DEFINE_HPP__
#define __ASIO2_DEFINE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
// use this method to disable the compile warning under mingw.
// note : the tail of "disable_warning_pedantic" don't has the char ';'
// warning: extra ';' [-Wpedantic]
namespace asio2::detail
{
template<class T, class U> class [[maybe_unused]] disable_warning_pedantic {};
}
// Note :
// All the following classes must be in the namespace asio2::detail
// All code that uses the following macros must also be in the namespace asio2::detail
#define ASIO2_CLASS_DECLARE_BASE(KEYWORD) \
KEYWORD io_t; \
KEYWORD iopool; \
template <class, class> KEYWORD iopool_cp; \
template <class, class> KEYWORD alive_time_cp; \
template <class, class> KEYWORD condition_event_cp; \
template <class, class> KEYWORD connect_cp; \
template <class, class> KEYWORD connect_time_cp; \
template <class, class> KEYWORD connect_timeout_cp; \
template <class, class> KEYWORD data_persistence_cp; \
template <class, class> KEYWORD shutdown_cp; \
template <class, class> KEYWORD close_cp; \
template <class, class> KEYWORD disconnect_cp; \
template <class, class> KEYWORD event_queue_cp; \
template <class > KEYWORD event_queue_guard; \
template <class, class> KEYWORD post_cp; \
template <class, class> KEYWORD rdc_call_cp; \
template <class, class> KEYWORD rdc_call_cp_impl; \
template <class, class> KEYWORD reconnect_timer_cp; \
template <class, class> KEYWORD send_cp; \
template <class, class> KEYWORD silence_timer_cp; \
template <class, class> KEYWORD socket_cp; \
template <class, class> KEYWORD user_data_cp; \
template <class, class> KEYWORD user_timer_cp; \
template <class > KEYWORD session_mgr_t; \
template <class, class> KEYWORD socks5_client_impl; \
template <class, class, class> KEYWORD socks5_client_connect_op; \
template <class, class> KEYWORD disable_warning_pedantic
#define ASIO2_CLASS_DECLARE_TCP_BASE(KEYWORD) \
template <class, class> KEYWORD ssl_context_cp; \
template <class, class> KEYWORD ssl_stream_cp; \
template <class, class> KEYWORD tcp_keepalive_cp; \
template <class, class> KEYWORD tcp_recv_op; \
template <class, class> KEYWORD tcp_send_op; \
template <class, class> KEYWORD ws_stream_cp; \
template <class, class> KEYWORD http_recv_op; \
template <class, class> KEYWORD http_send_op; \
template <class, class> KEYWORD ws_send_op; \
template <class, class> KEYWORD rpc_call_cp; \
template <class, class> KEYWORD rpc_recv_op; \
template <class, class> KEYWORD http_router_t; \
template <class, class> KEYWORD rpc_invoker_t; \
template <class, class> KEYWORD mqtt_send_op; \
template <class, class> KEYWORD mqtt_handler_t; \
template <class, class> KEYWORD mqtt_aop_auth ; \
template <class, class> KEYWORD mqtt_aop_connack ; \
template <class, class> KEYWORD mqtt_aop_connect ; \
template <class, class> KEYWORD mqtt_aop_disconnect ; \
template <class, class> KEYWORD mqtt_aop_pingreq ; \
template <class, class> KEYWORD mqtt_aop_pingresp ; \
template <class, class> KEYWORD mqtt_aop_puback ; \
template <class, class> KEYWORD mqtt_aop_pubcomp ; \
template <class, class> KEYWORD mqtt_aop_publish ; \
template <class, class> KEYWORD mqtt_aop_pubrec ; \
template <class, class> KEYWORD mqtt_aop_pubrel ; \
template <class, class> KEYWORD mqtt_aop_suback ; \
template <class, class> KEYWORD mqtt_aop_subscribe ; \
template <class, class> KEYWORD mqtt_aop_unsuback ; \
template <class, class> KEYWORD mqtt_aop_unsubscribe; \
template <class, class> KEYWORD mqtt_invoker_t; \
template <class, class> KEYWORD mqtt_subscribe_router_t; \
template <class, class> KEYWORD mqtt_message_router_t; \
template <class, class> KEYWORD mqtt_topic_alias_t; \
template <class, class> KEYWORD mqtt_session_persistence; \
template <class, class> KEYWORD disable_warning_pedantic
#define ASIO2_CLASS_DECLARE_TCP_CLIENT(KEYWORD) \
template <class, class> KEYWORD client_impl_t; \
template <class, class> KEYWORD tcp_client_impl_t; \
template <class, class> KEYWORD tcps_client_impl_t; \
template <class, class> KEYWORD http_client_impl_t; \
template <class, class> KEYWORD https_client_impl_t; \
template <class, class> KEYWORD ws_client_impl_t; \
template <class, class> KEYWORD wss_client_impl_t; \
template <class, class> KEYWORD rpc_client_impl_t; \
template <class, class> KEYWORD mqtt_client_impl_t; \
template <class, class> KEYWORD disable_warning_pedantic
#define ASIO2_CLASS_DECLARE_TCP_SERVER(KEYWORD) \
template <class, class> KEYWORD server_impl_t; \
template <class, class> KEYWORD tcp_server_impl_t; \
template <class, class> KEYWORD tcps_server_impl_t; \
template <class, class> KEYWORD http_server_impl_t; \
template <class, class> KEYWORD https_server_impl_t; \
template <class, class> KEYWORD ws_server_impl_t; \
template <class, class> KEYWORD wss_server_impl_t; \
template <class, class> KEYWORD rpc_server_impl_t; \
template <class, class> KEYWORD mqtt_server_impl_t; \
template <class, class> KEYWORD disable_warning_pedantic
#define ASIO2_CLASS_DECLARE_TCP_SESSION(KEYWORD) \
template <class, class> KEYWORD session_impl_t; \
template <class, class> KEYWORD tcp_session_impl_t; \
template <class, class> KEYWORD tcps_session_impl_t; \
template <class, class> KEYWORD http_session_impl_t; \
template <class, class> KEYWORD https_session_impl_t; \
template <class, class> KEYWORD ws_session_impl_t; \
template <class, class> KEYWORD wss_session_impl_t; \
template <class, class> KEYWORD rpc_session_impl_t; \
template <class, class> KEYWORD mqtt_session_impl_t; \
template <class, class> KEYWORD disable_warning_pedantic
#define ASIO2_CLASS_DECLARE_UDP_BASE(KEYWORD) \
template <class, class> KEYWORD kcp_stream_cp; \
template <class, class> KEYWORD udp_send_cp; \
template <class, class> KEYWORD udp_send_op; \
template <class, class> KEYWORD udp_recv_op; \
template <class, class> KEYWORD disable_warning_pedantic
#define ASIO2_CLASS_DECLARE_UDP_CLIENT(KEYWORD) \
template <class, class> KEYWORD client_impl_t; \
template <class, class> KEYWORD udp_client_impl_t; \
template <class, class> KEYWORD disable_warning_pedantic
#define ASIO2_CLASS_DECLARE_UDP_SERVER(KEYWORD) \
template <class, class> KEYWORD server_impl_t; \
template <class, class> KEYWORD udp_server_impl_t; \
template <class, class> KEYWORD disable_warning_pedantic
#define ASIO2_CLASS_DECLARE_UDP_SESSION(KEYWORD) \
template <class, class> KEYWORD session_impl_t; \
template <class, class> KEYWORD udp_session_impl_t; \
template <class, class> KEYWORD disable_warning_pedantic
//-------------------------------------------------------------------------------------------------
#define ASIO2_CLASS_FORWARD_DECLARE_BASE ASIO2_CLASS_DECLARE_BASE (class)
#define ASIO2_CLASS_FRIEND_DECLARE_BASE ASIO2_CLASS_DECLARE_BASE (friend class)
//-------------------------------------------------------------------------------------------------
#define ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE ASIO2_CLASS_DECLARE_TCP_BASE (class)
#define ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT ASIO2_CLASS_DECLARE_TCP_CLIENT (class)
#define ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER ASIO2_CLASS_DECLARE_TCP_SERVER (class)
#define ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION ASIO2_CLASS_DECLARE_TCP_SESSION(class)
#define ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE ASIO2_CLASS_DECLARE_TCP_BASE (friend class)
#define ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT ASIO2_CLASS_DECLARE_TCP_CLIENT (friend class)
#define ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER ASIO2_CLASS_DECLARE_TCP_SERVER (friend class)
#define ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION ASIO2_CLASS_DECLARE_TCP_SESSION(friend class)
//-------------------------------------------------------------------------------------------------
#define ASIO2_CLASS_FORWARD_DECLARE_UDP_BASE ASIO2_CLASS_DECLARE_UDP_BASE (class)
#define ASIO2_CLASS_FORWARD_DECLARE_UDP_CLIENT ASIO2_CLASS_DECLARE_UDP_CLIENT (class)
#define ASIO2_CLASS_FORWARD_DECLARE_UDP_SERVER ASIO2_CLASS_DECLARE_UDP_SERVER (class)
#define ASIO2_CLASS_FORWARD_DECLARE_UDP_SESSION ASIO2_CLASS_DECLARE_UDP_SESSION(class)
#define ASIO2_CLASS_FRIEND_DECLARE_UDP_BASE ASIO2_CLASS_DECLARE_UDP_BASE (friend class)
#define ASIO2_CLASS_FRIEND_DECLARE_UDP_CLIENT ASIO2_CLASS_DECLARE_UDP_CLIENT (friend class)
#define ASIO2_CLASS_FRIEND_DECLARE_UDP_SERVER ASIO2_CLASS_DECLARE_UDP_SERVER (friend class)
#define ASIO2_CLASS_FRIEND_DECLARE_UDP_SESSION ASIO2_CLASS_DECLARE_UDP_SESSION(friend class)
#endif // !__ASIO2_DEFINE_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_ERROR_HPP__
#define __ASIO2_ERROR_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
//#if !defined(NDEBUG) && !defined(_DEBUG) && !defined(DEBUG)
//#define NDEBUG
//#endif
#include <asio2/base/detail/push_options.hpp>
#include <cerrno>
#include <cassert>
#include <string>
#include <system_error>
#include <ios>
#include <future>
#include <asio2/external/asio.hpp>
#include <asio2/external/assert.hpp>
namespace asio2
{
// Very important features:
// One Definition Rule : https://en.wikipedia.org/wiki/One_Definition_Rule
// ---- internal linkage ----
// static global variable : static int x;
// static global function, namespace scope or not : static bool test(){...}
// enum definition : enum Boolean { NO,YES };
// class definition : class Point { int d_x; int d_y; ... };
// inline function definition : inline int operator==(const Point& left,const Point&right) { ... }
// union definition
// const variable definition
//
// ---- external linkage ----
// not inlined class member function : Point& Point::operator+=(const Point& right) { ... }
// not inlined not static function : Point operator+(const Point& left, const Point& right) { ... }
// global variable : int x;
// singleton class member function : class st{ static st& get(){static st& s; return s;} }
namespace detail
{
class [[maybe_unused]] external_linkaged_last_error
{
public:
[[maybe_unused]] static error_code & get() noexcept
{
// thread local variable of error_code
thread_local static error_code ec_last{};
return ec_last;
}
};
namespace internal_linkaged_last_error
{
[[maybe_unused]] static error_code & get() noexcept
{
// thread local variable of error_code
thread_local static error_code ec_last{};
return ec_last;
}
}
}
// use anonymous namespace to resolve global function redefinition problem
namespace
{
/**
* thread local variable of error_code
* In vs2017, sometimes the "namespace's thread_local error_code" will cause crash at
* system_category() -> (_Immortalize<_System_error_category>())-> _Execute_once(...),
* and the crash happens before the "main" function.
*/
//thread_local static error_code ec_last;
/**
* @brief get last error_code
*/
inline error_code & get_last_error() noexcept
{
return detail::external_linkaged_last_error::get();
}
/**
* @brief set last error_code
*/
template<class ErrorCodeEnum>
inline void set_last_error(ErrorCodeEnum e) noexcept
{
using type = std::remove_cv_t<std::remove_reference_t<ErrorCodeEnum>>;
if /**/ constexpr (
std::is_same_v<type, asio::error::basic_errors > ||
std::is_same_v<type, asio::error::netdb_errors > ||
std::is_same_v<type, asio::error::addrinfo_errors> ||
std::is_same_v<type, asio::error::misc_errors > )
{
get_last_error() = asio::error::make_error_code(e);
}
else if constexpr (
std::is_same_v<type, std::errc > ||
std::is_same_v<type, std::io_errc > ||
std::is_same_v<type, std::future_errc> )
{
#ifdef ASIO_STANDALONE
get_last_error() = std::make_error_code(e);
#else
get_last_error().assign(static_cast<int>(e), asio::error::get_system_category());
#endif
}
else if constexpr (std::is_integral_v<type>)
{
get_last_error().assign(static_cast<int>(e), asio::error::get_system_category());
}
else if constexpr (std::is_enum_v<type>)
{
get_last_error() = e;
}
else
{
ASIO2_ASSERT(false);
get_last_error().assign(static_cast<int>(e), asio::error::get_system_category());
}
}
/**
* @brief set last error_code
*/
template<typename T>
inline void set_last_error(int ec, const T& ecat) noexcept
{
get_last_error().assign(ec, ecat);
}
/**
* @brief set last error_code
*/
inline void set_last_error(const error_code & ec) noexcept
{
get_last_error() = ec;
}
/**
* @brief set last error_code
*/
inline void set_last_error(const system_error & e) noexcept
{
get_last_error() = e.code();
}
/**
* @brief Replaces the error code and error category with default values.
*/
inline void clear_last_error() noexcept
{
get_last_error().clear();
}
/**
* @brief get last error value, same as get_last_error_val
*/
inline auto last_error_val() noexcept
{
return get_last_error().value();
}
/**
* @brief get last error value
*/
inline auto get_last_error_val() noexcept
{
return get_last_error().value();
}
/**
* @brief get last error message, same as get_last_error_msg
*/
inline auto last_error_msg()
{
return get_last_error().message();
}
/**
* @brief get last error message
*/
inline auto get_last_error_msg()
{
return get_last_error().message();
}
}
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_ERROR_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_UDP_SESSION_HPP__
#define __ASIO2_UDP_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/session.hpp>
#include <asio2/base/detail/linear_buffer.hpp>
#include <asio2/udp/detail/kcp_util.hpp>
#include <asio2/udp/impl/udp_send_op.hpp>
#include <asio2/udp/impl/udp_recv_op.hpp>
#include <asio2/udp/impl/kcp_stream_cp.hpp>
namespace asio2::detail
{
struct template_args_udp_session
{
static constexpr bool is_session = true;
static constexpr bool is_client = false;
static constexpr bool is_server = false;
using socket_t = asio::ip::udp::socket&;
using buffer_t = detail::proxy_buffer<asio2::linear_buffer>;
using send_data_t = std::string_view;
using recv_data_t = std::string_view;
static constexpr std::size_t allocator_storage_size = 256;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SESSION;
template<class derived_t, class args_t = template_args_udp_session>
class udp_session_impl_t
: public session_impl_t<derived_t, args_t>
, public udp_send_op <derived_t, args_t>
, public udp_recv_op <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SESSION;
public:
using super = session_impl_t <derived_t, args_t>;
using self = udp_session_impl_t<derived_t, args_t>;
using args_type = args_t;
using key_type = asio::ip::udp::endpoint;
using buffer_type = typename args_t::buffer_t;
using send_data_t = typename args_t::send_data_t;
using recv_data_t = typename args_t::recv_data_t;
public:
/**
* @brief constructor
*/
explicit udp_session_impl_t(
session_mgr_t<derived_t> & sessions,
listener_t & listener,
io_t & rwio,
std::size_t init_buf_size,
std::size_t max_buf_size,
asio2::linear_buffer & buffer,
typename args_t::socket_t socket,
asio::ip::udp::endpoint & endpoint
)
: super(sessions, listener, rwio, init_buf_size, max_buf_size, socket)
, udp_send_op<derived_t, args_t>()
, udp_recv_op<derived_t, args_t>()
, remote_endpoint_(endpoint)
, wallocator_ ()
{
this->buffer_.bind_buffer(&buffer);
this->set_silence_timeout(std::chrono::milliseconds(udp_silence_timeout));
this->set_connect_timeout(std::chrono::milliseconds(udp_connect_timeout));
}
/**
* @brief destructor
*/
~udp_session_impl_t()
{
}
protected:
/**
* @brief start this session for prepare to recv msg
*/
template<typename C>
inline void start(std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = this->derived();
#if defined(ASIO2_ENABLE_LOG)
#if defined(ASIO2_ALLOCATOR_STORAGE_SIZE)
static_assert(decltype(wallocator_)::storage_size == ASIO2_ALLOCATOR_STORAGE_SIZE);
#else
static_assert(decltype(wallocator_)::storage_size == args_t::allocator_storage_size);
#endif
#endif
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
ASIO2_ASSERT(this->io().get_thread_id() != std::thread::id{});
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_silence_timer_called_ = false;
this->is_stop_connect_timeout_timer_called_ = false;
this->is_disconnect_called_ = false;
#endif
std::shared_ptr<derived_t> this_ptr = derive.selfptr();
try
{
this->remote_endpoint_copy_ = this->socket_.lowest_layer().remote_endpoint();
}
catch (const system_error&)
{
}
state_t expected = state_t::stopped;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
derive._do_disconnect(asio::error::already_started, std::move(this_ptr));
return;
}
// must read/write ecs in the io_context thread.
derive.ecs_ = ecs;
derive._do_init(this_ptr, ecs);
// First call the base class start function
super::start();
// if the ecs has remote data call mode,do some thing.
derive._rdc_init(ecs);
derive.push_event(
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(event_queue_guard<derived_t> g) mutable
{
derive.sessions().dispatch(
[&derive, this_ptr, ecs = std::move(ecs), g = std::move(g)]
() mutable
{
derive._handle_connect(
error_code{}, std::move(this_ptr), std::move(ecs), defer_event(std::move(g)));
});
});
}
public:
/**
* @brief stop session
* You can call this function in the communication thread and anywhere to stop the session.
* If this function is called in the communication thread, it will post a asynchronous
* event into the event queue, then return immediately.
* If this function is called not in the communication thread, it will blocking forever
* util the session is stopped completed.
* note : this function must be noblocking if it is called in the communication thread,
* otherwise if it's blocking, maybe cause circle lock.
* If the session stop is called in the server's bind connect callback, then the session
* will can't be added into the session manager, and the session's bind disconnect event
* can't be called also.
*/
inline void stop()
{
derived_t& derive = this->derived();
state_t expected = state_t::stopped;
if (this->state_.compare_exchange_strong(expected, state_t::stopped))
return;
expected = state_t::stopping;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
return;
// use promise to get the result of stop
std::promise<state_t> promise;
std::future<state_t> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[this, p = std::move(promise)]() mutable
{
p.set_value(this->state().load());
}
};
derive.post_event([&derive, this_ptr = derive.selfptr(), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
derive._do_disconnect(asio::error::operation_aborted, derive.selfptr(), defer_event
{
[&derive, this_ptr = std::move(this_ptr), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(derive, pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
});
});
// use this to ensure the client is stopped completed when the stop is called not in the io_context thread
while (!derive.running_in_this_thread() && !derive.sessions().io().running_in_this_thread())
{
std::future_status status = future.wait_for(std::chrono::milliseconds(100));
if (status == std::future_status::ready)
{
ASIO2_ASSERT(future.get() == state_t::stopped);
break;
}
else
{
if (derive.get_thread_id() == std::thread::id{})
break;
if (derive.sessions().io().get_thread_id() == std::thread::id{})
break;
if (derive.io().context().stopped())
break;
}
}
}
/**
* @brief check whether the session is stopped
*/
inline bool is_stopped()
{
return (this->state_ == state_t::stopped);
}
public:
/**
* @brief get the remote address
*/
inline std::string get_remote_address() const noexcept
{
try
{
return this->remote_endpoint_.address().to_string();
}
catch (system_error & e) { set_last_error(e); }
return std::string();
}
/**
* @brief get the remote address, same as get_remote_address
*/
inline std::string remote_address() const noexcept
{
return this->get_remote_address();
}
/**
* @brief get the remote port
*/
inline unsigned short get_remote_port() const noexcept
{
return this->remote_endpoint_.port();
}
/**
* @brief get the remote port, same as get_remote_port
*/
inline unsigned short remote_port() const noexcept
{
return this->get_remote_port();
}
/**
* @brief get this object hash key,used for session map
*/
inline key_type hash_key() const noexcept
{
// after test, there are a lot of hash collisions for asio::ip::udp::endpoint.
// so the map key can't be the hash result of asio::ip::udp::endpoint, it must
// be the asio::ip::udp::endpoint itself.
return this->remote_endpoint_;
}
/**
* @brief get the kcp pointer, just used for kcp mode
* default mode : ikcp_nodelay(kcp, 0, 10, 0, 0);
* generic mode : ikcp_nodelay(kcp, 0, 10, 0, 1);
* fast mode : ikcp_nodelay(kcp, 1, 10, 2, 1);
*/
inline kcp::ikcpcb* get_kcp() noexcept
{
return (this->kcp_ ? this->kcp_->kcp_ : nullptr);
}
/**
* @brief get the kcp pointer, just used for kcp mode. same as get_kcp
* default mode : ikcp_nodelay(kcp, 0, 10, 0, 0);
* generic mode : ikcp_nodelay(kcp, 0, 10, 0, 1);
* fast mode : ikcp_nodelay(kcp, 1, 10, 2, 1);
*/
inline kcp::ikcpcb* kcp() noexcept
{
return this->get_kcp();
}
protected:
template<typename C>
inline void _do_init(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
detail::ignore_unused(this_ptr, ecs);
// reset the variable to default status
this->derived().reset_connect_time();
this->derived().update_alive_time();
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs,
DeferEvent chain)
{
detail::ignore_unused(ec);
ASIO2_ASSERT(!ec);
ASIO2_ASSERT(this->derived().sessions().io().running_in_this_thread());
if constexpr (std::is_same_v<typename ecs_t<C>::condition_lowest_type, use_kcp_t>)
{
std::string& data = *(this->first_data_);
// step 3 : server recvd syn from client (the first data is syn)
// Check whether the first data packet is SYN handshake
if (!kcp::is_kcphdr_syn(data))
{
set_last_error(asio::error::address_family_not_supported);
this->derived()._fire_handshake(this_ptr);
this->derived()._do_disconnect(asio::error::address_family_not_supported,
std::move(this_ptr), std::move(chain));
return;
}
this->kcp_ = std::make_unique<kcp_stream_cp<derived_t, args_t>>(this->derived(), this->io_);
this->kcp_->_post_handshake(std::move(this_ptr), std::move(ecs), std::move(chain));
}
else
{
this->kcp_.reset();
this->derived()._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
}
template<typename C, typename DeferEvent>
inline void _do_start(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = this->derived();
if constexpr (std::is_same_v<typename ecs_t<C>::condition_lowest_type, use_kcp_t>)
{
ASIO2_ASSERT(this->kcp_);
if (this->kcp_)
this->kcp_->send_fin_ = true;
}
else
{
ASIO2_ASSERT(!this->kcp_);
}
derive.post_event(
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
defer_event chain(std::move(e), std::move(g));
if (!derive.is_started())
{
derive._do_disconnect(asio::error::operation_aborted, std::move(this_ptr), std::move(chain));
return;
}
derive._join_session(std::move(this_ptr), std::move(ecs), std::move(chain));
});
}
template<typename DeferEvent>
inline void _handle_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(this->state_ == state_t::stopped);
ASIO2_ASSERT(this->reading_ == false);
set_last_error(ec);
this->derived()._rdc_stop();
super::_handle_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _do_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
this->derived()._post_stop(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _post_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
// if we use asio::dispatch in server's _exec_stop, then we need:
// put _kcp_stop in front of super::stop, othwise the super::stop will execute
// "counter_ptr_.reset()", it will cause the udp server's _exec_stop is called,
// and the _handle_stop is called, and the socket will be closed, then the
// _kcp_stop send kcphdr will failed.
// but if we use asio::post in server's _exec_stop, there is no such problem.
if (this->kcp_)
this->kcp_->_kcp_stop();
// call the base class stop function
super::stop();
// call CRTP polymorphic stop
this->derived()._handle_stop(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
detail::ignore_unused(ec, this_ptr, chain);
ASIO2_ASSERT(this->state_ == state_t::stopped);
}
template<typename C, typename DeferEvent>
inline void _join_session(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
this->sessions_.emplace(this_ptr,
[this, this_ptr, ecs = std::move(ecs), chain = std::move(chain)]
(bool inserted) mutable
{
if (inserted)
this->derived()._start_recv(std::move(this_ptr), std::move(ecs), std::move(chain));
else
this->derived()._do_disconnect(asio::error::address_in_use, std::move(this_ptr), std::move(chain));
});
}
template<typename C, typename DeferEvent>
inline void _start_recv(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
// to avlid the user call stop in another thread,then it may be socket.async_read_some
// and socket.close be called at the same time
asio::dispatch(this->io().context(), make_allocator(this->wallocator_,
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
using condition_lowest_type = typename ecs_t<C>::condition_lowest_type;
detail::ignore_unused(chain);
// start the timer of check silence timeout
this->derived()._post_silence_timer(this->silence_timeout_, this_ptr);
if constexpr (std::is_same_v<condition_lowest_type, asio2::detail::use_kcp_t>)
{
detail::ignore_unused(this_ptr, ecs);
}
else
{
std::string& data = *(this->first_data_);
this->derived()._fire_recv(this_ptr, ecs, data);
}
this->first_data_.reset();
ASIO2_ASSERT(!this->first_data_);
ASIO2_ASSERT(this->reading_ == false);
}));
}
protected:
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
if (!this->kcp_)
return this->derived()._udp_send_to(
this->remote_endpoint_, data, std::forward<Callback>(callback));
return this->kcp_->_kcp_send(data, std::forward<Callback>(callback));
}
template<class Data>
inline send_data_t _rdc_convert_to_send_data(Data& data) noexcept
{
auto buffer = asio::buffer(data);
return send_data_t{ reinterpret_cast<
std::string_view::const_pointer>(buffer.data()),buffer.size() };
}
template<class Invoker>
inline void _rdc_invoke_with_none(const error_code& ec, Invoker& invoker)
{
if (invoker)
invoker(ec, send_data_t{}, recv_data_t{});
}
template<class Invoker>
inline void _rdc_invoke_with_recv(const error_code& ec, Invoker& invoker, recv_data_t data)
{
if (invoker)
invoker(ec, send_data_t{}, data);
}
template<class Invoker>
inline void _rdc_invoke_with_send(const error_code& ec, Invoker& invoker, send_data_t data)
{
if (invoker)
invoker(ec, data, recv_data_t{});
}
protected:
// this function will can't be called forever
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
ASIO2_ASSERT(false);
this->derived()._udp_post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
this->derived()._udp_handle_recv(ec, bytes_recvd, this_ptr, ecs);
}
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, this_ptr, data);
this->derived()._rdc_handle_recv(this_ptr, ecs, data);
}
inline void _fire_handshake(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_handshake must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
this->listener_.notify(event_type::handshake, this_ptr);
}
template<typename C>
inline void _fire_connect(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
// the _fire_connect must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_disconnect_called_ == false);
#endif
this->derived()._rdc_start(this_ptr, ecs);
this->listener_.notify(event_type::connect, this_ptr);
}
inline void _fire_disconnect(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_disconnect must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
this->is_disconnect_called_ = true;
#endif
this->listener_.notify(event_type::disconnect, this_ptr);
}
protected:
/**
* @brief get the recv/read allocator object refrence
*/
inline auto & rallocator() noexcept { return this->wallocator_; }
/**
* @brief get the send/write allocator object refrence
*/
inline auto & wallocator() noexcept { return this->wallocator_; }
protected:
/// used for session_mgr's session unordered_map key
asio::ip::udp::endpoint remote_endpoint_;
/// The memory to use for handler-based custom memory allocation. used fo send/write.
handler_memory<std::false_type, assizer<args_t>> wallocator_;
std::unique_ptr<kcp_stream_cp<derived_t, args_t>> kcp_;
std::uint32_t kcp_conv_ = 0;
/// first recvd data packet
std::unique_ptr<std::string> first_data_;
#if defined(_DEBUG) || defined(DEBUG)
bool is_disconnect_called_ = false;
#endif
};
}
namespace asio2
{
using udp_session_args = detail::template_args_udp_session;
template<class derived_t, class args_t>
using udp_session_impl_t = detail::udp_session_impl_t<derived_t, args_t>;
template<class derived_t>
class udp_session_t : public detail::udp_session_impl_t<derived_t, detail::template_args_udp_session>
{
public:
using detail::udp_session_impl_t<derived_t, detail::template_args_udp_session>::udp_session_impl_t;
};
class udp_session : public udp_session_t<udp_session>
{
public:
using udp_session_t<udp_session>::udp_session_t;
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_UDP_SESSION_HPP__
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_WEBSOCKET_DETAIL_UTF8_CHECKER_HPP
#define BHO_BEAST_WEBSOCKET_DETAIL_UTF8_CHECKER_HPP
#include <asio2/bho/beast/core/buffers_range.hpp>
#include <asio2/external/asio.hpp>
#include <cstdint>
namespace bho {
namespace beast {
namespace websocket {
namespace detail {
/** A UTF8 validator.
This validator can be used to check if a buffer containing UTF8 text is
valid. The write function may be called incrementally with segmented UTF8
sequences. The finish function determines if all processed text is valid.
*/
class utf8_checker
{
std::size_t need_ = 0; // chars we need to finish the code point
std::uint8_t* p_ = cp_; // current position in temp buffer
std::uint8_t cp_[4]; // a temp buffer for the code point
public:
/** Prepare to process text as valid utf8
*/
BHO_BEAST_DECL
void
reset();
/** Check that all processed text is valid utf8
*/
BHO_BEAST_DECL
bool
finish();
/** Check if text is valid UTF8
@return `true` if the text is valid utf8 or false otherwise.
*/
BHO_BEAST_DECL
bool
write(std::uint8_t const* in, std::size_t size);
/** Check if text is valid UTF8
@return `true` if the text is valid utf8 or false otherwise.
*/
template<class ConstBufferSequence>
bool
write(ConstBufferSequence const& bs);
};
template<class ConstBufferSequence>
bool
utf8_checker::
write(ConstBufferSequence const& buffers)
{
static_assert(
net::is_const_buffer_sequence<ConstBufferSequence>::value,
"ConstBufferSequence type requirements not met");
for(auto b : beast::buffers_range_ref(buffers))
if(! write(static_cast<
std::uint8_t const*>(b.data()),
b.size()))
return false;
return true;
}
BHO_BEAST_DECL
bool
check_utf8(char const* p, std::size_t n);
} // detail
} // websocket
} // beast
} // bho
#if BEAST_HEADER_ONLY
#include <asio2/bho/beast/websocket/detail/utf8_checker.ipp>
#endif
#endif
<file_sep>//
// Copyright (c) 2015-2019 <NAME> (<EMAIL> dot <EMAIL> at g<EMAIL> dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_CORE_FILE_HPP
#define BHO_BEAST_CORE_FILE_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/beast/core/file_base.hpp>
#include <asio2/bho/beast/core/file_stdio.hpp>
namespace bho {
namespace beast {
/** An implementation of File.
This alias is set to the best available implementation
of <em>File</em> given the platform and build settings.
*/
#if BHO_BEAST_DOXYGEN
struct file : file_stdio
{
};
#else
using file = file_stdio;
#endif
} // beast
} // bho
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RPC_CLIENT_HPP__
#define __ASIO2_RPC_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if __has_include(<cereal/cereal.hpp>)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/config.hpp>
#include <asio2/udp/udp_client.hpp>
#include <asio2/tcp/tcp_client.hpp>
#include <asio2/tcp/tcps_client.hpp>
#include <asio2/http/ws_client.hpp>
#include <asio2/http/wss_client.hpp>
#include <asio2/rpc/detail/rpc_protocol.hpp>
#include <asio2/rpc/detail/rpc_invoker.hpp>
#include <asio2/rpc/impl/rpc_recv_op.hpp>
#include <asio2/rpc/impl/rpc_call_cp.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_CLIENT;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class derived_t, class executor_t>
class rpc_client_impl_t
: public executor_t
, public rpc_invoker_t<derived_t, typename executor_t::args_type>
, public rpc_call_cp <derived_t, typename executor_t::args_type>
, public rpc_recv_op <derived_t, typename executor_t::args_type>
, protected id_maker <typename rpc_header::id_type>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_CLIENT;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using super = executor_t;
using self = rpc_client_impl_t<derived_t, executor_t>;
using executor_type = executor_t;
using args_type = typename executor_t::args_type;
static constexpr asio2::net_protocol net_protocol = args_type::net_protocol;
protected:
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
template<class ...Args>
explicit rpc_client_impl_t(
Args&&... args
)
: super(std::forward<Args>(args)...)
, rpc_invoker_t<derived_t, typename executor_t::args_type>()
, rpc_call_cp <derived_t, typename executor_t::args_type>(this->io_, this->serializer_, this->deserializer_)
, rpc_recv_op <derived_t, typename executor_t::args_type>()
, id_maker <typename rpc_header::id_type>()
{
}
/**
* @brief destructor
*/
~rpc_client_impl_t()
{
this->stop();
}
/**
* @brief start the client, blocking connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
bool start(String&& host, StrOrInt&& port, Args&&... args)
{
if constexpr (is_websocket_client<executor_t>::value)
{
return executor_t::template start(
std::forward<String>(host), std::forward<StrOrInt>(port),
std::forward<Args>(args)...);
}
else if constexpr (net_protocol == asio2::net_protocol::udp)
{
return executor_t::template start(
std::forward<String>(host), std::forward<StrOrInt>(port),
asio2::use_kcp, std::forward<Args>(args)...);
}
else
{
return executor_t::template start(
std::forward<String>(host), std::forward<StrOrInt>(port),
asio2::use_dgram, std::forward<Args>(args)...);
}
}
/**
* @brief start the client, asynchronous connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
bool async_start(String&& host, StrOrInt&& port, Args&&... args)
{
//static_assert(net_protocol != asio2::net_protocol::udp, "net_protocol::udp not supported");
if constexpr (is_websocket_client<executor_t>::value)
{
return executor_t::template async_start(
std::forward<String>(host), std::forward<StrOrInt>(port),
std::forward<Args>(args)...);
}
else if constexpr (net_protocol == asio2::net_protocol::udp)
{
return executor_t::template start(
std::forward<String>(host), std::forward<StrOrInt>(port),
asio2::use_kcp, std::forward<Args>(args)...);
}
else
{
return executor_t::template async_start(
std::forward<String>(host), std::forward<StrOrInt>(port),
asio2::use_dgram, std::forward<Args>(args)...);
}
}
protected:
template<typename C, typename Socket>
inline void _ws_start(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, Socket& socket)
{
super::_ws_start(this_ptr, ecs, socket);
this->derived().ws_stream().binary(true);
}
template<typename DeferEvent>
inline void _handle_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
while (!this->reqs_.empty())
{
auto& fn = this->reqs_.begin()->second;
fn(rpc::make_error_code(rpc::error::operation_aborted), std::string_view{});
}
super::_handle_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, data);
this->derived()._rpc_handle_recv(this_ptr, ecs, data);
}
protected:
detail::rpc_serializer serializer_;
detail::rpc_deserializer deserializer_;
detail::rpc_header header_;
};
}
namespace asio2
{
namespace detail
{
template<asio2::net_protocol np> struct template_args_rpc_client;
template<>
struct template_args_rpc_client<asio2::net_protocol::udp> : public template_args_udp_client
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::udp;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
template<>
struct template_args_rpc_client<asio2::net_protocol::tcp> : public template_args_tcp_client
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::tcp;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
template<>
struct template_args_rpc_client<asio2::net_protocol::ws> : public template_args_ws_client
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::ws;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
}
using rpc_client_args_udp = detail::template_args_rpc_client<asio2::net_protocol::udp>;
using rpc_client_args_tcp = detail::template_args_rpc_client<asio2::net_protocol::tcp>;
using rpc_client_args_ws = detail::template_args_rpc_client<asio2::net_protocol::ws >;
template<class derived_t, class executor_t>
using rpc_client_impl_t = detail::rpc_client_impl_t<derived_t, executor_t>;
template<class derived_t, asio2::net_protocol np> class rpc_client_t;
template<class derived_t>
class rpc_client_t<derived_t, asio2::net_protocol::udp> : public detail::rpc_client_impl_t<derived_t,
detail::udp_client_impl_t<derived_t, detail::template_args_rpc_client<asio2::net_protocol::udp>>>
{
public:
using detail::rpc_client_impl_t<derived_t, detail::udp_client_impl_t
<derived_t, detail::template_args_rpc_client<asio2::net_protocol::udp>>>::rpc_client_impl_t;
};
template<class derived_t>
class rpc_client_t<derived_t, asio2::net_protocol::tcp> : public detail::rpc_client_impl_t<derived_t,
detail::tcp_client_impl_t<derived_t, detail::template_args_rpc_client<asio2::net_protocol::tcp>>>
{
public:
using detail::rpc_client_impl_t<derived_t, detail::tcp_client_impl_t
<derived_t, detail::template_args_rpc_client<asio2::net_protocol::tcp>>>::rpc_client_impl_t;
};
template<class derived_t>
class rpc_client_t<derived_t, asio2::net_protocol::ws> : public detail::rpc_client_impl_t<derived_t,
detail::ws_client_impl_t<derived_t, detail::template_args_rpc_client<asio2::net_protocol::ws>>>
{
public:
using detail::rpc_client_impl_t<derived_t, detail::ws_client_impl_t<derived_t,
detail::template_args_rpc_client<asio2::net_protocol::ws>>>::rpc_client_impl_t;
};
template<asio2::net_protocol np>
class rpc_client_use : public rpc_client_t<rpc_client_use<np>, np>
{
public:
using rpc_client_t<rpc_client_use<np>, np>::rpc_client_t;
};
using rpc_kcp_client = rpc_client_use<asio2::net_protocol::udp>;
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpc_client = rpc_client_use<asio2::net_protocol::tcp>;
#else
/// Using websocket as the underlying communication support
using rpc_client = rpc_client_use<asio2::net_protocol::ws>;
#endif
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct rpc_rate_client_args_tcp : public rpc_client_args_tcp
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
struct rpc_rate_client_args_ws : public rpc_client_args_ws
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
using stream_t = websocket::stream<socket_t&>;
};
template<class derived_t, asio2::net_protocol np> class rpc_rate_client_t;
template<class derived_t>
class rpc_rate_client_t<derived_t, asio2::net_protocol::tcp> : public detail::rpc_client_impl_t<derived_t,
detail::tcp_client_impl_t<derived_t, rpc_rate_client_args_tcp>>
{
public:
using detail::rpc_client_impl_t<derived_t,
detail::tcp_client_impl_t<derived_t, rpc_rate_client_args_tcp>>::rpc_client_impl_t;
};
template<class derived_t>
class rpc_rate_client_t<derived_t, asio2::net_protocol::ws> : public detail::rpc_client_impl_t<derived_t,
detail::ws_client_impl_t<derived_t, rpc_rate_client_args_ws>>
{
public:
using detail::rpc_client_impl_t<derived_t,
detail::ws_client_impl_t<derived_t, rpc_rate_client_args_ws>>::rpc_client_impl_t;
};
template<asio2::net_protocol np>
class rpc_rate_client_use : public rpc_rate_client_t<rpc_rate_client_use<np>, np>
{
public:
using rpc_rate_client_t<rpc_rate_client_use<np>, np>::rpc_rate_client_t;
};
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpc_rate_client = rpc_rate_client_use<asio2::net_protocol::tcp>;
#else
/// Using websocket as the underlying communication support
using rpc_rate_client = rpc_rate_client_use<asio2::net_protocol::ws>;
#endif
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif
#endif // !__ASIO2_RPC_CLIENT_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_HTTPS_SERVER_HPP__
#define __ASIO2_HTTPS_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcps_server.hpp>
#include <asio2/http/https_session.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
template<class derived_t, class session_t>
class https_server_impl_t
: public tcps_server_impl_t<derived_t, session_t>
, public http_router_t <session_t, typename session_t::args_type>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
public:
using super = tcps_server_impl_t <derived_t, session_t>;
using self = https_server_impl_t<derived_t, session_t>;
using session_type = session_t;
public:
/**
* @brief constructor
*/
template<class... Args>
explicit https_server_impl_t(
asio::ssl::context::method method = asio::ssl::context::sslv23,
Args&&... args
)
: super(method, std::forward<Args>(args)...)
{
}
/**
* @brief destructor
*/
~https_server_impl_t()
{
this->stop();
}
/**
* @brief start the server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param service - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& service, Args&&... args)
{
return this->derived()._do_start(std::forward<String>(host), std::forward<StrOrInt>(service),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
public:
/**
* @brief bind recv listener
* @param fun - a user defined callback function.
* @li Function signature : void(std::shared_ptr<asio2::https_session>& session_ptr,
* http::web_request& req, http::web_response& rep)
* or : void(http::web_request& req, http::web_response& rep)
*/
template<class F, class ...C>
inline derived_t & bind_recv(F&& fun, C&&... obj)
{
if constexpr (detail::is_template_callable_v<F,
std::shared_ptr<session_t>&, http::web_request&, http::web_response&>)
{
this->is_arg0_session_ = true;
this->listener_.bind(event_type::recv, observer_t<std::shared_ptr<session_t>&,
http::web_request&, http::web_response&>(std::forward<F>(fun), std::forward<C>(obj)...));
}
else
{
this->is_arg0_session_ = false;
this->listener_.bind(event_type::recv, observer_t<
http::web_request&, http::web_response&>(std::forward<F>(fun), std::forward<C>(obj)...));
}
return (this->derived());
}
/**
* @brief bind websocket upgrade listener
* @param fun - a user defined callback function.
* @li Function signature : void(std::shared_ptr<asio2::http_session>& session_ptr)
*/
template<class F, class ...C>
inline derived_t & bind_upgrade(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::upgrade, observer_t<std::shared_ptr<session_t>&>
(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<typename... Args>
inline std::shared_ptr<session_t> _make_session(Args&&... args)
{
return super::_make_session(std::forward<Args>(args)..., *this,
this->root_directory_, this->is_arg0_session_, this->support_websocket_);
}
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
{
// can not use std::move(this_ptr), beacuse after handle stop with std::move(this_ptr),
// this object maybe destroyed, then call "this" will crash.
super::_handle_stop(ec, this_ptr);
this->derived().dispatch([this]() mutable
{
// clear the http cache
this->http_cache_.clear();
});
}
protected:
bool is_arg0_session_ = false;
};
}
namespace asio2
{
template<class derived_t, class session_t>
using https_server_impl_t = detail::https_server_impl_t<derived_t, session_t>;
template<class session_t>
class https_server_t : public detail::https_server_impl_t<https_server_t<session_t>, session_t>
{
public:
using detail::https_server_impl_t<https_server_t<session_t>, session_t>::https_server_impl_t;
};
using https_server = https_server_t<https_session>;
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
template<class session_t>
class https_rate_server_t : public asio2::https_server_impl_t<https_rate_server_t<session_t>, session_t>
{
public:
using asio2::https_server_impl_t<https_rate_server_t<session_t>, session_t>::https_server_impl_t;
};
using https_rate_server = https_rate_server_t<https_rate_session>;
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTPS_SERVER_HPP__
#endif
<file_sep>/*
Copyright <NAME> 2019
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_RISCV_H
#define BHO_PREDEF_ARCHITECTURE_RISCV_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_RISCV`
http://en.wikipedia.org/wiki/RISC-V[RISC-V] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__riscv+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_RISCV BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__riscv)
# undef BHO_ARCH_RISCV
# define BHO_ARCH_RISCV BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_RISCV
# define BHO_ARCH_RISCV_AVAILABLE
#endif
#if BHO_ARCH_RISCV
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_RISCV_NAME "RISC-V"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_RISCV,BHO_ARCH_RISCV_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* The cost of dynamic (virtual calls) vs. static (CRTP) dispatch in C++
* https://eli.thegreenplace.net/2013/12/05/the-cost-of-dynamic-virtual-calls-vs-static-crtp-dispatch-in-c/
*/
#ifndef __ASIO2_OBJECT_HPP__
#define __ASIO2_OBJECT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <asio2/base/error.hpp>
namespace asio2
{
class object
{
public:
};
}
namespace asio2::detail
{
/**
* the lowest based class used fo CRTP
* see : CRTP and multilevel inheritance
* https://stackoverflow.com/questions/18174441/crtp-and-multilevel-inheritance
*/
template<class derived_t, bool enable_shared_from_this = true>
class object_t : public asio2::object, public std::enable_shared_from_this<derived_t>
{
protected:
/**
* @brief constructor
*/
object_t() = default;
/**
* @brief destructor
*/
~object_t() = default;
protected:
/**
* @brief obtain derived class object through CRTP mechanism
*/
inline const derived_t & derived() const noexcept
{
return static_cast<const derived_t &>(*this);
}
/**
* @brief obtain derived class object through CRTP mechanism
*/
inline derived_t & derived() noexcept
{
return static_cast<derived_t &>(*this);
}
/**
* @brief if the "derived_t" is created like a "shared_ptr", it will return
* a not empty shared_ptr<derived_t>, othwise it will return a empty
* shared_ptr<derived_t>.
*/
inline std::shared_ptr<derived_t> selfptr() noexcept
{
// if the "derived_t" (maybe server,client,session...) is created like a
// "shared_ptr", then here will return a not empty shared_ptr, otherwise
// here will return a empty shared_ptr.
// e.g : when the "derived_t" is udp_cast, and user has called post_condition_event,
// and hold the "event_ptr" into another thread, and when the udp_cast is
// soppted and destroyed, and user called the "event_ptr->notify()"
// in the "another thread", if the udp_cast is created like a "shared_ptr",
// then the event_ptr's member variable "derive_ptr_" will hold the shared_ptr
// of udp_cast, this has no problem. but if the udp_cast is created as a
// local variable not a "shared_ptr", then the event_ptr's member variable
// "derive_ptr_" will hold a empty shared_ptr, then it will crash when
// user called the "event_ptr->notify()" in the "another thread", beacuse
// at this time, the "event_timer_io_" maybe destroyed already.
return this->derived().weak_from_this().lock();
}
};
template<class derived_t>
class object_t<derived_t, false> : public asio2::object
{
protected:
/**
* @brief constructor
*/
object_t() = default;
/**
* @brief destructor
*/
~object_t() = default;
protected:
/**
* @brief obtain derived class object through CRTP mechanism
*/
inline const derived_t & derived() const noexcept
{
return static_cast<const derived_t &>(*this);
}
/**
* @brief obtain derived class object through CRTP mechanism
*/
inline derived_t & derived() noexcept
{
return static_cast<derived_t &>(*this);
}
/**
* @brief always return a empty shared_ptr<derived_t>.
*/
inline std::shared_ptr<derived_t> selfptr() noexcept
{
return std::shared_ptr<derived_t>{};
}
};
}
#endif // !__ASIO2_OBJECT_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_RPCS_SERVER_HPP__
#define __ASIO2_RPCS_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if __has_include(<cereal/cereal.hpp>)
#include <asio2/rpc/rpc_server.hpp>
#include <asio2/rpc/rpcs_session.hpp>
namespace asio2
{
template<class derived_t, class session_t, asio2::net_protocol np = session_t::net_protocol>
class rpcs_server_impl_t;
template<class derived_t, class session_t>
class rpcs_server_impl_t<derived_t, session_t, asio2::net_protocol::tcps>
: public detail::rpc_server_impl_t<derived_t, detail::tcps_server_impl_t<derived_t, session_t>>
{
public:
using detail::rpc_server_impl_t<derived_t, detail::tcps_server_impl_t<derived_t, session_t>>::
rpc_server_impl_t;
};
template<class derived_t, class session_t>
class rpcs_server_impl_t<derived_t, session_t, asio2::net_protocol::wss>
: public detail::rpc_server_impl_t<derived_t, detail::wss_server_impl_t<derived_t, session_t>>
{
public:
using detail::rpc_server_impl_t<derived_t, detail::wss_server_impl_t<derived_t, session_t>>::
rpc_server_impl_t;
};
template<class session_t>
class rpcs_server_t : public rpcs_server_impl_t<rpcs_server_t<session_t>, session_t>
{
public:
using rpcs_server_impl_t<rpcs_server_t<session_t>, session_t>::rpcs_server_impl_t;
};
template<asio2::net_protocol np>
class rpcs_server_use : public rpcs_server_t<rpcs_session_use<np>>
{
public:
using rpcs_server_t<rpcs_session_use<np>>::rpcs_server_t;
};
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpcs_server = rpcs_server_use<asio2::net_protocol::tcps>;
#else
/// Using websocket as the underlying communication support
using rpcs_server = rpcs_server_use<asio2::net_protocol::wss>;
#endif
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
template<class derived_t, class session_t, asio2::net_protocol np = session_t::net_protocol>
class rpcs_rate_server_impl_t;
template<class derived_t, class session_t>
class rpcs_rate_server_impl_t<derived_t, session_t, asio2::net_protocol::tcps>
: public detail::rpc_server_impl_t<derived_t, detail::tcps_server_impl_t<derived_t, session_t>>
{
public:
using detail::rpc_server_impl_t<derived_t, detail::tcps_server_impl_t<derived_t, session_t>>::
rpc_server_impl_t;
};
template<class derived_t, class session_t>
class rpcs_rate_server_impl_t<derived_t, session_t, asio2::net_protocol::wss>
: public detail::rpc_server_impl_t<derived_t, detail::wss_server_impl_t<derived_t, session_t>>
{
public:
using detail::rpc_server_impl_t<derived_t, detail::wss_server_impl_t<derived_t, session_t>>::
rpc_server_impl_t;
};
template<class session_t>
class rpcs_rate_server_t : public rpcs_rate_server_impl_t<rpcs_rate_server_t<session_t>, session_t>
{
public:
using rpcs_rate_server_impl_t<rpcs_rate_server_t<session_t>, session_t>::rpcs_rate_server_impl_t;
};
template<asio2::net_protocol np>
class rpcs_rate_server_use : public rpcs_rate_server_t<rpcs_rate_session_use<np>>
{
public:
using rpcs_rate_server_t<rpcs_rate_session_use<np>>::rpcs_rate_server_t;
};
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpcs_rate_server = rpcs_rate_server_use<asio2::net_protocol::tcps>;
#else
/// Using websocket as the underlying communication support
using rpcs_rate_server = rpcs_rate_server_use<asio2::net_protocol::wss>;
#endif
}
#endif
#endif
#endif // !__ASIO2_RPCS_SERVER_HPP__
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_BROKER_STATE_HPP__
#define __ASIO2_MQTT_BROKER_STATE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/shared_mutex.hpp>
#include <asio2/mqtt/options.hpp>
#include <asio2/mqtt/detail/mqtt_invoker.hpp>
#include <asio2/mqtt/detail/mqtt_subscription_map.hpp>
#include <asio2/mqtt/detail/mqtt_shared_target.hpp>
#include <asio2/mqtt/detail/mqtt_retained_message.hpp>
#include <asio2/mqtt/detail/mqtt_security.hpp>
#include <asio2/mqtt/detail/mqtt_session_persistence.hpp>
namespace asio2::mqtt
{
template<class session_t, class args_t>
struct broker_state
{
using session_type = session_t;
using subnode_type = typename session_type::subnode_type;
broker_state(
asio2::detail::mqtt_options& options,
asio2::detail::mqtt_invoker_t<session_t, args_t>& invoker
)
: options_(options)
, invoker_(invoker)
{
security_.default_config();
}
asio2::detail::mqtt_options & options_;
asio2::detail::mqtt_invoker_t<session_t, args_t> & invoker_;
/// client id map
asio2::detail::mqtt_session_persistence<session_t, args_t> mqtt_sessions_;
/// subscription information map
mqtt::subscription_map<std::string_view, subnode_type> subs_map_;
/// shared subscription targets
mqtt::shared_target<mqtt::stnode<session_t>> shared_targets_;
/// A list of messages retained so they can be sent to newly subscribed clients.
mqtt::retained_messages<mqtt::rmnode> retained_messages_;
// Authorization and authentication settings
mqtt::security security_;
};
}
#endif // !__ASIO2_MQTT_BROKER_STATE_HPP__
<file_sep>#
# COPYRIGHT (C) 2017-2021, zhllxt
#
# author : zhllxt
# email : <EMAIL>
#
# Distributed under the GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
# (See accompanying file LICENSE or see <http://www.gnu.org/licenses/>)
#
#GroupSources (include/asio2 "/")
#GroupSources (3rd/asio "/")
aux_source_directory(. SRC_FILES)
source_group("" FILES ${SRC_FILES})
function (AddExecutableTarget InputTargetName)
set(TARGET_NAME ${InputTargetName})
link_directories(${ASIO2_LIBS_DIR})
add_executable (${TARGET_NAME} ${TARGET_NAME}.cpp)
set_property(TARGET ${TARGET_NAME} PROPERTY FOLDER "unit")
set_target_properties(${TARGET_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${ASIO2_EXES_DIR})
target_link_libraries(${TARGET_NAME} ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(${TARGET_NAME} ${GENERAL_LIBS})
if (MSVC)
set_target_properties(${TARGET_NAME} PROPERTIES LINK_FLAGS "/ignore:4099")
endif()
endfunction()
function (AddUtilExecutableTarget InputTargetName)
set(TARGET_NAME ${InputTargetName})
link_directories(${ASIO2_LIBS_DIR})
add_executable (${TARGET_NAME} ${TARGET_NAME}.cpp)
set_property(TARGET ${TARGET_NAME} PROPERTY FOLDER "unit/utils")
set_target_properties(${TARGET_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${ASIO2_EXES_DIR})
target_link_libraries(${TARGET_NAME} ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(${TARGET_NAME} ${GENERAL_LIBS})
if (MSVC)
set_target_properties(${TARGET_NAME} PROPERTIES LINK_FLAGS "/ignore:4099")
endif()
endfunction()
function (AddSslExecutableTarget InputTargetName)
set(TARGET_NAME ${InputTargetName})
link_directories(${ASIO2_LIBS_DIR})
add_executable (${TARGET_NAME} ${TARGET_NAME}.cpp)
set_property(TARGET ${TARGET_NAME} PROPERTY FOLDER "unit/ssl")
set_target_properties(${TARGET_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${ASIO2_EXES_DIR})
target_link_libraries(${TARGET_NAME} ${OPENSSL_LIBS})
target_link_libraries(${TARGET_NAME} ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(${TARGET_NAME} ${GENERAL_LIBS})
if (MSVC)
set_target_properties(${TARGET_NAME} PROPERTIES LINK_FLAGS "/ignore:4099")
endif()
endfunction()
AddExecutableTarget(mqtt)
AddExecutableTarget(rpc)
AddExecutableTarget(rpc_kcp)
AddExecutableTarget(timer)
AddExecutableTarget(timer_enable_error)
AddExecutableTarget(http)
AddExecutableTarget(shared_iopool)
AddExecutableTarget(tcp_general)
AddExecutableTarget(tcp_dgram)
AddExecutableTarget(tcp_custom)
AddExecutableTarget(websocket)
AddExecutableTarget(udp)
AddUtilExecutableTarget(aes)
AddUtilExecutableTarget(base64)
AddUtilExecutableTarget(codecvt)
AddUtilExecutableTarget(des)
AddUtilExecutableTarget(ini)
AddUtilExecutableTarget(md5)
AddUtilExecutableTarget(sha1)
AddUtilExecutableTarget(uuid)
AddUtilExecutableTarget(thread_pool)
AddUtilExecutableTarget(zlib)
AddUtilExecutableTarget(event_dispatcher)
AddUtilExecutableTarget(reflection)
AddUtilExecutableTarget(strutil)
AddSslExecutableTarget(https)
AddSslExecutableTarget(rdc)
AddSslExecutableTarget(rate_limit)
AddSslExecutableTarget(start_stop)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_QNXNTO_H
#define BHO_PREDEF_OS_QNXNTO_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_QNX`
http://en.wikipedia.org/wiki/QNX[QNX] operating system.
Version number available as major, and minor if possible. And
version 4 is specifically detected.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__QNX__+` | {predef_detection}
| `+__QNXNTO__+` | {predef_detection}
| `+_NTO_VERSION+` | V.R.0
| `+__QNX__+` | 4.0.0
|===
*/ // end::reference[]
#define BHO_OS_QNX BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__QNX__) || defined(__QNXNTO__) \
)
# undef BHO_OS_QNX
# if !defined(BHO_OS_QNX) && defined(_NTO_VERSION)
# define BHO_OS_QNX BHO_PREDEF_MAKE_10_VVRR(_NTO_VERSION)
# endif
# if !defined(BHO_OS_QNX) && defined(__QNX__)
# define BHO_OS_QNX BHO_VERSION_NUMBER(4,0,0)
# endif
# if !defined(BHO_OS_QNX)
# define BHO_OS_QNX BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_OS_QNX
# define BHO_OS_QNX_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_QNX_NAME "QNX"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_QNX,BHO_OS_QNX_NAME)
<file_sep>/*
Copyright <NAME> 2012-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_BSD_BSDI_H
#define BHO_PREDEF_OS_BSD_BSDI_H
#include <asio2/bho/predef/os/bsd.h>
/* tag::reference[]
= `BHO_OS_BSD_BSDI`
http://en.wikipedia.org/wiki/BSD/OS[BSDi BSD/OS] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__bsdi__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_BSD_BSDI BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__bsdi__) \
)
# ifndef BHO_OS_BSD_AVAILABLE
# undef BHO_OS_BSD
# define BHO_OS_BSD BHO_VERSION_NUMBER_AVAILABLE
# define BHO_OS_BSD_AVAILABLE
# endif
# undef BHO_OS_BSD_BSDI
# define BHO_OS_BSD_BSDI BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_BSD_BSDI
# define BHO_OS_BSD_BSDI_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_BSD_BSDI_NAME "BSDi BSD/OS"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_BSD_BSDI,BHO_OS_BSD_BSDI_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_CONNECT_COMPONENT_HPP__
#define __ASIO2_CONNECT_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/detail/ecs.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t, bool IsSession>
class connect_cp_member_variables;
template<class derived_t, class args_t>
class connect_cp_member_variables<derived_t, args_t, true>
{
};
template<class derived_t, class args_t>
class connect_cp_member_variables<derived_t, args_t, false>
{
public:
/**
* @brief Set the host of the server.
* If connect failed, and you want to use a different ip when reconnect,
* then you can do it like this:
* client.bind_connect([&client]()
* {
* if (asio2::get_last_error()) // has some error, means connect failed
* client.set_host("192.168.0.99");
* });
* when reconnecting, the ip "192.168.0.99" will be used as the server's ip.
*/
template<typename String>
inline derived_t& set_host(String&& host)
{
this->host_ = detail::to_string(std::forward<String>(host));
return (static_cast<derived_t&>(*this));
}
/**
* @brief Set the port of the server.
*/
template<typename StrOrInt>
inline derived_t& set_port(StrOrInt&& port)
{
this->port_ = detail::to_string(std::forward<StrOrInt>(port));
return (static_cast<derived_t&>(*this));
}
/**
* @brief Get the host of the connected server.
*/
inline const std::string& get_host() noexcept
{
return this->host_;
}
/**
* @brief Get the port of the connected server.
*/
inline const std::string& get_port() noexcept
{
return this->port_;
}
protected:
/// Save the host and port of the server
std::string host_, port_;
};
/*
* can't use "derived_t::is_session()" as the third template parameter of connect_cp_member_variables,
* must use "args_t::is_session", beacuse "tcp_session" is derived from "connect_cp", when the
* "connect_cp" is contructed, the "tcp_session" has't contructed yet, then it will can't find the
* "derived_t::is_session()" function, and compile failure.
*/
template<class derived_t, class args_t>
class connect_cp : public connect_cp_member_variables<derived_t, args_t, args_t::is_session>
{
public:
using socket_t = typename args_t::socket_t;
using decay_socket_t = typename std::remove_cv_t<std::remove_reference_t<socket_t>>;
using lowest_layer_t = typename decay_socket_t::lowest_layer_type;
using resolver_type = typename asio::ip::basic_resolver<typename lowest_layer_t::protocol_type>;
using endpoints_type = typename resolver_type::results_type;
using endpoints_iterator = typename endpoints_type::iterator;
using self = connect_cp<derived_t, args_t>;
public:
/**
* @brief constructor
*/
connect_cp() noexcept {}
/**
* @destructor
*/
~connect_cp() = default;
protected:
template<bool IsAsync, typename C, typename DeferEvent, bool IsSession = args_t::is_session>
inline typename std::enable_if_t<!IsSession, void>
_start_connect(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
clear_last_error();
#if defined(_DEBUG) || defined(DEBUG)
derive.is_stop_reconnect_timer_called_ = false;
derive.is_stop_connect_timeout_timer_called_ = false;
derive.is_disconnect_called_ = false;
#endif
state_t expected = state_t::starting;
if (!derive.state_.compare_exchange_strong(expected, state_t::starting))
{
ASIO2_ASSERT(false);
derive._handle_connect(asio::error::operation_aborted,
std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
derive._make_reconnect_timer(this_ptr, ecs);
// start the timeout timer
derive._make_connect_timeout_timer(this_ptr, derive.get_connect_timeout());
derive._post_resolve(std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename C, typename DeferEvent, bool IsSession = args_t::is_session>
inline typename std::enable_if_t<!IsSession, void>
_post_resolve(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::string_view h, p;
if constexpr (ecs_helper::has_socks5<C>())
{
auto sock5 = ecs->get_component().socks5_option(std::in_place);
h = sock5->host();
p = sock5->port();
}
else
{
h = this->host_;
p = this->port_;
}
// resolve the server address.
std::unique_ptr<resolver_type> resolver_ptr = std::make_unique<resolver_type>(
derive.io().context());
resolver_type* resolver_rptr = resolver_ptr.get();
// Before async_resolve execution is complete, we must hold the resolver object.
// so we captured the resolver_ptr into the lambda callback function.
resolver_rptr->async_resolve(h, p,
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs),
resolver_ptr = std::move(resolver_ptr), chain = std::move(chain)]
(error_code ec, endpoints_type endpoints) mutable
{
// if the connect timeout timer is timedout and called already, it means
// connect timed out already.
if (!derive.connect_timeout_timer_)
{
ec = asio::error::timed_out;
}
std::unique_ptr<endpoints_type> eps = std::make_unique<endpoints_type>(std::move(endpoints));
endpoints_type* p = eps.get();
if (ec)
derive._handle_connect(ec,
std::move(this_ptr), std::move(ecs), std::move(chain));
else
derive._post_connect(ec, std::move(eps), p->begin(),
std::move(this_ptr), std::move(ecs), std::move(chain));
});
}
template<typename C, typename DeferEvent, bool IsSession = args_t::is_session>
typename std::enable_if_t<!IsSession, void>
inline _post_connect(
error_code ec, std::unique_ptr<endpoints_type> eps, endpoints_iterator iter,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
state_t expected = state_t::starting;
if (!derive.state_.compare_exchange_strong(expected, state_t::starting))
{
// There are no more endpoints. Shut down the client.
derive._handle_connect(asio::error::operation_aborted,
std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
if (iter == eps->end())
{
// There are no more endpoints. Shut down the client.
derive._handle_connect(ec ? ec : asio::error::host_unreachable,
std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
auto& socket = derive.socket();
// the socket.open(...) must after async_resolve, beacuse only after async_resolve,
// we can get the remote endpoint is ipv4 or ipv6, then we can open the socket
// with ipv4 or ipv6 correctly.
error_code ec_ignore{};
// if the socket's binded endpoint is ipv4, and the finded endpoint is ipv6, then
// the async_connect will be failed, so we need reopen the socket with ipv6.
if (socket.is_open())
{
auto oldep = socket.local_endpoint(ec_ignore);
if (ec_ignore || oldep.protocol() != iter->endpoint().protocol())
{
socket.cancel(ec_ignore);
socket.close(ec_ignore);
}
}
if (!socket.is_open())
{
socket.open(iter->endpoint().protocol(), ec);
if (ec)
{
derive._handle_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
// set port reuse
socket.set_option(asio::socket_base::reuse_address(true), ec_ignore);
// open succeeded. set the keeplive values
if constexpr (std::is_same_v<typename lowest_layer_t::protocol_type, asio::ip::tcp>)
{
derive.set_keep_alive_options();
}
else
{
std::ignore = true;
}
// We don't call the bind function, beacuse it will be called internally in asio
//socket.bind(endpoint);
// And you can call the bind function youself in the bind_init() callback.
// eg:
//
// asio::ip::tcp::endpoint ep(asio::ip::tcp::v4(), 1234);
// asio::ip::udp::endpoint ep(asio::ip::udp::v6(), 9876);
// asio::ip::tcp::endpoint ep(asio::ip::make_address("0.0.0.0"), 1234);
//
// client.socket().bind(ep);
// maybe there has multi endpoints, and connect the first endpoint failed, then the
// next endpoint is connected, at this time, the ec and get_last_error maybe not 0,
// so we need clear the last error, otherwise if use call get_last_error in the
// fire init function, the get_last_error will be not 0.
clear_last_error();
// every time the socket is recreated, we should call the _do_init function, then
// the ssl stream will recreated too, otherwise when client disconnected and
// reconnect to the ssl server, this will happen: ssl handshake will failed, and
// next time reconnect again, ssl handshake will successed.
derive._do_init(ecs);
// call the user callback which setted by bind_init
derive._fire_init();
}
else
{
ASIO2_LOG_ERROR("The client socket is opened already.");
}
// Start the asynchronous connect operation.
socket.async_connect(iter->endpoint(), make_allocator(derive.rallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain),
eps = std::move(eps), iter]
(const error_code & ec) mutable
{
if (ec && ec != asio::error::operation_aborted)
derive._post_connect(ec, std::move(eps), ++iter,
std::move(this_ptr), std::move(ecs), std::move(chain));
else
derive._post_proxy(ec,
std::move(this_ptr), std::move(ecs), std::move(chain));
}));
}
template<typename C, typename DeferEvent>
inline void _post_proxy(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
set_last_error(ec);
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
try
{
derive.remote_endpoint_copy_ = derive.socket_.lowest_layer().remote_endpoint();
}
catch (const system_error&)
{
}
state_t expected = state_t::starting;
if (!derive.state_.compare_exchange_strong(expected, state_t::starting))
{
derive._handle_connect(asio::error::operation_aborted,
std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
if constexpr (std::is_base_of_v<component_tag, detail::remove_cvref_t<C>>)
{
if (ec)
{
return derive._handle_proxy(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
//// Traverse each component in order, and if it is a proxy component, start it
//detail::for_each_tuple(ecs->get_component().values(), [&](auto& component) mutable
//{
// using type = detail::remove_cvref_t<decltype(component)>;
// if constexpr (std::is_base_of_v<asio2::socks5::option_base, type>)
// derive._socks5_start(std::move(this_ptr), std::move(ecs));
// else
// {
// std::ignore = true;
// }
//});
if constexpr (C::has_socks5())
derive._socks5_start(std::move(this_ptr), std::move(ecs), std::move(chain));
else
derive._handle_proxy(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
else
{
derive._handle_proxy(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
}
template<typename C, typename DeferEvent>
inline void _handle_proxy(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
set_last_error(ec);
derived_t& derive = static_cast<derived_t&>(*this);
derive._handle_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
set_last_error(ec);
derived_t& derive = static_cast<derived_t&>(*this);
if constexpr (args_t::is_session)
{
ASIO2_ASSERT(derive.sessions().io().running_in_this_thread());
}
else
{
ASIO2_ASSERT(derive.io().running_in_this_thread());
}
derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename C, typename DeferEvent>
inline void _done_connect(
error_code ec, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
// code run to here, the state must not be stopped( stopping is possible but stopped is impossible )
//ASIO2_ASSERT(derive.state() != state_t::stopped);
if constexpr (args_t::is_session)
{
ASIO2_ASSERT(derive.sessions().io().running_in_this_thread());
// if socket is invalid, it means that the connect is timeout and the socket has
// been closed by the connect timeout timer, so reset the error to timed_out.
if (!derive.socket().is_open())
{
ec = asio::error::timed_out;
}
}
else
{
ASIO2_ASSERT(derive.io().running_in_this_thread());
// if connect_timeout_timer_ is empty, it means that the connect timeout timer is
// timeout and the callback has called already, so reset the error to timed_out.
// note : when the async_resolve is failed, the socket is invalid to.
if (!derive.connect_timeout_timer_)
{
ec = asio::error::timed_out;
}
}
state_t expected;
// Set the state to started before fire_connect because the user may send data in
// fire_connect and fail if the state is not set to started.
if (!ec)
{
expected = state_t::starting;
if (!derive.state().compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
}
// set last error before fire connect
set_last_error(ec);
// Is session : Only call fire_connect notification when the connection is succeed.
if constexpr (args_t::is_session)
{
ASIO2_ASSERT(derive.sessions().io().running_in_this_thread());
if (!ec)
{
expected = state_t::started;
if (derive.state().compare_exchange_strong(expected, state_t::started))
{
derive._fire_connect(this_ptr, ecs);
}
}
}
// Is client : Whether the connection succeeds or fails, always call fire_connect notification
else
{
ASIO2_ASSERT(derive.io().running_in_this_thread());
// if state is not stopped, call _fire_connect
expected = state_t::stopped;
if (!derive.state().compare_exchange_strong(expected, state_t::stopped))
{
derive._fire_connect(this_ptr, ecs);
}
}
if (!ec)
{
expected = state_t::started;
if (!derive.state().compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
}
// Whatever of connection success or failure or timeout, cancel the timeout timer.
derive._stop_connect_timeout_timer();
// must set last error again, beacuse in the _fire_connect some errors maybe occured.
set_last_error(ec);
if (ec)
{
// The connect process has finished, call the callback at here directly,
// otherwise the callback maybe passed to other event queue chain, and the
// last error maybe changed by other event.
// can't pass the whole chain to the client _do_disconnect, it will cause
// the auto reconnect has no effect.
{
[[maybe_unused]] detail::defer_event t{ chain.move_event() };
}
derive._do_disconnect(ec, std::move(this_ptr), defer_event(chain.move_guard()));
return;
}
derive._do_start(std::move(this_ptr), std::move(ecs), std::move(chain));
}
};
}
#endif // !__ASIO2_CONNECT_COMPONENT_HPP__
<file_sep>// abi_prefix header -------------------------------------------------------//
// (c) Copyright <NAME> 2003
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#ifndef BHO_CONFIG_ABI_PREFIX_HPP
# define BHO_CONFIG_ABI_PREFIX_HPP
#else
# error double inclusion of header bho/config/abi_prefix.hpp is an error
#endif
#include <asio2/bho/config.hpp>
// this must occur after all other includes and before any code appears:
#ifdef BHO_HAS_ABI_HEADERS
# include BHO_ABI_PREFIX
#endif
#if defined( BHO_BORLANDC )
#pragma nopushoptwarn
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_GCC_XML_H
#define BHO_PREDEF_COMPILER_GCC_XML_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_GCCXML`
http://www.gccxml.org/[GCC XML] compiler.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__GCCXML__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_COMP_GCCXML BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__GCCXML__)
# define BHO_COMP_GCCXML_DETECTION BHO_VERSION_NUMBER_AVAILABLE
#endif
#ifdef BHO_COMP_GCCXML_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_GCCXML_EMULATED BHO_COMP_GCCXML_DETECTION
# else
# undef BHO_COMP_GCCXML
# define BHO_COMP_GCCXML BHO_COMP_GCCXML_DETECTION
# endif
# define BHO_COMP_GCCXML_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_GCCXML_NAME "GCC XML"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_GCCXML,BHO_COMP_GCCXML_NAME)
#ifdef BHO_COMP_GCCXML_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_GCCXML_EMULATED,BHO_COMP_GCCXML_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_URL_HPP__
#define __ASIO2_HTTP_URL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/http/detail/http_util.hpp>
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::http
#else
namespace boost::beast::http
#endif
{
/**
* The object wrapped for a url string like "http://www.github.com"
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
*/
class url
{
public:
/**
* @brief constructor
* if the 'str' has unencoded char, it will be encoded automatically, otherwise
* the url parsing will be failed.
*/
url(std::string str) : string_(std::move(str))
{
std::memset((void*)(std::addressof(parser_)), 0, sizeof(http::parses::http_parser_url));
if (!string_.empty())
{
bool has_unencode_ch = http::has_unencode_char(string_);
if (has_unencode_ch)
{
string_ = http::url_encode(string_);
}
if (0 != http::parses::http_parser_parse_url(string_.data(), string_.size(), 0, std::addressof(parser_)))
{
if (has_unencode_ch)
{
string_ = http::url_decode(string_);
}
asio2::set_last_error(asio::error::invalid_argument);
}
}
}
url(url&&) noexcept = default;
url(url const&) = default;
url& operator=(url&&) noexcept = default;
url& operator=(url const&) = default;
/**
* @brief Gets the content of the "schema" section, maybe empty
* The return value is usually http or https
*/
inline std::string_view get_schema() noexcept
{
return this->field(http::parses::url_fields::UF_SCHEMA);
}
/**
* @brief Gets the content of the "schema" section, maybe empty
* The return value is usually http or https
* same as get_schema
*/
inline std::string_view schema() noexcept
{
return this->get_schema();
}
/**
* @brief Gets the content of the "host" section, maybe empty
*/
inline std::string_view get_host() noexcept
{
return this->field(http::parses::url_fields::UF_HOST);
}
/**
* @brief Gets the content of the "host" section, maybe empty
* same as get_host
*/
inline std::string_view host() noexcept
{
return this->get_host();
}
inline std::string_view get_default_port() noexcept
{
std::string_view schema = this->schema();
if (asio2::iequals(schema, "http"))
return std::string_view{ "80" };
if (asio2::iequals(schema, "https"))
return std::string_view{ "443" };
return std::string_view{ "80" };
}
inline std::string_view default_port() noexcept
{
return this->get_default_port();
}
/**
* @brief Gets the content of the "port" section
*/
inline std::string_view get_port() noexcept
{
std::string_view p = this->field(http::parses::url_fields::UF_PORT);
if (p.empty())
return this->default_port();
return p;
}
/**
* @brief Gets the content of the "port" section
* same as get_port
*/
inline std::string_view port() noexcept
{
return this->get_port();
}
/**
* @brief Gets the content of the "path" section
* the return value maybe has undecoded char, you can use http::url_decode(...) to decoded it.
*/
inline std::string_view get_path() noexcept
{
std::string_view p = this->field(http::parses::url_fields::UF_PATH);
if (p.empty())
return std::string_view{ "/" };
return p;
}
/**
* @brief Gets the content of the "path" section
* the return value maybe has undecoded char, you can use http::url_decode(...) to decoded it.
* same as get_path
*/
inline std::string_view path() noexcept
{
return this->get_path();
}
/**
* @brief Gets the content of the "query" section, maybe empty
* the return value maybe has undecoded char, you can use http::url_decode(...) to decoded it.
*/
inline std::string_view get_query() noexcept
{
return this->field(http::parses::url_fields::UF_QUERY);
}
/**
* @brief Gets the content of the "query" section, maybe empty
* the return value maybe has undecoded char, you can use http::url_decode(...) to decoded it.
* same as get_query
*/
inline std::string_view query() noexcept
{
return this->get_query();
}
/**
* @brief Gets the "target", which composed by path and query
* the return value maybe has undecoded char, you can use http::url_decode(...) to decoded it.
*/
inline std::string_view get_target() noexcept
{
if (parser_.field_set & (1 << (int)http::parses::url_fields::UF_PATH))
{
return std::string_view{ &string_[
parser_.field_data[(int)http::parses::url_fields::UF_PATH].off],
string_.size() -
parser_.field_data[(int)http::parses::url_fields::UF_PATH].off };
}
return std::string_view{ "/" };
}
/**
* @brief Gets the "target", which composed by path and query
* the return value maybe has undecoded char, you can use http::url_decode(...) to decoded it.
* same as get_target
*/
inline std::string_view target() noexcept
{
return this->get_target();
}
/**
* @brief Gets the content of the specific section, maybe empty
*/
inline std::string_view get_field(http::parses::url_fields f) noexcept
{
if (!(parser_.field_set & (1 << int(f))))
return std::string_view{};
return std::string_view{ &string_[parser_.field_data[int(f)].off], parser_.field_data[int(f)].len };
}
/**
* @brief Gets the content of the specific section, maybe empty
* same as get_field
*/
inline std::string_view field(http::parses::url_fields f) noexcept
{
return this->get_field(std::move(f));
}
inline http::parses::http_parser_url & parser() noexcept { return this->parser_; }
inline std::string & string() noexcept { return this->string_; }
inline http::parses::http_parser_url & get_parser() noexcept { return this->parser_; }
inline std::string & get_string() noexcept { return this->string_; }
protected:
http::parses::http_parser_url parser_;
std::string string_;
};
}
#endif // !__ASIO2_HTTP_URL_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_PPC_H
#define BHO_PREDEF_ARCHITECTURE_PPC_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_PPC`
http://en.wikipedia.org/wiki/PowerPC[PowerPC] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__powerpc+` | {predef_detection}
| `+__powerpc__+` | {predef_detection}
| `+__powerpc64__+` | {predef_detection}
| `+__POWERPC__+` | {predef_detection}
| `+__ppc__+` | {predef_detection}
| `+__ppc64__+` | {predef_detection}
| `+__PPC__+` | {predef_detection}
| `+__PPC64__+` | {predef_detection}
| `+_M_PPC+` | {predef_detection}
| `+_ARCH_PPC+` | {predef_detection}
| `+_ARCH_PPC64+` | {predef_detection}
| `+__PPCGECKO__+` | {predef_detection}
| `+__PPCBROADWAY__+` | {predef_detection}
| `+_XENON+` | {predef_detection}
| `+__ppc+` | {predef_detection}
| `+__ppc601__+` | 6.1.0
| `+_ARCH_601+` | 6.1.0
| `+__ppc603__+` | 6.3.0
| `+_ARCH_603+` | 6.3.0
| `+__ppc604__+` | 6.4.0
| `+__ppc604__+` | 6.4.0
|===
*/ // end::reference[]
#define BHO_ARCH_PPC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__powerpc) || defined(__powerpc__) || defined(__powerpc64__) || \
defined(__POWERPC__) || defined(__ppc__) || defined(__ppc64__) || \
defined(__PPC__) || defined(__PPC64__) || \
defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \
defined(__PPCGECKO__) || defined(__PPCBROADWAY__) || \
defined(_XENON) || \
defined(__ppc)
# undef BHO_ARCH_PPC
# if !defined (BHO_ARCH_PPC) && (defined(__ppc601__) || defined(_ARCH_601))
# define BHO_ARCH_PPC BHO_VERSION_NUMBER(6,1,0)
# endif
# if !defined (BHO_ARCH_PPC) && (defined(__ppc603__) || defined(_ARCH_603))
# define BHO_ARCH_PPC BHO_VERSION_NUMBER(6,3,0)
# endif
# if !defined (BHO_ARCH_PPC) && (defined(__ppc604__) || defined(__ppc604__))
# define BHO_ARCH_PPC BHO_VERSION_NUMBER(6,4,0)
# endif
# if !defined (BHO_ARCH_PPC)
# define BHO_ARCH_PPC BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_PPC
# define BHO_ARCH_PPC_AVAILABLE
#endif
#define BHO_ARCH_PPC_NAME "PowerPC"
/* tag::reference[]
= `BHO_ARCH_PPC_64`
http://en.wikipedia.org/wiki/PowerPC[PowerPC] 64 bit architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__powerpc64__+` | {predef_detection}
| `+__ppc64__+` | {predef_detection}
| `+__PPC64__+` | {predef_detection}
| `+_ARCH_PPC64+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_PPC_64 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) || \
defined(_ARCH_PPC64)
# undef BHO_ARCH_PPC_64
# define BHO_ARCH_PPC_64 BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_PPC_64
# define BHO_ARCH_PPC_64_AVAILABLE
#endif
#define BHO_ARCH_PPC_64_NAME "PowerPC64"
#if BHO_ARCH_PPC_64
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
#else
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_PPC,BHO_ARCH_PPC_NAME)
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_PPC_64,BHO_ARCH_PPC_64_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_TYPE_TRAITS_HPP__
#define __ASIO2_TYPE_TRAITS_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <cctype>
#include <string>
#include <string_view>
#include <type_traits>
#include <memory>
#include <functional>
#include <tuple>
#include <utility>
namespace asio2::detail
{
template<class T>
struct remove_cvref
{
typedef std::remove_cv_t<std::remove_reference_t<T>> type;
};
template< class T >
using remove_cvref_t = typename remove_cvref<T>::type;
template <typename Enumeration>
inline constexpr auto to_underlying(Enumeration const value) noexcept ->
typename std::underlying_type<Enumeration>::type
{
return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}
template <typename... Ts>
inline constexpr void ignore_unused(Ts const& ...) noexcept {}
template <typename... Ts>
inline constexpr void ignore_unused() noexcept {}
// https://stackoverflow.com/questions/53945490/how-to-assert-that-a-constexpr-if-else-clause-never-happen
// https://en.cppreference.com/w/cpp/utility/variant/visit
// https://en.cppreference.com/w/cpp/language/if#Constexpr_If
template<class...> inline constexpr bool always_false_v = false;
template <typename Tup, typename Fun, std::size_t... I>
inline void for_each_tuple_impl(Tup&& t, Fun&& f, std::index_sequence<I...>)
{
(f(std::get<I>(std::forward<Tup>(t))), ...);
}
template <typename Tup, typename Fun>
inline void for_each_tuple(Tup&& t, Fun&& f)
{
for_each_tuple_impl(std::forward<Tup>(t), std::forward<Fun>(f), std::make_index_sequence<
std::tuple_size_v<detail::remove_cvref_t<Tup>>>{});
}
// example : static_assert(is_template_instantiable_v<std::vector, double>);
// static_assert(is_template_instantiable_v<std::optional, int, int>);
template<template<typename...> typename T, typename AlwaysVoid, typename... Args>
struct is_template_instantiable : std::false_type {};
template<template<typename...> typename T, typename... Args>
struct is_template_instantiable<T, std::void_t<T<Args...>>, Args...> : std::true_type {};
template<template<typename...> typename T, typename... Args>
inline constexpr bool is_template_instantiable_v = is_template_instantiable<T, void, Args...>::value;
// example : static_assert(is_template_instance_of<std::vector, std::vector<int>>);
template<template<typename...> class U, typename T>
struct is_template_instance_of : std::false_type {};
template<template<typename...> class U, typename...Args>
struct is_template_instance_of<U, U<Args...>> : std::true_type {};
template<template<typename...> class U, typename...Args>
inline constexpr bool is_template_instance_of_v = is_template_instance_of<U, Args...>::value;
template<typename T> struct is_tuple : is_template_instance_of<std::tuple, T> {};
template<typename, typename = void>
struct is_char : std::false_type {};
template<typename T>
struct is_char<T, std::void_t<typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<T>, char > ||
std::is_same_v<detail::remove_cvref_t<T>, wchar_t > ||
#if defined(__cpp_lib_char8_t)
std::is_same_v<detail::remove_cvref_t<T>, char8_t > ||
#endif
std::is_same_v<detail::remove_cvref_t<T>, char16_t> ||
std::is_same_v<detail::remove_cvref_t<T>, char32_t>
>>> : std::true_type {};
template<class T>
inline constexpr bool is_char_v = is_char<detail::remove_cvref_t<T>>::value;
template<typename, typename = void>
struct is_string : std::false_type {};
template<typename T>
struct is_string<T, std::void_t<typename T::value_type, typename T::traits_type, typename T::allocator_type,
typename std::enable_if_t<std::is_same_v<T,
std::basic_string<typename T::value_type, typename T::traits_type, typename T::allocator_type>>>>>
: std::true_type {};
template<class T>
inline constexpr bool is_string_v = is_string<detail::remove_cvref_t<T>>::value;
template<typename, typename = void>
struct is_string_view : std::false_type {};
template<typename T>
struct is_string_view<T, std::void_t<typename T::value_type, typename T::traits_type,
typename std::enable_if_t<std::is_same_v<T,
std::basic_string_view<typename T::value_type, typename T::traits_type>>>>> : std::true_type {};
template<class T>
inline constexpr bool is_string_view_v = is_string_view<detail::remove_cvref_t<T>>::value;
template<typename, typename = void>
struct is_char_pointer : std::false_type {};
// char const *
// detail::remove_cvref_t<std::remove_pointer_t<detail::remove_cvref_t<T>>>
// char
template<typename T>
struct is_char_pointer<T, std::void_t<typename std::enable_if_t<
std::is_pointer_v< detail::remove_cvref_t<T>> &&
!std::is_pointer_v<detail::remove_cvref_t<std::remove_pointer_t<detail::remove_cvref_t<T>>>> &&
detail::is_char_v<std::remove_pointer_t<detail::remove_cvref_t<T>>>
>>> : std::true_type {};
template<class T>
inline constexpr bool is_char_pointer_v = is_char_pointer<detail::remove_cvref_t<T>>::value;
template<typename, typename = void>
struct is_char_array : std::false_type {};
template<typename T>
struct is_char_array<T, std::void_t<typename std::enable_if_t <
std::is_array_v<detail::remove_cvref_t<T>> &&
detail::is_char_v<std::remove_all_extents_t<detail::remove_cvref_t<T>>>
>>> : std::true_type {};
template<class T>
inline constexpr bool is_char_array_v = is_char_array<detail::remove_cvref_t<T>>::value;
template<class T, bool F = detail::is_char_v<T> || detail::is_char_pointer_v<T> || detail::is_char_array_v<T>>
struct char_type;
template<class T>
struct char_type<T, true>
{
using type = detail::remove_cvref_t<std::remove_pointer_t<std::remove_all_extents_t<detail::remove_cvref_t<T>>>>;
};
template<class T>
struct char_type<T, false>
{
using type = typename T::value_type;
};
template<class T>
inline constexpr bool is_character_string_v =
detail::is_string_v <T> ||
detail::is_string_view_v <T> ||
detail::is_char_pointer_v<T> ||
detail::is_char_array_v <T>;
template<class, class, class = void>
struct has_stream_operator : std::false_type {};
template<class T, class D>
struct has_stream_operator<T, D, std::void_t<decltype(T{} << D{})>> : std::true_type{};
template<class, class, class = void>
struct has_equal_operator : std::false_type {};
template<class T, class D>
struct has_equal_operator<T, D, std::void_t<decltype(T{} = D{})>> : std::true_type{};
template<class, class = void>
struct has_bool_operator : std::false_type {};
template<class T>
struct has_bool_operator<T, std::void_t<decltype(std::declval<T&>().operator bool())>> : std::true_type{};
template<class, class = void>
struct can_convert_to_string : std::false_type {};
template<class T>
struct can_convert_to_string<T, std::void_t<decltype(
std::string(std::declval<T>()).size(),
std::declval<std::string>() = std::declval<T>()
)>> : std::true_type{};
template<class T>
inline constexpr bool can_convert_to_string_v = can_convert_to_string<detail::remove_cvref_t<T>>::value;
template<class T>
struct shared_ptr_adapter
{
using rawt = typename detail::remove_cvref_t<T>;
using type = std::conditional_t<detail::is_template_instance_of_v<std::shared_ptr, rawt>,
rawt, std::shared_ptr<rawt>>;
};
template<class T>
typename detail::shared_ptr_adapter<T>::type to_shared_ptr(T&& t)
{
using rawt = typename detail::remove_cvref_t<T>;
if constexpr (detail::is_template_instance_of_v<std::shared_ptr, rawt>)
{
return std::forward<T>(t);
}
else
{
return std::make_shared<rawt>(std::forward<T>(t));
}
}
//// The following code will cause element_type_adapter<int> compilation failure:
//// the "int" don't has a type of element_type.
//template<class T>
//struct element_type_adapter
//{
// using rawt = typename remove_cvref_t<T>;
// using type = std::conditional_t<is_template_instance_of_v<std::shared_ptr, rawt>,
// typename rawt::element_type, rawt>;
//};
template<class T>
struct element_type_adapter
{
using type = typename detail::remove_cvref_t<T>;
};
template<class T>
struct element_type_adapter<std::shared_ptr<T>>
{
using type = typename detail::remove_cvref_t<T>;
};
template<class T>
struct element_type_adapter<std::unique_ptr<T>>
{
using type = typename detail::remove_cvref_t<T>;
};
template<class T>
struct element_type_adapter<T*>
{
using type = typename detail::remove_cvref_t<T>;
};
}
namespace asio2
{
using detail::to_underlying;
using detail::ignore_unused;
using detail::to_shared_ptr;
}
#endif // !__ASIO2_TYPE_TRAITS_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_ROGUEWAVE_H
#define BHO_PREDEF_LIBRARY_STD_ROGUEWAVE_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_RW`
http://stdcxx.apache.org/[Roguewave] Standard {CPP} library.
If available version number as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__STD_RWCOMPILER_H__+` | {predef_detection}
| `+_RWSTD_VER+` | {predef_detection}
| `+_RWSTD_VER+` | V.R.P
|===
*/ // end::reference[]
#define BHO_LIB_STD_RW BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__STD_RWCOMPILER_H__) || defined(_RWSTD_VER)
# undef BHO_LIB_STD_RW
# if defined(_RWSTD_VER)
# if _RWSTD_VER < 0x010000
# define BHO_LIB_STD_RW BHO_PREDEF_MAKE_0X_VVRRP(_RWSTD_VER)
# else
# define BHO_LIB_STD_RW BHO_PREDEF_MAKE_0X_VVRRPP(_RWSTD_VER)
# endif
# else
# define BHO_LIB_STD_RW BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_LIB_STD_RW
# define BHO_LIB_STD_RW_AVAILABLE
#endif
#define BHO_LIB_STD_RW_NAME "Roguewave"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_RW,BHO_LIB_STD_RW_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_POST_COMPONENT_HPP__
#define __ASIO2_POST_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <set>
#include <future>
#include <functional>
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/allocator.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t = void>
class post_cp
{
public:
/**
* @brief constructor
*/
post_cp() {}
/**
* @brief destructor
*/
~post_cp() = default;
public:
/**
* @brief Submits a completion token or function object for execution.
* This function submits an object for execution using the object's associated
* executor. The function object is queued for execution, and is never called
* from the current thread prior to returning from <tt>post()</tt>.
*/
template<typename Function>
inline derived_t & post(Function&& f)
{
derived_t& derive = static_cast<derived_t&>(*this);
// if use call post, but the user callback "f" has't hold the session_ptr,
// it maybe cause crash, so we need hold the session_ptr again at here.
// if the session_ptr is already destroyed, the selfptr() will cause crash.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[p = derive.selfptr(), f = std::forward<Function>(f)]() mutable
{
detail::ignore_unused(p);
f();
}));
return (derive);
}
/**
* @brief Submits a completion token or function object for execution after specified delay time.
* This function submits an object for execution using the object's associated
* executor. The function object is queued for execution, and is never called
* from the current thread prior to returning from <tt>post()</tt>.
*/
template<typename Function, typename Rep, typename Period>
inline derived_t & post(Function&& f, std::chrono::duration<Rep, Period> delay)
{
derived_t& derive = static_cast<derived_t&>(*this);
// note : need test.
// has't check where the server or client is stopped, if the server is stopping, but the
// iopool's wait_for_io_context_stopped() has't compelete and just at sleep, then user
// call post but don't call stop_all_timed_tasks, it maybe cause the
// wait_for_io_context_stopped() can't compelete forever,and the server.stop or client.stop
// never compeleted.
if (delay > std::chrono::duration_cast<
std::chrono::duration<Rep, Period>>((asio::steady_timer::duration::max)()))
delay = std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(
(asio::steady_timer::duration::max)());
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, &derive, p = derive.selfptr(), f = std::forward<Function>(f), delay]() mutable
{
std::unique_ptr<asio::steady_timer> timer = std::make_unique<
asio::steady_timer>(derive.io().context());
this->timed_tasks_.emplace(timer.get());
derive.io().timers().emplace(timer.get());
timer->expires_after(delay);
timer->async_wait(
[this, &derive, p = std::move(p), timer = std::move(timer), f = std::move(f)]
(const error_code& ec) mutable
{
ASIO2_ASSERT((!ec) || ec == asio::error::operation_aborted);
derive.io().timers().erase(timer.get());
detail::ignore_unused(p);
set_last_error(ec);
#if defined(ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR)
f();
#else
if (!ec)
{
f();
}
#endif
this->timed_tasks_.erase(timer.get());
});
}));
return (derive);
}
/**
* @brief Submits a completion token or function object for execution.
* This function submits an object for execution using the object's associated
* executor. The function object is queued for execution, and is never called
* from the current thread prior to returning from <tt>post()</tt>.
* note : Never call future's waiting function(eg:wait,get) in a communication(eg:on_recv)
* thread, it will cause dead lock;
*/
template<typename Function, typename Allocator>
inline auto post(Function&& f, asio::use_future_t<Allocator>) ->
std::future<std::invoke_result_t<Function>>
{
using return_type = std::invoke_result_t<Function>;
derived_t& derive = static_cast<derived_t&>(*this);
std::packaged_task<return_type()> task(std::forward<Function>(f));
std::future<return_type> future = task.get_future();
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[p = derive.selfptr(), t = std::move(task)]() mutable
{
detail::ignore_unused(p);
t();
}));
return future;
}
/**
* @brief Submits a completion token or function object for execution after specified delay time.
* This function submits an object for execution using the object's associated
* executor. The function object is queued for execution, and is never called
* from the current thread prior to returning from <tt>post()</tt>.
* note : Never call future's waiting function(eg:wait,get) in a communication(eg:on_recv)
* thread, it will cause dead lock;
*/
template<typename Function, typename Rep, typename Period, typename Allocator>
inline auto post(Function&& f, std::chrono::duration<Rep, Period> delay, asio::use_future_t<Allocator>)
-> std::future<std::invoke_result_t<Function>>
{
using return_type = std::invoke_result_t<Function>;
derived_t& derive = static_cast<derived_t&>(*this);
if (delay > std::chrono::duration_cast<
std::chrono::duration<Rep, Period>>((asio::steady_timer::duration::max)()))
delay = std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(
(asio::steady_timer::duration::max)());
std::packaged_task<return_type()> task(std::forward<Function>(f));
std::future<return_type> future = task.get_future();
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, &derive, p = derive.selfptr(), t = std::move(task), delay]() mutable
{
std::unique_ptr<asio::steady_timer> timer = std::make_unique<
asio::steady_timer>(derive.io().context());
this->timed_tasks_.emplace(timer.get());
derive.io().timers().emplace(timer.get());
timer->expires_after(delay);
timer->async_wait(
[this, &derive, p = std::move(p), timer = std::move(timer), t = std::move(t)]
(const error_code& ec) mutable
{
ASIO2_ASSERT((!ec) || ec == asio::error::operation_aborted);
derive.io().timers().erase(timer.get());
detail::ignore_unused(p);
set_last_error(ec);
#if defined(ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR)
t();
#else
if (!ec)
{
t();
}
#endif
this->timed_tasks_.erase(timer.get());
});
}));
return future;
}
/**
* @brief Submits a completion token or function object for execution.
* This function submits an object for execution using the object's associated
* executor. The function object is queued for execution. if current thread is
* the io_context's thread, the function will be executed immediately, otherwise
* the task will be asynchronously post to io_context to execute.
*/
template<typename Function>
inline derived_t & dispatch(Function&& f)
{
derived_t& derive = static_cast<derived_t&>(*this);
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[p = derive.selfptr(), f = std::forward<Function>(f)]() mutable
{
detail::ignore_unused(p);
f();
}));
return (derive);
}
/**
* @brief Submits a completion token or function object for execution.
* This function submits an object for execution using the object's associated
* executor. The function object is queued for execution. if current thread is
* the io_context's thread, the function will be executed immediately, otherwise
* the task will be asynchronously post to io_context to execute.
* note : Never call future's waiting function(eg:wait,get) in a communication(eg:on_recv)
* thread, it will cause dead lock;
*/
template<typename Function, typename Allocator>
inline auto dispatch(Function&& f, asio::use_future_t<Allocator>) ->
std::future<std::invoke_result_t<Function>>
{
using return_type = std::invoke_result_t<Function>;
derived_t& derive = static_cast<derived_t&>(*this);
std::packaged_task<return_type()> task(std::forward<Function>(f));
std::future<return_type> future = task.get_future();
// Make sure we run on the io_context thread
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[p = derive.selfptr(), t = std::move(task)]() mutable
{
detail::ignore_unused(p);
t();
}));
return future;
}
/**
* @brief Stop all timed events which you posted with a delay duration.
*/
inline derived_t& stop_all_timed_events()
{
derived_t& derive = static_cast<derived_t&>(*this);
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, p = derive.selfptr()]() mutable
{
detail::ignore_unused(p);
for (asio::steady_timer* timer : this->timed_tasks_)
{
detail::cancel_timer(*timer);
}
}));
return (derive);
}
/**
* @brief Stop all timed tasks which you posted with a delay duration.
* This function is the same as stop_all_timed_events.
*/
inline derived_t& stop_all_timed_tasks()
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.stop_all_timed_events();
}
protected:
/**
* @brief Stop all timed events which you posted with a delay duration.
* Use dispatch instead of post, this function is used for inner.
*/
inline derived_t& _dispatch_stop_all_timed_events()
{
derived_t& derive = static_cast<derived_t&>(*this);
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, p = derive.selfptr()]() mutable
{
detail::ignore_unused(p);
for (asio::steady_timer* timer : this->timed_tasks_)
{
detail::cancel_timer(*timer);
}
}));
return (derive);
}
protected:
/// Used to exit the timer tasks when component is ready to stop.
std::set<asio::steady_timer*> timed_tasks_;
};
}
#endif // !__ASIO2_POST_COMPONENT_HPP__
<file_sep>#include <asio2/tcp/tcp_server.hpp>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8028";
asio2::tcp_server server;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session>& session_ptr, std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}).bind_accept([](std::shared_ptr<asio2::tcp_session>& session_ptr)
{
// accept callback maybe has error like "Too many open files", etc...
if (!asio2::get_last_error())
{
// eg: If the remote ip is in the blacklist, we close the connection with RST.
if (session_ptr->remote_address() == "192.168.0.250")
session_ptr->stop();
else
session_ptr->set_silence_timeout(std::chrono::seconds(60));
}
else
{
printf("error occurred when calling the accept function : %d %s\n",
asio2::get_last_error_val(), asio2::get_last_error_msg().data());
}
}).bind_connect([&](std::shared_ptr<asio2::tcp_session>& session_ptr)
{
session_ptr->no_delay(true);
// Or you can close the connection here.
// Of course, you can also close the connection anywhere.
if (session_ptr->remote_address() == "192.168.0.254")
session_ptr->stop();
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([&](std::shared_ptr<asio2::tcp_session>& session_ptr)
{
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
}).bind_start([&]()
{
printf("start tcp server : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
printf("stop tcp server : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.start(host, port);
while (std::getchar() != '\n'); // press enter to exit this program
server.stop();
return 0;
}
<file_sep># 基于c++和asio的网络编程框架asio2教程基础篇:2、各个回调函数的触发顺序和执行流程
## 以tcp举例:
### tcp服务端流程:
```cpp
#include <asio2/asio2.hpp>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8028";
asio2::tcp_server server;
server.bind_init([]()
{
// 第1步:触发init回调函数
// 当监听socket打开成功(即socket(AF_INET, SOCK_STREAM, 0)函数调用结束)之后,这里被触发。
// 这个函数只会在服务端启动时触发1次。
// 可以在这里给监听socket设置一些选项什么的。
}).bind_start([&]()
{
// 第2步:触发start回调函数
// 当监听socket监听成功(即bind,listen函数调用结束)之后,这里被触发。
// 这个函数只会在服务端启动时触发1次。
// 可以在这里记录服务端启动成功的日志。
printf("start tcp server : %s %u\n",
server.listen_address().c_str(), server.listen_port());
}).bind_accept([](std::shared_ptr<asio2::tcp_session>& session_ptr)
{
// 第3步:触发accept回调函数
// 当某个客户端刚连接上服务端之后,这里被触发。
// 这个函数会多次触发,每有1个客户端连接上来之后,就会触发1次。但1个客户端只
// 触发1次。由于客户端有掉线自动重连机制,所以客户端每重连1次,就会触发1次。
// 可以在这里判断该客户端是不是在黑名单中,如果是,直接调用stop将该客户端断开。
// 此时还不能给这个客户端发送数据,会由于连接还未完全建立而导致发送失败。
if (session_ptr->remote_address() == "192.168.1.100")
session_ptr->stop();
}).bind_connect([&](auto & session_ptr)
{
// 第4步:触发connect回调函数
// 当某个客户端和服务端的连接完全建立成功之后,这里被触发。
// 这个函数会多次触发,每有1个客户端连接完成之后,就会触发1次。但1个客户端只
// 触发1次。
// 可以在这里给该客户端发送数据了。
// 可能有人会问,对于tcp来说,只要连接建立了,不就立即可以发数据了吗?为什么在上面的
// bind_accept中不能发,在这里的bind_connect中才能发呢?
// 这是因为asio2框架人为的给这个连接做了一个状态标识(status),在bind_accept中该status
// 是starting,表示连接还未完全建立,当触发到bind_connect时才会给该连接的状态标识设置
// 为started,表示连接建立全部完成了。所以如果在bind_accept中发送数据的话,框架会判断
// 到状态标识不是started所以就不允许发送数据。
// 那为什么要做这样一个状态标识呢?
// 因为对于ssl来说,连接建立之后,还有ssl握手,只有ssl握手成功以后才能收发数据。对于
// websocket来说,连接建立之后,还有upgrade升级协商,只有upgrade升级之后才能收发数据,
// 所以为了整体框架流程统一,人为的做了一个规定,只有触发了bind_connect的回调函数之后
// 才表示整个连接完全建立结束了。
session_ptr->no_delay(true);
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
// 第5步:触发recv回调函数
// 当收到某个客户端发送过来的数据之后,这里被触发。
// 这个函数会多次触发,每有1个客户端发送数据过来之后,就会触发1次。且1个客户端也会
// 触发多次,即发送数据就触发1次。
// 在这里对接收到的数据进行解析处理。
printf("recv : %u %.*s\n", (unsigned)data.size(), (int)data.size(), data.data());
session_ptr->async_send(data, [](std::size_t bytes_sent) {});
}).bind_disconnect([&](auto & session_ptr)
{
// 第6步:触发disconnect回调函数
// 当某个客户端关闭了,服务端收到该客户端的连接断开事件之后,
// 在该连接对应的socket关闭之前(即closesocket函数调用之前),这里被触发。
// 这个函数会多次触发,每有1个客户端连接完成之后,就会触发1次。但1个客户端只
// 触发1次。
// 可以在这里记录客户端的断开日志。
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(),
session_ptr->remote_port(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
// 第7步:触发stop回调函数
// 当关闭服务端时,在所有的连接都全部断开了之后,在监听socket关闭之前,这里被触发。
// 注意:必须所有连接全部断开了,且所有的session_ptr的引用计数为0了,这里才会触发,
// 因此如果你将session_ptr保存在了其它地方,一定要记得将你保存的session_ptr删除,
// 否则server.stop()函数会一直阻塞无法结束,这里的回调函数也无法触发。
// 这个函数只会在服务端关闭时触发1次。
// 可以在这里记录服务端的停止日志。
printf("stop tcp server : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.start(host, port);
while (std::getchar() != '\n'); // press enter to exit this program
server.stop();
return 0;
}
```
### tcp客户端流程:
```cpp
#include <asio2/asio2.hpp>
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8028";
asio2::tcp_client client;
client.bind_init([]()
{
// 第1步:触发init回调函数
// 当客户端socket打开成功(即socket(AF_INET, SOCK_STREAM, 0)函数调用结束)之后,这里被触发。
// 这个函数只会在客户端启动时触发1次。
// 可以在这里给socket设置一些选项什么的。
}).bind_connect([&]()
{
// 第2步:触发connect回调函数
// 当客户端连接服务端完成之后,这里被触发。
// 这个函数只会在客户端连接服务端时触发1次,不管连接成功还是连接失败都会触发。连接
// 成功还是失败,可以使用asio2::get_last_error()来进行判断。
// 注意:客户端有掉线自动重连机制,因此,如果客户端连接服务端失败,那么客户端过几秒后
// 会再次自动连接服务端,每连接一次服务端,不管连接成功还是失败,此函数就会被触发1次。
// 可以在这里给向服务端发送数据了。
if (asio2::get_last_error())
printf("connect failure : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n", client.local_address().c_str(), client.local_port());
// 如果没有错误,就表示连接成功,可以向服务端发送数据了。
if (!asio2::get_last_error())
client.async_send("<abcdefghijklmnopqrstovuxyz0123456789>");
}).bind_recv([&](std::string_view data)
{
// 第3步:触发recv回调函数
// 当收到服务端发送过来的数据之后,这里被触发。
// 这个函数会多次触发,每接收到1次数据,就会触发1次。
// 可以在这里对接收到的数据进行解析处理。
printf("recv : %u %.*s\n", (unsigned)data.size(), (int)data.size(), data.data());
client.async_send(data);
}).bind_disconnect([&]()
{
// 第4步:触发disconnect回调函数
// 当客户端关闭时(或者服务端关闭了),在socket即将关闭之前,这里被触发。
// 这个函数只会在客户端关闭时触发1次。且只有在客户端连接成功之后才会被触发,就是
// 说如果客户端没有成功连接上服务端,那么客户端在关闭时是不会触发disconnect的。
// 可以在这里记录客户端的关闭日志。
printf("disconnect : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
});
client.start(host, port);
while (std::getchar() != '\n');
return 0;
}
```
### 所有回调函数都必须要写吗?
- 服务端大约有至少7个回调函数可以写,客户端的回调函数少一些,那是不是所有的回调函数都必须要写呢?
- 不是的,想写几个就写几个即可。
- 比如只想要接收数据的功能,其它都不要,那就只写一个bind_recv就行了。如下:
```cpp
#include <asio2/asio2.hpp>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8028";
asio2::tcp_server server;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
printf("recv : %u %.*s\n", (unsigned)data.size(), (int)data.size(), data.data());
session_ptr->async_send(data, [](std::size_t bytes_sent) {});
});
server.start(host, port);
while (std::getchar() != '\n'); // press enter to exit this program
server.stop();
return 0;
}
```
- 但要注意的是,不管你有没有绑定事件回调函数,实际上所有事件都是执行过了的,只不过你没有绑定回调函数,在执行到该事件时asio2框架就没有通知你罢了。比如,如果你没有调用bind_recv来绑定一个接收数据的回调函数,那asio2内部还是照样在接收数据的,只是收到数据时没有通知你。
## 项目地址:
github : [https://github.com/zhllxt/asio2](https://github.com/zhllxt/asio2)
码云 : [https://gitee.com/zhllxt/asio2](https://gitee.com/zhllxt/asio2)
### 最后编辑于2022-06-23
<file_sep>#ifndef ASIO2_ENABLE_SSL
#define ASIO2_ENABLE_SSL
#endif
//#include <asio2/asio2.hpp>
#include <asio2/tcp/tcps_client.hpp>
#include <iostream>
std::string_view client_key = R"(
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,967AA0B1DF77C592
<KEY>
)";
std::string_view client_crt = R"(
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 2 (0x2)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=AU, ST=HENAN, L=ZHENGZHOU, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=<EMAIL>
Validity
Not Before: Nov 26 09:04:13 2021 GMT
Not After : Nov 24 09:04:13 2031 GMT
Subject: C=AU, ST=HENAN, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=<EMAIL>
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (1024 bit)
Modulus:
00:be:94:6f:5b:ae:20:a8:73:25:3f:a8:4d:92:5a:
5b:8b:64:4d:7b:53:2c:fb:10:e9:ad:e5:06:41:5a:
f6:eb:58:9a:22:6b:5c:ac:04:03:c5:09:2a:3d:84:
fdf8:f53e:61e4::18:64:cd:5d:ce:ee:03:54:
da:af:dd:da:f2:b4:93:72:3f:26:d6:57:ea:18:ec:
9c:c8:20:bc:1a:a1:f9:e0:f5:64:67:9d:61:b8:f6:
87:a4:d3:36:01:24:b4:e7:00:c3:54:82:bd:7f:22:
48:40:df:43:8c:26:83:aa:b3:68:5d:e9:a1:fe:7c:
fdf8:f53e:61e4::18:25
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
fc00:db20:35b:7399::5:3C:1C:5C:58:96:08:59:94:A5:7A:A1:22
X509v3 Authority Key Identifier:
keyid:61:74:1F:7E:B1:0E:0D:F9:46:DD:6A:97:85:72:DE:1A:7D:A2:34:65
Signature Algorithm: sha256WithRSAEncryption
39:c1:66:e0:1a:68:2a:bc:6e:56:a0:a4:18:53:ac:2e:49:03:
d3:df:e0:7d:4e:51:4c:0b:fb:f9:1d:ae:a5:b8:16:b1:b6:23:
db:62:33:25:72:14:99:e1:3a:1a:52:d2:f4:51:74:ef:df:04:
fc00:db20:35b:7399::5:60:05:d5:65:09:6c:44:14:e6:29:
b8:51:03:e0:bd:33:c3:9d:da:99:24:eb:a8:76:18:88:14:84:
83:ee:33:a3:5c:05:9a:3c:e3:f0:35:e3:52:a2:4e:aa:39:07:
fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:a9:90:ef:5a:53:3b:5b:c7:4d:bb:
76:05:70:eb:a7:15:22:ad:b5:ed:3b:74:58:71:c0:53:90:44:
fdf8:f53e:61e4::18:66:ee:18:53:d4:4c:5e:d6:29:f4:
4c:18:2c:7a:79:96:38:d7:cf:51:e4:3b:72:9f:9c:be:7f:2e:
05:8a:06:18:61:62:d5:9c:cc:31:a7:4c:d9:94:bd:d3:b4:22:
b8:42:d2:6f:99:7a:72:43:b3:a9:03:e2:36:6d:6b:28:4f:f8:
c5:b5:1b:2b:1d:e9:34:8f:66:0a:13:58:d5:28:38:03:22:bc:
37:27:ed:c7:b3:c7:80:63:25:d7:fc:38:ad:ac:f9:aa:5b:07:
15:df:56:17
-----BEGIN CERTIFICATE-----
<KEY>
-----END CERTIFICATE-----
)";
std::string_view ca_crt = R"(
-----BEGIN <KEY>
-----END CERTIFICATE-----
)";
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8002";
asio2::tcps_client client;
client.set_connect_timeout(std::chrono::seconds(10));
client.auto_reconnect(true, std::chrono::seconds(3));
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
client.bind_recv([&](std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
client.async_send(data);
}).bind_connect([&]()
{
printf("connect : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
std::string str;
str.resize(64);
client.async_send(std::move(str));
}).bind_handshake([&]()
{
printf("handshake : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_disconnect([]()
{
printf("disconnect : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
});
if (!client.start(host, port))
{
std::cout << "start failed : " << asio2::last_error_msg() << std::endl;
}
else
{
std::cout << "start success " << std::endl;
}
// send data, beacuse may be connect failed,
// if connect failed, the data will sent failed too.
client.async_send(std::string("abc0123456789xyz"), []()
{
if (asio2::get_last_error())
std::cout << "send failed : " << asio2::last_error_msg() << std::endl;
});
while (std::getchar() != '\n');
return 0;
}
<file_sep>#define ASIO2_ENABLE_LOG
#include <asio2/mqtt/mqtt_client.hpp>
#include <iostream>
#include <asio2/external/fmt.hpp>
#include <asio2/mqtt/message.hpp>
int main()
{
std::string_view host = "broker.hivemq.com";
//std::string_view host = "127.0.0.1";
std::string_view port = "1883";
asio2::mqtt_client client;
mqtt::v5::connect connect;
connect.client_id(u8"<EMAIL>");
client.set_connect_message(std::move(connect));
client.bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n",
client.local_address().c_str(), client.local_port());
if (!asio2::get_last_error())
{
client.start_timer(1, 1000, 1, [&]()
{
mqtt::v5::subscribe sub;
sub.packet_id(1001);
sub.add_subscriptions(mqtt::subscription{ "/asio2/mqtt/qos1",mqtt::qos_type::at_least_once });
client.async_send(std::move(sub), []()
{
std::cout << "send v5::subscribe, packet_id : 1001" << std::endl;
});
});
client.start_timer(2, 2000, 5, [&]()
{
static std::uint16_t id = 3000; id++;
mqtt::v5::publish pub;
pub.qos(mqtt::qos_type::at_least_once);
pub.packet_id(id);
pub.topic_name("/asio2/mqtt/qos1");
pub.payload(fmt::format("{}", id));
client.async_send(std::move(pub), [pid = id]()
{
fmt::print("send v5::publish , packet id : {:5d}\n", pid);
});
});
}
}).bind_disconnect([]()
{
printf("disconnect : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
client.on_connack([](mqtt::v5::connack& connack)
{
fmt::print("recv v5::connack , reason code: {}", int(connack.reason_code()));
for (auto& vprop : connack.properties().data())
{
std::visit([](auto& prop)
{
[[maybe_unused]] auto name = prop.name();
[[maybe_unused]] auto type = prop.type();
[[maybe_unused]] auto value = prop.value();
fmt::print(" {}:{}", name, value);
}, vprop.variant());
}
fmt::print("\n");
});
client.on_suback([](mqtt::v5::suback& msg)
{
fmt::print("recv v5::suback , packet id : {:5d} reason code: {}\n",
msg.packet_id(), msg.reason_codes().at(0));
});
client.on_publish([](mqtt::v5::publish& msg, mqtt::message& rep)
{
asio2::ignore_unused(msg, rep);
fmt::print("recv v5::publish , packet id : {:5d} QoS : {} topic_name : {} payload : {}\n",
msg.packet_id(), int(msg.qos()), msg.topic_name(), msg.payload());
});
client.on_puback([](mqtt::v5::puback& puback)
{
fmt::print("recv v5::puback , packet id : {:5d} reason code : {}\n", puback.packet_id(), puback.reason_code());
});
client.on_pubrec([](mqtt::v5::pubrec& msg, mqtt::v5::pubrel& rep)
{
asio2::ignore_unused(msg, rep);
fmt::print("recv v5::pubrec , packet id : {:5d} reason_code : {}\n",
msg.packet_id(), int(msg.reason_code()));
});
client.on_pubcomp([](mqtt::v5::pubcomp& msg)
{
fmt::print("recv v5::pubcomp , packet id : {:5d} reason_code : {}\n",
msg.packet_id(), int(msg.reason_code()));
});
client.on_pingresp([](mqtt::message& msg)
{
std::ignore = msg;
printf("recv v5::pingresp\n");
});
client.on_disconnect([](mqtt::message& msg)
{
asio2::ignore_unused(msg);
if (mqtt::v5::disconnect* p = static_cast<mqtt::v5::disconnect*>(msg); p)
printf("recv v5::disconnect, reason code : %u\n", p->reason_code());
});
client.start(host, port);
client.subscribe("/asio2/mqtt/qos1", 1, [](mqtt::v5::publish& msg) mutable
{
fmt::print("recv v5::publish , packet id : {:5d} QoS : {} topic_name : {} payload : {}\n",
msg.packet_id(), int(msg.qos()), msg.topic_name(), msg.payload());
});
client.subscribe("/asio2/mqtt/qos0", 0, [](mqtt::message& msg) mutable
{
ASIO2_ASSERT(!msg.empty());
mqtt::v5::publish* p = msg.get_if<mqtt::v5::publish>();
if (p)
{
fmt::print("recv v5::publish , packet id : {:5d} QoS : {} topic_name : {} payload : {}\n",
p->packet_id(), int(p->qos()), p->topic_name(), p->payload());
}
});
bool ret1 = client.subscribe<bool>("/asio2/mqtt/qos1", 1, [](mqtt::v5::publish& msg) mutable
{
fmt::print("recv v5::publish , packet id : {:5d} QoS : {} topic_name : {} payload : {}\n",
msg.packet_id(), int(msg.qos()), msg.topic_name(), msg.payload());
});
bool ret2 = client.subscribe<bool>("/asio2/mqtt/qos0", 0, [](mqtt::message& msg) mutable
{
ASIO2_ASSERT(!msg.empty());
mqtt::v5::publish* p = msg.get_if<mqtt::v5::publish>();
if (p)
{
fmt::print("recv v5::publish , packet id : {:5d} QoS : {} topic_name : {} payload : {}\n",
p->packet_id(), int(p->qos()), p->topic_name(), p->payload());
}
});
mqtt::message msg1 = client.subscribe<mqtt::message>("/asio2/mqtt/qos1", 1, [](mqtt::v5::publish& msg) mutable
{
fmt::print("recv v5::publish , packet id : {:5d} QoS : {} topic_name : {} payload : {}\n",
msg.packet_id(), int(msg.qos()), msg.topic_name(), msg.payload());
});
mqtt::v5::suback* psuback1 = msg1.get_if<mqtt::v5::suback>();
mqtt::message msg2 = client.subscribe<mqtt::message>("/asio2/mqtt/qos0", 0, [](mqtt::message& msg) mutable
{
ASIO2_ASSERT(!msg.empty());
mqtt::v5::publish* p = msg.get_if<mqtt::v5::publish>();
if (p)
{
fmt::print("recv v5::publish , packet id : {:5d} QoS : {} topic_name : {} payload : {}\n",
p->packet_id(), int(p->qos()), p->topic_name(), p->payload());
}
});
mqtt::v5::suback* psuback2 = msg2.get_if<mqtt::v5::suback>();
client.unsubscribe("/asio2/mqtt/qos1");
bool unret = client.unsubscribe<bool>("/asio2/mqtt/qos1");
mqtt::message unmsg = client.unsubscribe<mqtt::message>("/asio2/mqtt/qos1");
mqtt::v5::unsuback* punsuback = unmsg.get_if<mqtt::v5::unsuback>();
client.publish("/asio2/mqtt/qos0", "0", 0);
bool pubret = client.publish<bool>("/asio2/mqtt/qos1", "1", 1);
mqtt::message pubmsg = client.publish<mqtt::message>("/asio2/mqtt/qos2", "2", 2);
mqtt::v5::pubcomp* ppubcomp = pubmsg.get_if<mqtt::v5::pubcomp>();
asio2::ignore_unused(ret1, ret2, msg1, msg2, psuback1, psuback2, unret, unmsg, punsuback, pubret, ppubcomp);
while (std::getchar() != '\n');
return 0;
}
<file_sep>#include <asio2/rpc/rpc_server.hpp>
#include <asio2/external/json.hpp>
struct userinfo
{
std::string name;
int age;
std::map<int, std::string> purview;
// User defined object types require serialized the members like this:
template <class Archive>
void serialize(Archive & ar)
{
ar(name);
ar(age);
ar(purview);
}
};
// -- serialize the third party object
namespace nlohmann
{
template<class Archive>
void save(Archive& ar, json const& j)
{
ar << j.dump();
}
template<class Archive>
void load(Archive& ar, json& j)
{
std::string v;
ar >> v;
j = json::parse(v);
}
}
int add(int a, int b)
{
return a + b;
}
// Asynchronous rpc function
rpc::future<int> async_add(int a, int b)
{
// If you want to know which client called this function, method 1:
std::shared_ptr<asio2::rpc_session> sptr = asio2::get_current_caller<std::shared_ptr<asio2::rpc_session>>();
rpc::promise<int> promise;
rpc::future<int> f = promise.get_future();
std::thread([a, b, promise = std::move(promise), sptr = std::move(sptr)]() mutable
{
ASIO2_ASSERT(sptr);
std::this_thread::sleep_for(std::chrono::seconds(1));
promise.set_value(a + b);
}).detach();
return f;
}
// Asynchronous rpc function, and the return value is void
rpc::future<void> async_test(std::shared_ptr<asio2::rpc_session>& session_ptr, std::string a, std::string b)
{
asio2::ignore_unused(session_ptr, a, b);
rpc::promise<void> promise;
rpc::future<void> f = promise.get_future();
ASIO2_ASSERT(a == "abc" && b == "def");
std::thread([a, b, promise]() mutable
{
asio2::ignore_unused(a, b);
promise.set_value();
}).detach();
return f;
}
// rpc function with return third party object
nlohmann::json test_json(nlohmann::json j)
{
std::string s = j.dump();
return nlohmann::json::parse(s);
}
class user_crud
{
public:
double mul(double a, double b)
{
return a * b;
}
// If you want to know which client called this function, method 2:
// set the first parameter to std::shared_ptr<asio2::rpc_session>& session_ptr
userinfo get_user(std::shared_ptr<asio2::rpc_session>& session_ptr)
{
// use get_current_caller to get the client again, this is just for test.
std::shared_ptr<asio2::rpc_session> sptr = asio2::get_current_caller<std::shared_ptr<asio2::rpc_session>>();
ASIO2_ASSERT(session_ptr.get() == sptr.get());
asio2::ignore_unused(session_ptr, sptr);
userinfo u;
u.name = "lilei";
u.age = ((int)time(nullptr)) % 100;
u.purview = { {1,"read"},{2,"write"} };
return u;
}
void del_user(std::shared_ptr<asio2::rpc_session>& session_ptr, const userinfo& u)
{
printf("del_user is called by %s %u : %s %d \n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
u.name.c_str(), u.age);
}
};
void heartbeat(std::shared_ptr<asio2::rpc_session>& session_ptr)
{
printf("heartbeat %s\n", session_ptr->remote_address().c_str());
}
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8010";
// Specify the "max recv buffer size" to avoid malicious packets, if some client
// sent data packets size is too long to the "max recv buffer size", then the
// client will be disconnect automatic .
asio2::rpc_server server(
512, // the initialize recv buffer size :
1024, // the max recv buffer size :
4 // the thread count :
);
server.bind_connect([&](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
// when a client is connected, we call the client's rpc function.
session_ptr->async_call([](int v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 15 - 6);
}
printf("sub : %d err : %d %s\n", v,
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, std::chrono::seconds(10), "sub", 15, 6);
// just call the client's rpc function, and don't care the client's response
session_ptr->async_call("test", "i love you");
}).bind_start([&]()
{
printf("start rpc server : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
user_crud usercrud;
// bind member rpc function
server
.bind("add", add)
.bind("mul", &user_crud::mul, usercrud)
.bind("get_user", &user_crud::get_user, usercrud)
.bind("del_user", &user_crud::del_user, &usercrud);
// bind global rpc function
server.bind("async_add", async_add);
server.bind("async_test", async_test);
server.bind("test_json", test_json);
server.bind("heartbeat", heartbeat);
// bind lambda rpc function
server.bind("cat", [&](std::shared_ptr<asio2::rpc_session>& session_ptr,
const std::string& a, const std::string& b)
{
// Nested call rpc function in business function is ok.
session_ptr->async_call([session_ptr](int v) mutable
{
// Nested call rpc function in business function is ok.
session_ptr->async_call([](int v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 15 + 18);
}
printf("async_add : %d err : %d %s\n", v,
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "async_add", 15, 18);
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 15 - 8);
}
printf("sub : %d err : %d %s\n", v,
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "sub", 15, 8);
return a + b;
});
server.start(host, port);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
Copyright <NAME> 2013-2015
Copyright (c) Microsoft Corporation 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#if !defined(BHO_PREDEF_PLATFORM_H) || defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BHO_PREDEF_PLATFORM_H
#define BHO_PREDEF_PLATFORM_H
#endif
#include <asio2/bho/predef/platform/android.h>
#include <asio2/bho/predef/platform/cloudabi.h>
#include <asio2/bho/predef/platform/mingw.h>
#include <asio2/bho/predef/platform/mingw32.h>
#include <asio2/bho/predef/platform/mingw64.h>
#include <asio2/bho/predef/platform/windows_uwp.h>
#include <asio2/bho/predef/platform/windows_desktop.h>
#include <asio2/bho/predef/platform/windows_phone.h>
#include <asio2/bho/predef/platform/windows_server.h>
#include <asio2/bho/predef/platform/windows_store.h>
#include <asio2/bho/predef/platform/windows_system.h>
#include <asio2/bho/predef/platform/windows_runtime.h> // deprecated
#include <asio2/bho/predef/platform/ios.h>
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* https://github.com/r-lyeh-archived/bundle
*
*/
#ifndef __ASIO2_ZLIB_HPP__
#define __ASIO2_ZLIB_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <string>
#include <string_view>
#include <algorithm>
#include <asio2/external/asio.hpp>
#include <asio2/external/beast.hpp>
#include <asio2/base/error.hpp>
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::zlib
#else
namespace boost::beast::zlib
#endif
{
/**
* impl : use the beast::zlib for compress and uncompress
* Problem: compress data with beast::zlib and uncompress data with zlib(www.zlib.net) will fail
*/
class impl
{
public:
impl(
beast::zlib::Flush compress_flush = beast::zlib::Flush::sync,
beast::zlib::Flush uncompress_flush = beast::zlib::Flush::sync
)
: deflate_flush_( compress_flush)
, inflate_flush_(uncompress_flush)
{
}
~impl() = default;
impl(impl&&) = delete;
impl(const impl&) = delete;
impl& operator=(impl&&) = delete;
impl& operator=(const impl&) = delete;
inline std::string compress(std::string_view data)
{
return work(deflate_stream_, deflate_flush_, data, asio2::get_last_error());
}
inline std::string uncompress(std::string_view data)
{
return work(inflate_stream_, inflate_flush_, data, asio2::get_last_error());
}
inline static std::size_t compress_bound(std::size_t size)
{
return beast::zlib::deflate_upper_bound(size);
}
inline static std::size_t uncompress_bound(std::size_t size)
{
std::size_t bound = size;
std::size_t deflate_bound = beast::zlib::deflate_upper_bound(bound) + 5 + 6 + 1;
while (deflate_bound < size)
{
bound += (size - deflate_bound) * 2;
deflate_bound = beast::zlib::deflate_upper_bound(bound) + 5 + 6 + 1;
}
return (std::max)(bound, deflate_bound);
}
inline beast::zlib::deflate_stream& compressor() { return deflate_stream_; }
inline beast::zlib::inflate_stream& uncompressor() { return inflate_stream_; }
protected:
template<class CompressOrUncompress>
inline std::size_t calc_bound(CompressOrUncompress&, beast::zlib::Flush, std::size_t size)
{
using optype = std::remove_cv_t<std::remove_reference_t<CompressOrUncompress>>;
if constexpr /**/ (std::is_same_v<beast::zlib::deflate_stream, optype>)
{
return compress_bound(size);
}
else if constexpr (std::is_same_v<beast::zlib::inflate_stream, optype>)
{
return uncompress_bound(size);
}
else
{
// http://www.purecpp.cn/detail?id=2293
static_assert(!sizeof(CompressOrUncompress));
}
}
template<class CompressOrUncompress>
inline std::string work(CompressOrUncompress& op, beast::zlib::Flush flush, std::string_view data, asio::error_code& ec)
{
ec.clear();
std::string result{};
result.resize(calc_bound(op, flush, data.size()));
beast::zlib::z_params zs{};
zs.next_in = decltype(zs.next_in)(data.data());
zs.avail_in = data.size();
zs.next_out = decltype(zs.next_out)(result.data());
zs.avail_out = result.size();
while (true)
{
op.write(zs, flush, ec);
if (ec)
break;
if (zs.avail_in == std::size_t(0))
break;
result.resize(result.size() + calc_bound(op, flush, zs.avail_in));
zs.next_out = decltype(zs.next_out)(result.data() + zs.total_out);
zs.avail_out = result.size() - zs.total_out;
}
if (!ec)
result.resize(zs.total_out);
else
result.resize(0);
return result;
}
protected:
beast::zlib::deflate_stream deflate_stream_{};
beast::zlib::inflate_stream inflate_stream_{};
beast::zlib::Flush deflate_flush_{ beast::zlib::Flush::sync };
beast::zlib::Flush inflate_flush_{ beast::zlib::Flush::sync };
};
}
#endif // !__ASIO2_ZLIB_HPP__
<file_sep># 基于c++和asio的网络编程框架asio2教程使用篇:使用rpc模块编写rpc server和rpc client
rpc的基础概念这里就不再介绍了,不熟悉的可以网络搜索,先了解一下。asio2框架实现了轻量级的rpc功能,使用起来非常简单。
## 最简单的例子
##### 服务端代码
```cpp
int add(int a, int b)
{
return a + b;
}
asio2::rpc_server server;
server.bind("add", add); // 绑定rpc函数,第1个参数是字符串,表示rpc函数的名字是什么,第2个参数是真正的rpc函数
server.start("0.0.0.0", 8010); // 启动服务端
```
##### 客户端代码
```cpp
asio2::rpc_client client;
client.start("127.0.0.1", 8010); // 连接服务端
int sum = client.call<int>("add", 1, 2); // 调用rpc函数,得到结果:sum == 3
```
## 同步调用
```cpp
// 最简单的同步调用如下:
// 第1个参数是个字符串,表示rpc函数的名字,后面的参数表示rpc函数的参数(这里的1,2即是add函数的参数)
int sum = client.call<int>("add", 1, 2);
// 如果函数调用失败,怎么办?在哪里获取通知?
int sum = client.call<int>("add", 1, 2);
// 使用asio2::get_last_error()来判断是否发生错误
if (asio2::get_last_error()) // 有错误
printf("add failed : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
// 怎么设置同步调用的超时时间?
int sum = client.call<int>(std::chrono::seconds(3), "add", 1, 2);
```
## 异步调用
```cpp
// 最简单的异步调用如下:
// 第1个参数是回调函数,后面的参数是rpc函数名称和rpc函数参数
// 回调函数的参数即是rpc函数的返回值
client.async_call([](int sum)
{
if (!asio2::get_last_error()) // 没有错误
{
ASIO2_ASSERT(sum == 1 + 2);
}
else // 有错误
{
printf("error : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
}
}, "add", 1, 2);
// 如何指定异步调用的超时时间?
client.async_call([](int sum)
{
}, std::chrono::seconds(3), "add", 1, 2);
// 如果rpc函数返回值是void怎么办?
// 比如有个心跳函数:
void heartbeat(){}
// 那么可以像下面这样调用即可,也就是说回调函数参数为空即可
client.async_call([]()
{
}, std::chrono::seconds(3), "heartbeat");
// 如果你不关心调用结果,也就是说不关心rpc函数的返回值,你可以直接调用,可以不关心调用成功还是失败,
// 这种情况下当服务器收到rpc请求后,是不会给客户端回复的。
client.async_call("heartbeat");
```
## 链式调用
不管是同步调用,还是异步调用,都有“超时设置,rpc函数名称,rpc函数参数”等参数,由于参数很多,而且参数的位置不能出错,所以在实际使用时容易忘记各个参数的前后位置,增加了心智负担,所以框架也提供了链式调用功能,如下:
```cpp
// 同步调用的链式调用,如下:
int sum = client.call<int>("add", 1, 2); // ok
int sum = client.timeout(std::chrono::seconds(3)).call<int>("add", 1, 2); // ok
// 同步调用时.call函数必须在链的最后一个
int sum = client.call<int>("add", 1, 2).timeout(std::chrono::seconds(3)); // 错误
// 异步调用的链式调用,如下:
client.timeout(std::chrono::seconds(3)).response([](int sum){}).async_call("add", 1, 2); // ok
client.response([](int sum){}).timeout(std::chrono::seconds(3)).async_call("add", 1, 2); // ok
// 异步调用时async_call可以在链的任意位置 所以下面都是正确的
client.async_call("add", 1, 2).timeout(std::chrono::seconds(3)).response([](int sum){}); // ok
client.timeout(std::chrono::seconds(3)).async_call("add", 1, 2).response([](int sum){}); // ok
client.response([](int sum){}).async_call("add", 1, 2); // ok
client.async_call("add", 1, 2).response([](int sum){}); // ok
```
## 双向调用
上面所举的例子中,都是在客户端调用服务端的rpc函数。
框架既支持客户端调用服务端的rpc函数,同样也支持服务端调用客户端的rpc函数,如下:
```cpp
// bind_connect是server提前绑定的回调函数,当有一个客户端连接上来之时,此回调函数会被调用,关于bind_connect知识请参考其它文章。
// 当然,并不是只能在bind_connect这里,也可以在其它地方调用客户端的rpc函数。
server.bind_connect([&](auto & session_ptr)
{
// 这里session_ptr表示客户端的连接对象
// 这个客户端连接上来之后,server通过session_ptr向该客户端发起一个rpc函数调用
session_ptr->async_call([](int v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 15 - 6);
}
}, std::chrono::seconds(5), "sub", 15, 6);
});
```
## 嵌套调用
当业务流程复杂时,会出现嵌套调用rpc函数的需求,框架同样支持,如下:
```cpp
// server端提前绑定一个rpc函数"cat"(这里这个rpc函数是个lambda函数)
server.bind("cat", [&](std::shared_ptr<asio2::rpc_session>& session_ptr, std::string a, std::string b)
{
// 当客户端调用rpc函数"cat"时,会执行到这里来.....
// server端收到客户端的调用请求时,在这里用session_ptr嵌套的给该client发送一个rpc调用请求
session_ptr->async_call([session_ptr](int v) mutable
{
// 当server端发送的调用请求,收到了回复时,再次嵌套的给该client发送一个rpc调用请求,如此等等。
session_ptr->async_call([](int v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 15 + 18);
}
printf("async_add : %d err : %d %s\n", v, asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "add", 15, 18);
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 15 - 8);
}
printf("sub : %d err : %d %s\n", v, asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "sub", 15, 8);
return a + b;
});
```
## 服务端如何知道是哪个客户端调用的rpc函数?
```cpp
int add(int a, int b)
{
return a + b;
}
```
比如上面的add函数,当有1个server和1000个client,且1000个client都会调用这个add函数时,怎么知道是哪个client调用的呢?
方法1:
```cpp
// 将rpc函数的第1个参数改为连接对象的指针,如下,此时通过session_ptr就能知道是哪个client调用的了
// 当然,如果你不关心是哪个client调用的,那么std::shared_ptr<asio2::rpc_session>& session_ptr这个参数可以不要,
// 也就是说下面这种带session_ptr的方式和上面那种不带session_ptr的方式,都支持,而且都只需server.bind("add", add)
// 即可,不同的版本不需要其它不同的bind操作。
int add(std::shared_ptr<asio2::rpc_session>& session_ptr, int a, int b)
{
return a + b;
}
```
方法2:
```cpp
int add(int a, int b)
{
// 调用get_current_caller函数直接获取即可(注意模板参数必须完全匹配)
std::shared_ptr<asio2::rpc_session> session_ptr =
asio2::get_current_caller<std::shared_ptr<asio2::rpc_session>>();
return a + b;
}
```
## 怎么让rpc函数支持自定义的结构体?
比如我有个结构体,如下:
```cpp
struct userinfo
{
std::string name;
int age;
std::map<int, std::string> purview;
};
```
然后有个rpc函数,如下:
```cpp
userinfo get_user(std::string name)
{
// 根据参数name找到对应的userinfo并返回(这里不再写“根据name找到userinfo”的代码了)
userinfo u;
u.name = name;
u.age = 100;
u.purview = { {1,"read"},{2,"write"} };
return u;
}
```
那么只需要像下面这样修改一下结构体userinfo即可。
也就是说手工给结构体userinfo添加一个序列化的成员函数即可。
给userinfo添加了序列化的成员函数之后,userinfo这个结构体就可以像普通的int, std::string这些基础类一样使用了,不需要再做任何其它的操作,这个userinfo就可以用作rpc函数的参数,或rpc函数的返回值了。
```cpp
struct userinfo
{
std::string name;
int age;
std::map<int, std::string> purview;
// 添加一个模板形式的序列化函数,函数名称和函数参数必须保持和下面示例的一样才行。
template <class Archive>
void serialize(Archive & ar)
{
ar(name);
ar(age);
ar(purview);
}
};
```
## 怎么让rpc函数支持第三方开源库里面的类型?
比如程序中经常有json操作,我们一般都会找一个开源json库来使用。
比如使用了nlohmann::json这个库,此时,我想把nlohmann::json这个类作为rpc函数的参数或返回值,如下:
```cpp
nlohmann::json test_json(nlohmann::json j)
{
std::string s = j.dump();
return nlohmann::json::parse(s);
}
```
这时该怎么呢?因为此时是没法像自定义结构体userinfo那样,去手工给json类添加一个序列化的成员函数的。
那么像下面这样添加两个全局的序列化和反序列化函数即可,如下:
```cpp
void operator<<(asio2::rpc::oarchive& sr, const nlohmann::json& j)
{
sr << j.dump(); // j.dump()是把json对象转换为std::string
}
void operator>>(asio2::rpc::iarchive& dr, nlohmann::json& j)
{
std::string v;
dr >> v;
j = nlohmann::json::parse(v); // json::parse(v) 是把std::string转换为json对象
}
```
添加了两个全局的序列化和反序列化函数之后,这个json类型就可以像普通的int, std::string这些基础类一样使用了,不需要再做任何其它的操作。
## 异步rpc函数
上面举例中的rpc函数都是非常简单的函数,实际项目中的函数一般都比较复杂,那些复杂的rpc函数,它们的返回值,不一定能立即计算得到,而是需要交给其它的工作线程去处理,处理之后才能得到结果,至于那个异步的处理过程到底需要多久却是不确定的。
下面还是用add函数来举例:
```cpp
int add(int a, int b)
{
int result;
// 当收到rpc调用时,需要交给其它的工作线程中去异步处理
std::thread([&result, a, b]() mutable
{
result = a + b; // 此时处理完毕,才有了结果
}).detach();
// return result; // 这里如果直接返回result是不对的,因为上面的异步调用无法确定在什么时候才会完成
}
```
那这该怎么呢?框架也已经支持了,像下面这样修改即可如下:
```cpp
// 第1,函数的返回值要用rpc::future包裹起来
rpc::future<int> add(int a, int b)
{
// 第2,定义两个辅助变量,promise和future ,如下:
rpc::promise<int> promise;
rpc::future<int> f = promise.get_future();
// 第3,把promise传到那个异步的工作线程中
std::thread([a, b, promise = std::move(promise)]() mutable
{
// ...... 比如这里经过了很多工作处理......
// 第4,处理完毕后,给promise设置值,这个值就是这个add函数的返回值了
promise.set_value(a + b);
// 代码执行到这里之后,promise变量会析构,当promise析构时,asio2框架就会自动给客户端回复了,
// 回复时的结果就是上面promise.set_value函数中设置的那个值。
}).detach();
// 第5,在这里返回上面那个定义的变量future即可。注意比较和同步rpc函数的区别,同步rpc函数直接返回了a+b;
return f;
}
```
## 其它
调用rpc函数的默认超时是5秒,可以通过下面这个函数进行设置:
注意这个函数设置的是全局的超时设置,如果你在调用rpc函数时,传递的参数中又包含了超时设置,那么那一次的rpc调用就会使用那个单独设置的超时,如果在调用rpc函数时,传递的参数中没有超时参数,那就使用默认的超时。
```cpp
client.set_default_timeout(std::chrono::seconds(3));
```
更多功能或用法请参考工程示例。
### QQ群:833425075
## 项目地址:
github : [https://github.com/zhllxt/asio2](https://github.com/zhllxt/asio2)
码云 : [https://gitee.com/zhllxt/asio2](https://gitee.com/zhllxt/asio2)
### 最后编辑于:2022-06-23
<file_sep>#include "unit_test.hpp"
#include <asio2/util/zlib.hpp>
#include <asio2/util/base64.hpp>
#include <fmt/format.h>
void zlib_test()
{
beast::zlib::impl zliber;
std::string src = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string dst = "<KEY>;
std::string en = zliber.compress(src);
//if (!(en[0] == 0x50 && en[1] == 0x4b && en[2] == 0x03 && en[3] == 0x04))
//{
// fmt::print("{:02X} {:02X} {:02X} {:02X}\n", en[0], en[1], en[2], en[3]);
//}
std::string base64 = asio2::base64_encode(en);
ASIO2_CHECK(base64 == dst);
ASIO2_CHECK(zliber.uncompress(asio2::base64_decode(base64)) == src);
}
ASIO2_TEST_SUITE
(
"zlib",
ASIO2_TEST_CASE(zlib_test)
)
<file_sep>#ifndef BHO_CORE_NO_EXCEPTIONS_SUPPORT_HPP
#define BHO_CORE_NO_EXCEPTIONS_SUPPORT_HPP
#if defined(_MSC_VER)
# pragma once
#endif
//----------------------------------------------------------------------
// (C) Copyright 2004 <NAME>.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//
// This file contains helper macros used when exception support may be
// disabled (as indicated by macro BHO_NO_EXCEPTIONS).
//
// Before picking up these macros you may consider using RAII techniques
// to deal with exceptions - their syntax can be always the same with
// or without exception support enabled.
//----------------------------------------------------------------------
#include <asio2/bho/config.hpp>
#include <asio2/bho/config/workaround.hpp>
#if !(defined BHO_NO_EXCEPTIONS)
# define BHO_TRY { try
# define BHO_CATCH(x) catch(x)
# define BHO_RETHROW throw;
# define BHO_CATCH_END }
#else
# if BHO_WORKAROUND(BHO_BORLANDC, BHO_TESTED_AT(0x564))
# define BHO_TRY { if ("")
# define BHO_CATCH(x) else if (!"")
# elif !defined(BHO_MSVC) || BHO_MSVC >= 1900
# define BHO_TRY { if (true)
# define BHO_CATCH(x) else if (false)
# else
// warning C4127: conditional expression is constant
# define BHO_TRY { \
__pragma(warning(push)) \
__pragma(warning(disable: 4127)) \
if (true) \
__pragma(warning(pop))
# define BHO_CATCH(x) else \
__pragma(warning(push)) \
__pragma(warning(disable: 4127)) \
if (false) \
__pragma(warning(pop))
# endif
# define BHO_RETHROW
# define BHO_CATCH_END }
#endif
#endif
<file_sep>/*
Copyright <NAME> 2018
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_NVCC_H
#define BHO_PREDEF_COMPILER_NVCC_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_NVCC`
https://en.wikipedia.org/wiki/NVIDIA_CUDA_Compiler[NVCC] compiler.
Version number available as major, minor, and patch beginning with version 7.5.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__NVCC__+` | {predef_detection}
| `+__CUDACC_VER_MAJOR__+`, `+__CUDACC_VER_MINOR__+`, `+__CUDACC_VER_BUILD__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_NVCC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__NVCC__)
# if !defined(__CUDACC_VER_MAJOR__) || !defined(__CUDACC_VER_MINOR__) || !defined(__CUDACC_VER_BUILD__)
# define BHO_COMP_NVCC_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# else
# define BHO_COMP_NVCC_DETECTION BHO_VERSION_NUMBER(__CUDACC_VER_MAJOR__, __CUDACC_VER_MINOR__, __CUDACC_VER_BUILD__)
# endif
#endif
#ifdef BHO_COMP_NVCC_DETECTION
/*
Always define BHO_COMP_NVCC instead of BHO_COMP_NVCC_EMULATED
The nvcc compilation process is somewhat special as can be read here:
https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#cuda-compilation-trajectory
The nvcc compiler precompiles the input two times. Once for the device code
being compiled by the cicc device compiler and once for the host code
compiled by the real host compiler. NVCC uses gcc/clang/msvc/...
depending on the host compiler being set on the command line.
Predef (as a preprocessor only lib) detects the one doing the preprocessing
as compiler and expects it to be the one doing the real compilation.
This is not true for NVCC which is only doing the preprocessing and which
is using another compiler for parts of its work. So for NVCC it should be
allowed to set BHO_COMP_NVCC additionally to the already detected host
compiler because both is true: It is gcc/clang/... compiling the code, but it
is also NVCC doing the preprocessing and adding some other quirks you may
want to detect.
This behavior is similar to what boost config is doing in `select_compiler_config.hpp`.
There the NVCC detection is not handled as a real compiler (part of the
#if-#elif) but as additional option before the real compiler.
*/
# undef BHO_COMP_NVCC
# define BHO_COMP_NVCC BHO_COMP_NVCC_DETECTION
# define BHO_COMP_NVCC_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_NVCC_NAME "NVCC"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_NVCC,BHO_COMP_NVCC_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_C_VMS_H
#define BHO_PREDEF_LIBRARY_C_VMS_H
#include <asio2/bho/predef/library/c/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_C_VMS`
VMS libc Standard C library.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__CRTL_VER+` | {predef_detection}
| `+__CRTL_VER+` | V.R.P
|===
*/ // end::reference[]
#define BHO_LIB_C_VMS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__CRTL_VER)
# undef BHO_LIB_C_VMS
# define BHO_LIB_C_VMS BHO_PREDEF_MAKE_10_VVRR0PP00(__CRTL_VER)
#endif
#if BHO_LIB_C_VMS
# define BHO_LIB_C_VMS_AVAILABLE
#endif
#define BHO_LIB_C_VMS_NAME "VMS"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_C_VMS,BHO_LIB_C_VMS_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_WS_STREAM_COMPONENT_HPP__
#define __ASIO2_WS_STREAM_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/external/asio.hpp>
#include <asio2/external/beast.hpp>
#include <asio2/base/error.hpp>
namespace asio2::detail
{
template<class, class = std::void_t<>>
struct is_websocket_client : std::false_type {};
template<class T>
struct is_websocket_client<T, std::void_t<decltype(std::declval<T&>().ws_stream())>> : std::true_type {};
template<class, class = std::void_t<>>
struct is_websocket_server : std::false_type {};
template<class T>
struct is_websocket_server<T, std::void_t<decltype(std::declval<typename T::session_type&>().
ws_stream())>> : std::true_type {};
template<class derived_t, class args_t>
class ws_stream_cp
{
public:
using ws_stream_type = typename args_t::stream_t;
/**
* @brief constructor
*/
ws_stream_cp() {}
/**
* @brief destructor
*/
~ws_stream_cp() noexcept {}
/**
* @brief get the websocket stream object refrence
*/
inline ws_stream_type & ws_stream() noexcept
{
ASIO2_ASSERT(bool(this->ws_stream_));
return (*(this->ws_stream_));
}
protected:
template<typename C, typename Socket>
inline void _ws_init(std::shared_ptr<ecs_t<C>>& ecs, Socket& socket)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::ignore_unused(derive, ecs, socket);
// In previous versions, "_ws_init" maybe called multi times, when "_ws_init" was called,
// the "_ws_stop" maybe called at the same time, but "_ws_init" and "_ws_stop" was called
// at different threads, this will cause the diffrent threads "read, write" the "ws_stream_"
// variable, and then cause crash.
if constexpr (args_t::is_client)
{
ASIO2_ASSERT(derive.io().running_in_this_thread());
}
else
{
ASIO2_ASSERT(derive.sessions().io().running_in_this_thread());
}
this->ws_stream_ = std::make_unique<ws_stream_type>(socket);
websocket::stream_base::timeout opt{};
// Set suggested timeout settings for the websocket
if constexpr (args_t::is_session)
{
opt = websocket::stream_base::timeout::suggested(beast::role_type::server);
}
else
{
opt = websocket::stream_base::timeout::suggested(beast::role_type::client);
}
opt.handshake_timeout = derive.get_connect_timeout();
this->ws_stream_->set_option(opt);
}
template<typename C, typename Socket>
inline void _ws_start(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, Socket& socket)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::ignore_unused(derive, this_ptr, ecs, socket);
ASIO2_ASSERT(derive.io().running_in_this_thread());
}
template<typename DeferEvent>
inline void _ws_stop(std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
if (!this->ws_stream_)
return;
// bug fixed : resolve beast::websocket::detail::soft_mutex
// BHO_ASSERT(id_ != T::id); failed (line 89).
//
// If this assert goes off it means you are attempting to
// simultaneously initiate more than one of same asynchronous
// operation, which is not allowed. For example, you must wait
// for an async_read to complete before performing another
// async_read.
derive.disp_event([this, &derive, this_ptr = std::move(this_ptr), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
// must construct a new chain
defer_event chain(std::move(e), std::move(g));
// Set the handshake timeout to a small value, otherwise if the remote don't
// send a websocket close frame, the async_close's callback will never be
// called.
websocket::stream_base::timeout opt{};
opt.handshake_timeout = derive.get_disconnect_timeout();
opt.idle_timeout = websocket::stream_base::none();
try
{
derive.ws_stream_->set_option(opt);
// Reset the decorator, beacuse the decorator maybe hold the self
// shared_ptr, if don't reset it, the session ptr maybe can't detroyed.
derive.ws_stream_->set_option(
websocket::stream_base::decorator([](websocket::request_type&) {}));
derive.ws_stream_->set_option(
websocket::stream_base::decorator([](websocket::response_type&) {}));
}
catch (system_error const& e)
{
set_last_error(e);
}
// Can't call close twice
// TODO return a custom error code
// BHO_ASSERT(! impl.wr_close);
if (!this->ws_stream_->is_open())
{
// must Reset the control frame callback. the control frame callback hold the
// self shared_ptr, if don't reset it, will cause memory leaks.
this->ws_stream_->control_callback();
return;
}
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
ASIO2_LOG_DEBUG("ws_stream_cp enter async_close");
// Close the WebSocket connection
// async_close behavior :
// send a websocket close frame to the remote, and wait for recv a websocket close
// frame from the remote.
// async_close maybe close the socket directly.
this->ws_stream_->async_close(websocket::close_code::normal,
[&derive, this_ptr = std::move(this_ptr), chain = std::move(chain)]
(error_code ec) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
detail::ignore_unused(derive, ec);
ASIO2_LOG_DEBUG("ws_stream_cp leave async_close:{} {}", ec.value(), ec.message());
// if async close failed, the inner timer of async close will exists for timeout,
// it will cause the ws client can't be exited, so we reset the timeout to none
// to notify the timer to exit.
if (ec)
{
websocket::stream_base::timeout opt{};
opt.handshake_timeout = websocket::stream_base::none();
opt.idle_timeout = websocket::stream_base::none();
try
{
derive.ws_stream_->set_option(opt);
}
catch (system_error const&)
{
}
}
//if (ec)
// return;
// If we get here then the connection is closed gracefully
// must Reset the control frame callback. the control frame callback hold the
// self shared_ptr, if don't reset it, will cause memory leaks.
derive.ws_stream_->control_callback();
});
}, chain.move_guard());
}
template<typename C>
inline void _ws_post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (!derive.is_started())
{
if (derive.state() == state_t::started)
{
derive._do_disconnect(asio2::get_last_error(), std::move(this_ptr));
}
return;
}
ASIO2_ASSERT(derive.io().running_in_this_thread());
ASIO2_ASSERT(bool(this->ws_stream_));
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_recv_counter_.load() == 0);
derive.post_recv_counter_++;
#endif
derive.reading_ = true;
// Read a message into our buffer
this->ws_stream_->async_read(derive.buffer().base(), make_allocator(derive.rallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(const error_code& ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
derive.reading_ = false;
derive._handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}));
}
template<typename C>
void _ws_handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
set_last_error(ec);
if (!derive.is_started())
{
if (derive.state() == state_t::started)
{
ASIO2_LOG_INFOR("_ws_handle_recv with closed socket: {} {}", ec.value(), ec.message());
derive._do_disconnect(ec, this_ptr);
}
derive._stop_readend_timer(std::move(this_ptr));
return;
}
// bytes_recvd : The number of bytes in the streambuf's get area up to and including the delimiter.
if (!ec)
{
// every times recv data,we update the last alive time.
derive.update_alive_time();
derive._fire_recv(this_ptr, ecs, std::string_view(reinterpret_cast<
std::string_view::const_pointer>(derive.buffer().data().data()), bytes_recvd));
derive.buffer().consume(bytes_recvd);
derive._post_recv(std::move(this_ptr), std::move(ecs));
}
else
{
ASIO2_LOG_DEBUG("_ws_handle_recv with error: {} {}", ec.value(), ec.message());
derive._do_disconnect(ec, this_ptr);
derive._stop_readend_timer(std::move(this_ptr));
}
// If an error occurs then no new asynchronous operations are started. This
// means that all shared_ptr references to the connection object will
// disappear and the object will be destroyed automatically after this
// handler returns. The connection class's destructor closes the socket.
}
template<typename C>
inline void _post_control_callback(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(bool(this->ws_stream_));
// Set the control callback. This will be called
// on every incoming ping, pong, and close frame.
// can't use push_event, just only use asio::post, beacuse the callback handler
// will not be called immediately, it is called only when it receives an event
// on the another side.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, &derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]() mutable
{
// Because hole this_ptr in control callback can easily cause circular references,
// Once forget to call control callback with empty param or due to exceptions or
// other reasons, will result in a circular reference, so we hold the weak ptr
// in the control callback instead of shared ptr.
std::weak_ptr<derived_t> this_wptr{ this_ptr };
bool check_alive = (this_ptr != nullptr);
this->ws_stream_->control_callback(
[&derive, this_wptr = std::move(this_wptr), ecs = std::move(ecs), check_alive]
(websocket::frame_type kind, beast::string_view payload) mutable
{
std::shared_ptr<derived_t> this_ptr = this_wptr.lock();
// If the original shared ptr is not empty, but now it is empty, it means that
// the object is destroyed, so we need return.
// But this situation shouldn't happen.
if (check_alive && this_ptr == nullptr)
{
ASIO2_ASSERT(false);
return;
}
derive._handle_control_callback(kind, payload, std::move(this_ptr), ecs);
});
}));
}
template<typename C>
inline void _handle_control_callback(
websocket::frame_type kind, beast::string_view payload,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::ignore_unused(payload, this_ptr, ecs);
// Note that the connection is alive
derive.update_alive_time();
switch (kind)
{
case websocket::frame_type::ping:
derive._handle_control_ping(payload, std::move(this_ptr), std::move(ecs));
break;
case websocket::frame_type::pong:
derive._handle_control_pong(payload, std::move(this_ptr), std::move(ecs));
break;
case websocket::frame_type::close:
derive._handle_control_close(payload, std::move(this_ptr), std::move(ecs));
break;
default:break;
}
}
template<typename C>
inline void _handle_control_ping(
beast::string_view payload, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
detail::ignore_unused(payload, this_ptr, ecs);
}
template<typename C>
inline void _handle_control_pong(
beast::string_view payload, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
detail::ignore_unused(payload, this_ptr, ecs);
}
template<typename C>
inline void _handle_control_close(
beast::string_view payload, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::ignore_unused(payload, this_ptr, ecs);
if (derive.state() == state_t::started)
{
ASIO2_LOG_DEBUG("ws_stream_cp::_handle_control_close _do_disconnect");
derive._do_disconnect(websocket::error::closed, std::move(this_ptr));
}
}
template<typename C, typename DeferEvent>
inline void _post_read_upgrade_request(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
// Make the request empty before reading,
// otherwise the operation behavior is undefined.
derive.upgrade_req_ = {};
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_recv_counter_.load() == 0);
derive.post_recv_counter_++;
#endif
derive.reading_ = true;
// Read a request
http::async_read(derive.upgrade_stream(), derive.buffer().base(), derive.upgrade_req_,
make_allocator(derive.rallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
(const error_code & ec, [[maybe_unused]] std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
derive.reading_ = false;
derive._handle_read_upgrade_request(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}));
}
template<typename C, typename DeferEvent>
inline void _handle_read_upgrade_request(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
set_last_error(ec);
if (!ec)
{
// every times recv data,we update the last alive time.
derive.update_alive_time();
derive._post_control_callback(this_ptr, ecs);
derive._post_upgrade(
std::move(this_ptr), std::move(ecs), derive.upgrade_req_, std::move(chain));
}
else
{
derive._handle_upgrade(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
}
template<typename C, typename DeferEvent, typename Response, bool IsSession = args_t::is_session>
typename std::enable_if_t<!IsSession, void>
inline _post_upgrade(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, Response& rep, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(bool(this->ws_stream_));
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
// Perform the websocket handshake
this->ws_stream_->async_handshake(rep, derive.host_, derive.get_upgrade_target(),
make_allocator(derive.wallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
(error_code const& ec) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
derive._handle_upgrade(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}));
}
template<typename C, typename DeferEvent, typename Request, bool IsSession = args_t::is_session>
typename std::enable_if_t<IsSession, void>
inline _post_upgrade(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, Request const& req, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(bool(this->ws_stream_));
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
// Accept the websocket handshake
// just write response.
this->ws_stream_->async_accept(req, make_allocator(derive.wallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
(error_code ec) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
derive._handle_upgrade(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}));
}
template<typename C, typename DeferEvent, bool IsSession = args_t::is_session>
typename std::enable_if_t<IsSession, void>
inline _post_upgrade(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(bool(this->ws_stream_));
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_recv_counter_.load() == 0);
derive.post_recv_counter_++;
#endif
// Accept the websocket handshake
// first read request, then write response.
this->ws_stream_->async_accept(make_allocator(derive.wallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
(error_code ec) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
derive._handle_upgrade(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}));
}
template<typename C, typename DeferEvent>
inline void _session_handle_upgrade(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
// Use "sessions().dispatch" to ensure that the _fire_accept function and the _fire_upgrade
// function are fired in the same thread
derive.sessions().dispatch(
[&derive, ec, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
set_last_error(ec);
derive._fire_upgrade(this_ptr);
if (ec)
{
derive._do_disconnect(ec, std::move(this_ptr), std::move(chain));
return;
}
derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
});
}
template<typename C, typename DeferEvent>
inline void _client_handle_upgrade(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
set_last_error(ec);
derive._fire_upgrade(this_ptr);
derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename C, typename DeferEvent>
inline void _handle_upgrade(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(bool(this->ws_stream_));
if constexpr (args_t::is_session)
{
derive._session_handle_upgrade(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
else
{
derive._client_handle_upgrade(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
}
protected:
std::unique_ptr<ws_stream_type> ws_stream_;
};
}
#endif // !__ASIO2_WS_STREAM_COMPONENT_HPP__
<file_sep>#include "unit_test.hpp"
#include <asio2/util/string.hpp>
#include <asio2/base/detail/util.hpp>
struct userinfo
{
std::uint8_t age{ 0 };
std::string name = "abc";
};
inline std::ostream& operator<<(std::ostream& os, userinfo v)
{
std::string s;
s += std::to_string(v.age);
s += v.name;
return os << std::move(s);
}
inline std::istream& operator>>(std::istream& is, userinfo& v)
{
is >> v.age;
v.age -= '0';
is >> v.name;
return is;
}
void strutil_test()
{
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
std::string_view sv = "Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::iequals("text\n With\tSome \t whitespaces\n\n", "Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::iequals(str, "Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::iequals(sv, "Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::iequals("Text\n With\tSome \t whitespaces\n\n", str));
ASIO2_CHECK(asio2::iequals("Text\n With\tSome \t whitespaces\n\n", sv));
ASIO2_CHECK(asio2::iequals(str, sv));
ASIO2_CHECK(asio2::iequals(sv, str));
ASIO2_CHECK(asio2::iequals(str, str));
ASIO2_CHECK(asio2::iequals(sv, sv));
str = "a";
sv = "a";
ASIO2_CHECK(asio2::iequals("a", 'a'));
ASIO2_CHECK(asio2::iequals('a', "A"));
ASIO2_CHECK(asio2::iequals(str, 'a'));
ASIO2_CHECK(asio2::iequals(sv, 'a'));
ASIO2_CHECK(asio2::iequals('a', str));
ASIO2_CHECK(asio2::iequals('a', sv));
ASIO2_CHECK(asio2::iequals(str, sv));
ASIO2_CHECK(asio2::iequals(sv, str));
ASIO2_CHECK(asio2::iequals(str, str));
ASIO2_CHECK(asio2::iequals(sv, sv));
}
{
std::wstring str = L"Text\n with\tsome \t whitespaces\n\n";
std::wstring_view sv = L"Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::iequals(L"text\n With\tSome \t whitespaces\n\n", L"Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::iequals(str, L"Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::iequals(sv, L"Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::iequals(L"Text\n With\tSome \t whitespaces\n\n", str));
ASIO2_CHECK(asio2::iequals(L"Text\n With\tSome \t whitespaces\n\n", sv));
ASIO2_CHECK(asio2::iequals(str, sv));
ASIO2_CHECK(asio2::iequals(sv, str));
ASIO2_CHECK(asio2::iequals(str, str));
ASIO2_CHECK(asio2::iequals(sv, sv));
str = L"a";
sv = L"a";
ASIO2_CHECK(asio2::iequals(L"a", L'a'));
ASIO2_CHECK(asio2::iequals(L'a', L"A"));
ASIO2_CHECK(asio2::iequals(str, L'a'));
ASIO2_CHECK(asio2::iequals(sv, L'a'));
ASIO2_CHECK(asio2::iequals(L'a', str));
ASIO2_CHECK(asio2::iequals(L'a', sv));
ASIO2_CHECK(asio2::iequals(str, sv));
ASIO2_CHECK(asio2::iequals(sv, str));
ASIO2_CHECK(asio2::iequals(str, str));
ASIO2_CHECK(asio2::iequals(sv, sv));
}
{
std::u16string str = u"z\u00df\u6c34\U0001f34c";
std::u16string_view sv = u"z\u00df\u6c34\U0001f34c";
ASIO2_CHECK(asio2::iequals(u"z\u00df\u6c34\U0001f34c", u"Z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(asio2::iequals(str, u"z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(asio2::iequals(sv, u"z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(asio2::iequals(u"z\u00df\u6c34\U0001f34c", str));
ASIO2_CHECK(asio2::iequals(u"z\u00df\u6c34\U0001f34c", sv));
ASIO2_CHECK(asio2::iequals(str, sv));
ASIO2_CHECK(asio2::iequals(sv, str));
ASIO2_CHECK(asio2::iequals(str, str));
ASIO2_CHECK(asio2::iequals(sv, sv));
str = u"a";
sv = u"a";
ASIO2_CHECK(asio2::iequals(u"a", u'a'));
ASIO2_CHECK(asio2::iequals(u'a', u"A"));
ASIO2_CHECK(asio2::iequals(str, u'a'));
ASIO2_CHECK(asio2::iequals(sv, u'a'));
ASIO2_CHECK(asio2::iequals(u'a', str));
ASIO2_CHECK(asio2::iequals(u'a', sv));
ASIO2_CHECK(asio2::iequals(str, sv));
ASIO2_CHECK(asio2::iequals(sv, str));
ASIO2_CHECK(asio2::iequals(str, str));
ASIO2_CHECK(asio2::iequals(sv, sv));
}
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
std::string_view sv = "Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(!asio2::iequals("text\n With\tSome \t x whitespaces\n\n", "Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(!asio2::iequals("text\n With\tSome \t whitespaces\n\n", "Text\n With\tSome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::iequals(str, "Text\n with\tsome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::iequals(sv, "Text\n with\tsome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::iequals(" Text\n With\tSome \t whitespaces\n\n", str));
ASIO2_CHECK(!asio2::iequals(" Text\n With\tSome \t whitespaces\n\n", sv));
str = "a";
sv = "a";
ASIO2_CHECK(!asio2::iequals("a", 'B'));
ASIO2_CHECK(!asio2::iequals('B', "A"));
ASIO2_CHECK(!asio2::iequals(str, 'B'));
ASIO2_CHECK(!asio2::iequals(sv, 'b'));
ASIO2_CHECK(!asio2::iequals('b', str));
ASIO2_CHECK(!asio2::iequals('B', sv));
}
{
std::wstring str = L"Text\n with\tsome \t whitespaces\n\n";
std::wstring_view sv = L"Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(!asio2::iequals(L"text\n With\tSome \t x whitespaces\n\n", L"Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(!asio2::iequals(L"text\n With\tSome \t whitespaces\n\n", L"Text\n With\tSome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::iequals(str, L"Text\n with\tsome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::iequals(sv, L"Text\n with\tsome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::iequals(L" Text\n With\tSome \t whitespaces\n\n", str));
ASIO2_CHECK(!asio2::iequals(L" Text\n With\tSome \t whitespaces\n\n", sv));
str = L"a";
sv = L"a";
ASIO2_CHECK(!asio2::iequals(L"a", L'B'));
ASIO2_CHECK(!asio2::iequals(L'b', L"A"));
ASIO2_CHECK(!asio2::iequals(str, L'b'));
ASIO2_CHECK(!asio2::iequals(sv, L'B'));
ASIO2_CHECK(!asio2::iequals(L'B', str));
ASIO2_CHECK(!asio2::iequals(L'b', sv));
}
{
std::u16string str = u"z\u00df\u6c34\U0001f34c";
std::u16string_view sv = u"z\u00df\u6c34\U0001f34c";
ASIO2_CHECK(!asio2::iequals(u"z\u00df\u6c34\U0001f34c", u" Z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(!asio2::iequals(u"z\u00df\u6c34\U0001f34c", u" Z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(!asio2::iequals(str, u"z x\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(!asio2::iequals(sv, u"z x\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(!asio2::iequals(u"z x\u00df\u6c34\U0001f34c", str));
ASIO2_CHECK(!asio2::iequals(u"z x\u00df\u6c34\U0001f34c", sv));
str = u"a";
sv = u"a";
ASIO2_CHECK(!asio2::iequals(u"a", u'B'));
ASIO2_CHECK(!asio2::iequals(u'B', u"A"));
ASIO2_CHECK(!asio2::iequals(str, u'b'));
ASIO2_CHECK(!asio2::iequals(sv, u'B'));
ASIO2_CHECK(!asio2::iequals(u'b', str));
ASIO2_CHECK(!asio2::iequals(u'B', sv));
}
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
std::string_view sv = "Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::compare_ignore_case("text\n With\tSome \t whitespaces\n\n", "Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::compare_ignore_case(str, "Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::compare_ignore_case(sv, "Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::compare_ignore_case("Text\n With\tSome \t whitespaces\n\n", str));
ASIO2_CHECK(asio2::compare_ignore_case("Text\n With\tSome \t whitespaces\n\n", sv));
ASIO2_CHECK(asio2::compare_ignore_case(str, sv));
ASIO2_CHECK(asio2::compare_ignore_case(sv, str));
ASIO2_CHECK(asio2::compare_ignore_case(str, str));
ASIO2_CHECK(asio2::compare_ignore_case(sv, sv));
str = "a";
sv = "a";
ASIO2_CHECK(asio2::compare_ignore_case("a", 'a'));
ASIO2_CHECK(asio2::compare_ignore_case('a', "A"));
ASIO2_CHECK(asio2::compare_ignore_case(str, 'a'));
ASIO2_CHECK(asio2::compare_ignore_case(sv, 'a'));
ASIO2_CHECK(asio2::compare_ignore_case('a', str));
ASIO2_CHECK(asio2::compare_ignore_case('a', sv));
ASIO2_CHECK(asio2::compare_ignore_case(str, sv));
ASIO2_CHECK(asio2::compare_ignore_case(sv, str));
ASIO2_CHECK(asio2::compare_ignore_case(str, str));
ASIO2_CHECK(asio2::compare_ignore_case(sv, sv));
}
{
std::wstring str = L"Text\n with\tsome \t whitespaces\n\n";
std::wstring_view sv = L"Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::compare_ignore_case(L"text\n With\tSome \t whitespaces\n\n", L"Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::compare_ignore_case(str, L"Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::compare_ignore_case(sv, L"Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(asio2::compare_ignore_case(L"Text\n With\tSome \t whitespaces\n\n", str));
ASIO2_CHECK(asio2::compare_ignore_case(L"Text\n With\tSome \t whitespaces\n\n", sv));
ASIO2_CHECK(asio2::compare_ignore_case(str, sv));
ASIO2_CHECK(asio2::compare_ignore_case(sv, str));
ASIO2_CHECK(asio2::compare_ignore_case(str, str));
ASIO2_CHECK(asio2::compare_ignore_case(sv, sv));
str = L"a";
sv = L"a";
ASIO2_CHECK(asio2::compare_ignore_case(L"a", L'a'));
ASIO2_CHECK(asio2::compare_ignore_case(L'a', L"A"));
ASIO2_CHECK(asio2::compare_ignore_case(str, L'a'));
ASIO2_CHECK(asio2::compare_ignore_case(sv, L'a'));
ASIO2_CHECK(asio2::compare_ignore_case(L'a', str));
ASIO2_CHECK(asio2::compare_ignore_case(L'a', sv));
ASIO2_CHECK(asio2::compare_ignore_case(str, sv));
ASIO2_CHECK(asio2::compare_ignore_case(sv, str));
ASIO2_CHECK(asio2::compare_ignore_case(str, str));
ASIO2_CHECK(asio2::compare_ignore_case(sv, sv));
}
{
std::u16string str = u"z\u00df\u6c34\U0001f34c";
std::u16string_view sv = u"z\u00df\u6c34\U0001f34c";
ASIO2_CHECK(asio2::compare_ignore_case(u"z\u00df\u6c34\U0001f34c", u"Z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(asio2::compare_ignore_case(str, u"z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(asio2::compare_ignore_case(sv, u"z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(asio2::compare_ignore_case(u"z\u00df\u6c34\U0001f34c", str));
ASIO2_CHECK(asio2::compare_ignore_case(u"z\u00df\u6c34\U0001f34c", sv));
ASIO2_CHECK(asio2::compare_ignore_case(str, sv));
ASIO2_CHECK(asio2::compare_ignore_case(sv, str));
ASIO2_CHECK(asio2::compare_ignore_case(str, str));
ASIO2_CHECK(asio2::compare_ignore_case(sv, sv));
str = u"a";
sv = u"a";
ASIO2_CHECK(asio2::compare_ignore_case(u"a", u'a'));
ASIO2_CHECK(asio2::compare_ignore_case(u'a', u"A"));
ASIO2_CHECK(asio2::compare_ignore_case(str, u'a'));
ASIO2_CHECK(asio2::compare_ignore_case(sv, u'a'));
ASIO2_CHECK(asio2::compare_ignore_case(u'a', str));
ASIO2_CHECK(asio2::compare_ignore_case(u'a', sv));
ASIO2_CHECK(asio2::compare_ignore_case(str, sv));
ASIO2_CHECK(asio2::compare_ignore_case(sv, str));
ASIO2_CHECK(asio2::compare_ignore_case(str, str));
ASIO2_CHECK(asio2::compare_ignore_case(sv, sv));
}
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
std::string_view sv = "Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(!asio2::compare_ignore_case("text\n With\tSome \t x whitespaces\n\n", "Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(!asio2::compare_ignore_case("text\n With\tSome \t whitespaces\n\n", "Text\n With\tSome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::compare_ignore_case(str, "Text\n with\tsome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::compare_ignore_case(sv, "Text\n with\tsome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::compare_ignore_case(" Text\n With\tSome \t whitespaces\n\n", str));
ASIO2_CHECK(!asio2::compare_ignore_case(" Text\n With\tSome \t whitespaces\n\n", sv));
str = "a";
sv = "a";
ASIO2_CHECK(!asio2::compare_ignore_case("a", 'B'));
ASIO2_CHECK(!asio2::compare_ignore_case('B', "A"));
ASIO2_CHECK(!asio2::compare_ignore_case(str, 'B'));
ASIO2_CHECK(!asio2::compare_ignore_case(sv, 'b'));
ASIO2_CHECK(!asio2::compare_ignore_case('b', str));
ASIO2_CHECK(!asio2::compare_ignore_case('B', sv));
}
{
std::wstring str = L"Text\n with\tsome \t whitespaces\n\n";
std::wstring_view sv = L"Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(!asio2::compare_ignore_case(L"text\n With\tSome \t x whitespaces\n\n", L"Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(!asio2::compare_ignore_case(L"text\n With\tSome \t whitespaces\n\n", L"Text\n With\tSome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::compare_ignore_case(str, L"Text\n with\tsome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::compare_ignore_case(sv, L"Text\n with\tsome \t x whitespaces\n\n"));
ASIO2_CHECK(!asio2::compare_ignore_case(L" Text\n With\tSome \t whitespaces\n\n", str));
ASIO2_CHECK(!asio2::compare_ignore_case(L" Text\n With\tSome \t whitespaces\n\n", sv));
str = L"a";
sv = L"a";
ASIO2_CHECK(!asio2::compare_ignore_case(L"a", L'B'));
ASIO2_CHECK(!asio2::compare_ignore_case(L'b', L"A"));
ASIO2_CHECK(!asio2::compare_ignore_case(str, L'b'));
ASIO2_CHECK(!asio2::compare_ignore_case(sv, L'B'));
ASIO2_CHECK(!asio2::compare_ignore_case(L'B', str));
ASIO2_CHECK(!asio2::compare_ignore_case(L'b', sv));
}
{
std::u16string str = u"z\u00df\u6c34\U0001f34c";
std::u16string_view sv = u"z\u00df\u6c34\U0001f34c";
ASIO2_CHECK(!asio2::compare_ignore_case(u"z\u00df\u6c34\U0001f34c", u" Z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(!asio2::compare_ignore_case(u"z\u00df\u6c34\U0001f34c", u" Z\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(!asio2::compare_ignore_case(str, u"z x\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(!asio2::compare_ignore_case(sv, u"z x\u00df\u6c34\U0001f34c"));
ASIO2_CHECK(!asio2::compare_ignore_case(u"z x\u00df\u6c34\U0001f34c", str));
ASIO2_CHECK(!asio2::compare_ignore_case(u"z x\u00df\u6c34\U0001f34c", sv));
str = u"a";
sv = u"a";
ASIO2_CHECK(!asio2::compare_ignore_case(u"a", u'B'));
ASIO2_CHECK(!asio2::compare_ignore_case(u'B', u"A"));
ASIO2_CHECK(!asio2::compare_ignore_case(str, u'b'));
ASIO2_CHECK(!asio2::compare_ignore_case(sv, u'B'));
ASIO2_CHECK(!asio2::compare_ignore_case(u'b', str));
ASIO2_CHECK(!asio2::compare_ignore_case(u'B', sv));
}
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
std::string_view sv = "Text\n with\tsome \t whitespaces\n\n";
const char* p = "Text\n with\tsome \t whitespaces\n\n";
char buf[] = "Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::format("%d %s", 10, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") == "10 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
//ASIO2_CHECK(asio2::format(L"%d %s", 10, L"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") == L"10 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
ASIO2_CHECK(asio2::to_string(sv) == sv);
ASIO2_CHECK(asio2::to_string(str) == str);
ASIO2_CHECK(asio2::to_string(10) == "10");
ASIO2_CHECK(asio2::to_string(999999) == "999999");
ASIO2_CHECK(asio2::to_string(10.0).find("10") == 0);
ASIO2_CHECK(asio2::to_string(999999.0).find("999999") == 0);
ASIO2_CHECK(asio2::to_string(10.0f).find("10") == 0);
ASIO2_CHECK(asio2::to_string(999999.0f).find("999999") == 0);
ASIO2_CHECK(asio2::to_string(p) == str);
ASIO2_CHECK(asio2::to_string("Text\n with\tsome \t whitespaces\n\n") == str);
ASIO2_CHECK(asio2::to_string(buf) == str);
ASIO2_CHECK(asio2::to_string(userinfo{}) == "0abc");
ASIO2_CHECK(asio2::to_string_view(sv) == sv);
ASIO2_CHECK(asio2::to_string_view(str) == sv);
ASIO2_CHECK(asio2::to_string_view('a') == "a");
ASIO2_CHECK(asio2::to_string_view(p) == str);
ASIO2_CHECK(asio2::to_string_view("Text\n with\tsome \t whitespaces\n\n") == str);
ASIO2_CHECK(asio2::to_string_view(buf) == str);
ASIO2_CHECK(asio2::to_string_view(str.begin(), str.end()) == str);
ASIO2_CHECK(asio2::to_string_view(sv.begin(), sv.end()) == str);
ASIO2_CHECK(asio2::to_string_view(p, p + std::strlen(p)) == str);
str = "20";
sv = "30";
const char* np = "40";
char nb[] = "50";
ASIO2_CHECK(asio2::to_numeric<int>("10") == 10);
ASIO2_CHECK(asio2::to_numeric<int>(10) == 10);
ASIO2_CHECK(asio2::to_numeric<int>(10.0) == 10);
ASIO2_CHECK(asio2::to_numeric<int>("0x10") == 0x10);
ASIO2_CHECK(asio2::to_numeric<int>("0X10") == 0x10);
ASIO2_CHECK(asio2::to_numeric<int>(str) == 20);
ASIO2_CHECK(asio2::to_numeric<int>(sv) == 30);
ASIO2_CHECK(asio2::to_numeric<int>(np) == 40);
ASIO2_CHECK(asio2::to_numeric<int>(nb) == 50);
ASIO2_CHECK(asio2::string_to<std::string>("999999") == "999999");
ASIO2_CHECK(asio2::string_to<int>("999999") == 999999);
ASIO2_CHECK(asio2::string_to<double>("999999") == 999999.0);
ASIO2_CHECK(asio2::string_to<float>("999999") == 999999.0f);
ASIO2_CHECK(asio2::string_to<bool>("0") == false);
ASIO2_CHECK(asio2::string_to<bool>("1") == true);
userinfo u = asio2::string_to<userinfo>("0abc");
ASIO2_CHECK(u.age == 0);
ASIO2_CHECK(u.name == "abc");
}
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::to_lower(str) == "text\n with\tsome \t whitespaces\n\n");
}
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::to_upper(str) == "TEXT\n WITH\tSOME \t WHITESPACES\n\n");
}
{
std::string str = "Textwithsomewhitespaces";
ASIO2_CHECK(asio2::to_lower(str) == "textwithsomewhitespaces");
}
{
std::string str = "Textwithsomewhitespaces";
ASIO2_CHECK(asio2::to_upper(str) == "TEXTWITHSOMEWHITESPACES");
}
{
std::string str = "text\n With\tSome \t whitespaces\n\n";
ASIO2_CHECK(asio2::capitalize(str) == "Text\n with\tsome \t whitespaces\n\n");
}
{
std::string str = "text\n With\tSome \t whitespaces\n\n";
ASIO2_CHECK(asio2::capitalize_first_char(str) == "Text\n With\tSome \t whitespaces\n\n");
}
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
std::string_view sv = "Text\n with\tsome \t whitespaces\n\n";
const char* p = "Text\n with\tsome \t whitespaces\n\n";
char buf[] = "Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::contains("text\n With\tSome \t whitespaces\n\n", "Some"));
ASIO2_CHECK(!asio2::contains("text\n With\tSome \t whitespaces\n\n", "some"));
ASIO2_CHECK(asio2::contains("text\n With\tSome \t whitespaces\n\n", 'c'));
ASIO2_CHECK(!asio2::contains("text\n With\tSome \t whitespaces\n\n", 'C'));
ASIO2_CHECK(asio2::contains(str, "some"));
ASIO2_CHECK(asio2::contains(str, 'c'));
ASIO2_CHECK(asio2::contains(sv, "some"));
ASIO2_CHECK(asio2::contains(sv, 'c'));
ASIO2_CHECK(asio2::contains(p, "some"));
ASIO2_CHECK(asio2::contains(p, 'c'));
ASIO2_CHECK(asio2::contains(buf, "some"));
ASIO2_CHECK(asio2::contains(buf, 'c'));
}
{
ASIO2_CHECK(asio2::compare_ignore_case("text\n With\tSome \t whitespaces\n\n", "Text\n with\tsome \t whitespaces\n\n"));
ASIO2_CHECK(!asio2::compare_ignore_case("text\n With\tSome \t whitespaces\n\n", "Text\n With\tSome \t x whitespaces\n\n"));
}
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::trim_all(str) == "Textwithsomewhitespaces");
}
{
std::string str = " \nText\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::trim_left(str) == "Text\n with\tsome \t whitespaces\n\n");
}
{
std::string str = " \nText\n with\tsome \t whitespaces\n\n";
ASIO2_CHECK(asio2::ltrim(str) == "Text\n with\tsome \t whitespaces\n\n");
}
{
std::string str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim_right(str) == " \nText\n with\tsome \t whitespaces");
}
{
std::string str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::rtrim(str) == " \nText\n with\tsome \t whitespaces");
}
{
std::string str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim_both(str) == "Text\n with\tsome \t whitespaces");
}
{
std::string str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim(str) == "Text\n with\tsome \t whitespaces");
}
{
std::string str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim_left_copy(str) == "Text\n with\tsome \t whitespaces \n\n ");
ASIO2_CHECK(str == " \nText\n with\tsome \t whitespaces \n\n ");
}
{
std::string str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::ltrim_copy(str) == "Text\n with\tsome \t whitespaces \n\n ");
ASIO2_CHECK(str == " \nText\n with\tsome \t whitespaces \n\n ");
}
{
std::string str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim_right_copy(str) == " \nText\n with\tsome \t whitespaces");
ASIO2_CHECK(str == " \nText\n with\tsome \t whitespaces \n\n ");
}
{
std::string str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::rtrim_copy(str) == " \nText\n with\tsome \t whitespaces");
ASIO2_CHECK(str == " \nText\n with\tsome \t whitespaces \n\n ");
}
{
std::string str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim_copy(str) == "Text\n with\tsome \t whitespaces");
ASIO2_CHECK(str == " \nText\n with\tsome \t whitespaces \n\n ");
}
{
std::string_view str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim_left(str) == "Text\n with\tsome \t whitespaces \n\n ");
}
{
std::string_view str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::ltrim(str) == "Text\n with\tsome \t whitespaces \n\n ");
}
{
std::string_view str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim_right(str) == " \nText\n with\tsome \t whitespaces");
}
{
std::string_view str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::rtrim(str) == " \nText\n with\tsome \t whitespaces");
}
{
std::string_view str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim_both(str) == "Text\n with\tsome \t whitespaces");
}
{
std::string_view str = " \nText\n with\tsome \t whitespaces \n\n ";
ASIO2_CHECK(asio2::trim(str) == "Text\n with\tsome \t whitespaces");
}
{
std::string str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, "some", "Any") == " \nText\n with\tAny \t some whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, "Some", "Any") == " \nText\n with\tsome \t some whitespaces \n\n ");
std::string st = "some", sr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, st, sr) == " \nText\n with\tAny \t some whitespaces \n\n ");
std::string_view vt = "some", vr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, vt, vr) == " \nText\n with\tAny \t some whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, st, vr) == " \nText\n with\tAny \t some whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, vt, sr) == " \nText\n with\tAny \t some whitespaces \n\n ");
const char* pt = "some"; const char* pr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, pt, pr) == " \nText\n with\tAny \t some whitespaces \n\n ");
char bt[] = "some"; char br[] = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, bt, br) == " \nText\n with\tAny \t some whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, 'T', 't') == " \ntext\n with\tsome \t some whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, "T", 't') == " \ntext\n with\tsome \t some whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_first(str, 'T', "t") == " \ntext\n with\tsome \t some whitespaces \n\n ");
}
{
std::string str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, "some", "Any") == " \nText\n with\tsome \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, "Some", "Any") == " \nText\n with\tsome \t some whitespaces \n\n ");
std::string st = "some", sr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, st, sr) == " \nText\n with\tsome \t Any whitespaces \n\n ");
std::string_view vt = "some", vr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, vt, vr) == " \nText\n with\tsome \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, st, vr) == " \nText\n with\tsome \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, vt, sr) == " \nText\n with\tsome \t Any whitespaces \n\n ");
const char* pt = "some"; const char* pr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, pt, pr) == " \nText\n with\tsome \t Any whitespaces \n\n ");
char bt[] = "some"; char br[] = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, bt, br) == " \nText\n with\tsome \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, 't', 'x') == " \nText\n with\tsome \t some whixespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, "t", 'x') == " \nText\n with\tsome \t some whixespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_last(str, 't', "x") == " \nText\n with\tsome \t some whixespaces \n\n ");
}
{
std::string str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, "some", "Any") == " \nText\n with\tAny \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, "Some", "Any") == " \nText\n with\tsome \t some whitespaces \n\n ");
std::string st = "some", sr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, st, sr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
std::string_view vt = "some", vr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, vt, vr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, st, vr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, vt, sr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
const char* pt = "some"; const char* pr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, pt, pr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
char bt[] = "some"; char br[] = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, bt, br) == " \nText\n with\tAny \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, 't', 'x') == " \nTexx\n wixh\tsome \t some whixespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, "t", 'x') == " \nTexx\n wixh\tsome \t some whixespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace_all(str, 't', "x") == " \nTexx\n wixh\tsome \t some whixespaces \n\n ");
}
{
std::string str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, "some", "Any") == " \nText\n with\tAny \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, "Some", "Any") == " \nText\n with\tsome \t some whitespaces \n\n ");
std::string st = "some", sr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, st, sr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
std::string_view vt = "some", vr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, vt, vr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, st, vr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, vt, sr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
const char* pt = "some"; const char* pr = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, pt, pr) == " \nText\n with\tAny \t Any whitespaces \n\n ");
char bt[] = "some"; char br[] = "Any";
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, bt, br) == " \nText\n with\tAny \t Any whitespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, 't', 'x') == " \nTexx\n wixh\tsome \t some whixespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, "t", 'x') == " \nTexx\n wixh\tsome \t some whixespaces \n\n ");
str = " \nText\n with\tsome \t some whitespaces \n\n ";
ASIO2_CHECK(asio2::replace(str, 't', "x") == " \nTexx\n wixh\tsome \t some whixespaces \n\n ");
}
{
std::string str = " \nText\n with\tsome \t some whitespaces \n\n ";
std::string_view sv = " \nText\n with\tsome \t some whitespaces \n\n ";
const char* p = " \nText\n with\tsome \t some whitespaces \n\n ";
char buf[] = " \nText\n with\tsome \t some whitespaces \n\n ";
std::string sln = "\n";
char cln = '\n';
const char* pln = "\n";
std::string_view vln = "\n";
std::string sspace = " ";
char cspace = ' ';
const char* pspace = " ";
std::string_view vspace = " ";
ASIO2_CHECK(asio2::ends_with(str, " ") == true);
ASIO2_CHECK(asio2::ends_with(str, ' ') == true);
ASIO2_CHECK(asio2::ends_with(str, sspace) == true);
ASIO2_CHECK(asio2::ends_with(str, cspace) == true);
ASIO2_CHECK(asio2::ends_with(str, pspace) == true);
ASIO2_CHECK(asio2::ends_with(str, vspace) == true);
ASIO2_CHECK(asio2::ends_with(str, "\n") == false);
ASIO2_CHECK(asio2::ends_with(str, '\n') == false);
ASIO2_CHECK(asio2::ends_with(str, sln) == false);
ASIO2_CHECK(asio2::ends_with(str, cln) == false);
ASIO2_CHECK(asio2::ends_with(str, pln) == false);
ASIO2_CHECK(asio2::ends_with(str, vln) == false);
ASIO2_CHECK(asio2::ends_with(sv, " ") == true);
ASIO2_CHECK(asio2::ends_with(sv, ' ') == true);
ASIO2_CHECK(asio2::ends_with(sv, sspace) == true);
ASIO2_CHECK(asio2::ends_with(sv, cspace) == true);
ASIO2_CHECK(asio2::ends_with(sv, pspace) == true);
ASIO2_CHECK(asio2::ends_with(sv, vspace) == true);
ASIO2_CHECK(asio2::ends_with(sv, "\n") == false);
ASIO2_CHECK(asio2::ends_with(sv, '\n') == false);
ASIO2_CHECK(asio2::ends_with(sv, sln) == false);
ASIO2_CHECK(asio2::ends_with(sv, cln) == false);
ASIO2_CHECK(asio2::ends_with(sv, pln) == false);
ASIO2_CHECK(asio2::ends_with(sv, vln) == false);
ASIO2_CHECK(asio2::ends_with(p, " ") == true);
ASIO2_CHECK(asio2::ends_with(p, ' ') == true);
ASIO2_CHECK(asio2::ends_with(p, sspace) == true);
ASIO2_CHECK(asio2::ends_with(p, cspace) == true);
ASIO2_CHECK(asio2::ends_with(p, pspace) == true);
ASIO2_CHECK(asio2::ends_with(p, vspace) == true);
ASIO2_CHECK(asio2::ends_with(p, "\n") == false);
ASIO2_CHECK(asio2::ends_with(p, '\n') == false);
ASIO2_CHECK(asio2::ends_with(p, sln) == false);
ASIO2_CHECK(asio2::ends_with(p, cln) == false);
ASIO2_CHECK(asio2::ends_with(p, pln) == false);
ASIO2_CHECK(asio2::ends_with(p, vln) == false);
ASIO2_CHECK(asio2::ends_with(buf, " ") == true);
ASIO2_CHECK(asio2::ends_with(buf, ' ') == true);
ASIO2_CHECK(asio2::ends_with(buf, sspace) == true);
ASIO2_CHECK(asio2::ends_with(buf, cspace) == true);
ASIO2_CHECK(asio2::ends_with(buf, pspace) == true);
ASIO2_CHECK(asio2::ends_with(buf, vspace) == true);
ASIO2_CHECK(asio2::ends_with(buf, "\n") == false);
ASIO2_CHECK(asio2::ends_with(buf, '\n') == false);
ASIO2_CHECK(asio2::ends_with(buf, sln) == false);
ASIO2_CHECK(asio2::ends_with(buf, cln) == false);
ASIO2_CHECK(asio2::ends_with(buf, pln) == false);
ASIO2_CHECK(asio2::ends_with(buf, vln) == false);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", " ") == true);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", ' ') == true);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", sspace) == true);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", cspace) == true);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", pspace) == true);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", vspace) == true);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", "\n") == false);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", '\n') == false);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", sln) == false);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", cln) == false);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", pln) == false);
ASIO2_CHECK(asio2::ends_with(" \nText\n with\tsome \t some whitespaces \n\n ", vln) == false);
}
{
std::string str = " \nText\n with\tsome \t some whitespaces \n\n ";
std::string_view sv = " \nText\n with\tsome \t some whitespaces \n\n ";
const char* p = " \nText\n with\tsome \t some whitespaces \n\n ";
char buf[] = " \nText\n with\tsome \t some whitespaces \n\n ";
std::string sln = "\n";
char cln = '\n';
const char* pln = "\n";
std::string_view vln = "\n";
std::string sspace = " ";
char cspace = ' ';
const char* pspace = " ";
std::string_view vspace = " ";
ASIO2_CHECK(asio2::starts_with(str, " ") == true);
ASIO2_CHECK(asio2::starts_with(str, ' ') == true);
ASIO2_CHECK(asio2::starts_with(str, sspace) == true);
ASIO2_CHECK(asio2::starts_with(str, cspace) == true);
ASIO2_CHECK(asio2::starts_with(str, pspace) == true);
ASIO2_CHECK(asio2::starts_with(str, vspace) == true);
ASIO2_CHECK(asio2::starts_with(str, "\n") == false);
ASIO2_CHECK(asio2::starts_with(str, '\n') == false);
ASIO2_CHECK(asio2::starts_with(str, sln) == false);
ASIO2_CHECK(asio2::starts_with(str, cln) == false);
ASIO2_CHECK(asio2::starts_with(str, pln) == false);
ASIO2_CHECK(asio2::starts_with(str, vln) == false);
ASIO2_CHECK(asio2::starts_with(sv, " ") == true);
ASIO2_CHECK(asio2::starts_with(sv, ' ') == true);
ASIO2_CHECK(asio2::starts_with(sv, sspace) == true);
ASIO2_CHECK(asio2::starts_with(sv, cspace) == true);
ASIO2_CHECK(asio2::starts_with(sv, pspace) == true);
ASIO2_CHECK(asio2::starts_with(sv, vspace) == true);
ASIO2_CHECK(asio2::starts_with(sv, "\n") == false);
ASIO2_CHECK(asio2::starts_with(sv, '\n') == false);
ASIO2_CHECK(asio2::starts_with(sv, sln) == false);
ASIO2_CHECK(asio2::starts_with(sv, cln) == false);
ASIO2_CHECK(asio2::starts_with(sv, pln) == false);
ASIO2_CHECK(asio2::starts_with(sv, vln) == false);
ASIO2_CHECK(asio2::starts_with(p, " ") == true);
ASIO2_CHECK(asio2::starts_with(p, ' ') == true);
ASIO2_CHECK(asio2::starts_with(p, sspace) == true);
ASIO2_CHECK(asio2::starts_with(p, cspace) == true);
ASIO2_CHECK(asio2::starts_with(p, pspace) == true);
ASIO2_CHECK(asio2::starts_with(p, vspace) == true);
ASIO2_CHECK(asio2::starts_with(p, "\n") == false);
ASIO2_CHECK(asio2::starts_with(p, '\n') == false);
ASIO2_CHECK(asio2::starts_with(p, sln) == false);
ASIO2_CHECK(asio2::starts_with(p, cln) == false);
ASIO2_CHECK(asio2::starts_with(p, pln) == false);
ASIO2_CHECK(asio2::starts_with(p, vln) == false);
ASIO2_CHECK(asio2::starts_with(buf, " ") == true);
ASIO2_CHECK(asio2::starts_with(buf, ' ') == true);
ASIO2_CHECK(asio2::starts_with(buf, sspace) == true);
ASIO2_CHECK(asio2::starts_with(buf, cspace) == true);
ASIO2_CHECK(asio2::starts_with(buf, pspace) == true);
ASIO2_CHECK(asio2::starts_with(buf, vspace) == true);
ASIO2_CHECK(asio2::starts_with(buf, "\n") == false);
ASIO2_CHECK(asio2::starts_with(buf, '\n') == false);
ASIO2_CHECK(asio2::starts_with(buf, sln) == false);
ASIO2_CHECK(asio2::starts_with(buf, cln) == false);
ASIO2_CHECK(asio2::starts_with(buf, pln) == false);
ASIO2_CHECK(asio2::starts_with(buf, vln) == false);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", " ") == true);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", ' ') == true);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", sspace) == true);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", cspace) == true);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", pspace) == true);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", vspace) == true);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", "\n") == false);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", '\n') == false);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", sln) == false);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", cln) == false);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", pln) == false);
ASIO2_CHECK(asio2::starts_with(" \nText\n with\tsome \t some whitespaces \n\n ", vln) == false);
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string> result = asio2::split(str, '\n');
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string> result = asio2::split(str, "\n");
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string d = "\n";
std::vector<std::string> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string_view d = "\n";
std::vector<std::string> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
const char* d = "\n";
std::vector<std::string> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
char d[] = "\n";
std::vector<std::string> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
char d = '\n';
std::vector<std::string> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string_view> result = asio2::split(str, '\n');
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string_view> result = asio2::split(str, "\n");
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string d = "\n";
std::vector<std::string_view> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string_view d = "\n";
std::vector<std::string_view> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
const char* d = "\n";
std::vector<std::string_view> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
char d[] = "\n";
std::vector<std::string_view> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
char d = '\n';
std::vector<std::string_view> result = asio2::split(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
// ----------------------------------------------------------------------------------------
{
std::vector<std::string> result = asio2::split("\n \nText\n with\tsome \t some whitespaces \n\n \n", '\n');
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::vector<std::string> result = asio2::split("\n \nText\n with\tsome \t some whitespaces \n\n \n", "\n");
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string d = "\n";
std::vector<std::string> result = asio2::split("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view d = "\n";
std::vector<std::string> result = asio2::split("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
const char* d = "\n";
std::vector<std::string> result = asio2::split("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
char d[] = "\n";
std::vector<std::string> result = asio2::split("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
char d = '\n';
std::vector<std::string> result = asio2::split("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
// ----------------------------------------------------------------------------------------
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string> result = asio2::split_any(str, '\n');
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string> result = asio2::split_any(str, "\n");
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string d = "\n";
std::vector<std::string> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string_view d = "\n";
std::vector<std::string> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
const char* d = "\n";
std::vector<std::string> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
char d[] = "\n";
std::vector<std::string> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
char d = '\n';
std::vector<std::string> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string_view> result = asio2::split_any(str, '\n');
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string_view> result = asio2::split_any(str, "\n");
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string d = "\n";
std::vector<std::string_view> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string_view d = "\n";
std::vector<std::string_view> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
const char* d = "\n";
std::vector<std::string_view> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
char d[] = "\n";
std::vector<std::string_view> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
char d = '\n';
std::vector<std::string_view> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
// ----------------------------------------------------------------------------------------
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string> result = asio2::split_any(str, "\t\n");
ASIO2_CHECK(result.size() == 9);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with");
ASIO2_CHECK(result[4] == "some ");
ASIO2_CHECK(result[5] == " some whitespaces ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
ASIO2_CHECK(result[7] == " ");
ASIO2_CHECK(result[8] == "" && result[8].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string d = "\t\n";
std::vector<std::string> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 9);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with");
ASIO2_CHECK(result[4] == "some ");
ASIO2_CHECK(result[5] == " some whitespaces ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
ASIO2_CHECK(result[7] == " ");
ASIO2_CHECK(result[8] == "" && result[8].empty());
}
{
std::string str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string_view d = "\t\n";
std::vector<std::string> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 9);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with");
ASIO2_CHECK(result[4] == "some ");
ASIO2_CHECK(result[5] == " some whitespaces ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
ASIO2_CHECK(result[7] == " ");
ASIO2_CHECK(result[8] == "" && result[8].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::vector<std::string_view> result = asio2::split_any(str, "\t\n");
ASIO2_CHECK(result.size() == 9);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with");
ASIO2_CHECK(result[4] == "some ");
ASIO2_CHECK(result[5] == " some whitespaces ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
ASIO2_CHECK(result[7] == " ");
ASIO2_CHECK(result[8] == "" && result[8].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string d = "\t\n";
std::vector<std::string_view> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 9);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with");
ASIO2_CHECK(result[4] == "some ");
ASIO2_CHECK(result[5] == " some whitespaces ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
ASIO2_CHECK(result[7] == " ");
ASIO2_CHECK(result[8] == "" && result[8].empty());
}
{
std::string_view str = "\n \nText\n with\tsome \t some whitespaces \n\n \n";
std::string_view d = "\t\n";
std::vector<std::string_view> result = asio2::split_any(str, d);
ASIO2_CHECK(result.size() == 9);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with");
ASIO2_CHECK(result[4] == "some ");
ASIO2_CHECK(result[5] == " some whitespaces ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
ASIO2_CHECK(result[7] == " ");
ASIO2_CHECK(result[8] == "" && result[8].empty());
}
{
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", '\n');
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", "\n");
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string d = "\n";
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
std::string_view d = "\n";
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
const char* d = "\n";
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
char d[] = "\n";
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
{
char d = '\n';
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 7);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with\tsome \t some whitespaces ");
ASIO2_CHECK(result[4] == "" && result[4].empty());
ASIO2_CHECK(result[5] == " ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
}
// ----------------------------------------------------------------------------------------
{
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", "\t\n");
ASIO2_CHECK(result.size() == 9);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with");
ASIO2_CHECK(result[4] == "some ");
ASIO2_CHECK(result[5] == " some whitespaces ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
ASIO2_CHECK(result[7] == " ");
ASIO2_CHECK(result[8] == "" && result[8].empty());
}
{
std::string d = "\t\n";
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 9);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with");
ASIO2_CHECK(result[4] == "some ");
ASIO2_CHECK(result[5] == " some whitespaces ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
ASIO2_CHECK(result[7] == " ");
ASIO2_CHECK(result[8] == "" && result[8].empty());
}
{
std::string_view d = "\t\n";
std::vector<std::string> result = asio2::split_any("\n \nText\n with\tsome \t some whitespaces \n\n \n", d);
ASIO2_CHECK(result.size() == 9);
ASIO2_CHECK(result[0] == "" && result[0].empty());
ASIO2_CHECK(result[1] == " ");
ASIO2_CHECK(result[2] == "Text");
ASIO2_CHECK(result[3] == " with");
ASIO2_CHECK(result[4] == "some ");
ASIO2_CHECK(result[5] == " some whitespaces ");
ASIO2_CHECK(result[6] == "" && result[6].empty());
ASIO2_CHECK(result[7] == " ");
ASIO2_CHECK(result[8] == "" && result[8].empty());
}
{
std::vector<std::string> res;
std::string str = "abc,abcd;abce.abcf?";
// Basic usage
res = asio2::regex_split(str, "[,;\\.\\?]+");
ASIO2_CHECK(res.size() == 4);
ASIO2_CHECK(res[0] == "abc");
ASIO2_CHECK(res[1] == "abcd");
ASIO2_CHECK(res[2] == "abce");
ASIO2_CHECK(res[3] == "abcf");
// Empty input => empty string
ASIO2_CHECK(asio2::regex_split("", ",:")[0] == "");
// No matches => original string
res = asio2::regex_split("abc_123", ",; ");
ASIO2_CHECK(res.size() == 1);
ASIO2_CHECK(res[0] == "abc_123");
// Empty delimiters => original string
res = asio2::regex_split("abc;def", "");
ASIO2_CHECK(res.size() == 8);
ASIO2_CHECK(res[0]== "");
ASIO2_CHECK(res[1]== "a");
ASIO2_CHECK(res[2]== "b");
ASIO2_CHECK(res[3]== "c");
ASIO2_CHECK(res[4]== ";");
ASIO2_CHECK(res[5]== "d");
ASIO2_CHECK(res[6]== "e");
ASIO2_CHECK(res[7]== "f");
// Leading delimiters => leading empty string
res = asio2::regex_split(";abc", ",; ");
ASIO2_CHECK(res.size() == 1);
ASIO2_CHECK(res[0] == ";abc");
}
{
std::map<std::string, std::string> res = asio2::regex_split_map(
"[abc] name = 123; [abd] name = 123;[abe] name = 123; ", "\\[[^\\]]+\\]");
std::map<std::string, std::string> ans = {
{"[abc]", "name = 123;"}, {"[abd]", "name = 123;"}, {"[abe]", "name = 123;"}
};
for (auto each : res)
{
ASIO2_CHECK(ans.count(each.first) == 1);
if (ans.count(each.first) == 1)
{
auto str = each.second;
asio2::trim(str);
ASIO2_CHECK(str == ans[each.first]);
}
}
// TODO: More test is to be added.
}
{
std::map<std::wstring, std::wstring> res = asio2::regex_split_map(
L"[abc] name = 123; [abd] name = 123;[abe] name = 123; ", L"\\[[^\\]]+\\]");
std::map<std::wstring, std::wstring> ans = {
{L"[abc]", L"name = 123;"}, {L"[abd]", L"name = 123;"}, {L"[abe]", L"name = 123;"}
};
for (auto each : res)
{
ASIO2_CHECK(ans.count(each.first) == 1);
if (ans.count(each.first) == 1)
{
auto str = each.second;
asio2::trim(str);
ASIO2_CHECK(str == ans[each.first]);
}
}
}
{
std::string str1 = "Col1;Col2;Col3";
std::vector<std::string> tokens1 = { "Col1", "Col2", "Col3" };
ASIO2_CHECK(str1 == asio2::join(tokens1, ";"));
std::string str2 = "1|2|3";
std::vector<unsigned> tokens2 = { 1, 2, 3 };
ASIO2_CHECK(str2 == asio2::join(tokens2, "|"));
}
{
std::vector<std::string> tokens = { "t1", "t2", "", "t4", "" };
asio2::drop_empty(tokens);
ASIO2_CHECK(tokens.size() == 3);
ASIO2_CHECK(tokens[0] == "t1");
ASIO2_CHECK(tokens[1] == "t2");
ASIO2_CHECK(tokens[2] == "t4");
}
{
std::vector<std::string> tokens = { "t1", "t2", "", "t4", "" };
auto res = asio2::drop_empty_copy(tokens);
ASIO2_CHECK(res.size() == 3);
ASIO2_CHECK(res[0] == "t1");
ASIO2_CHECK(res[1] == "t2");
ASIO2_CHECK(res[2] == "t4");
}
{
std::vector<std::string> str1 = { "t1", "t2", "", "t4", "", "t1" };
asio2::drop_duplicate(str1);
std::vector<std::string> str2 = { "", "t1", "t2", "t4" };
ASIO2_CHECK(std::equal(str1.cbegin(), str1.cend(), str2.cbegin()) == true);
}
{
std::vector<std::string> str1 = { "t1", "t2", "", "t4", "", "t1" };
auto str3 = asio2::drop_duplicate_copy(str1);
std::vector<std::string> str2 = { "", "t1", "t2", "t4" };
ASIO2_CHECK(std::equal(str2.cbegin(), str2.cend(), str3.cbegin()) == true);
}
{
ASIO2_CHECK(asio2::repeat("Go", 4) == "GoGoGoGo");
ASIO2_CHECK(asio2::repeat('Z', 10) == "ZZZZZZZZZZ");
}
{
const std::regex check_mail("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$");
ASIO2_CHECK(true == asio2::matches("<EMAIL>", check_mail));
ASIO2_CHECK(false == asio2::matches("jon.doe@", check_mail));
}
{
std::vector<std::string> str1 = { "ABC", "abc", "bcd", "", "-", " ", "123", "-100" };
asio2::sorting_ascending(str1);
std::vector<std::string> str2 = { "", " ", "-", "-100", "123", "ABC", "abc", "bcd" };
ASIO2_CHECK(std::equal(str1.cbegin(), str1.cend(), str2.cbegin()) == true);
}
{
std::vector<std::string> str1 = { "ABC", "abc", "bcd", "", "-", " ", "123", "-100" };
asio2::sorting_descending(str1);
std::vector<std::string> str2 = { "bcd", "abc", "ABC", "123", "-100", "-", " ", "" };
ASIO2_CHECK(std::equal(str1.cbegin(), str1.cend(), str2.cbegin()) == true);
}
{
std::vector<std::string> str1 = { "bcd", "abc", "ABC", "123", "-100", "-", " ", "" };
asio2::reverse_inplace(str1);
std::vector<std::string> str2 = { "", " ", "-", "-100", "123", "ABC", "abc", "bcd" };
ASIO2_CHECK(std::equal(str1.cbegin(), str1.cend(), str2.cbegin()) == true);
}
{
std::vector<std::string> str1 = { "bcd", "abc", "ABC", "123", "-100", "-", " ", "" };
std::vector<std::string> str3(str1.begin(), str1.end());
auto str4 = asio2::reverse_copy(str1);
std::vector<std::string> str2 = { "", " ", "-", "-100", "123", "ABC", "abc", "bcd" };
ASIO2_CHECK(std::equal(str1.cbegin(), str1.cend(), str3.cbegin())== true);
ASIO2_CHECK(std::equal(str4.cbegin(), str4.cend(), str2.cbegin()) == true);
}
{
std::string str = "Text\n with\tsome \t whitespaces\n\n";
std::string_view sv = "Text\n with\tsome \t whitespaces\n\n";
const char* p = "Text\n with\tsome \t whitespaces\n\n";
char buf[] = "Text\n with\tsome \t whitespaces\n\n";;
ASIO2_CHECK(asio2::ifind("text\n with\tSome \t whitespaces\n\n", "With") == 6);
ASIO2_CHECK(asio2::ifind(str, "With") == 6);
ASIO2_CHECK(asio2::ifind(sv, "With") == 6);
ASIO2_CHECK(asio2::ifind(p, "With") == 6);
ASIO2_CHECK(asio2::ifind(buf, "With") == 6);
ASIO2_CHECK(asio2::ifind("text\n with\tSome \t whitespaces\n\n", "Soem") == std::string::npos);
ASIO2_CHECK(asio2::ifind(str, "Soem") == std::string::npos);
ASIO2_CHECK(asio2::ifind(sv, "Soem") == std::string::npos);
ASIO2_CHECK(asio2::ifind(p, "Soem") == std::string::npos);
ASIO2_CHECK(asio2::ifind(buf, "Soem") == std::string::npos);
ASIO2_CHECK(asio2::ifind("text\n with\tSome \t whitespaces\n\n", 'W') == 6);
ASIO2_CHECK(asio2::ifind(str, 'W') == 6);
ASIO2_CHECK(asio2::ifind(sv, 'W') == 6);
ASIO2_CHECK(asio2::ifind(p, 'W') == 6);
ASIO2_CHECK(asio2::ifind(buf, 'W') == 6);
}
//ASIO2_TEST_BEGIN_LOOP(test_loop_times);
//ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"strutil",
ASIO2_TEST_CASE(strutil_test)
)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_RS6K_H
#define BHO_PREDEF_ARCHITECTURE_RS6K_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_RS6000`
http://en.wikipedia.org/wiki/RS/6000[RS/6000] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__THW_RS6000+` | {predef_detection}
| `+_IBMR2+` | {predef_detection}
| `+_POWER+` | {predef_detection}
| `+_ARCH_PWR+` | {predef_detection}
| `+_ARCH_PWR2+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_RS6000 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__THW_RS6000) || defined(_IBMR2) || \
defined(_POWER) || defined(_ARCH_PWR) || \
defined(_ARCH_PWR2)
# undef BHO_ARCH_RS6000
# define BHO_ARCH_RS6000 BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_RS6000
# define BHO_ARCH_RS6000_AVAILABLE
#endif
#if BHO_ARCH_RS6000
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_RS6000_NAME "RS/6000"
#define BHO_ARCH_PWR BHO_ARCH_RS6000
#if BHO_ARCH_PWR
# define BHO_ARCH_PWR_AVAILABLE
#endif
#if BHO_ARCH_PWR
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_PWR_NAME BHO_ARCH_RS6000_NAME
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_RS6000,BHO_ARCH_RS6000_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* chinese : http://mqtt.p2hp.com/mqtt-5-0
* english : https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_MESSAGE_HPP__
#define __ASIO2_MQTT_MESSAGE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/mqtt/protocol_v3.hpp>
#include <asio2/mqtt/protocol_v4.hpp>
#include <asio2/mqtt/protocol_v5.hpp>
namespace asio2::mqtt
{
template<typename M>
inline constexpr bool is_ctrlmsg()
{
return (is_v3_message<M>() || is_v4_message<M>() || is_v5_message<M>());
}
template<typename M>
inline constexpr bool is_nullmsg()
{
return (std::is_same_v<asio2::detail::remove_cvref_t<M>, mqtt::nullmsg>);
}
template<typename M>
inline constexpr bool is_rawmsg()
{
return (is_ctrlmsg<M>() || is_nullmsg<M>());
}
template<typename M> inline constexpr bool is_connect_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::connect > || std::is_same_v<T, mqtt::v4::connect > || std::is_same_v<T, mqtt::v5::connect >); }
template<typename M> inline constexpr bool is_connack_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::connack > || std::is_same_v<T, mqtt::v4::connack > || std::is_same_v<T, mqtt::v5::connack >); }
template<typename M> inline constexpr bool is_publish_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::publish > || std::is_same_v<T, mqtt::v4::publish > || std::is_same_v<T, mqtt::v5::publish >); }
template<typename M> inline constexpr bool is_puback_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::puback > || std::is_same_v<T, mqtt::v4::puback > || std::is_same_v<T, mqtt::v5::puback >); }
template<typename M> inline constexpr bool is_pubrec_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::pubrec > || std::is_same_v<T, mqtt::v4::pubrec > || std::is_same_v<T, mqtt::v5::pubrec >); }
template<typename M> inline constexpr bool is_pubrel_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::pubrel > || std::is_same_v<T, mqtt::v4::pubrel > || std::is_same_v<T, mqtt::v5::pubrel >); }
template<typename M> inline constexpr bool is_pubcomp_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::pubcomp > || std::is_same_v<T, mqtt::v4::pubcomp > || std::is_same_v<T, mqtt::v5::pubcomp >); }
template<typename M> inline constexpr bool is_subscribe_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::subscribe > || std::is_same_v<T, mqtt::v4::subscribe > || std::is_same_v<T, mqtt::v5::subscribe >); }
template<typename M> inline constexpr bool is_suback_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::suback > || std::is_same_v<T, mqtt::v4::suback > || std::is_same_v<T, mqtt::v5::suback >); }
template<typename M> inline constexpr bool is_unsubscribe_message() { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::unsubscribe> || std::is_same_v<T, mqtt::v4::unsubscribe> || std::is_same_v<T, mqtt::v5::unsubscribe>); }
template<typename M> inline constexpr bool is_unsuback_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::unsuback > || std::is_same_v<T, mqtt::v4::unsuback > || std::is_same_v<T, mqtt::v5::unsuback >); }
template<typename M> inline constexpr bool is_pingreq_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::pingreq > || std::is_same_v<T, mqtt::v4::pingreq > || std::is_same_v<T, mqtt::v5::pingreq >); }
template<typename M> inline constexpr bool is_pingresp_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::pingresp > || std::is_same_v<T, mqtt::v4::pingresp > || std::is_same_v<T, mqtt::v5::pingresp >); }
template<typename M> inline constexpr bool is_disconnect_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v3::disconnect > || std::is_same_v<T, mqtt::v4::disconnect > || std::is_same_v<T, mqtt::v5::disconnect >); }
template<typename M> inline constexpr bool is_auth_message () { using T = asio2::detail::remove_cvref_t<M>; return (std::is_same_v<T, mqtt::v5::auth > || std::is_same_v<T, mqtt::v5::auth > || std::is_same_v<T, mqtt::v5::auth >); }
using message_variant = std::variant<
mqtt::nullmsg , // 0
v3::connect , // 1
v3::connack , // 2
v3::publish , // 3
v3::puback , // 4
v3::pubrec , // 5
v3::pubrel , // 6
v3::pubcomp , // 7
v3::subscribe , // 8
v3::suback , // 9
v3::unsubscribe , // 10
v3::unsuback , // 11
v3::pingreq , // 12
v3::pingresp , // 13
v3::disconnect , // 14
v4::connect , // 15
v4::connack , // 16
v4::publish , // 17
v4::puback , // 18
v4::pubrec , // 19
v4::pubrel , // 20
v4::pubcomp , // 21
v4::subscribe , // 22
v4::suback , // 23
v4::unsubscribe , // 24
v4::unsuback , // 25
v4::pingreq , // 26
v4::pingresp , // 27
v4::disconnect , // 28
v5::connect , // 29
v5::connack , // 30
v5::publish , // 31
v5::puback , // 32
v5::pubrec , // 33
v5::pubrel , // 34
v5::pubcomp , // 35
v5::subscribe , // 36
v5::suback , // 37
v5::unsubscribe , // 38
v5::unsuback , // 39
v5::pingreq , // 40
v5::pingresp , // 41
v5::disconnect , // 42
v5::auth // 43
>;
//using message_index_type = std::conditional_t<
// std::variant_size_v<message_variant> <= (std::numeric_limits<std::uint8_t>::max)(),
// std::uint8_t, std::uint16_t
//>;
namespace detail
{
struct invoke_if_callback_return_type_tag {};
template<class T>
struct invoke_if_callback_return_type
{
using type = T;
};
template<>
struct invoke_if_callback_return_type<void>
{
using type = invoke_if_callback_return_type_tag;
};
}
class message : public message_variant
{
public:
using super = message_variant;
// a default-constructed variant holds a value of its first alternative
message() noexcept : message_variant()
{
}
template<class T, std::enable_if_t<is_rawmsg<T>(), int> = 0>
message(T&& v) : message_variant(std::forward<T>(v))
{
}
template<class T, std::enable_if_t<is_rawmsg<T>(), int> = 0>
message& operator=(T&& v)
{
this->base() = std::forward<T>(v);
return (*this);
}
message(message&&) noexcept = default;
message(message const&) = default;
message& operator=(message&&) noexcept = default;
message& operator=(message const&) = default;
template<class T, std::enable_if_t<is_rawmsg<T>(), int> = 0>
operator T&()
{
return std::get<T>(this->base());
}
template<class T, std::enable_if_t<is_rawmsg<T>(), int> = 0>
operator const T&()
{
return std::get<T>(this->base());
}
template<class T, std::enable_if_t<is_rawmsg<T>(), int> = 0>
operator T*() noexcept
{
return std::get_if<T>(std::addressof(this->base()));
}
template<class T, std::enable_if_t<is_rawmsg<T>(), int> = 0>
operator const T*() noexcept
{
return std::get_if<T>(std::addressof(this->base()));
}
/**
* this overload will cause compile error on gcc, i don't know why:
* mqtt::message msg(mqtt::v3::subscribe{});
* mqtt::v3::subscribe sub = static_cast<mqtt::v3::subscribe>(msg);
* compile error : call of overloaded subscribe(asio2::mqtt::message&) is ambiguous
*/
//template<class T, std::enable_if_t<is_rawmsg<T>(), int> = 0>
//operator T()
//{
// return std::get<T>(this->base());
//}
/// Returns the base variant of the message
inline super const& base() const noexcept { return *this; }
/// Returns the base variant of the message
inline super& base() noexcept { return *this; }
/// Returns the base variant of the message
inline super const& variant() const noexcept { return *this; }
/// Returns the base variant of the message
inline super& variant() noexcept { return *this; }
/**
* @brief Checks if the variant holds anyone of the alternative Types...
*/
template<class... Types>
inline bool has() noexcept
{
return (std::holds_alternative<Types>(this->base()) || ...);
}
/**
* @brief Checks if the variant holds anyone of the alternative Types...
*/
template<class... Types>
inline bool holds() noexcept
{
return (std::holds_alternative<Types>(this->base()) || ...);
}
/**
* @brief Checks if the variant holds any v3 message
*/
inline bool holds_v3_message() const noexcept
{
int i = static_cast<int>(this->base().index());
return (i >= 1 && i <= 14);
}
/**
* @brief Checks if the variant holds any v4 message
*/
inline bool holds_v4_message() const noexcept
{
int i = static_cast<int>(this->base().index());
return (i >= 15 && i <= 28);
}
/**
* @brief Checks if the variant holds any v5 message
*/
inline bool holds_v5_message() const noexcept
{
int i = static_cast<int>(this->base().index());
return (i >= 29 && i <= 43);
}
/**
* @brief If this holds the alternative T, returns a pointer to the value stored in the variant.
* Otherwise, returns a null pointer value.
*/
template<class T>
inline std::add_pointer_t<T> get_if() noexcept
{
return std::get_if<T>(std::addressof(this->base()));
}
/**
* @brief If this holds the alternative T, returns a reference to the value stored in the variant.
* Otherwise, throws std::bad_variant_access.
*/
template<class T>
inline T& get()
{
return std::get<T>(this->base());
}
/**
* @brief If this holds a valid value.
*/
inline bool empty() noexcept
{
return (this->index() == std::variant_npos || std::holds_alternative<mqtt::nullmsg>(this->base()));
}
/**
* @brief Invoke the callback if the variant holds the alternative Types...
* @return
* If the callback return type is void :
* If the variant holds the alternative Types... , the callback will be called, then return true
* If the variant has't holds the alternative Types... , the callback will not be called, then return false
* If the callback return type is not void :
* If the variant holds the alternative Types... , the callback will be called,
* This return value is the callback returned value.
* If the variant has't holds the alternative Types... , the callback will not be called,
* This return value is a empty object of the callback returned type.
* The callback signature : void(auto& msg) or bool(auto& msg) or others...
*/
template<class... Types, class FunctionT>
inline auto invoke_if(FunctionT&& callback) noexcept
{
using return_type = std::tuple_element_t<0, std::tuple<typename
detail::invoke_if_callback_return_type<decltype(callback(std::declval<Types&>()))>::type...>>;
if constexpr (std::is_same_v<return_type, detail::invoke_if_callback_return_type_tag>)
{
return ((this->template _invoke_for_each_type<Types>(callback)) || ...);
}
else
{
return_type r{};
[[maybe_unused]] bool f = ((this->template _invoke_for_each_type<Types>(r, callback)) || ...);
return r;
}
}
protected:
template<class T, class FunctionT>
inline bool _invoke_for_each_type(FunctionT&& callback) noexcept
{
if (std::holds_alternative<T>(this->base()))
{
callback(std::get<T>(this->base()));
return true;
}
return false;
}
template<class T, class ReturnT, class FunctionT>
inline bool _invoke_for_each_type(ReturnT& r, FunctionT&& callback) noexcept
{
if (std::holds_alternative<T>(this->base()))
{
r = callback(std::get<T>(this->base()));
return true;
}
return false;
}
};
template<class, class = void>
struct has_packet_id : std::false_type { };
template<class T>
struct has_packet_id<T, std::void_t<decltype(std::declval<T&>().packet_id())>> : std::true_type { };
template<class Byte>
inline mqtt::control_packet_type message_type_from_byte(Byte byte)
{
mqtt::fixed_header<0>::type_and_flags tf{};
tf.byte = static_cast<std::uint8_t>(byte);
return static_cast<mqtt::control_packet_type>(tf.bits.type);
}
template<typename = void>
inline mqtt::control_packet_type message_type_from_data(std::string_view data)
{
return message_type_from_byte(data.front());
}
template<class Fun>
inline void data_to_message(mqtt::version ver, std::string_view& data, Fun&& f)
{
mqtt::control_packet_type type = mqtt::message_type_from_data(data);
asio2::clear_last_error();
if /**/ (ver == mqtt::version::v3)
{
switch (type)
{
case mqtt::control_packet_type::connect : { mqtt::message m{ mqtt::v3::connect {} }; std::get<mqtt::v3::connect >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::connack : { mqtt::message m{ mqtt::v3::connack {} }; std::get<mqtt::v3::connack >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::publish : { mqtt::message m{ mqtt::v3::publish {} }; std::get<mqtt::v3::publish >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::puback : { mqtt::message m{ mqtt::v3::puback {} }; std::get<mqtt::v3::puback >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pubrec : { mqtt::message m{ mqtt::v3::pubrec {} }; std::get<mqtt::v3::pubrec >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pubrel : { mqtt::message m{ mqtt::v3::pubrel {} }; std::get<mqtt::v3::pubrel >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pubcomp : { mqtt::message m{ mqtt::v3::pubcomp {} }; std::get<mqtt::v3::pubcomp >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::subscribe : { mqtt::message m{ mqtt::v3::subscribe {} }; std::get<mqtt::v3::subscribe >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::suback : { mqtt::message m{ mqtt::v3::suback {} }; std::get<mqtt::v3::suback >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::unsubscribe : { mqtt::message m{ mqtt::v3::unsubscribe {} }; std::get<mqtt::v3::unsubscribe >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::unsuback : { mqtt::message m{ mqtt::v3::unsuback {} }; std::get<mqtt::v3::unsuback >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pingreq : { mqtt::message m{ mqtt::v3::pingreq {} }; std::get<mqtt::v3::pingreq >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pingresp : { mqtt::message m{ mqtt::v3::pingresp {} }; std::get<mqtt::v3::pingresp >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::disconnect : { mqtt::message m{ mqtt::v3::disconnect {} }; std::get<mqtt::v3::disconnect >(m).deserialize(data); f(std::move(m)); } break;
default:
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
f(mqtt::message{});
break;
}
}
else if (ver == mqtt::version::v4)
{
switch (type)
{
case mqtt::control_packet_type::connect : { mqtt::message m{ mqtt::v4::connect {} }; std::get<mqtt::v4::connect >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::connack : { mqtt::message m{ mqtt::v4::connack {} }; std::get<mqtt::v4::connack >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::publish : { mqtt::message m{ mqtt::v4::publish {} }; std::get<mqtt::v4::publish >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::puback : { mqtt::message m{ mqtt::v4::puback {} }; std::get<mqtt::v4::puback >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pubrec : { mqtt::message m{ mqtt::v4::pubrec {} }; std::get<mqtt::v4::pubrec >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pubrel : { mqtt::message m{ mqtt::v4::pubrel {} }; std::get<mqtt::v4::pubrel >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pubcomp : { mqtt::message m{ mqtt::v4::pubcomp {} }; std::get<mqtt::v4::pubcomp >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::subscribe : { mqtt::message m{ mqtt::v4::subscribe {} }; std::get<mqtt::v4::subscribe >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::suback : { mqtt::message m{ mqtt::v4::suback {} }; std::get<mqtt::v4::suback >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::unsubscribe : { mqtt::message m{ mqtt::v4::unsubscribe {} }; std::get<mqtt::v4::unsubscribe >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::unsuback : { mqtt::message m{ mqtt::v4::unsuback {} }; std::get<mqtt::v4::unsuback >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pingreq : { mqtt::message m{ mqtt::v4::pingreq {} }; std::get<mqtt::v4::pingreq >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pingresp : { mqtt::message m{ mqtt::v4::pingresp {} }; std::get<mqtt::v4::pingresp >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::disconnect : { mqtt::message m{ mqtt::v4::disconnect {} }; std::get<mqtt::v4::disconnect >(m).deserialize(data); f(std::move(m)); } break;
default:
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
f(mqtt::message{});
break;
}
}
else if (ver == mqtt::version::v5)
{
switch (type)
{
case mqtt::control_packet_type::connect : { mqtt::message m{ mqtt::v5::connect {} }; std::get<mqtt::v5::connect >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::connack : { mqtt::message m{ mqtt::v5::connack {} }; std::get<mqtt::v5::connack >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::publish : { mqtt::message m{ mqtt::v5::publish {} }; std::get<mqtt::v5::publish >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::puback : { mqtt::message m{ mqtt::v5::puback {} }; std::get<mqtt::v5::puback >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pubrec : { mqtt::message m{ mqtt::v5::pubrec {} }; std::get<mqtt::v5::pubrec >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pubrel : { mqtt::message m{ mqtt::v5::pubrel {} }; std::get<mqtt::v5::pubrel >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pubcomp : { mqtt::message m{ mqtt::v5::pubcomp {} }; std::get<mqtt::v5::pubcomp >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::subscribe : { mqtt::message m{ mqtt::v5::subscribe {} }; std::get<mqtt::v5::subscribe >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::suback : { mqtt::message m{ mqtt::v5::suback {} }; std::get<mqtt::v5::suback >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::unsubscribe : { mqtt::message m{ mqtt::v5::unsubscribe {} }; std::get<mqtt::v5::unsubscribe >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::unsuback : { mqtt::message m{ mqtt::v5::unsuback {} }; std::get<mqtt::v5::unsuback >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pingreq : { mqtt::message m{ mqtt::v5::pingreq {} }; std::get<mqtt::v5::pingreq >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::pingresp : { mqtt::message m{ mqtt::v5::pingresp {} }; std::get<mqtt::v5::pingresp >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::disconnect : { mqtt::message m{ mqtt::v5::disconnect {} }; std::get<mqtt::v5::disconnect >(m).deserialize(data); f(std::move(m)); } break;
case mqtt::control_packet_type::auth : { mqtt::message m{ mqtt::v5::auth {} }; std::get<mqtt::v5::auth >(m).deserialize(data); f(std::move(m)); } break;
default:
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
f(mqtt::message{});
break;
}
}
else
{
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
f(mqtt::message{});
}
}
template<typename = void>
inline mqtt::version version_from_connect_data(std::string_view data)
{
asio2::clear_last_error();
mqtt::fixed_header<0> header{};
header.deserialize(data);
if (asio2::get_last_error())
return static_cast<mqtt::version>(0);
// The Protocol Name is a UTF-8 Encoded String that represents the protocol name MQTT.
// The string, its offset and length will not be changed by future versions of the MQTT specification.
mqtt::utf8_string protocol_name{};
protocol_name.deserialize(data);
if (asio2::get_last_error())
return static_cast<mqtt::version>(0);
// The 8 bit unsigned value that represents the revision level of the protocol used by the Client.
// The value of the Protocol Level field for the version 3.1.1 of the protocol is 4 (0x04).
mqtt::one_byte_integer protocol_version{};
protocol_version.deserialize(data);
if (asio2::get_last_error())
return static_cast<mqtt::version>(0);
return static_cast<mqtt::version>(protocol_version.value());
}
}
#endif // !__ASIO2_MQTT_MESSAGE_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_MIPS_H
#define BHO_PREDEF_ARCHITECTURE_MIPS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_MIPS`
http://en.wikipedia.org/wiki/MIPS_architecture[MIPS] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__mips__+` | {predef_detection}
| `+__mips+` | {predef_detection}
| `+__MIPS__+` | {predef_detection}
| `+__mips+` | V.0.0
| `+_MIPS_ISA_MIPS1+` | 1.0.0
| `+_R3000+` | 1.0.0
| `+_MIPS_ISA_MIPS2+` | 2.0.0
| `+__MIPS_ISA2__+` | 2.0.0
| `+_R4000+` | 2.0.0
| `+_MIPS_ISA_MIPS3+` | 3.0.0
| `+__MIPS_ISA3__+` | 3.0.0
| `+_MIPS_ISA_MIPS4+` | 4.0.0
| `+__MIPS_ISA4__+` | 4.0.0
|===
*/ // end::reference[]
#define BHO_ARCH_MIPS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__mips__) || defined(__mips) || \
defined(__MIPS__)
# undef BHO_ARCH_MIPS
# if !defined(BHO_ARCH_MIPS) && (defined(__mips))
# define BHO_ARCH_MIPS BHO_VERSION_NUMBER(__mips,0,0)
# endif
# if !defined(BHO_ARCH_MIPS) && (defined(_MIPS_ISA_MIPS1) || defined(_R3000))
# define BHO_ARCH_MIPS BHO_VERSION_NUMBER(1,0,0)
# endif
# if !defined(BHO_ARCH_MIPS) && (defined(_MIPS_ISA_MIPS2) || defined(__MIPS_ISA2__) || defined(_R4000))
# define BHO_ARCH_MIPS BHO_VERSION_NUMBER(2,0,0)
# endif
# if !defined(BHO_ARCH_MIPS) && (defined(_MIPS_ISA_MIPS3) || defined(__MIPS_ISA3__))
# define BHO_ARCH_MIPS BHO_VERSION_NUMBER(3,0,0)
# endif
# if !defined(BHO_ARCH_MIPS) && (defined(_MIPS_ISA_MIPS4) || defined(__MIPS_ISA4__))
# define BHO_ARCH_MIPS BHO_VERSION_NUMBER(4,0,0)
# endif
# if !defined(BHO_ARCH_MIPS)
# define BHO_ARCH_MIPS BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_MIPS
# define BHO_ARCH_MIPS_AVAILABLE
#endif
#if BHO_ARCH_MIPS
# if BHO_ARCH_MIPS >= BHO_VERSION_NUMBER(3,0,0)
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
# else
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#define BHO_ARCH_MIPS_NAME "MIPS"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_MIPS,BHO_ARCH_MIPS_NAME)
<file_sep>/*
*****
sha1.hpp is a repackaging of the sha1.cpp and sha1.h files from the smallsha1
library (http://code.google.com/p/smallsha1/) into a single header suitable for
use as a header only library. This conversion was done by <NAME>
(<EMAIL>) in 2013. All modifications to the code are redistributed
under the same license as the original, which is listed below.
*****
Copyright (c) 2011, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Micael Hildenborg nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <NAME> ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Micael Hildenborg BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __ASIO2_SHA1_IMPL_HPP__
#define __ASIO2_SHA1_IMPL_HPP__
#include <cstring>
#include <cstdint>
#include <cstddef>
#include <string>
namespace asio2
{
class sha1
{
protected:
// Rotate an integer value to left.
inline unsigned int rol(unsigned int value, unsigned int steps) {
return ((value << steps) | (value >> (32 - steps)));
}
// Sets the first 16 integers in the buffert to zero.
// Used for clearing the W buffert.
inline void clearWBuffert(unsigned int * buffert)
{
for (int pos = 16; --pos >= 0;)
{
buffert[pos] = 0;
}
}
inline void innerHash(unsigned int * result, unsigned int * w)
{
unsigned int a = result[0];
unsigned int b = result[1];
unsigned int c = result[2];
unsigned int d = result[3];
unsigned int e = result[4];
int round = 0;
#define ASIO2_SHA1MACRO(func,val) \
{ \
const unsigned int t = rol(a, 5) + (func) + e + val + w[round]; \
e = d; \
d = c; \
c = rol(b, 30); \
b = a; \
a = t; \
}
while (round < 16)
{
ASIO2_SHA1MACRO((b & c) | (~b & d), 0x5a827999)
++round;
}
while (round < 20)
{
w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
ASIO2_SHA1MACRO((b & c) | (~b & d), 0x5a827999)
++round;
}
while (round < 40)
{
w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
ASIO2_SHA1MACRO(b ^ c ^ d, 0x6ed9eba1)
++round;
}
while (round < 60)
{
w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
ASIO2_SHA1MACRO((b & c) | (b & d) | (c & d), 0x8f1bbcdc)
++round;
}
while (round < 80)
{
w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
ASIO2_SHA1MACRO(b ^ c ^ d, 0xca62c1d6)
++round;
}
#undef ASIO2_SHA1MACRO
result[0] += a;
result[1] += b;
result[2] += c;
result[3] += d;
result[4] += e;
}
/// Calculate a SHA1 hash
/**
* @param src points to any kind of data to be hashed.
* @param bytelength the number of bytes to hash from the src pointer.
* @param hash should point to a buffer of at least 20 bytes of size for storing
* the sha1 result in.
*/
inline void calc(void const * src, size_t bytelength, unsigned char * hash) {
// Init the result array.
unsigned int result[5] = { 0x67452301, 0xefcdab89, 0x98badcfe,
0x10325476, 0xc3d2e1f0 };
// Cast the void src pointer to be the byte array we can work with.
unsigned char const * sarray = (unsigned char const *)src;
// The reusable round buffer
unsigned int w[80];
// Loop through all complete 64byte blocks.
size_t endCurrentBlock;
size_t currentBlock = 0;
if (bytelength >= 64) {
size_t const endOfFullBlocks = bytelength - 64;
while (currentBlock <= endOfFullBlocks) {
endCurrentBlock = currentBlock + 64;
// Init the round buffer with the 64 byte block data.
for (int roundPos = 0; currentBlock < endCurrentBlock; currentBlock += 4)
{
// This line will swap endian on big endian and keep endian on
// little endian.
w[roundPos++] = (unsigned int)sarray[currentBlock + 3]
| (((unsigned int)sarray[currentBlock + 2]) << 8)
| (((unsigned int)sarray[currentBlock + 1]) << 16)
| (((unsigned int)sarray[currentBlock]) << 24);
}
innerHash(result, w);
}
}
// Handle the last and not full 64 byte block if existing.
endCurrentBlock = bytelength - currentBlock;
clearWBuffert(w);
size_t lastBlockBytes = 0;
for (; lastBlockBytes < endCurrentBlock; ++lastBlockBytes) {
w[lastBlockBytes >> 2] |= (unsigned int)sarray[lastBlockBytes + currentBlock] << ((3 - (lastBlockBytes & 3)) << 3);
}
w[lastBlockBytes >> 2] |= 0x80 << ((3 - (lastBlockBytes & 3)) << 3);
if (endCurrentBlock >= 56) {
innerHash(result, w);
clearWBuffert(w);
}
w[15] = static_cast<unsigned int>(bytelength << 3);
innerHash(result, w);
// Store hash in result pointer, and make sure we get in in the correct
// order on both endian models.
for (int hashByte = 20; --hashByte >= 0;) {
hash[hashByte] = (result[hashByte >> 2] >> (((3 - hashByte) & 0x3) << 3)) & 0xff;
}
}
unsigned char hash_[20];
public:
/**
* @construct Construct a sha1 object with a std::string.
*/
sha1(const std::string & message)
{
calc((void const *)message.data(), message.size(), hash_);
}
/**
* @construct Construct a sha1 object with a char pointer.
*/
sha1(const char * message)
{
calc((const void*)message, std::strlen(message), hash_);
}
/**
* @construct Construct a sha1 object with a unsigned char pointer.
*/
sha1(const void * message, std::size_t size)
{
calc((const void*)message, size, hash_);
}
/* Convert digest to std::string value */
std::string str(bool upper = false)
{
/* Hex numbers. */
char hex_upper[16] = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'A', 'B',
'C', 'D', 'E', 'F'
};
char hex_lower[16] = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
std::string str;
str.reserve(20 << 1);
for (std::size_t i = 0; i < 20; ++i)
{
int t = hash_[i];
int a = t / 16;
int b = t % 16;
str.append(1, upper ? hex_upper[a] : hex_lower[a]);
str.append(1, upper ? hex_upper[b] : hex_lower[b]);
}
return str;
}
};
} // namespace asio2
#endif // __ASIO2_SHA1_IMPL_HPP__
<file_sep>#ifndef BHO_MP11_MPL_HPP_INCLUDED
#define BHO_MP11_MPL_HPP_INCLUDED
// Copyright 2017, 2019 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/mp11/mpl_list.hpp>
#include <asio2/bho/mp11/mpl_tuple.hpp>
#endif // #ifndef BHO_MP11_MPL_HPP_INCLUDED
<file_sep>#include "unit_test.hpp"
#include <asio2/util/base64.hpp>
void base64_test()
{
std::string src = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string dst = "<KEY>;
std::string en = asio2::base64().encode(src);
std::string de = asio2::base64().decode(dst);
ASIO2_CHECK(en == dst);
ASIO2_CHECK(de == src);
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
std::string str;
int len = 500 + std::rand() % (500);
for (int i = 0; i < len; i++)
{
str += (char)(std::rand() % 255);
}
ASIO2_CHECK(asio2::base64_decode(asio2::base64_encode(str)) == str);
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"base64",
ASIO2_TEST_CASE(base64_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SOCKS5_OPTION_HPP__
#define __ASIO2_SOCKS5_OPTION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <array>
#include <asio2/component/socks/socks5_core.hpp>
namespace asio2::socks5::detail
{
template<class derived_t, method m>
class method_field
{
};
template<class derived_t>
class method_field<derived_t, method::password>
{
public:
method_field() = default;
method_field(method_field&&) noexcept = default;
method_field(method_field const&) = default;
method_field& operator=(method_field&&) noexcept = default;
method_field& operator=(method_field const&) = default;
method_field(std::string username, std::string password)
: username_(std::move(username))
, password_(std::move(password))
{
ASIO2_ASSERT(username_.size() <= std::size_t(0xff) && password_.size() <= std::size_t(0xff));
}
inline derived_t& set_username(std::string v)
{
username_ = std::move(v);
ASIO2_ASSERT(username_.size() <= std::size_t(0xff));
return static_cast<derived_t&>(*this);
}
inline derived_t& set_password(std::string v)
{
password_ = std::move(v);
ASIO2_ASSERT(password_.size() <= std::size_t(0xff));
return static_cast<derived_t&>(*this);
}
inline derived_t& username(std::string v)
{
return this->set_username(std::move(v));
}
inline derived_t& password(std::string v)
{
return this->set_password(std::move(v));
}
inline std::string& username() noexcept { return username_; }
inline std::string& password() noexcept { return password_; }
inline std::string& get_username() noexcept { return username_; }
inline std::string& get_password() noexcept { return password_; }
protected:
std::string username_{};
std::string password_{};
};
template<class T, class = void>
struct has_member_username : std::false_type {};
template<class T>
struct has_member_username<T, std::void_t<decltype(std::declval<std::decay_t<T>>().username())>> : std::true_type {};
template<class T, class = void>
struct has_member_password : std::false_type {};
template<class T>
struct has_member_password<T, std::void_t<decltype(std::declval<std::decay_t<T>>().password())>> : std::true_type {};
}
namespace asio2::socks5
{
struct option_base {};
template<method... ms>
class option : public socks5::option_base, public socks5::detail::method_field<option<ms...>, ms>...
{
protected:
// vs2017 15.9.31 not supported
//std::enable_if_t<((!std::is_base_of_v<socks5::option_base, asio2::detail::remove_cvref_t<Args>>) && ...)
template<class... Args>
constexpr static bool not_options() noexcept
{
return ((!std::is_base_of_v<socks5::option_base, asio2::detail::remove_cvref_t<Args>>) && ...);
}
public:
option() = default;
option(option&&) = default;
option(option const&) = default;
option& operator=(option&&) = default;
option& operator=(option const&) = default;
// constructor sfinae
template<class... Args, std::enable_if_t<not_options<Args...>(), int> = 0>
explicit option(Args&&... args) : option(
std::conditional_t<option<ms...>::has_password_method(),
std::integral_constant<int, asio2::detail::to_underlying(method::password)>,
std::integral_constant<int, asio2::detail::to_underlying(method::anonymous)>>{}
, std::forward<Args>(args)...)
{
}
template<class String1, class String2, std::enable_if_t<
!std::is_base_of_v<socks5::option_base, asio2::detail::remove_cvref_t<String1>> &&
!std::is_base_of_v<socks5::option_base, asio2::detail::remove_cvref_t<String2>>, int> = 0>
explicit option(
std::integral_constant<int, asio2::detail::to_underlying(method::anonymous)>,
String1&& proxy_host, String2&& proxy_port,
socks5::command cmd = socks5::command::connect)
: host_(asio2::detail::to_string(std::forward<String1>(proxy_host)))
, port_(asio2::detail::to_string(std::forward<String2>(proxy_port)))
, cmd_ (cmd)
{
}
template<class String1, class String2, class String3, class String4, std::enable_if_t<
!std::is_base_of_v<socks5::option_base, asio2::detail::remove_cvref_t<String1>> &&
!std::is_base_of_v<socks5::option_base, asio2::detail::remove_cvref_t<String2>> &&
!std::is_base_of_v<socks5::option_base, asio2::detail::remove_cvref_t<String3>> &&
!std::is_base_of_v<socks5::option_base, asio2::detail::remove_cvref_t<String4>>, int> = 0>
explicit option(
std::integral_constant<int, asio2::detail::to_underlying(method::password)>,
String1&& proxy_host, String2&& proxy_port, String3&& username, String4&& password,
socks5::command cmd = socks5::command::connect)
: host_(asio2::detail::to_string(std::forward<String1>(proxy_host)))
, port_(asio2::detail::to_string(std::forward<String2>(proxy_port)))
, cmd_ (cmd)
{
this->username(asio2::detail::to_string(std::forward<String3>(username)));
this->password(asio2::detail::to_string(std::forward<String4>(password)));
}
inline option& set_host(std::string proxy_host)
{
host_ = std::move(proxy_host);
return (*this);
}
template<class StrOrInt>
inline option& set_port(StrOrInt&& proxy_port)
{
port_ = asio2::detail::to_string(std::forward<StrOrInt>(proxy_port));
return (*this);
}
inline option& host(std::string proxy_host)
{
return this->set_host(std::move(proxy_host));
}
template<class StrOrInt>
inline option& port(StrOrInt&& proxy_port)
{
return this->set_port(std::forward<StrOrInt>(proxy_port));
}
inline std::string& host() noexcept { return host_; }
inline std::string& port() noexcept { return port_; }
inline std::string& get_host() noexcept { return host_; }
inline std::string& get_port() noexcept { return port_; }
// vs2017 15.9.31 not supported
//constexpr static bool has_password_method = ((ms == method::password) || ...);
template<typename = void>
constexpr static bool has_password_method() noexcept
{
return ((ms == method::password) || ...);
}
inline std::array<method, sizeof...(ms)> get_methods() noexcept
{
return methods_;
}
inline std::array<method, sizeof...(ms)> methods() noexcept
{
return methods_;
}
constexpr auto get_methods_count() const noexcept
{
return methods_.size();
}
constexpr auto methods_count() const noexcept
{
return methods_.size();
}
inline socks5::command command() noexcept { return cmd_; }
inline socks5::command get_command() noexcept { return cmd_; }
inline option& command(socks5::command cmd) noexcept { cmd_ = cmd; return (*this); }
inline option& set_command(socks5::command cmd) noexcept { cmd_ = cmd; return (*this); }
protected:
std::array<method, sizeof...(ms)> methods_{ ms... };
std::string host_{};
std::string port_{};
socks5::command cmd_{ socks5::command::connect };
};
}
#endif // !__ASIO2_SOCKS5_OPTION_HPP__
<file_sep>#ifndef BHO_MP11_DETAIL_MP_MIN_ELEMENT_HPP_INCLUDED
#define BHO_MP11_DETAIL_MP_MIN_ELEMENT_HPP_INCLUDED
// Copyright 2015-2017 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/mp11/detail/mp_fold.hpp>
#include <asio2/bho/mp11/list.hpp>
#include <asio2/bho/mp11/utility.hpp>
namespace bho
{
namespace mp11
{
// mp_min_element<L, P>
namespace detail
{
template<template<class...> class P> struct select_min
{
template<class T1, class T2> using fn = mp_if<P<T1, T2>, T1, T2>;
};
} // namespace detail
template<class L, template<class...> class P> using mp_min_element = mp_fold_q<mp_rest<L>, mp_first<L>, detail::select_min<P>>;
template<class L, class Q> using mp_min_element_q = mp_min_element<L, Q::template fn>;
// mp_max_element<L, P>
namespace detail
{
template<template<class...> class P> struct select_max
{
template<class T1, class T2> using fn = mp_if<P<T2, T1>, T1, T2>;
};
} // namespace detail
template<class L, template<class...> class P> using mp_max_element = mp_fold_q<mp_rest<L>, mp_first<L>, detail::select_max<P>>;
template<class L, class Q> using mp_max_element_q = mp_max_element<L, Q::template fn>;
} // namespace mp11
} // namespace bho
#endif // #ifndef BHO_MP11_DETAIL_MP_MIN_ELEMENT_HPP_INCLUDED
<file_sep>#include "unit_test.hpp"
#include <iostream>
#include <asio2/external/asio.hpp>
#include <fmt/format.h>
struct userinfo
{
int id;
char name[20];
int8_t age;
};
#ifdef ASIO_STANDALONE
namespace asio
#else
namespace boost::asio
#endif
{
inline asio::const_buffer buffer(const userinfo& u) noexcept
{
return asio::const_buffer(&u, sizeof(userinfo));
}
}
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/tcp/tcp_client.hpp>
static std::string_view chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
void tcp_general_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
{
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
std::atomic<std::size_t> server_recv_size = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
server_recv_size += data.size();
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
// after test, on linux, when disconnect is called, and there has some data
// is transmiting(by async_send), the remote_address maybe empty.
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
ASIO2_CHECK(server.find_session(0) == nullptr);
ASIO2_CHECK(server.find_session_if([](std::shared_ptr<asio2::tcp_session>& session_ptr)
{
return session_ptr->get_remote_port() == 0;
}) == nullptr);
server.foreach_session([](std::shared_ptr<asio2::tcp_session>&) {});
ASIO2_CHECK(server.get_session_count() == 0);
bool server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
asio2::tcp_client client;
// disable auto reconnect, default reconnect option is "enable"
//client.set_auto_reconnect(false);
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(true, std::chrono::milliseconds(2000));
ASIO2_CHECK(client.is_auto_reconnect());
ASIO2_CHECK(client.get_auto_reconnect_delay() == std::chrono::milliseconds(2000));
std::atomic<std::size_t> client_send_size = 0;
std::atomic<std::size_t> client_recv_size = 0;
std::atomic<int> client_init_counter = 0;
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
ASIO2_CHECK(client.get_sndbuf_size() > 0); // just used for test "const function"
ASIO2_CHECK(client.get_rcvbuf_size() > 0); // just used for test "const function"
ASIO2_CHECK(int(client.get_linger().enabled()) != 100); // just used for test "const function"
});
std::atomic<int> client_connect_counter = 0;
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18028);
client_connect_counter++;
const char * p1 = "abc";
char buf[10] = "1234";
char * p2 = buf;
client_send_size += std::strlen(p1);
client.async_send(p1, [p1](std::size_t bytes)
{
ASIO2_CHECK(bytes == 3);
ASIO2_CHECK(bytes == std::strlen(p1));
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += std::strlen(buf);
client.async_send(buf, [buf](std::size_t bytes)
{
ASIO2_CHECK(bytes == 4);
ASIO2_CHECK(bytes == std::strlen(buf));
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += std::strlen(p2);
client.async_send(p2, [p2, buf](std::size_t bytes) mutable
{
p2 = buf;
ASIO2_CHECK(bytes == 4);
ASIO2_CHECK(bytes == std::strlen(p2));
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += std::strlen("<abc>");
client.async_send("<abc>", [](std::size_t bytes)
{
ASIO2_CHECK(bytes == 5);
ASIO2_CHECK(bytes == std::strlen("<abc>"));
ASIO2_CHECK(!asio2::get_last_error());
});
std::string str;
str += '<';
int len = 128 + std::rand() % (300);
for (int i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
str += '>';
client_send_size += str.size();
client.async_send(str);
client_send_size += str.size();
client.async_send(str, [str](std::size_t bytes)
{
ASIO2_CHECK(bytes == str.size());
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += 10;
client.async_send((uint8_t*)"<abcdefghijklmnopqrstovuxyz0123456789>", 10, [](std::size_t bytes)
{
ASIO2_CHECK(bytes == 10);
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += 10;
client.async_send((const uint8_t*)"<abcdefghijklmnopqrstovuxyz0123456789>", 10, [](std::size_t bytes)
{
ASIO2_CHECK(bytes == 10);
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += str.size();
client.async_send(str.data(), int(str.size()));
client_send_size += str.size();
client.async_send(str.data(), []() { ASIO2_CHECK(!asio2::get_last_error()); });
client_send_size += str.size();
client.async_send(str.c_str(), size_t(str.size()));
client_send_size += str.size();
client.async_send(str);
int narys[2] = { 1,2 };
client_send_size += 2 * sizeof(int);
client.async_send(narys);
client_send_size += 2 * sizeof(int);
client.async_send(narys, []() { ASIO2_CHECK(!asio2::get_last_error()); });
client_send_size += 2 * sizeof(int);
client.async_send(narys, [](std::size_t bytes)
{
ASIO2_CHECK(bytes == 2 * sizeof(int));
ASIO2_CHECK(!asio2::get_last_error());
});
std::vector<uint8_t> vec;
len = 128 + std::rand() % (300);
for (int i = 0; i < len; i++)
{
vec.emplace_back((uint8_t)((std::rand() % 255)));
}
client_send_size += vec.size();
client.async_send(vec, [vec](std::size_t bytes)
{
ASIO2_CHECK(bytes == vec.size());
ASIO2_CHECK(!asio2::get_last_error());
});
std::array<uint8_t, 99> ary;
client_send_size += ary.size();
client.async_send(ary, [ary](std::size_t bytes)
{
ASIO2_CHECK(bytes == ary.size());
ASIO2_CHECK(!asio2::get_last_error());
});
const char * msg = "<abcdefghijklmnopqrstovuxyz0123456789>";
asio::const_buffer buffer = asio::buffer(msg);
client_send_size += buffer.size();
client.async_send(buffer, [buffer](std::size_t bytes)
{
ASIO2_CHECK(bytes == buffer.size());
ASIO2_CHECK(!asio2::get_last_error());
});
userinfo u;
u.id = 11;
memset(u.name, 0, sizeof(u.name));
memcpy(u.name, "abc", 3);
u.age = 20;
client_send_size += sizeof(u);
client.async_send(u, [](std::size_t bytes)
{
ASIO2_CHECK(bytes == sizeof(userinfo));
ASIO2_CHECK(!asio2::get_last_error());
});
double scores[5] = { 0.1,0.2,0.3 };
client_send_size += sizeof(double) * 3;
client.async_send(scores, 3, [](std::size_t bytes)
{
ASIO2_CHECK(bytes == sizeof(double) * 3);
ASIO2_CHECK(!asio2::get_last_error());
});
std::size_t sent_bytes;
sent_bytes = client.send(p1);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += std::strlen(p1);
sent_bytes = client.send(buf);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += std::strlen(buf);
sent_bytes = client.send(p2);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += std::strlen(p2);
sent_bytes = client.send("<abcdefghijklmnopqrstovuxyz0123456789>");
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += std::strlen("<abcdefghijklmnopqrstovuxyz0123456789>");
sent_bytes = client.send(str);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += str.size();
sent_bytes = client.send((uint8_t*)"<abcdefghijklmnopqrstovuxyz0123456789>", 10);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += 10;
sent_bytes = client.send((const uint8_t*)"<abcdefghijklmnopqrstovuxyz0123456789>", 10);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += 10;
sent_bytes = client.send(str.data(), int(str.size()));
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += str.size();
sent_bytes = client.send(str.data());
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += str.size();
sent_bytes = client.send(str.c_str(), size_t(str.size()));
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += str.size();
sent_bytes = client.send(str);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += str.size();
sent_bytes = client.send(narys);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += 2 * sizeof(int);
sent_bytes = client.send(vec);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += vec.size();
sent_bytes = client.send(ary);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += ary.size();
sent_bytes = client.send(buffer);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += buffer.size();
sent_bytes = client.send(u);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += sizeof(u);
sent_bytes = client.send(scores, 3);
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
client_send_size += sizeof(double) * 3;
});
std::atomic<int> client_disconnect_counter = 0;
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&](std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(client.is_started());
client_recv_size += data.size();
});
bool client_start_ret = client.start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(client.is_started());
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == 1);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == 1);
// use this to ensure the ASIO2_CHECK(server.get_session_count() == std::size_t(1));
while (server_recv_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK(server.get_session_count() == std::size_t(1));
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == 1);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == 1);
//-----------------------------------------------------------------------------------------
const char * p1 = "defg";
char buf[10] = "123456";
char * p2 = buf;
client_send_size += std::strlen(p1);
client.async_send(p1, [p1](std::size_t bytes)
{
ASIO2_CHECK(bytes == 4);
ASIO2_CHECK(bytes == std::strlen(p1));
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += std::strlen(buf);
client.async_send(buf, [buf](std::size_t bytes)
{
ASIO2_CHECK(bytes == 6);
ASIO2_CHECK(bytes == std::strlen(buf));
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += std::strlen(p2);
client.async_send(p2, [p2](std::size_t bytes)
{
ASIO2_CHECK(bytes == 6);
ASIO2_CHECK(bytes == std::strlen(p2));
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += std::strlen("<123>");
client.async_send("<123>", [](std::size_t bytes)
{
ASIO2_CHECK(bytes == 5);
ASIO2_CHECK(bytes == std::strlen("<123>"));
ASIO2_CHECK(!asio2::get_last_error());
});
std::string str;
str += '<';
int len = 128 + std::rand() % (300);
for (int i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
str += '>';
client_send_size += str.size();
client.async_send(str);
client_send_size += str.size();
client.async_send(str, [str](std::size_t bytes)
{
ASIO2_CHECK(bytes == str.size());
ASIO2_CHECK(!asio2::get_last_error());
});
client_send_size += 10;
client.async_send((uint8_t*)"<abcdefghijklmnopqrstovuxyz0123456789>", 10);
client_send_size += 10;
client.async_send((const uint8_t*)"<abcdefghijklmnopqrstovuxyz0123456789>", 10);
client_send_size += str.size();
client.async_send(str.data(), int(str.size()));
client_send_size += str.size();
client.async_send(str.data(), []() { ASIO2_CHECK(!asio2::get_last_error()); });
client_send_size += str.size();
client.async_send(str.c_str(), size_t(str.size()));
client_send_size += str.size();
client.async_send(str);
int narys[2] = { 1,2 };
client_send_size += 2 * sizeof(int);
client.async_send(narys);
client_send_size += 2 * sizeof(int);
client.async_send(narys, []() { ASIO2_CHECK(!asio2::get_last_error()); });
client_send_size += 2 * sizeof(int);
client.async_send(narys, [](std::size_t bytes)
{
ASIO2_CHECK(bytes == 2 * sizeof(int));
ASIO2_CHECK(!asio2::get_last_error());
});
std::vector<uint8_t> vec;
len = 128 + std::rand() % (300);
for (int i = 0; i < len; i++)
{
vec.emplace_back((uint8_t)((std::rand() % 255)));
}
client_send_size += vec.size();
client.async_send(vec, [vec](std::size_t bytes)
{
ASIO2_CHECK(bytes == vec.size());
ASIO2_CHECK(!asio2::get_last_error());
});
std::array<uint8_t, 99> ary;
client_send_size += ary.size();
client.async_send(ary, [ary](std::size_t bytes)
{
ASIO2_CHECK(bytes == ary.size());
ASIO2_CHECK(!asio2::get_last_error());
});
const char * msg = "<abcdefghijklmnopqrstovuxyz0123456789>";
asio::const_buffer buffer = asio::buffer(msg);
client_send_size += buffer.size();
client.async_send(buffer, [buffer](std::size_t bytes)
{
ASIO2_CHECK(bytes == buffer.size());
ASIO2_CHECK(!asio2::get_last_error());
});
userinfo u;
u.id = 11;
memset(u.name, 0, sizeof(u.name));
memcpy(u.name, "abc", 3);
u.age = 20;
client_send_size += sizeof(u);
client.async_send(u, [](std::size_t bytes)
{
ASIO2_CHECK(bytes == sizeof(userinfo));
ASIO2_CHECK(!asio2::get_last_error());
});
double scores[5] = { 0.1,0.2,0.3 };
client_send_size += sizeof(double) * 3;
client.async_send(scores, 3, [](std::size_t bytes)
{
ASIO2_CHECK(bytes == sizeof(double) * 3);
ASIO2_CHECK(!asio2::get_last_error());
});
std::size_t sent_bytes;
sent_bytes = client.send(p1);
ASIO2_CHECK(sent_bytes == std::strlen(p1));
ASIO2_CHECK(sent_bytes == 4);
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += std::strlen(p1);
sent_bytes = client.send(buf);
ASIO2_CHECK(sent_bytes == std::strlen(buf));
ASIO2_CHECK(sent_bytes == 6);
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += std::strlen(buf);
sent_bytes = client.send(p2);
ASIO2_CHECK(sent_bytes == std::strlen(p2));
ASIO2_CHECK(sent_bytes == 6);
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += std::strlen(p2);
sent_bytes = client.send("<456>");
ASIO2_CHECK(sent_bytes == std::strlen("<456>"));
ASIO2_CHECK(sent_bytes == 5);
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += std::strlen("<456>");
sent_bytes = client.send(str);
ASIO2_CHECK(sent_bytes == str.size());
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += str.size();
sent_bytes = client.send((uint8_t*)"<abcdefghijklmnopqrstovuxyz0123456789>", 10);
ASIO2_CHECK(sent_bytes == 10);
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += 10;
sent_bytes = client.send((const uint8_t*)"<abcdefghijklmnopqrstovuxyz0123456789>", 10);
ASIO2_CHECK(sent_bytes == 10);
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += 10;
sent_bytes = client.send(str.data(), int(str.size()));
ASIO2_CHECK(sent_bytes == str.size());
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += str.size();
sent_bytes = client.send(str.data());
ASIO2_CHECK(sent_bytes == str.size());
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += str.size();
sent_bytes = client.send(str.c_str(), size_t(str.size()));
ASIO2_CHECK(sent_bytes == str.size());
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += str.size();
sent_bytes = client.send(str);
ASIO2_CHECK(sent_bytes == str.size());
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += str.size();
sent_bytes = client.send(narys);
ASIO2_CHECK(sent_bytes == 2 * sizeof(int));
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += 2 * sizeof(int);
sent_bytes = client.send(vec);
ASIO2_CHECK(sent_bytes == vec.size());
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += vec.size();
sent_bytes = client.send(ary);
ASIO2_CHECK(sent_bytes == ary.size());
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += ary.size();
sent_bytes = client.send(buffer);
ASIO2_CHECK(sent_bytes == buffer.size());
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += buffer.size();
sent_bytes = client.send(u);
ASIO2_CHECK(sent_bytes == sizeof(u));
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += sizeof(u);
sent_bytes = client.send(scores, 3);
ASIO2_CHECK(sent_bytes == sizeof(double) * 3);
ASIO2_CHECK(!asio2::get_last_error());
client_send_size += sizeof(double) * 3;
client_send_size += str.size();
client.async_send(str, asio::use_future);
client_send_size += 5;
client.async_send("<789>", asio::use_future);
client_send_size += str.size();
client.async_send(str.data(), asio::use_future);
client_send_size += str.size();
client.async_send(str.data(), str.size(), asio::use_future);
client_send_size += str.size();
client.async_send(str.c_str(), asio::use_future);
client_send_size += str.size();
client.async_send(str.c_str(), str.size(), asio::use_future);
client_send_size += vec.size();
client.async_send(vec, asio::use_future);
client_send_size += ary.size();
client.async_send(ary, asio::use_future);
client_send_size += 2 * sizeof(int);
auto future1 = client.async_send(narys, asio::use_future);
auto[ec1, bytes1] = future1.get();
ASIO2_CHECK(!ec1);
ASIO2_CHECK(bytes1 == 2 * sizeof(int));
client_send_size += 5;
auto future2 = client.async_send("0123456789", 5, asio::use_future);
auto[ec2, bytes2] = future2.get();
ASIO2_CHECK(!ec2);
ASIO2_CHECK(bytes2 == 5);
while (server_recv_size != client_send_size)
{
ASIO2_TEST_WAIT_CHECK();
}
while (server_recv_size != client_recv_size)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK(server_recv_size == client_send_size);
ASIO2_CHECK(server_recv_size == client_recv_size);
client.stop();
ASIO2_CHECK(client.is_stopped());
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == 1);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == 1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
{
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
asio2::tcp_client client;
// disable auto reconnect, default reconnect option is "enable"
//client.set_auto_reconnect(false);
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(true, std::chrono::milliseconds(2000));
std::atomic<int> client_init_counter = 0;
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
std::atomic<int> client_connect_counter = 0;
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18028);
client_connect_counter++;
client.async_send("<abcdefghijklmnopqrstovuxyz0123456789>");
});
std::atomic<int> client_disconnect_counter = 0;
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&](std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(client.is_started());
client.async_send(data);
});
bool client_start_ret = client.start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(client.is_started());
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == 1);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == 1);
std::string str = "[abcdefghijklmnopqrstovuxyz0123456789]";
if (client.is_started())
{
// ## All of the following ways of send operation are correct.
client.async_send(str, [str](std::size_t sent_bytes)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == str.size());
});
client.async_send(str.data(), str.size() / 2, [str](std::size_t sent_bytes)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == str.size() / 2);
});
int intarray[2] = { 1, 2 };
// callback with no params
client.async_send(intarray, [](std::size_t sent_bytes)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == 2 * sizeof(int));
});
// callback with param
client.async_send(intarray, [](std::size_t sent_bytes)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == 2 * sizeof(int));
});
// use future to wait util the send is finished.
std::future<std::pair<asio::error_code, std::size_t>> future =
client.async_send(str, asio::use_future);
auto[ec, bytes] = future.get();
ASIO2_CHECK(!ec);
ASIO2_CHECK(bytes == str.size());
// use asio::buffer to avoid memory allocation, the underlying
// buffer must be persistent, like the static pointer "msg" below
const char * msg = "<abcdefghijklmnopqrstovuxyz0123456789>";
asio::const_buffer buffer = asio::buffer(msg);
client.async_send(buffer, [msg](std::size_t sent_bytes)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == std::strlen(msg));
});
// Example for Synchronous send data. The return value is the sent bytes.
// You can use asio2::get_last_error() to check whether some error occured.
std::size_t sent_bytes = client.send(str);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == str.size());
// ##Example how to send a struct directly:
userinfo u;
u.id = 11;
memset(u.name, 0, sizeof(u.name));
memcpy(u.name, "abc", 3);
u.age = 20;
client.async_send(u, [](std::size_t sent_bytes)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == sizeof(userinfo));
});
// send vector, array, .... and others
std::vector<uint8_t> data{ 1,2,3 };
sent_bytes = client.send(data);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == data.size());
}
// use this to ensure the ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == 1);
while (server_recv_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == 1);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == 1);
client.stop();
ASIO2_CHECK(client.is_stopped());
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == 1);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == 1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
{
asio2::tcp_server server;
std::size_t session_key = std::size_t(std::rand() % test_client_count);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
if (session_key == std::size_t(server_connect_counter.load()))
session_key = session_ptr->hash_key();
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
//client.set_auto_reconnect(false);
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(true, std::chrono::milliseconds(2000));
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18028);
client_connect_counter++;
client.async_send("<abcdefghijklmnopqrstovuxyz0123456789>");
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
});
bool client_start_ret = client.async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
auto session_ptr1 = server.find_session(session_key);
ASIO2_CHECK(session_ptr1 != nullptr);
std::size_t sent_bytes = session_ptr1->send("0123456789");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == std::strlen("0123456789"));
auto session_ptr2 = server.find_session_if([session_key](std::shared_ptr<asio2::tcp_session>& session_ptr)
{
if (session_ptr->hash_key() == session_key)
return true;
return false;
});
ASIO2_CHECK(session_ptr1.get() == session_ptr2.get());
bool find_session_key = false;
server.foreach_session([session_ptr1, session_key, &find_session_key]
(std::shared_ptr<asio2::tcp_session>& session_ptr) mutable
{
if (session_ptr.get() == session_ptr1.get())
{
ASIO2_CHECK(session_key == session_ptr->hash_key());
find_session_key = true;
}
std::size_t sent_bytes = session_ptr->send("0123456789");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == std::strlen("0123456789"));
});
server.async_send(std::string("abcdefxxx0123456"));
server.async_send("abcdefxxx0123456");
server.async_send("abcdefxxx0123456", 10);
ASIO2_CHECK(find_session_key);
session_ptr1.reset();
session_ptr2.reset();
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
server.async_send(std::string("abcdefxxx0123456"));
server.async_send("abcdefxxx0123456");
server.async_send("abcdefxxx0123456", 10);
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
{
asio2::tcp_server server;
std::size_t session_key = std::size_t(std::rand() % test_client_count);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
if (session_key == std::size_t(server_connect_counter.load()))
session_key = session_ptr->hash_key();
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
std::atomic<int> client_recv_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
//client.set_auto_reconnect(false);
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(true, std::chrono::milliseconds(2000));
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18028);
client_connect_counter++;
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
client_recv_counter++;
});
bool client_start_ret = client.async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
server.async_send(std::string("abcdefxxx0123456"));
while (client_recv_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_recv_counter.load(), client_recv_counter >= test_client_count);
client_recv_counter = 0;
server.async_send("abcdefxxx0123456");
while (client_recv_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_recv_counter.load(), client_recv_counter >= test_client_count);
client_recv_counter = 0;
server.async_send("abcdefxxx0123456", 10);
while (client_recv_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_recv_counter.load(), client_recv_counter >= test_client_count);
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
{
struct ext_data
{
int num = 1;
std::string buf;
};
asio2::tcp_server server;
std::size_t session_key = std::size_t(std::rand() % test_client_count);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
ex.buf += data;
while (true)
{
auto pos = ex.buf.find('\n');
if (pos == std::string::npos)
break;
ASIO2_CHECK(ex.buf[5] == ',');
ASIO2_CHECK(std::stoi(ex.buf.substr(0, 5)) == ex.num);
std::string_view frag{ &ex.buf[6], size_t(&ex.buf[pos] - &ex.buf[6]) };
for (int i = 0; i < ex.num; i++)
{
ASIO2_CHECK(frag.size() >= chars.size());
ASIO2_CHECK(std::memcmp(frag.data(), chars.data(), chars.size()) == 0);
frag = frag.substr(chars.size());
}
ex.num++;
ex.buf.erase(0, pos + 1);
}
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
if (session_key == std::size_t(server_connect_counter.load()))
session_key = session_ptr->hash_key();
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
std::atomic<int> client_finish_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
//client.set_auto_reconnect(false);
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(true, std::chrono::milliseconds(2000));
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18028);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
msg += "\n";
client.async_send(std::move(msg));
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
ext_data* ex = client.get_user_data<ext_data*>();
ex->buf += data;
while (true)
{
auto pos = ex->buf.find('\n');
if (pos == std::string::npos)
break;
ASIO2_CHECK(ex->buf[5] == ',');
ASIO2_CHECK(std::stoi(ex->buf.substr(0, 5)) == ex->num);
std::string_view frag{ &ex->buf[6], size_t(&ex->buf[pos] - &ex->buf[6]) };
for (int i = 0; i < ex->num; i++)
{
ASIO2_CHECK(frag.size() >= chars.size());
ASIO2_CHECK(std::memcmp(frag.data(), chars.data(), chars.size()) == 0);
frag = frag.substr(chars.size());
}
if (pos > size_t(6400))
{
client_finish_counter++;
return;
}
ex->num++;
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
msg += "\n";
client.async_send(std::move(msg));
ex->buf.erase(0, pos + 1);
}
});
bool client_start_ret = client.async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (client_finish_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_finish_counter.load(), client_finish_counter == std::size_t(test_client_count));
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
clients[i]->user_data_any().reset();
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
{
asio2::tcp_server server;
std::size_t session_key = std::size_t(std::rand() % test_client_count);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send("abc", [session_ptr](std::size_t sent_bytes)
{
// when the client stopped, the async_send maybe failed.
if (!asio2::get_last_error())
{
// the session_ptr->is_started() maybe false,
//ASIO2_CHECK(session_ptr->is_started());
ASIO2_CHECK(sent_bytes == std::size_t(3));
}
});
std::size_t bytes = session_ptr->send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
if (session_key == std::size_t(server_connect_counter.load()))
session_key = session_ptr->hash_key();
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(true, std::chrono::milliseconds(2000));
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18028);
client_connect_counter++;
client.async_send("abc", [](std::size_t sent_bytes)
{
ASIO2_CHECK(sent_bytes == std::size_t(3));
ASIO2_CHECK(!asio2::get_last_error());
});
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
bool client_start_ret = client.start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
client.async_send("abc", [](std::size_t sent_bytes)
{
ASIO2_CHECK(sent_bytes == std::size_t(3));
ASIO2_CHECK(!asio2::get_last_error());
});
// this sync send will block util all "send" operation is completed, include async_send above,
// and the "send" in the bind_connect function.
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 4);
ASIO2_CHECK(!asio2::get_last_error());
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
{
asio2::tcp_client client;
client.set_auto_reconnect(false);
ASIO2_CHECK(!client.is_auto_reconnect());
std::atomic<int> client_init_counter = 0;
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
std::atomic<int> client_connect_counter = 0;
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error());
client_connect_counter++;
client.async_send(chars, [](std::size_t sent_bytes)
{
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::not_connected);
});
std::size_t sent_bytes = client.send("3abcdefghijklmnopqrxtovwxyz");
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress && sent_bytes == std::size_t(0));
});
std::atomic<int> client_disconnect_counter = 0;
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&](std::string_view data)
{
ASIO2_CHECK(false);
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
bool client_start_ret = client.start("127.0.0.1", 18028);
client.async_send(chars, [](std::size_t sent_bytes)
{
ASIO2_CHECK(sent_bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::not_connected);
});
std::size_t sent_bytes = client.send("3abcdefghijklmnopqrxtovwxyz");
ASIO2_CHECK(asio2::get_last_error() == asio::error::not_connected && sent_bytes == std::size_t(0));
ASIO2_CHECK(!client_start_ret);
ASIO2_CHECK(!client.is_started());
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == 1);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == 1);
//-----------------------------------------------------------------------------------------
client.stop();
ASIO2_CHECK(client.is_stopped());
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == 0);
}
// test auto reconnect
{
struct ext_data
{
int client_init_counter = 0;
int client_connect_counter = 0;
int client_disconnect_counter = 0;
std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now();
};
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
client.set_connect_timeout(std::chrono::milliseconds(100));
client.set_auto_reconnect(true, std::chrono::milliseconds(100));
ASIO2_CHECK(client.is_auto_reconnect());
ASIO2_CHECK(client.get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ASIO2_CHECK(client.get_connect_timeout() == std::chrono::milliseconds(100));
client.bind_init([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error());
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_connect_counter++;
if (ex.client_connect_counter == 1)
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - ex.start_time).count() - 100);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= test_timer_deviation);
}
else
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - ex.start_time).count() - 200);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= test_timer_deviation);
}
ex.start_time = std::chrono::high_resolution_clock::now();
if (ex.client_connect_counter == 3)
{
client.set_auto_reconnect(false);
ASIO2_CHECK(!client.is_auto_reconnect());
}
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
});
client.bind_disconnect([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
ext_data ex;
client.set_user_data(std::move(ex));
bool client_start_ret = client.async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::not_connected);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter , ex.client_init_counter == 3);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 3);
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_disconnect_counter, ex.client_disconnect_counter == 0);
}
//-----------------------------------------------------------------------------------------
for (int i = 0; i < test_client_count; i++)
{
clients[i]->set_auto_reconnect(true);
ASIO2_CHECK(clients[i]->is_auto_reconnect());
ASIO2_CHECK(clients[i]->get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ASIO2_CHECK(clients[i]->get_connect_timeout() == std::chrono::milliseconds(100));
ext_data ex;
clients[i]->set_user_data(std::move(ex));
bool client_start_ret = clients[i]->start("127.0.0.1", 18028);
ASIO2_CHECK(!client_start_ret);
ASIO2_CHECK_VALUE(asio2::last_error_msg().data(),
asio2::get_last_error() == asio::error::timed_out ||
asio2::get_last_error() == asio::error::connection_refused);
std::size_t bytes = clients[i]->send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::not_connected);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter , ex.client_init_counter == 3);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 3);
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_disconnect_counter, ex.client_disconnect_counter == 0);
}
//-----------------------------------------------------------------------------------------
asio2::tcp_server server;
std::size_t session_key = std::size_t(std::rand() % test_client_count);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send("abc", [session_ptr](std::size_t sent_bytes)
{
// when the client stopped, the async_send maybe failed.
if (!asio2::get_last_error())
{
// the session_ptr->is_started() maybe false,
//ASIO2_CHECK(session_ptr->is_started());
ASIO2_CHECK(sent_bytes == std::size_t(3));
}
});
std::size_t bytes = session_ptr->send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
if (session_key == std::size_t(server_connect_counter.load()))
session_key = session_ptr->hash_key();
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->set_auto_reconnect(true);
clients[i]->set_connect_timeout(std::chrono::milliseconds(5000));
ASIO2_CHECK(clients[i]->is_auto_reconnect());
ASIO2_CHECK(clients[i]->get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ASIO2_CHECK(clients[i]->get_connect_timeout() == std::chrono::milliseconds(5000));
asio2::tcp_client& client = *clients[i];
client.bind_init([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_connect_counter++;
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
});
client.bind_disconnect([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
ext_data ex;
clients[i]->set_user_data(std::move(ex));
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter , ex.client_init_counter == 1);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 1);
}
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->user_data_any().has_value());
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test close session
{
asio2::tcp_server server;
std::size_t session_key = std::size_t(std::rand() % test_client_count);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send("abc", [session_ptr](std::size_t sent_bytes)
{
// when the client stopped, the async_send maybe failed.
if (!asio2::get_last_error())
{
// the session_ptr->is_started() maybe false,
//ASIO2_CHECK(session_ptr->is_started());
ASIO2_CHECK(sent_bytes == std::size_t(3));
}
});
std::size_t bytes = session_ptr->send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
if (session_key == std::size_t(server_connect_counter.load()))
{
session_key = session_ptr->hash_key();
session_ptr->set_user_data(session_key);
session_ptr->stop();
}
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18028);
client_connect_counter++;
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
bool client_start_ret = client.start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
}
while (server.get_session_count() < std::size_t(test_client_count - 1))
{
ASIO2_TEST_WAIT_CHECK();
}
while (client_disconnect_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count - 1));
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
// find session maybe true, beacuse the next session maybe used the stopped session "this" address
//ASIO2_CHECK(!server.find_session(session_key));
server.foreach_session([](std::shared_ptr<asio2::tcp_session>& session_ptr) mutable
{
ASIO2_CHECK(!session_ptr->user_data_any().has_value());
});
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == 1);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count - 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count - 1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
session_key = std::size_t(std::rand() % test_client_count);
server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count - 1))
{
ASIO2_TEST_WAIT_CHECK();
}
while (client_disconnect_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == 1);
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count - 1));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.foreach_session([](std::shared_ptr<asio2::tcp_session>& session_ptr) mutable
{
ASIO2_CHECK(!session_ptr->user_data_any().has_value());
});
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count - 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count - 1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test hook_buffer
{
struct ext_data
{
int num = 1;
};
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ext_data& ex = session_ptr->get_user_data<ext_data&>();
while (true)
{
auto pos = data.find('\n');
if (pos != std::string::npos)
{
server_recv_counter++;
std::string_view message = data.substr(0, pos + 1);
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
msg += '\n';
ASIO2_CHECK(msg == message);
ex.num++;
session_ptr->async_send(msg.substr(0, msg.size() / 2));
session_ptr->async_send(msg.substr(msg.size() / 2));
session_ptr->buffer().consume(pos + 1);
data = session_ptr->buffer().data_view();
}
else
{
break;
}
}
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18028, asio2::hook_buffer);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18028);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 20)
{
client.stop();
return;
}
while (true)
{
auto pos = data.find('\n');
if (pos != std::string::npos)
{
std::string_view message = data.substr(0, pos + 1);
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
msg += '\n';
ASIO2_CHECK(msg == message);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
msg += '\n';
client.async_send(msg.substr(0, msg.size() / 2));
client.async_send(msg.substr(msg.size() / 2));
client.buffer().consume(pos + 1);
data = client.buffer().data_view();
}
else
{
break;
}
}
});
bool client_start_ret = client.async_start("127.0.0.1", 18028, asio2::hook_buffer);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
msg += '\n';
clients[i]->async_send(msg.substr(0, msg.size() / 2));
clients[i]->async_send(msg.substr(msg.size() / 2));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18028, asio2::hook_buffer);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18028, asio2::hook_buffer);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
msg += '\n';
clients[i]->async_send(msg.substr(0, msg.size() / 2));
clients[i]->async_send(msg.substr(msg.size() / 2));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test close session in no io_context thread.
{
asio2::tcp_server server;
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
session_ptr->set_user_data(server_connect_counter.load());
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18028);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18028);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18028);
client_connect_counter++;
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
bool client_start_ret = client.start("127.0.0.1", 18028);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
std::vector<std::shared_ptr<asio2::tcp_session>> sessions;
// find session maybe true, beacuse the next session maybe used the stopped session "this" address
//ASIO2_CHECK(!server.find_session(session_key));
server.foreach_session([&sessions](std::shared_ptr<asio2::tcp_session>& session_ptr) mutable
{
ASIO2_CHECK(session_ptr->user_data_any().has_value());
sessions.emplace_back(session_ptr);
});
ASIO2_CHECK_VALUE(sessions.size(), sessions.size() == std::size_t(test_client_count));
for (std::size_t i = 0; i < sessions.size(); i++)
{
std::shared_ptr<asio2::tcp_session>& session = sessions[i];
if (i % 2 == 0)
{
session->stop();
ASIO2_CHECK(session->is_stopped());
}
else
{
session->post([session]()
{
session->stop();
});
ASIO2_CHECK(!session->is_stopped());
}
}
sessions.clear();
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// must call stop, otherwise will cause memory leaks.
for (auto& c : clients)
{
c->stop();
ASIO2_CHECK(c->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"tcp_general",
ASIO2_TEST_CASE(tcp_general_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SESSION_HPP__
#define __ASIO2_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdint>
#include <memory>
#include <chrono>
#include <atomic>
#include <string>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/log.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/session_mgr.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/object.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/base/detail/ecs.hpp>
#include <asio2/base/impl/thread_id_cp.hpp>
#include <asio2/base/impl/connect_time_cp.hpp>
#include <asio2/base/impl/alive_time_cp.hpp>
#include <asio2/base/impl/user_data_cp.hpp>
#include <asio2/base/impl/socket_cp.hpp>
#include <asio2/base/impl/connect_cp.hpp>
#include <asio2/base/impl/shutdown_cp.hpp>
#include <asio2/base/impl/close_cp.hpp>
#include <asio2/base/impl/disconnect_cp.hpp>
#include <asio2/base/impl/user_timer_cp.hpp>
#include <asio2/base/impl/silence_timer_cp.hpp>
#include <asio2/base/impl/post_cp.hpp>
#include <asio2/base/impl/connect_timeout_cp.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
#include <asio2/base/impl/condition_event_cp.hpp>
#include <asio2/base/impl/send_cp.hpp>
#include <asio2/component/rdc/rdc_call_cp.hpp>
namespace asio2
{
class session
{
public:
inline constexpr static bool is_session() noexcept { return true ; }
inline constexpr static bool is_client () noexcept { return false; }
inline constexpr static bool is_server () noexcept { return false; }
};
}
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
template<class derived_t, class args_t>
class session_impl_t
: public asio2::session
, public object_t <derived_t >
, public thread_id_cp <derived_t, args_t>
, public event_queue_cp <derived_t, args_t>
, public user_data_cp <derived_t, args_t>
, public connect_time_cp <derived_t, args_t>
, public alive_time_cp <derived_t, args_t>
, public socket_cp <derived_t, args_t>
, public connect_cp <derived_t, args_t>
, public shutdown_cp <derived_t, args_t>
, public close_cp <derived_t, args_t>
, public disconnect_cp <derived_t, args_t>
, public user_timer_cp <derived_t, args_t>
, public silence_timer_cp <derived_t, args_t>
, public connect_timeout_cp <derived_t, args_t>
, public send_cp <derived_t, args_t>
, public post_cp <derived_t, args_t>
, public condition_event_cp <derived_t, args_t>
, public rdc_call_cp <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
public:
using super = object_t <derived_t >;
using self = session_impl_t<derived_t, args_t>;
using args_type = args_t;
using buffer_type = typename args_t::buffer_t;
using send_cp<derived_t, args_t>::send;
using send_cp<derived_t, args_t>::async_send;
public:
/**
* @brief constructor
* @throws maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
template<class ...Args>
explicit session_impl_t(
session_mgr_t<derived_t> & sessions,
listener_t & listener,
io_t & rwio,
std::size_t init_buf_size,
std::size_t max_buf_size,
Args&&... args
)
: super()
, event_queue_cp <derived_t, args_t>()
, user_data_cp <derived_t, args_t>()
, connect_time_cp <derived_t, args_t>()
, alive_time_cp <derived_t, args_t>()
, socket_cp <derived_t, args_t>(std::forward<Args>(args)...)
, connect_cp <derived_t, args_t>()
, shutdown_cp <derived_t, args_t>()
, close_cp <derived_t, args_t>()
, disconnect_cp <derived_t, args_t>()
, user_timer_cp <derived_t, args_t>()
, silence_timer_cp <derived_t, args_t>(rwio)
, connect_timeout_cp <derived_t, args_t>()
, send_cp <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp <derived_t, args_t>()
, rdc_call_cp <derived_t, args_t>()
, sessions_(sessions)
, listener_(listener)
, io_ (rwio)
, buffer_ (init_buf_size, max_buf_size)
{
}
/**
* @brief destructor
*/
~session_impl_t()
{
// Previously "counter_ptr_.reset()" was in the "stop" function, I don't remember
// why I put "counter_ptr_.reset()" in "stop" function before, but now, i find
// some problem if put "counter_ptr_.reset()" in "stop" function, It looks like
// this:
// when use async rpc user function, when code run to
// "asio::dispatch(caller->io().context(), make_allocator(caller->wallocator(),"
// ( the code is in the rpc_invoker.hpp, line 405 ), the server maybe stopped
// already ( beacuse server.stop will call all session's stop, and session.stop
// will call "counter_ptr_.reset()", so the server's counter_ptr_'s destructor
// can be called, so the iopool.stop can be returned in the server's stop function)
// after the iopool is stopped, the all io_context will be invalid, so when the
// rpc_invoker call "caller->io().context()", it will be crashed.
// destroy the counter
this->counter_ptr_.reset();
}
protected:
/**
* @brief start session
*/
inline void start()
{
this->derived().dispatch([this]() mutable
{
// init the running thread id
this->derived().io().init_thread_id();
// start the timer of check connect timeout
this->derived()._make_connect_timeout_timer(
this->derived().selfptr(), this->connect_timeout_);
});
}
public:
/**
* @brief stop session
* note : this function must be noblocking,if it's blocking,
* will cause circle lock in session_mgr::stop function
*/
inline void stop()
{
ASIO2_ASSERT(this->io_.running_in_this_thread());
// can't use post, we need ensure when the derived stop is called, the chain
// must be executed completed.
this->derived().dispatch([this]() mutable
{
// close silence timer
this->_stop_silence_timer();
// close connect timeout timer
this->_stop_connect_timeout_timer();
// close user custom timers
this->_dispatch_stop_all_timers();
// close all posted timed tasks
this->_dispatch_stop_all_timed_events();
// close all async_events
this->notify_all_condition_events();
// clear recv buffer
this->buffer().consume(this->buffer().size());
// destroy user data, maybe the user data is self shared_ptr,
// if don't destroy it, will cause loop refrence.
// read/write user data in other thread which is not the io_context
// thread maybe cause crash.
this->user_data_.reset();
// destroy the ecs, the user maybe saved the session ptr in the match role init
// function, so we must destroy ecs, otherwise the server will can't be exited
// forever.
this->ecs_.reset();
//
this->reset_life_id();
});
}
/**
* @brief check whether the session is started
*/
inline bool is_started()
{
return (this->state_ == state_t::started && this->socket().is_open());
}
/**
* @brief check whether the session is stopped
*/
inline bool is_stopped()
{
return (this->state_ == state_t::stopped && !this->socket().is_open());
}
/**
* @brief get the buffer object refrence
*/
inline buffer_wrap<buffer_type> & buffer() noexcept
{
return this->buffer_;
}
/**
* @brief get the io object refrence
*/
inline io_t & io() noexcept
{
return this->io_;
}
/**
* @brief set the default remote call timeout for rpc/rdc
*/
template<class Rep, class Period>
inline derived_t & set_default_timeout(std::chrono::duration<Rep, Period> duration) noexcept
{
this->rc_timeout_ = duration;
return (this->derived());
}
/**
* @brief get the default remote call timeout for rpc/rdc
*/
inline std::chrono::steady_clock::duration get_default_timeout() noexcept
{
return this->rc_timeout_;
}
protected:
inline session_mgr_t<derived_t> & sessions() noexcept { return this->sessions_; }
inline listener_t & listener() noexcept { return this->listener_; }
inline std::atomic<state_t> & state () noexcept { return this->state_; }
inline constexpr bool life_id () noexcept { return true; }
inline constexpr void reset_life_id () noexcept { }
protected:
/// asio::strand ,used to ensure socket multi thread safe,we must ensure that only one operator
/// can operate the same socket at the same time,and strand can enuser that the event will
/// be processed in the order of post, eg : strand.post(1);strand.post(2); the 2 will processed
/// certaion after the 1,if 1 is block,the 2 won't be processed,util the 1 is processed completed
/// more details see : http://bbs.csdn.net/topics/390931471
/// session_mgr
session_mgr_t<derived_t> & sessions_;
/// listener
listener_t & listener_;
/// The io_context wrapper used to handle the recv/send event.
io_t & io_;
/// buffer
buffer_wrap<buffer_type> buffer_;
/// use to check whether the user call stop in the listener
std::atomic<state_t> state_ = state_t::stopped;
/// use this to ensure that server stop only after all sessions are closed
std::shared_ptr<void> counter_ptr_;
/// Remote call (rpc/rdc) response timeout.
std::chrono::steady_clock::duration rc_timeout_ = std::chrono::milliseconds(http_execute_timeout);
/// the pointer of ecs_t
std::shared_ptr<ecs_base> ecs_;
/// Whether the async_read... is called.
bool reading_ = false;
#if defined(_DEBUG) || defined(DEBUG)
std::atomic<int> post_send_counter_ = 0;
std::atomic<int> post_recv_counter_ = 0;
#endif
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_SESSION_HPP__
<file_sep>#include <asio2/rpc/rpc_server.hpp>
decltype(std::chrono::steady_clock::now()) time1 = std::chrono::steady_clock::now();
decltype(std::chrono::steady_clock::now()) time2 = std::chrono::steady_clock::now();
std::size_t qps = 0;
bool _first = true;
std::string echo(std::string a)
{
if (_first)
{
_first = false;
time1 = std::chrono::steady_clock::now();
time2 = std::chrono::steady_clock::now();
}
qps++;
decltype(std::chrono::steady_clock::now()) time3 = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time2).count();
if (ms > 1)
{
time2 = time3;
ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time1).count();
double speed = (double)qps / (double)ms;
printf("%.1lf\n", speed);
}
return a;
}
int main()
{
asio2::rpc_kcp_server server;
server.bind("echo", echo);
server.bind_init([&]() {
server.acceptor().set_option(
asio::ip::multicast::enable_loopback()
);
server.acceptor().set_option(
asio::ip::multicast::join_group(asio::ip::make_address("172.16.58.3"))
);
});
server.start("0.0.0.0", "8080");
while (std::getchar() != '\n');
return 0;
}
<file_sep>#include <asio2/mqtt/mqtt_server.hpp>
#include <iostream>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "1883";
asio2::mqtt_server server;
asio2::mqtt_options options;
//mqtt::options options;
server.set_options(options);
server.bind_accept([](std::shared_ptr<asio2::mqtt_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
}).bind_recv([](auto & session_ptr, std::string_view s)
{
asio2::ignore_unused(session_ptr, s);
//printf("recv : %zu %.*s\n", s.size(), (int)s.size(), s.data());
//session_ptr->async_send(std::string(s), [](std::size_t bytes_sent) {});
}).bind_connect([](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([](auto & session_ptr)
{
printf("client leave : %s %u %s\n", session_ptr->remote_address().c_str(),
session_ptr->remote_port(), asio2::last_error_msg().c_str());
}).bind_start([&]()
{
printf("start mqtt server : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
printf("stop : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.on_publish([](std::shared_ptr<asio2::mqtt_session>& session_ptr, mqtt::message& msg, mqtt::message& rep)
{
asio2::ignore_unused(session_ptr, msg, rep);
});
server.on_subscribe(
[](std::shared_ptr<asio2::mqtt_session>& session_ptr, mqtt::message& msg, mqtt::message& rep) mutable
{
asio2::ignore_unused(session_ptr, msg, rep);
mqtt::subscriptions_set* subset = nullptr;
msg.invoke_if<mqtt::v3::subscribe, mqtt::v4::subscribe, mqtt::v5::subscribe>([&subset](auto& msg) mutable
{
// if the msg is v3::subscribe or v4::subscribe or v5::subscribe, then this lambda will
// be called, otherwise this lambda will can't be called
subset = std::addressof(msg.subscriptions());
});
if (subset)
{
rep.invoke_if<mqtt::v3::suback, mqtt::v4::suback, mqtt::v5::suback>([](auto& msg) mutable
{
// if the msg is v3::suback or v4::suback or v5::suback, then this lambda
// will be called, otherwise this lambda will can't be called
msg.reason_codes().clear();
});
}
});
server.start(host, port);
while (std::getchar() != '\n');
return 0;
}
<file_sep>#include <asio2/tcp/tcp_server.hpp>
decltype(std::chrono::steady_clock::now()) time1 = std::chrono::steady_clock::now();
decltype(std::chrono::steady_clock::now()) time2 = std::chrono::steady_clock::now();
std::size_t qps = 0;
bool _first = true;
int main()
{
asio2::tcp_server server;
server.bind_recv([](auto& session_ptr, std::string_view data)
{
if (_first)
{
_first = false;
time1 = std::chrono::steady_clock::now();
time2 = std::chrono::steady_clock::now();
}
qps++;
decltype(std::chrono::steady_clock::now()) time3 = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time2).count();
if (ms > 1)
{
time2 = time3;
ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time1).count();
double speed = (double)qps / (double)ms;
printf("%.1lf\n", speed);
}
session_ptr->async_send(data);
});
server.start("0.0.0.0", "8110", '\n');
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_HANDLER_HPP__
#define __ASIO2_MQTT_HANDLER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/error.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
#include <asio2/mqtt/detail/mqtt_subscription_map.hpp>
#include <asio2/mqtt/detail/mqtt_shared_target.hpp>
#include <asio2/mqtt/detail/mqtt_retained_message.hpp>
#include <asio2/mqtt/detail/mqtt_offline_message.hpp>
#include <asio2/mqtt/aop/aop_auth.hpp>
#include <asio2/mqtt/aop/aop_connack.hpp>
#include <asio2/mqtt/aop/aop_connect.hpp>
#include <asio2/mqtt/aop/aop_disconnect.hpp>
#include <asio2/mqtt/aop/aop_pingreq.hpp>
#include <asio2/mqtt/aop/aop_pingresp.hpp>
#include <asio2/mqtt/aop/aop_puback.hpp>
#include <asio2/mqtt/aop/aop_pubcomp.hpp>
#include <asio2/mqtt/aop/aop_publish.hpp>
#include <asio2/mqtt/aop/aop_pubrec.hpp>
#include <asio2/mqtt/aop/aop_pubrel.hpp>
#include <asio2/mqtt/aop/aop_suback.hpp>
#include <asio2/mqtt/aop/aop_subscribe.hpp>
#include <asio2/mqtt/aop/aop_unsuback.hpp>
#include <asio2/mqtt/aop/aop_unsubscribe.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class caller_t, class args_t>
class mqtt_handler_t
: public mqtt_aop_auth <caller_t, args_t>
, public mqtt_aop_connack <caller_t, args_t>
, public mqtt_aop_connect <caller_t, args_t>
, public mqtt_aop_disconnect <caller_t, args_t>
, public mqtt_aop_pingreq <caller_t, args_t>
, public mqtt_aop_pingresp <caller_t, args_t>
, public mqtt_aop_puback <caller_t, args_t>
, public mqtt_aop_pubcomp <caller_t, args_t>
, public mqtt_aop_publish <caller_t, args_t>
, public mqtt_aop_pubrec <caller_t, args_t>
, public mqtt_aop_pubrel <caller_t, args_t>
, public mqtt_aop_suback <caller_t, args_t>
, public mqtt_aop_subscribe <caller_t, args_t>
, public mqtt_aop_unsuback <caller_t, args_t>
, public mqtt_aop_unsubscribe<caller_t, args_t>
{
friend caller_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
protected:
using mqtt_aop_auth <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_connack <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_connect <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_disconnect <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_pingreq <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_pingresp <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_puback <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_pubcomp <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_publish <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_pubrec <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_pubrel <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_suback <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_subscribe <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_unsuback <caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_unsubscribe<caller_t, args_t>::_before_user_callback_impl;
using mqtt_aop_auth <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_connack <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_connect <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_disconnect <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_pingreq <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_pingresp <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_puback <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_pubcomp <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_publish <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_pubrec <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_pubrel <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_suback <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_subscribe <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_unsuback <caller_t, args_t>::_after_user_callback_impl;
using mqtt_aop_unsubscribe<caller_t, args_t>::_after_user_callback_impl;
template<class Message>
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
ASIO2_ASSERT(false);
}
template<class Message>
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
ASIO2_ASSERT(false);
}
template<class Message, class Response>
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
ASIO2_ASSERT(false);
}
template<class Message, class Response>
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
ASIO2_ASSERT(false);
}
template<class Message>
inline void _before_user_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
if constexpr (std::is_same_v<message_type, mqtt::message>)
{
std::visit([&ec, &caller_ptr, &caller, &om](auto& pm) mutable
{
caller->_before_user_callback_impl(ec, caller_ptr, caller, om, pm);
}, msg.variant());
}
else
{
caller->_before_user_callback_impl(ec, caller_ptr, caller, om, msg);
}
}
template<class Message>
inline void _after_user_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
if constexpr (std::is_same_v<message_type, mqtt::message>)
{
std::visit([&ec, &caller_ptr, &caller, &om](auto& pm) mutable
{
caller->_after_user_callback_impl(ec, caller_ptr, caller, om, pm);
}, msg.variant());
}
else
{
caller->_after_user_callback_impl(ec, caller_ptr, caller, om, msg);
}
}
template<class Message, class Response>
inline void _before_user_callback_with_message(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if constexpr (std::is_same_v<response_type, mqtt::message>)
{
if (!rep.empty())
{
std::visit([&ec, &caller_ptr, &caller, &om, &rep](auto& pm) mutable
{
std::visit([&ec, &caller_ptr, &caller, &om, &pm](auto& pr) mutable
{
caller->_before_user_callback_impl(ec, caller_ptr, caller, om, pm, pr);
}, rep.variant());
}, msg.variant());
}
}
else
{
std::visit([&ec, &caller_ptr, &caller, &om, &rep](auto& pm) mutable
{
caller->_before_user_callback_impl(ec, caller_ptr, caller, om, pm, rep);
}, msg.variant());
}
}
template<class Message, class Response>
inline void _before_user_callback_with_packet(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if constexpr (std::is_same_v<response_type, mqtt::message>)
{
if (!rep.empty())
{
std::visit([&ec, &caller_ptr, &caller, &om, &msg](auto& pr) mutable
{
caller->_before_user_callback_impl(ec, caller_ptr, caller, om, msg, pr);
}, rep.variant());
}
}
else
{
caller->_before_user_callback_impl(ec, caller_ptr, caller, om, msg, rep);
}
}
template<class Message, class Response>
inline void _before_user_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg, Response& rep)
{
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if constexpr (std::is_same_v<message_type, mqtt::message>)
{
this->_before_user_callback_with_message(ec, caller_ptr, caller, om, msg, rep);
}
else
{
this->_before_user_callback_with_packet(ec, caller_ptr, caller, om, msg, rep);
}
}
template<class Message, class Response>
inline void _after_user_callback_with_message(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if constexpr (std::is_same_v<response_type, mqtt::message>)
{
if (!rep.empty())
{
std::visit([&ec, &caller_ptr, &caller, &om, &rep](auto& pm) mutable
{
std::visit([&ec, &caller_ptr, &caller, &om, &pm](auto& pr) mutable
{
caller->_after_user_callback_impl(ec, caller_ptr, caller, om, pm, pr);
}, rep.variant());
}, msg.variant());
}
}
else
{
std::visit([&ec, &caller_ptr, &caller, &om, &rep](auto& pm) mutable
{
caller->_after_user_callback_impl(ec, caller_ptr, caller, om, pm, rep);
}, msg.variant());
}
}
template<class Message, class Response>
inline void _after_user_callback_with_packet(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if constexpr (std::is_same_v<response_type, mqtt::message>)
{
if (!rep.empty())
{
std::visit([&ec, &caller_ptr, &caller, &om, &msg](auto& pr) mutable
{
caller->_after_user_callback_impl(ec, caller_ptr, caller, om, msg, pr);
}, rep.variant());
}
}
else
{
caller->_after_user_callback_impl(ec, caller_ptr, caller, om, msg, rep);
}
}
template<class Message, class Response>
inline void _after_user_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om, Message& msg, Response& rep)
{
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
if constexpr (std::is_same_v<message_type, mqtt::message>)
{
this->_after_user_callback_with_message(ec, caller_ptr, caller, om, msg, rep);
}
else
{
this->_after_user_callback_with_packet(ec, caller_ptr, caller, om, msg, rep);
}
}
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_MQTT_HANDLER_HPP__
<file_sep>// Copyright Nuxi, https://nuxi.nl/ 2015.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#define BHO_PLATFORM "CloudABI"
#define BHO_HAS_DIRENT_H
#define BHO_HAS_STDINT_H
#define BHO_HAS_UNISTD_H
#define BHO_HAS_CLOCK_GETTIME
#define BHO_HAS_EXPM1
#define BHO_HAS_GETTIMEOFDAY
#define BHO_HAS_LOG1P
#define BHO_HAS_NANOSLEEP
#define BHO_HAS_PTHREADS
#define BHO_HAS_SCHED_YIELD
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL> dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_HPP
#define BHO_BEAST_HPP
#include <asio2/bho/beast/core/detail/config.hpp> // must come first
#include <asio2/bho/beast/core.hpp>
#include <asio2/bho/beast/http.hpp>
#include <asio2/bho/beast/version.hpp>
#include <asio2/bho/beast/websocket.hpp>
#include <asio2/bho/beast/zlib.hpp>
#endif
<file_sep>/*
Copyright <NAME> 2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_WORKAROUND_H
#define BHO_PREDEF_WORKAROUND_H
/* tag::reference[]
= `BHO_PREDEF_WORKAROUND`
[source]
----
BHO_PREDEF_WORKAROUND(symbol,comp,major,minor,patch)
----
Usage:
[source]
----
#if BHO_PREDEF_WORKAROUND(BHO_COMP_CLANG,<,3,0,0)
// Workaround for old clang compilers..
#endif
----
Defines a comparison against two version numbers that depends on the definion
of `BHO_STRICT_CONFIG`. When `BHO_STRICT_CONFIG` is defined this will expand
to a value convertible to `false`. Which has the effect of disabling all code
conditionally guarded by `BHO_PREDEF_WORKAROUND`. When `BHO_STRICT_CONFIG`
is undefine this expand to test the given `symbol` version value with the
`comp` comparison against `BHO_VERSION_NUMBER(major,minor,patch)`.
*/ // end::reference[]
#ifdef BHO_STRICT_CONFIG
# define BHO_PREDEF_WORKAROUND(symbol, comp, major, minor, patch) (0)
#else
# include <asio2/bho/predef/version_number.h>
# define BHO_PREDEF_WORKAROUND(symbol, comp, major, minor, patch) \
( (symbol) != (0) ) && \
( (symbol) comp (BHO_VERSION_NUMBER( (major) , (minor) , (patch) )) )
#endif
/* tag::reference[]
= `BHO_PREDEF_TESTED_AT`
[source]
----
BHO_PREDEF_TESTED_AT(symbol,major,minor,patch)
----
Usage:
[source]
----
#if BHO_PREDEF_TESTED_AT(BHO_COMP_CLANG,3,5,0)
// Needed for clang, and last checked for 3.5.0.
#endif
----
Defines a comparison against two version numbers that depends on the definion
of `BHO_STRICT_CONFIG` and `BHO_DETECT_OUTDATED_WORKAROUNDS`.
When `BHO_STRICT_CONFIG` is defined this will expand to a value convertible
to `false`. Which has the effect of disabling all code
conditionally guarded by `BHO_PREDEF_TESTED_AT`. When `BHO_STRICT_CONFIG`
is undefined this expand to either:
* A value convertible to `true` when `BHO_DETECT_OUTDATED_WORKAROUNDS` is not
defined.
* A value convertible `true` when the expansion of
`BHO_PREDEF_WORKAROUND(symbol, <=, major, minor, patch)` is `true` and
`BHO_DETECT_OUTDATED_WORKAROUNDS` is defined.
* A compile error when the expansion of
`BHO_PREDEF_WORKAROUND(symbol, >, major, minor, patch)` is true and
`BHO_DETECT_OUTDATED_WORKAROUNDS` is defined.
*/ // end::reference[]
#ifdef BHO_STRICT_CONFIG
# define BHO_PREDEF_TESTED_AT(symbol, major, minor, patch) (0)
#else
# ifdef BHO_DETECT_OUTDATED_WORKAROUNDS
# define BHO_PREDEF_TESTED_AT(symbol, major, minor, patch) ( \
BHO_PREDEF_WORKAROUND(symbol, <=, major, minor, patch) \
? 1 \
: (1%0) )
# else
# define BHO_PREDEF_TESTED_AT(symbol, major, minor, patch) \
( (symbol) >= BHO_VERSION_NUMBER_AVAILABLE )
# endif
#endif
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SOCKET_COMPONENT_HPP__
#define __ASIO2_SOCKET_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <string>
#include <asio2/external/asio.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class socket_cp
{
public:
using socket_type = std::remove_cv_t<std::remove_reference_t<typename args_t::socket_t>>;
/**
* @brief constructor
* @throws maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
template<class ...Args>
explicit socket_cp(Args&&... args) : socket_(std::forward<Args>(args)...)
{
}
/**
* @brief destructor
*/
~socket_cp() = default;
public:
/**
* @brief get the socket object refrence
*/
inline socket_type & socket() noexcept
{
return this->socket_;
}
/**
* @brief get the socket object refrence
*/
inline const socket_type & socket() const noexcept
{
return this->socket_;
}
/**
* @brief get the stream object refrence
*/
inline socket_type & stream() noexcept
{
return this->socket_;
}
/**
* @brief get the stream object refrence
*/
inline const socket_type & stream() const noexcept
{
return this->socket_;
}
/**
* @brief get the local address, same as get_local_address
*/
inline std::string local_address() noexcept
{
return this->get_local_address();
}
/**
* @brief get the local address
*/
inline std::string get_local_address() noexcept
{
clear_last_error();
try
{
return this->socket_.lowest_layer().local_endpoint().address().to_string();
}
catch (const system_error& e)
{
set_last_error(e);
}
return std::string();
}
/**
* @brief get the local port, same as get_local_port
*/
inline unsigned short local_port() noexcept
{
return this->get_local_port();
}
/**
* @brief get the local port
*/
inline unsigned short get_local_port() noexcept
{
return this->socket_.lowest_layer().local_endpoint(get_last_error()).port();
}
/**
* @brief get the remote address, same as get_remote_address
*/
inline std::string remote_address() noexcept
{
return this->get_remote_address();
}
/**
* @brief get the remote address
*/
inline std::string get_remote_address() noexcept
{
clear_last_error();
error_code ec{};
try
{
return this->socket_.lowest_layer().remote_endpoint().address().to_string();
}
catch (const system_error& e)
{
ec = e.code();
}
try
{
asio::ip::address addr = this->remote_endpoint_copy_.address();
if (!addr.is_unspecified())
{
return addr.to_string();
}
}
catch (const system_error&)
{
}
set_last_error(ec);
return std::string();
}
/**
* @brief get the remote port, same as get_remote_port
*/
inline unsigned short remote_port() noexcept
{
return this->get_remote_port();
}
/**
* @brief get the remote port
*/
inline unsigned short get_remote_port() noexcept
{
clear_last_error();
error_code ec{};
try
{
return this->socket_.lowest_layer().remote_endpoint().port();
}
catch (const system_error& e)
{
ec = e.code();
}
try
{
return this->remote_endpoint_copy_.port();
}
catch (const system_error&)
{
}
set_last_error(ec);
return 0;
}
public:
/**
* @brief Implements the SOL_SOCKET/SO_SNDBUF socket option.
*/
inline derived_t& set_sndbuf_size(int val) noexcept
{
this->socket_.lowest_layer().set_option(asio::socket_base::send_buffer_size(val), get_last_error());
return (static_cast<derived_t&>(*this));
}
/**
* @brief Implements the SOL_SOCKET/SO_SNDBUF socket option.
*/
inline int get_sndbuf_size() const noexcept
{
asio::socket_base::send_buffer_size option{};
this->socket_.lowest_layer().get_option(option, get_last_error());
return option.value();
}
/**
* @brief Implements the SOL_SOCKET/SO_RCVBUF socket option.
*/
inline derived_t& set_rcvbuf_size(int val) noexcept
{
this->socket_.lowest_layer().set_option(asio::socket_base::receive_buffer_size(val), get_last_error());
return (static_cast<derived_t&>(*this));
}
/**
* @brief Implements the SOL_SOCKET/SO_RCVBUF socket option.
*/
inline int get_rcvbuf_size() const noexcept
{
asio::socket_base::receive_buffer_size option{};
this->socket_.lowest_layer().get_option(option, get_last_error());
return option.value();
}
/**
* @brief Implements the SOL_SOCKET/SO_KEEPALIVE socket option. same as set_keep_alive
*/
inline derived_t & keep_alive(bool val) noexcept
{
return this->set_keep_alive(val);
}
/**
* @brief Implements the SOL_SOCKET/SO_KEEPALIVE socket option.
*/
inline derived_t& set_keep_alive(bool val) noexcept
{
this->socket_.lowest_layer().set_option(asio::socket_base::keep_alive(val), get_last_error());
return (static_cast<derived_t&>(*this));
}
/**
* @brief Implements the SOL_SOCKET/SO_KEEPALIVE socket option.
*/
inline bool is_keep_alive() const noexcept
{
asio::socket_base::keep_alive option{};
this->socket_.lowest_layer().get_option(option, get_last_error());
return option.value();
}
/**
* @brief Implements the SOL_SOCKET/SO_REUSEADDR socket option. same as set_reuse_address
*/
inline derived_t & reuse_address(bool val) noexcept
{
return this->set_reuse_address(val);
}
/**
* @brief Implements the SOL_SOCKET/SO_REUSEADDR socket option.
*/
inline derived_t& set_reuse_address(bool val) noexcept
{
this->socket_.lowest_layer().set_option(asio::socket_base::reuse_address(val), get_last_error());
return (static_cast<derived_t&>(*this));
}
/**
* @brief Implements the SOL_SOCKET/SO_REUSEADDR socket option.
*/
inline bool is_reuse_address() const noexcept
{
asio::socket_base::reuse_address option{};
this->socket_.lowest_layer().get_option(option, get_last_error());
return option.value();
}
/**
* @brief Implements the TCP_NODELAY socket option. same as set_no_delay.
* If it's not a tcp socket, do nothing
*/
inline derived_t & no_delay(bool val) noexcept
{
return this->set_no_delay(val);
}
/**
* @brief Implements the TCP_NODELAY socket option.
* If it's not a tcp socket, do nothing
*/
inline derived_t& set_no_delay(bool val) noexcept
{
this->socket_.lowest_layer().set_option(asio::ip::tcp::no_delay(val), get_last_error());
return (static_cast<derived_t&>(*this));
}
/**
* @brief Implements the TCP_NODELAY socket option.
*/
inline bool is_no_delay() const noexcept
{
asio::ip::tcp::no_delay option{};
this->socket_.lowest_layer().get_option(option, get_last_error());
return option.value();
}
/**
* @brief Implements the SO_LINGER socket option.
* set_linger(true, 0) - RST will be sent instead of FIN/ACK/FIN/ACK
* @param enable - option on/off
* @param timeout - linger time
*/
inline derived_t& set_linger(bool enable, int timeout) noexcept
{
this->socket_.lowest_layer().set_option(asio::socket_base::linger(enable, timeout), get_last_error());
return (static_cast<derived_t&>(*this));
}
/**
* @brief Get the SO_LINGER socket option.
*/
inline asio::socket_base::linger get_linger() const noexcept
{
asio::socket_base::linger option{};
this->socket_.lowest_layer().get_option(option, get_last_error());
return option;
}
protected:
/// socket
typename args_t::socket_t socket_;
/// the call of remote_endpoint() maybe failed when the remote socket is closed,
/// even if local socket is not closed, so we use this variable to ensure the
/// call of remote_endpoint() must be successed.
typename socket_type::endpoint_type remote_endpoint_copy_;
};
}
#endif // !__ASIO2_SOCKET_COMPONENT_HPP__
<file_sep>// scoped_enum.hpp ---------------------------------------------------------//
// Copyright <NAME>, 2009
// Copyright (C) 2011-2012 <NAME>
// Copyright (C) 2012 <NAME>
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
#ifndef BHO_CORE_SCOPED_ENUM_HPP
#define BHO_CORE_SCOPED_ENUM_HPP
#include <asio2/bho/config.hpp>
#ifdef BHO_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace bho
{
#ifdef BHO_NO_CXX11_SCOPED_ENUMS
/**
* Meta-function to get the native enum type associated to an enum class or its emulation.
*/
template <typename EnumType>
struct native_type
{
/**
* The member typedef type names the native enum type associated to the scoped enum,
* which is it self if the compiler supports scoped enums or EnumType::enum_type if it is an emulated scoped enum.
*/
typedef typename EnumType::enum_type type;
};
/**
* Casts a scoped enum to its underlying type.
*
* This function is useful when working with scoped enum classes, which doens't implicitly convert to the underlying type.
* @param v A scoped enum.
* @returns The underlying type.
* @throws No-throws.
*/
template <typename UnderlyingType, typename EnumType>
inline
BHO_CONSTEXPR UnderlyingType underlying_cast(EnumType v) BHO_NOEXCEPT
{
return v.get_underlying_value_();
}
/**
* Casts a scoped enum to its native enum type.
*
* This function is useful to make programs portable when the scoped enum emulation can not be use where native enums can.
*
* EnumType the scoped enum type
*
* @param v A scoped enum.
* @returns The native enum value.
* @throws No-throws.
*/
template <typename EnumType>
inline
BHO_CONSTEXPR typename EnumType::enum_type native_value(EnumType e) BHO_NOEXCEPT
{
return e.get_native_value_();
}
#else // BHO_NO_CXX11_SCOPED_ENUMS
template <typename EnumType>
struct native_type
{
typedef EnumType type;
};
template <typename UnderlyingType, typename EnumType>
inline
BHO_CONSTEXPR UnderlyingType underlying_cast(EnumType v) BHO_NOEXCEPT
{
return static_cast<UnderlyingType>(v);
}
template <typename EnumType>
inline
BHO_CONSTEXPR EnumType native_value(EnumType e) BHO_NOEXCEPT
{
return e;
}
#endif // BHO_NO_CXX11_SCOPED_ENUMS
}
#ifdef BHO_NO_CXX11_SCOPED_ENUMS
#ifndef BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#define BHO_SCOPED_ENUM_UT_DECLARE_CONVERSION_OPERATOR \
explicit BHO_CONSTEXPR operator underlying_type() const BHO_NOEXCEPT { return get_underlying_value_(); }
#else
#define BHO_SCOPED_ENUM_UT_DECLARE_CONVERSION_OPERATOR
#endif
/**
* Start a declaration of a scoped enum.
*
* @param EnumType The new scoped enum.
* @param UnderlyingType The underlying type.
*/
#define BHO_SCOPED_ENUM_UT_DECLARE_BEGIN(EnumType, UnderlyingType) \
struct EnumType { \
typedef void is_bho_scoped_enum_tag; \
typedef UnderlyingType underlying_type; \
EnumType() BHO_NOEXCEPT {} \
explicit BHO_CONSTEXPR EnumType(underlying_type v) BHO_NOEXCEPT : v_(v) {} \
BHO_CONSTEXPR underlying_type get_underlying_value_() const BHO_NOEXCEPT { return v_; } \
BHO_SCOPED_ENUM_UT_DECLARE_CONVERSION_OPERATOR \
private: \
underlying_type v_; \
typedef EnumType self_type; \
public: \
enum enum_type
#define BHO_SCOPED_ENUM_DECLARE_END2() \
BHO_CONSTEXPR enum_type get_native_value_() const BHO_NOEXCEPT { return enum_type(v_); } \
friend BHO_CONSTEXPR bool operator ==(self_type lhs, self_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)==enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator ==(self_type lhs, enum_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)==rhs; } \
friend BHO_CONSTEXPR bool operator ==(enum_type lhs, self_type rhs) BHO_NOEXCEPT { return lhs==enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator !=(self_type lhs, self_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)!=enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator !=(self_type lhs, enum_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)!=rhs; } \
friend BHO_CONSTEXPR bool operator !=(enum_type lhs, self_type rhs) BHO_NOEXCEPT { return lhs!=enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator <(self_type lhs, self_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)<enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator <(self_type lhs, enum_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)<rhs; } \
friend BHO_CONSTEXPR bool operator <(enum_type lhs, self_type rhs) BHO_NOEXCEPT { return lhs<enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator <=(self_type lhs, self_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)<=enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator <=(self_type lhs, enum_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)<=rhs; } \
friend BHO_CONSTEXPR bool operator <=(enum_type lhs, self_type rhs) BHO_NOEXCEPT { return lhs<=enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator >(self_type lhs, self_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)>enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator >(self_type lhs, enum_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)>rhs; } \
friend BHO_CONSTEXPR bool operator >(enum_type lhs, self_type rhs) BHO_NOEXCEPT { return lhs>enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator >=(self_type lhs, self_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)>=enum_type(rhs.v_); } \
friend BHO_CONSTEXPR bool operator >=(self_type lhs, enum_type rhs) BHO_NOEXCEPT { return enum_type(lhs.v_)>=rhs; } \
friend BHO_CONSTEXPR bool operator >=(enum_type lhs, self_type rhs) BHO_NOEXCEPT { return lhs>=enum_type(rhs.v_); } \
};
#define BHO_SCOPED_ENUM_DECLARE_END(EnumType) \
; \
BHO_CONSTEXPR EnumType(enum_type v) BHO_NOEXCEPT : v_(v) {} \
BHO_SCOPED_ENUM_DECLARE_END2()
/**
* Starts a declaration of a scoped enum with the default int underlying type.
*
* @param EnumType The new scoped enum.
*/
#define BHO_SCOPED_ENUM_DECLARE_BEGIN(EnumType) \
BHO_SCOPED_ENUM_UT_DECLARE_BEGIN(EnumType,int)
/**
* Name of the native enum type.
*
* @param EnumType The new scoped enum.
*/
#define BHO_SCOPED_ENUM_NATIVE(EnumType) EnumType::enum_type
/**
* Forward declares an scoped enum.
*
* @param EnumType The scoped enum.
*/
#define BHO_SCOPED_ENUM_FORWARD_DECLARE(EnumType) struct EnumType
#else // BHO_NO_CXX11_SCOPED_ENUMS
#define BHO_SCOPED_ENUM_UT_DECLARE_BEGIN(EnumType,UnderlyingType) enum class EnumType : UnderlyingType
#define BHO_SCOPED_ENUM_DECLARE_BEGIN(EnumType) enum class EnumType
#define BHO_SCOPED_ENUM_DECLARE_END2()
#define BHO_SCOPED_ENUM_DECLARE_END(EnumType) ;
#define BHO_SCOPED_ENUM_NATIVE(EnumType) EnumType
#define BHO_SCOPED_ENUM_FORWARD_DECLARE(EnumType) enum class EnumType
#endif // BHO_NO_CXX11_SCOPED_ENUMS
// Deprecated macros
#define BHO_SCOPED_ENUM_START(name) BHO_SCOPED_ENUM_DECLARE_BEGIN(name)
#define BHO_SCOPED_ENUM_END BHO_SCOPED_ENUM_DECLARE_END2()
#define BHO_SCOPED_ENUM(name) BHO_SCOPED_ENUM_NATIVE(name)
#endif // BHO_CORE_SCOPED_ENUM_HPP
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_USER_DATA_COMPONENT_HPP__
#define __ASIO2_USER_DATA_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <any>
#include <asio2/base/error.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t = void>
class user_data_cp
{
public:
/**
* @brief constructor
*/
user_data_cp() = default;
/**
* @brief destructor
*/
~user_data_cp() = default;
user_data_cp(user_data_cp&&) noexcept = default;
user_data_cp(user_data_cp const&) = default;
user_data_cp& operator=(user_data_cp&&) noexcept = default;
user_data_cp& operator=(user_data_cp const&) = default;
public:
/**
* @brief set user data, internal use std::any to storage, you can set any type of data
* same as set_user_data
*/
template<class DataT>
[[deprecated("Replace user_data with set_user_data")]]
inline derived_t & user_data(DataT && data)
{
return this->set_user_data(std::forward<DataT>(data));
}
/**
* @brief get user data, same as get_user_data
* example : MyStruct my = user_data<MyStruct>(); MyStruct* my = user_data<MyStruct*>();
*/
template<class DataT>
[[deprecated("Replace user_data with get_user_data")]]
inline DataT user_data() noexcept
{
return this->get_user_data<DataT>();
}
/**
* @brief set user data, internal use std::any to storage, you can set any type of data
* example : struct MyStruct{ ... }; MyStruct my; set_user_data(my);
*/
template<class DataT>
inline derived_t & set_user_data(DataT && data)
{
this->user_data_ = std::forward<DataT>(data);
return (static_cast<derived_t &>(*this));
}
/**
* @brief get user data
* example :
* MyStruct my = get_user_data<MyStruct>();
* MyStruct* my = get_user_data<MyStruct*>();
* MyStruct& my = get_user_data<MyStruct&>();
*/
template<class DataT>
inline DataT get_user_data() noexcept
{
if constexpr (std::is_reference_v<DataT>)
{
typename std::add_pointer_t<std::remove_reference_t<DataT>> r =
std::any_cast<std::remove_reference_t<DataT>>(std::addressof(this->user_data_));
if (r)
{
return (*r);
}
else
{
static typename std::remove_reference_t<DataT> st{};
return st;
}
}
else if constexpr (std::is_pointer_v<DataT>)
{
// user_data_ is pointer, and DataT is pointer too.
if (this->user_data_.type() == typeid(DataT))
return std::any_cast<DataT>(this->user_data_);
// user_data_ is not pointer, but DataT is pointer.
return std::any_cast<std::remove_pointer_t<DataT>>(std::addressof(this->user_data_));
}
else
{
try
{
return std::any_cast<DataT>(this->user_data_);
}
catch (const std::bad_any_cast&)
{
if (this->user_data_.has_value())
{
ASIO2_ASSERT(false);
}
}
return DataT{};
}
}
/**
* @brief return the std::any reference
*/
inline std::any& user_data_any() noexcept { return this->user_data_; }
protected:
/// user data
std::any user_data_;
};
}
#endif // !__ASIO2_USER_DATA_COMPONENT_HPP__
<file_sep>/*
Copyright <NAME> 2012-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_BSD_NET_H
#define BHO_PREDEF_OS_BSD_NET_H
#include <asio2/bho/predef/os/bsd.h>
/* tag::reference[]
= `BHO_OS_BSD_NET`
http://en.wikipedia.org/wiki/Netbsd[NetBSD] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__NETBSD__+` | {predef_detection}
| `+__NetBSD__+` | {predef_detection}
| `+__NETBSD_version+` | V.R.P
| `NetBSD0_8` | 0.8.0
| `NetBSD0_9` | 0.9.0
| `NetBSD1_0` | 1.0.0
| `+__NetBSD_Version+` | V.R.P
|===
*/ // end::reference[]
#define BHO_OS_BSD_NET BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__NETBSD__) || defined(__NetBSD__) \
)
# ifndef BHO_OS_BSD_AVAILABLE
# undef BHO_OS_BSD
# define BHO_OS_BSD BHO_VERSION_NUMBER_AVAILABLE
# define BHO_OS_BSD_AVAILABLE
# endif
# undef BHO_OS_BSD_NET
# if defined(__NETBSD__)
# if defined(__NETBSD_version)
# if __NETBSD_version < 500000
# define BHO_OS_BSD_NET \
BHO_PREDEF_MAKE_10_VRP000(__NETBSD_version)
# else
# define BHO_OS_BSD_NET \
BHO_PREDEF_MAKE_10_VRR000(__NETBSD_version)
# endif
# else
# define BHO_OS_BSD_NET BHO_VERSION_NUMBER_AVAILABLE
# endif
# elif defined(__NetBSD__)
# if !defined(BHO_OS_BSD_NET) && defined(NetBSD0_8)
# define BHO_OS_BSD_NET BHO_VERSION_NUMBER(0,8,0)
# endif
# if !defined(BHO_OS_BSD_NET) && defined(NetBSD0_9)
# define BHO_OS_BSD_NET BHO_VERSION_NUMBER(0,9,0)
# endif
# if !defined(BHO_OS_BSD_NET) && defined(NetBSD1_0)
# define BHO_OS_BSD_NET BHO_VERSION_NUMBER(1,0,0)
# endif
# if !defined(BHO_OS_BSD_NET) && defined(__NetBSD_Version)
# define BHO_OS_BSD_NET \
BHO_PREDEF_MAKE_10_VVRR00PP00(__NetBSD_Version)
# endif
# if !defined(BHO_OS_BSD_NET)
# define BHO_OS_BSD_NET BHO_VERSION_NUMBER_AVAILABLE
# endif
# endif
#endif
#if BHO_OS_BSD_NET
# define BHO_OS_BSD_NET_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_BSD_NET_NAME "NetBSD"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_BSD_NET,BHO_OS_BSD_NET_NAME)
<file_sep>#include <asio2/rpc/rpc_client.hpp>
std::string strmsg(128, 'A');
std::function<void()> sender;
int main()
{
asio2::rpc_kcp_client client;
sender = [&]()
{
client.async_call([](std::string)
{
if (!asio2::get_last_error())
sender();
}, "echo", strmsg);
};
client.bind_init([&]() {
client.socket().set_option(
asio::ip::multicast::enable_loopback()
);
client.socket().set_option(
asio::ip::multicast::join_group(asio::ip::make_address("192.168.3.11"))
);
})
.bind_connect([&]()
{
if (!asio2::get_last_error())
sender();
});
client.start("127.0.0.1", "8080");
// -- sync qps test
//while (true)
//{
// client.call<std::string>("echo", strmsg);
//}
while (std::getchar() != '\n');
return 0;
}
<file_sep>#include "unit_test.hpp"
#include <asio2/config.hpp>
#undef ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR
#include <asio2/base/timer.hpp>
void timer_test()
{
#if defined(ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR)
ASIO2_CHECK(false);
#endif
ASIO2_TEST_BEGIN_LOOP(test_loop_times / 50);
#define diff 100ll
asio2::timer timer1;
int c0 = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0;
int n0 = 0;
auto t0 = std::chrono::high_resolution_clock::now();
timer1.start_timer(0, 500, [&c0, &t0, &n0, &timer1]() mutable
{
c0++;
ASIO2_CHECK(!asio2::get_last_error());
if (n0 == 0)
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t0).count() - 500);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= diff);
timer1.set_timer_interval(0, 1000);
}
else if (n0 == 1)
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t0).count() - 1000);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= diff);
timer1.set_timer_interval(0, std::chrono::milliseconds(500));
}
else if (n0 == 2)
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t0).count() - 500);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= diff);
timer1.reset_timer_interval(0, std::chrono::milliseconds(1000));
}
else if (n0 == 3)
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t0).count() - 1000);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= diff);
timer1.reset_timer_interval(0, 500);
}
else
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t0).count() - 500);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= diff);
}
t0 = std::chrono::high_resolution_clock::now();
n0++;
});
auto t1 = std::chrono::high_resolution_clock::now();
timer1.start_timer(1, 100, [&c1, &t1]() mutable
{
c1++;
ASIO2_CHECK(!asio2::get_last_error());
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t1).count() - 100);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= diff);
t1 = std::chrono::high_resolution_clock::now();
});
auto t2 = std::chrono::high_resolution_clock::now();
timer1.start_timer("id2", 500, 9, [&c2, &t2]() mutable
{
c2++;
ASIO2_CHECK(!asio2::get_last_error());
auto elapse2 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t2).count() - 500);
ASIO2_CHECK_VALUE(elapse2, elapse2 <= diff);
t2 = std::chrono::high_resolution_clock::now();
});
auto t3 = std::chrono::high_resolution_clock::now();
timer1.start_timer(3, std::chrono::milliseconds(1100), [&c3, &t3]() mutable
{
c3++;
ASIO2_CHECK(!asio2::get_last_error());
auto elapse3 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t3).count() - 1100);
ASIO2_CHECK_VALUE(elapse3, elapse3 <= diff);
t3 = std::chrono::high_resolution_clock::now();
});
auto t4 = std::chrono::high_resolution_clock::now();
timer1.start_timer(4, std::chrono::milliseconds(600), 7, [&c4, &t4]() mutable
{
c4++;
ASIO2_CHECK(!asio2::get_last_error());
auto elapse4 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t4).count() - 600);
ASIO2_CHECK_VALUE(elapse4, elapse4 <= diff);
t4 = std::chrono::high_resolution_clock::now();
});
bool f5 = true;
auto t5 = std::chrono::high_resolution_clock::now();
timer1.start_timer(5, std::chrono::milliseconds(1000), std::chrono::milliseconds(2300), [&c5, &t5, &f5]() mutable
{
c5++;
ASIO2_CHECK(!asio2::get_last_error());
if (f5)
{
f5 = false;
auto elapse5 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t5).count() - 2300);
ASIO2_CHECK_VALUE(elapse5, elapse5 <= diff);
}
else
{
auto elapse5 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t5).count() - 1000);
ASIO2_CHECK_VALUE(elapse5, elapse5 <= diff);
}
t5 = std::chrono::high_resolution_clock::now();
});
bool f6 = true;
auto t6 = std::chrono::high_resolution_clock::now();
timer1.start_timer(6, std::chrono::milliseconds(400), 6, std::chrono::milliseconds(2200), [&c6, &t6, &f6]() mutable
{
c6++;
ASIO2_CHECK(!asio2::get_last_error());
if (f6)
{
f6 = false;
auto elapse6 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t6).count() - 2200);
ASIO2_CHECK_VALUE(elapse6, elapse6 <= diff);
}
else
{
auto elapse6 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t6).count() - 400);
ASIO2_CHECK_VALUE(elapse6, elapse6 <= diff);
}
t6 = std::chrono::high_resolution_clock::now();
});
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
// The actual timeout of the timer is about 10 milliseconds more than the preset timeout,
// but at here we use 15 milliseconds to ensure the value is within the range
ASIO2_CHECK_VALUE(c1, c1 >= (5000 - (5000 / 100 * 15)) / 100 && c1 <= 5000 / 100);
ASIO2_CHECK_VALUE(c2, c2 == 9);
ASIO2_CHECK_VALUE(c3, c3 >= 4 && c3 < 5);
ASIO2_CHECK_VALUE(c4, c4 == 7);
ASIO2_CHECK_VALUE(c5, c5 >= 3 && c5 < 4);
ASIO2_CHECK_VALUE(c6, c6 == 6);
if (c2 == 9)
{
ASIO2_CHECK(!timer1.is_timer_exists("id2"));
}
if (c4 == 7)
{
ASIO2_CHECK(!timer1.is_timer_exists(4));
}
if (c6 == 6)
{
ASIO2_CHECK(!timer1.is_timer_exists(6));
}
timer1.stop_all_timers();
ASIO2_CHECK(!timer1.is_timer_exists(1));
ASIO2_CHECK(!timer1.is_timer_exists("id2"));
ASIO2_CHECK(!timer1.is_timer_exists(2));
ASIO2_CHECK(!timer1.is_timer_exists(3));
ASIO2_CHECK(!timer1.is_timer_exists(4));
ASIO2_CHECK(!timer1.is_timer_exists(5));
ASIO2_CHECK(!timer1.is_timer_exists(6));
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"timer",
ASIO2_TEST_CASE(timer_test)
)
<file_sep>// (C) Copyright <NAME> 2001 - 2002.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
#if __IBMCPP__ <= 501
# define BHO_NO_STD_ALLOCATOR
#endif
#define BHO_HAS_MACRO_USE_FACET
#define BHO_NO_STD_MESSAGES
// Apple doesn't seem to reliably defined a *unix* macro
#if !defined(CYGWIN) && ( defined(__unix__) \
|| defined(__unix) \
|| defined(unix) \
|| defined(__APPLE__) \
|| defined(__APPLE) \
|| defined(APPLE))
# include <unistd.h>
#endif
// C++0x headers not yet implemented
//
# define BHO_NO_CXX11_HDR_ARRAY
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_HDR_CODECVT
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_FORWARD_LIST
# define BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_RANDOM
# define BHO_NO_CXX11_HDR_RATIO
# define BHO_NO_CXX11_HDR_REGEX
# define BHO_NO_CXX11_HDR_SYSTEM_ERROR
# define BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_HDR_TUPLE
# define BHO_NO_CXX11_HDR_TYPE_TRAITS
# define BHO_NO_CXX11_HDR_TYPEINDEX
# define BHO_NO_CXX11_HDR_UNORDERED_MAP
# define BHO_NO_CXX11_HDR_UNORDERED_SET
# define BHO_NO_CXX11_NUMERIC_LIMITS
# define BHO_NO_CXX11_ALLOCATOR
# define BHO_NO_CXX11_POINTER_TRAITS
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
# define BHO_NO_CXX11_SMART_PTR
# define BHO_NO_CXX11_HDR_FUNCTIONAL
# define BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_STD_ALIGN
# define BHO_NO_CXX11_ADDRESSOF
# define BHO_NO_CXX11_HDR_EXCEPTION
#if defined(__has_include)
#if !__has_include(<shared_mutex>)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#elif __cplusplus < 201402
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#else
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
// C++14 features
# define BHO_NO_CXX14_STD_EXCHANGE
// C++17 features
# define BHO_NO_CXX17_STD_APPLY
# define BHO_NO_CXX17_STD_INVOKE
# define BHO_NO_CXX17_ITERATOR_TRAITS
#define BHO_STDLIB "Visual Age default standard library"
<file_sep>#include <asio2/tcp/tcp_client.hpp>
// how to use the match_role, see : https://blog.csdn.net/zhllxt/article/details/127670983
// the byte 1 head (1 bytes) : #
// the byte 2 length (1 bytes) : the body length
// the byte 3... body (n bytes) : the body content
using buffer_iterator = asio::buffers_iterator<asio::streambuf::const_buffers_type>;
std::pair<buffer_iterator, bool> match_role(buffer_iterator begin, buffer_iterator end)
{
buffer_iterator p = begin;
while (p != end)
{
// how to convert the Iterator to char*
[[maybe_unused]] const char * buf = &(*p);
if (*p != '#')
return std::pair(begin, true); // head character is not #, return and kill the client
p++;
if (p == end) break;
int length = std::uint8_t(*p); // get content length
p++;
if (p == end) break;
if (end - p >= length)
return std::pair(p + length, true);
break;
}
return std::pair(begin, false);
}
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8026";
asio2::tcp_client client;
client.bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n",
client.local_address().c_str(), client.local_port());
std::string str;
str += '#';
str += char(3);
str += "abc";
client.async_send(str);
}).bind_recv([&](std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
std::string str;
str += '#';
uint8_t len = uint8_t(100 + (std::rand() % 100));
str += char(len);
for (uint8_t i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
// this is just a demo to show :
// even if we force one packet data to be sent twice,
// but the server must recvd whole packet once
client.async_send(str.substr(0, str.size() / 2));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
client.async_send(str.substr(str.size() / 2));
// of course you can sent the whole data once
//client.async_send(std::move(str));
});
client.async_start(host, port, match_role);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RECV_CONNECT_OP_HPP__
#define __ASIO2_RECV_CONNECT_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/core.hpp>
namespace asio2::detail
{
template<class SocketT, class HandlerT>
class mqtt_recv_connect_op : public asio::coroutine
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
asio::io_context & context_;
SocketT& socket_;
HandlerT handler_;
std::unique_ptr<asio::streambuf> stream{ std::make_unique<asio::streambuf>() };
template<class SKT, class H>
mqtt_recv_connect_op(asio::io_context& context, SKT& skt, H&& h)
: context_(context)
, socket_ (skt)
, handler_(std::forward<H>(h))
{
(*this)();
}
template<typename = void>
void operator()(error_code ec = {}, std::size_t bytes_transferred = 0)
{
detail::ignore_unused(ec, bytes_transferred);
// There is no need to use a timeout timer because there is already has
// connect_timeout_cp
ASIO_CORO_REENTER(*this)
{
// The client connects to the server, and sends a connect message
// The server wait for recv the connect message
ASIO_CORO_YIELD
{
asio::streambuf& strbuf = *stream;
asio::async_read_until(socket_, strbuf, mqtt::mqtt_match_role, std::move(*this));
}
handler_(ec, std::move(stream));
}
}
};
// C++17 class template argument deduction guides
template<class SKT, class H>
mqtt_recv_connect_op(asio::io_context&, SKT&, H)->mqtt_recv_connect_op<SKT, H>;
}
#endif // !__ASIO2_RECV_CONNECT_OP_HPP__
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2002 - 2003.
// (C) Copyright <NAME> 2002 - 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Visual Age (IBM) C++ compiler setup:
#if __IBMCPP__ <= 501
# define BHO_NO_MEMBER_TEMPLATE_FRIENDS
# define BHO_NO_MEMBER_FUNCTION_SPECIALIZATIONS
#endif
#if (__IBMCPP__ <= 502)
// Actually the compiler supports inclass member initialization but it
// requires a definition for the class member and it doesn't recognize
// it as an integral constant expression when used as a template argument.
# define BHO_NO_INCLASS_MEMBER_INITIALIZATION
# define BHO_NO_INTEGRAL_INT64_T
# define BHO_NO_MEMBER_TEMPLATE_KEYWORD
#endif
#if (__IBMCPP__ <= 600) || !defined(BHO_STRICT_CONFIG)
# define BHO_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS
#endif
#if (__IBMCPP__ <= 1110)
// XL C++ V11.1 and earlier versions may not always value-initialize
// a temporary object T(), when T is a non-POD aggregate class type.
// <NAME> (IBM Canada Ltd) has confirmed this issue and gave it
// high priority. -- <NAME> (LKEB), May 2010.
# define BHO_NO_COMPLETE_VALUE_INITIALIZATION
#endif
//
// On AIX thread support seems to be indicated by _THREAD_SAFE:
//
#ifdef _THREAD_SAFE
# define BHO_HAS_THREADS
#endif
#define BHO_COMPILER "IBM Visual Age version " BHO_STRINGIZE(__IBMCPP__)
//
// versions check:
// we don't support Visual age prior to version 5:
#if __IBMCPP__ < 500
#error "Compiler not supported or configured - please reconfigure"
#endif
//
// last known and checked version is 1210:
#if (__IBMCPP__ > 1210)
# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown compiler version - please run the configure tests and report the results"
# endif
#endif
// Some versions of the compiler have issues with default arguments on partial specializations
#if __IBMCPP__ <= 1010
#define BHO_NO_PARTIAL_SPECIALIZATION_IMPLICIT_DEFAULT_ARGS
#endif
// Type aliasing hint. Supported since XL C++ 13.1
#if (__IBMCPP__ >= 1310)
# define BHO_MAY_ALIAS __attribute__((__may_alias__))
#endif
//
// C++0x features
//
// See boost\config\suffix.hpp for BHO_NO_LONG_LONG
//
#if ! __IBMCPP_AUTO_TYPEDEDUCTION
# define BHO_NO_CXX11_AUTO_DECLARATIONS
# define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#endif
#if ! __IBMCPP_UTF_LITERAL__
# define BHO_NO_CXX11_CHAR16_T
# define BHO_NO_CXX11_CHAR32_T
#endif
#if ! __IBMCPP_CONSTEXPR
# define BHO_NO_CXX11_CONSTEXPR
#endif
#if ! __IBMCPP_DECLTYPE
# define BHO_NO_CXX11_DECLTYPE
#else
# define BHO_HAS_DECLTYPE
#endif
#define BHO_NO_CXX11_DECLTYPE_N3276
#define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#define BHO_NO_CXX11_DELETED_FUNCTIONS
#if ! __IBMCPP_EXPLICIT_CONVERSION_OPERATORS
# define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#endif
#if ! __IBMCPP_EXTERN_TEMPLATE
# define BHO_NO_CXX11_EXTERN_TEMPLATE
#endif
#if ! __IBMCPP_VARIADIC_TEMPLATES
// not enabled separately at this time
# define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#endif
#define BHO_NO_CXX11_HDR_INITIALIZER_LIST
#define BHO_NO_CXX11_LAMBDAS
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_RAW_LITERALS
#define BHO_NO_CXX11_USER_DEFINED_LITERALS
#if ! __IBMCPP_RVALUE_REFERENCES
# define BHO_NO_CXX11_RVALUE_REFERENCES
#endif
#if ! __IBMCPP_SCOPED_ENUM
# define BHO_NO_CXX11_SCOPED_ENUMS
#endif
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_CXX11_SFINAE_EXPR
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#if ! __IBMCPP_STATIC_ASSERT
# define BHO_NO_CXX11_STATIC_ASSERT
#endif
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_UNICODE_LITERALS
#if ! __IBMCPP_VARIADIC_TEMPLATES
# define BHO_NO_CXX11_VARIADIC_TEMPLATES
#endif
#if ! __C99_MACRO_WITH_VA_ARGS
# define BHO_NO_CXX11_VARIADIC_MACROS
#endif
#define BHO_NO_CXX11_ALIGNAS
#define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#define BHO_NO_CXX11_INLINE_NAMESPACES
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_FINAL
#define BHO_NO_CXX11_OVERRIDE
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_UNRESTRICTED_UNION
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include <asio2/bho/predef/detail/test.h>
#ifndef BHO_PREDEF_MAKE_H
#define BHO_PREDEF_MAKE_H
/*
Shorthands for the common version number formats used by vendors...
*/
/* tag::reference[]
= `BHO_PREDEF_MAKE_..` macros
These set of macros decompose common vendor version number
macros which are composed version, revision, and patch digits.
The naming convention indicates:
* The base of the specified version number. "`BHO_PREDEF_MAKE_0X`" for
hexadecimal digits, and "`BHO_PREDEF_MAKE_10`" for decimal digits.
* The format of the vendor version number. Where "`V`" indicates the version digits,
"`R`" indicates the revision digits, "`P`" indicates the patch digits, and "`0`"
indicates an ignored digit.
Macros are:
*/ // end::reference[]
/* tag::reference[]
* `BHO_PREDEF_MAKE_0X_VRP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_0X_VRP(V) BHO_VERSION_NUMBER((V&0xF00)>>8,(V&0xF0)>>4,(V&0xF))
/* tag::reference[]
* `BHO_PREDEF_MAKE_0X_VVRP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_0X_VVRP(V) BHO_VERSION_NUMBER((V&0xFF00)>>8,(V&0xF0)>>4,(V&0xF))
/* tag::reference[]
* `BHO_PREDEF_MAKE_0X_VRPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_0X_VRPP(V) BHO_VERSION_NUMBER((V&0xF000)>>12,(V&0xF00)>>8,(V&0xFF))
/* tag::reference[]
* `BHO_PREDEF_MAKE_0X_VVRR(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_0X_VVRR(V) BHO_VERSION_NUMBER((V&0xFF00)>>8,(V&0xFF),0)
/* tag::reference[]
* `BHO_PREDEF_MAKE_0X_VRRPPPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_0X_VRRPPPP(V) BHO_VERSION_NUMBER((V&0xF000000)>>24,(V&0xFF0000)>>16,(V&0xFFFF))
/* tag::reference[]
* `BHO_PREDEF_MAKE_0X_VVRRP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_0X_VVRRP(V) BHO_VERSION_NUMBER((V&0xFF000)>>12,(V&0xFF0)>>4,(V&0xF))
/* tag::reference[]
* `BHO_PREDEF_MAKE_0X_VRRPP000(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_0X_VRRPP000(V) BHO_VERSION_NUMBER((V&0xF0000000)>>28,(V&0xFF00000)>>20,(V&0xFF000)>>12)
/* tag::reference[]
* `BHO_PREDEF_MAKE_0X_VVRRPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_0X_VVRRPP(V) BHO_VERSION_NUMBER((V&0xFF0000)>>16,(V&0xFF00)>>8,(V&0xFF))
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VPPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VPPP(V) BHO_VERSION_NUMBER(((V)/1000)%10,0,(V)%1000)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VVPPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VVPPP(V) BHO_VERSION_NUMBER(((V)/1000)%100,0,(V)%1000)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VR0(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VR0(V) BHO_VERSION_NUMBER(((V)/100)%10,((V)/10)%10,0)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VRP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VRP(V) BHO_VERSION_NUMBER(((V)/100)%10,((V)/10)%10,(V)%10)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VRP000(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VRP000(V) BHO_VERSION_NUMBER(((V)/100000)%10,((V)/10000)%10,((V)/1000)%10)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VRPPPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VRPPPP(V) BHO_VERSION_NUMBER(((V)/100000)%10,((V)/10000)%10,(V)%10000)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VRPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VRPP(V) BHO_VERSION_NUMBER(((V)/1000)%10,((V)/100)%10,(V)%100)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VRR(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VRR(V) BHO_VERSION_NUMBER(((V)/100)%10,(V)%100,0)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VRRPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VRRPP(V) BHO_VERSION_NUMBER(((V)/10000)%10,((V)/100)%100,(V)%100)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VRR000(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VRR000(V) BHO_VERSION_NUMBER(((V)/100000)%10,((V)/1000)%100,0)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VV00(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VV00(V) BHO_VERSION_NUMBER(((V)/100)%100,0,0)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VVRR(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VVRR(V) BHO_VERSION_NUMBER(((V)/100)%100,(V)%100,0)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VVRRP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VVRRP(V) BHO_VERSION_NUMBER(((V)/1000)%100,((V)/10)%100,(V)%10)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VVRRPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VVRRPP(V) BHO_VERSION_NUMBER(((V)/10000)%100,((V)/100)%100,(V)%100)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VVRRPPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VVRRPPP(V) BHO_VERSION_NUMBER(((V)/100000)%100,((V)/1000)%100,(V)%1000)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VVRR0PP00(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VVRR0PP00(V) BHO_VERSION_NUMBER(((V)/10000000)%100,((V)/100000)%100,((V)/100)%100)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VVRR0PPPP(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VVRR0PPPP(V) BHO_VERSION_NUMBER(((V)/10000000)%100,((V)/100000)%100,(V)%10000)
/* tag::reference[]
* `BHO_PREDEF_MAKE_10_VVRR00PP00(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_10_VVRR00PP00(V) BHO_VERSION_NUMBER(((V)/100000000)%100,((V)/1000000)%100,((V)/100)%100)
/* tag::reference[]
= `BHO_PREDEF_MAKE_*..` date macros
Date decomposition macros return a date in the relative to the 1970
Epoch date. If the month is not available, January 1st is used as the month and day.
If the day is not available, but the month is, the 1st of the month is used as the day.
*/ // end::reference[]
/* tag::reference[]
* `BHO_PREDEF_MAKE_DATE(Y,M,D)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_DATE(Y,M,D) BHO_VERSION_NUMBER((Y)%10000-1970,(M)%100,(D)%100)
/* tag::reference[]
* `BHO_PREDEF_MAKE_YYYYMMDD(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_YYYYMMDD(V) BHO_PREDEF_MAKE_DATE(((V)/10000)%10000,((V)/100)%100,(V)%100)
/* tag::reference[]
* `BHO_PREDEF_MAKE_YYYY(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_YYYY(V) BHO_PREDEF_MAKE_DATE(V,1,1)
/* tag::reference[]
* `BHO_PREDEF_MAKE_YYYYMM(V)`
*/ // end::reference[]
#define BHO_PREDEF_MAKE_YYYYMM(V) BHO_PREDEF_MAKE_DATE((V)/100,(V)%100,1)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_EXTERNAL_CONFIG_HPP__
#define __ASIO2_EXTERNAL_CONFIG_HPP__
#include <asio2/config.hpp>
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/config.hpp>)
#include <boost/config.hpp>
#ifndef ASIO2_JOIN
#define ASIO2_JOIN BOOST_JOIN
#endif
#ifndef ASIO2_STRINGIZE
#define ASIO2_STRINGIZE BOOST_STRINGIZE
#endif
#else
#include <asio2/bho/config.hpp>
#ifndef ASIO2_JOIN
#define ASIO2_JOIN BHO_JOIN
#endif
#ifndef ASIO2_STRINGIZE
#define ASIO2_STRINGIZE BHO_STRINGIZE
#endif
#endif
#endif
<file_sep>/*
Copyright 2018 <NAME>
(<EMAIL>)
Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_CORE_EXCHANGE_HPP
#define BHO_CORE_EXCHANGE_HPP
#include <asio2/bho/config.hpp>
#if !defined(BHO_NO_CXX11_RVALUE_REFERENCES)
#include <asio2/bho/config/workaround.hpp>
#include <utility>
#endif
namespace bho {
#if defined(BHO_NO_CXX11_RVALUE_REFERENCES)
template<class T, class U>
inline T exchange(T& t, const U& u)
{
T v = t;
t = u;
return v;
}
#else
#if BHO_WORKAROUND(BHO_MSVC, < 1800)
template<class T, class U>
inline T exchange(T& t, U&& u)
{
T v = std::move(t);
t = std::forward<U>(u);
return v;
}
#else
template<class T, class U = T>
BHO_CXX14_CONSTEXPR inline T exchange(T& t, U&& u)
{
T v = std::move(t);
t = std::forward<U>(u);
return v;
}
#endif
#endif
} /* boost */
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_UTIL_HPP__
#define __ASIO2_UTIL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <cstdarg>
#include <cstdio>
#include <cwchar>
#include <climits>
#include <cctype>
#include <string>
#include <string_view>
#include <type_traits>
#include <memory>
#include <future>
#include <functional>
#include <tuple>
#include <utility>
#include <atomic>
#include <limits>
#include <thread>
#include <mutex>
#include <shared_mutex>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/type_traits.hpp>
#include <asio2/util/string.hpp>
namespace asio2
{
template<typename = void>
inline std::string to_string(const asio::const_buffer& v)
{
return std::string{ (std::string::pointer)(v.data()), v.size() };
}
template<typename = void>
inline std::string to_string(const asio::mutable_buffer& v)
{
return std::string{ (std::string::pointer)(v.data()), v.size() };
}
#if !defined(ASIO_NO_DEPRECATED) && !defined(BOOST_ASIO_NO_DEPRECATED)
template<typename = void>
inline std::string to_string(const asio::const_buffers_1& v)
{
return std::string{ (std::string::pointer)(v.data()), v.size() };
}
template<typename = void>
inline std::string to_string(const asio::mutable_buffers_1& v)
{
return std::string{ (std::string::pointer)(v.data()), v.size() };
}
#endif
template<typename = void>
inline std::string_view to_string_view(const asio::const_buffer& v)
{
return std::string_view{ (std::string_view::const_pointer)(v.data()), v.size() };
}
template<typename = void>
inline std::string_view to_string_view(const asio::mutable_buffer& v)
{
return std::string_view{ (std::string_view::const_pointer)(v.data()), v.size() };
}
#if !defined(ASIO_NO_DEPRECATED) && !defined(BOOST_ASIO_NO_DEPRECATED)
template<typename = void>
inline std::string_view to_string_view(const asio::const_buffers_1& v)
{
return std::string_view{ (std::string_view::const_pointer)(v.data()), v.size() };
}
template<typename = void>
inline std::string_view to_string_view(const asio::mutable_buffers_1& v)
{
return std::string_view{ (std::string_view::const_pointer)(v.data()), v.size() };
}
#endif
}
namespace asio2::detail
{
using asio2::to_string;
using asio2::to_string_view;
using asio2::to_numeric;
}
namespace asio2
{
template<typename Protocol, typename String, typename StrOrInt>
inline Protocol to_endpoint(String&& host, StrOrInt&& port)
{
std::string h = detail::to_string(std::forward<String>(host));
std::string p = detail::to_string(std::forward<StrOrInt>(port));
asio::io_context ioc;
// the resolve function is a time-consuming operation
if /**/ constexpr (std::is_same_v<asio::ip::udp::endpoint, Protocol>)
{
error_code ec;
asio::ip::udp::resolver resolver(ioc);
auto rs = resolver.resolve(h, p, asio::ip::resolver_base::flags::address_configured, ec);
if (ec || rs.empty())
{
set_last_error(ec ? ec : asio::error::host_not_found);
return *rs;
}
else
{
clear_last_error();
return asio::ip::udp::endpoint{};
}
}
else if constexpr (std::is_same_v<asio::ip::tcp::endpoint, Protocol>)
{
error_code ec;
asio::ip::tcp::resolver resolver(ioc);
auto rs = resolver.resolve(h, p, asio::ip::resolver_base::flags::address_configured, ec);
if (ec || rs.empty())
{
set_last_error(ec ? ec : asio::error::host_not_found);
return *rs;
}
else
{
clear_last_error();
return asio::ip::tcp::endpoint{};
}
}
else
{
static_assert(detail::always_false_v<Protocol>);
}
}
}
namespace asio2::detail
{
using asio2::to_endpoint;
}
namespace asio2::detail
{
enum class state_t : std::int8_t { stopped, stopping, starting, started };
template<typename = void>
inline constexpr std::string_view to_string(state_t v)
{
using namespace std::string_view_literals;
switch (v)
{
case state_t::stopped : return "stopped";
case state_t::stopping : return "stopping";
case state_t::starting : return "starting";
case state_t::started : return "started";
default : return "none";
}
return "none";
}
// /bho/beast/websocket/stream_base.hpp line 147
// opt.handshake_timeout = std::chrono::seconds(30);
// When there are a lot of connections, there will maybe a lot of COSE_WAIT,LAST_ACK,TIME_WAIT
// and other problems, resulting in the client being unable to connect to the server normally.
// Increasing the connect,handshake,shutdown timeout can effectively alleviate this problem.
static long constexpr tcp_handshake_timeout = 30 * 1000;
static long constexpr udp_handshake_timeout = 30 * 1000;
static long constexpr http_handshake_timeout = 30 * 1000;
static long constexpr tcp_connect_timeout = 30 * 1000;
static long constexpr udp_connect_timeout = 30 * 1000;
static long constexpr http_connect_timeout = 30 * 1000;
static long constexpr tcp_silence_timeout = 60 * 60 * 1000;
static long constexpr udp_silence_timeout = 60 * 1000;
static long constexpr http_silence_timeout = 85 * 1000;
static long constexpr mqtt_silence_timeout = 90 * 1000; // 60 * 1.5
static long constexpr http_execute_timeout = 15 * 1000;
static long constexpr icmp_execute_timeout = 4 * 1000;
static long constexpr ssl_shutdown_timeout = 30 * 1000;
static long constexpr ws_shutdown_timeout = 30 * 1000;
static long constexpr ssl_handshake_timeout = 30 * 1000;
static long constexpr ws_handshake_timeout = 30 * 1000;
/*
* The read buffer has to be at least as large
* as the largest possible control frame including
* the frame header.
* refrenced from beast stream.hpp
*/
// udp MTU : https://zhuanlan.zhihu.com/p/301276548
static std::size_t constexpr tcp_frame_size = 1536;
static std::size_t constexpr udp_frame_size = 1024;
static std::size_t constexpr http_frame_size = 1536;
static std::size_t constexpr max_buffer_size = (std::numeric_limits<std::size_t>::max)();
// std::thread::hardware_concurrency() is not constexpr, so use it with function form
// @see: asio::detail::default_thread_pool_size()
template<typename = void>
inline std::size_t default_concurrency() noexcept
{
std::size_t num_threads = std::thread::hardware_concurrency() * 2;
num_threads = num_threads == 0 ? 2 : num_threads;
return num_threads;
}
}
namespace asio2::detail
{
/**
* BKDR Hash Function
*/
template<typename = void>
inline std::size_t bkdr_hash(const unsigned char * const p, std::size_t size) noexcept
{
std::size_t v = 0;
for (std::size_t i = 0; i < size; ++i)
{
v = v * 131 + static_cast<std::size_t>(p[i]);
}
return v;
}
/**
* Fnv1a Hash Function
* Reference from Visual c++ implementation, see vc++ std::hash
*/
template<typename T>
inline T fnv1a_hash(const unsigned char * const p, const T size) noexcept
{
static_assert(sizeof(T) == 4 || sizeof(T) == 8, "Must be 32 or 64 digits");
T v;
if constexpr (sizeof(T) == 4)
v = 2166136261u;
else
v = 14695981039346656037ull;
for (T i = 0; i < size; ++i)
{
v ^= static_cast<T>(p[i]);
if constexpr (sizeof(T) == 4)
v *= 16777619u;
else
v *= 1099511628211ull;
}
return (v);
}
template<typename T>
inline T fnv1a_hash(T v, const unsigned char * const p, const T size) noexcept
{
static_assert(sizeof(T) == 4 || sizeof(T) == 8, "Must be 32 or 64 digits");
for (T i = 0; i < size; ++i)
{
v ^= static_cast<T>(p[i]);
if constexpr (sizeof(T) == 4)
v *= 16777619u;
else
v *= 1099511628211ull;
}
return (v);
}
template<class T>
class copyable_wrapper
{
public:
using value_type = T;
template<typename ...Args>
copyable_wrapper(Args&&... args) noexcept : raw(std::forward<Args>(args)...) { }
template<typename = void>
copyable_wrapper(T&& o) noexcept : raw(std::move(o)) { }
copyable_wrapper(copyable_wrapper&&) noexcept = default;
copyable_wrapper& operator=(copyable_wrapper&&) noexcept = default;
copyable_wrapper(copyable_wrapper const& r) noexcept : raw(const_cast<T&&>(r.raw)) { }
copyable_wrapper& operator=(copyable_wrapper const& r) noexcept { raw = const_cast<T&&>(r.raw); }
T& operator()() noexcept { return raw; }
protected:
T raw;
};
template<typename, typename = void>
struct is_copyable_wrapper : std::false_type {};
template<typename T>
struct is_copyable_wrapper<T, std::void_t<typename T::value_type,
typename std::enable_if_t<std::is_same_v<T,
copyable_wrapper<typename T::value_type>>>>> : std::true_type {};
template<class T>
inline constexpr bool is_copyable_wrapper_v = is_copyable_wrapper<T>::value;
inline void cancel_timer(asio::steady_timer& timer) noexcept
{
try
{
timer.cancel();
}
catch (system_error const&)
{
}
}
struct safe_timer
{
explicit safe_timer(asio::io_context& ioc) : timer(ioc)
{
canceled.clear();
}
inline void cancel()
{
this->canceled.test_and_set();
detail::cancel_timer(this->timer);
}
/// Timer impl
asio::steady_timer timer;
/// Why use this flag, beacuase the ec param maybe zero when the timer callback is
/// called after the timer cancel function has called already.
/// Before : need reset the "canceled" flag to false, otherwise after "client.stop();"
/// then call client.start(...) again, this reconnect timer will doesn't work .
/// can't put this "clear" code into the timer handle function, beacuse the stop timer
/// maybe called many times. so, when the "canceled" flag is set false in the timer handle
/// and the stop timer is called later, then the "canceled" flag will be set true again .
std::atomic_flag canceled;
};
template<class Rep, class Period, class Fn>
std::shared_ptr<safe_timer> mktimer(asio::io_context& ioc, std::chrono::duration<Rep, Period> duration, Fn&& fn)
{
std::shared_ptr<safe_timer> timer = std::make_shared<safe_timer>(ioc);
auto post = std::make_shared<std::unique_ptr<std::function<void()>>>();
*post = std::make_unique<std::function<void()>>(
[duration, f = std::forward<Fn>(fn), timer, post]() mutable
{
timer->timer.expires_after(duration);
timer->timer.async_wait([&f, &timer, &post](const error_code& ec) mutable
{
if (!timer->canceled.test_and_set())
{
timer->canceled.clear();
if (f(ec))
(**post)();
else
(*post).reset();
}
else
{
(*post).reset();
}
});
});
(**post)();
return timer;
}
template<class T, bool isIntegral = true, bool isUnsigned = true, bool SkipZero = true>
class id_maker
{
public:
id_maker(T init = static_cast<T>(1)) noexcept : id(init)
{
if constexpr (isIntegral)
{
static_assert(std::is_integral_v<T>, "T must be integral");
if constexpr (isUnsigned)
{
static_assert(std::is_unsigned_v<T>, "T must be unsigned integral");
}
else
{
static_assert(true);
}
}
else
{
static_assert(true);
}
}
inline T mkid() noexcept
{
if constexpr (SkipZero)
{
T r = id.fetch_add(static_cast<T>(1));
return (r == 0 ? id.fetch_add(static_cast<T>(1)) : r);
}
else
{
return id.fetch_add(static_cast<T>(1));
}
}
protected:
std::atomic<T> id;
};
// Returns true if the current machine is little endian
template<typename = void>
inline bool is_little_endian() noexcept
{
static std::int32_t test = 1;
return (*reinterpret_cast<std::int8_t*>(std::addressof(test)) == 1);
}
/**
* Swaps the order of bytes for some chunk of memory
* @param data - The data as a uint8_t pointer
* @tparam DataSize - The true size of the data
*/
template <std::size_t DataSize>
inline void swap_bytes(std::uint8_t * data) noexcept
{
for (std::size_t i = 0, end = DataSize / 2; i < end; ++i)
std::swap(data[i], data[DataSize - i - 1]);
}
template<class T, class Pointer>
inline void write(Pointer& p, T v) noexcept
{
if constexpr (int(sizeof(T)) > 1)
{
// MSDN: The htons function converts a u_short from host to TCP/IP network byte order (which is big-endian).
// ** This mean the network byte order is big-endian **
if (is_little_endian())
{
swap_bytes<sizeof(T)>(reinterpret_cast<std::uint8_t *>(std::addressof(v)));
}
std::memcpy((void*)p, (const void*)&v, sizeof(T));
}
else
{
static_assert(sizeof(T) == std::size_t(1));
*p = std::decay_t<std::remove_pointer_t<detail::remove_cvref_t<Pointer>>>(v);
}
p += sizeof(T);
}
template<class T, class Pointer>
inline T read(Pointer& p) noexcept
{
T v{};
if constexpr (int(sizeof(T)) > 1)
{
std::memcpy((void*)&v, (const void*)p, sizeof(T));
// MSDN: The htons function converts a u_short from host to TCP/IP network byte order (which is big-endian).
// ** This mean the network byte order is big-endian **
if (is_little_endian())
{
swap_bytes<sizeof(T)>(reinterpret_cast<std::uint8_t *>(std::addressof(v)));
}
}
else
{
static_assert(sizeof(T) == std::size_t(1));
v = T(*p);
}
p += sizeof(T);
return v;
}
// C++ SSO : How to programatically find if a std::wstring is allocated with Short String Optimization?
// https://stackoverflow.com/questions/65736613/c-sso-how-to-programatically-find-if-a-stdwstring-is-allocated-with-short
template <class T>
bool is_used_sso(const T& t) noexcept
{
using type = typename detail::remove_cvref_t<T>;
static type st{};
return t.capacity() == st.capacity();
}
template<class T>
std::size_t sso_buffer_size() noexcept
{
using type = typename detail::remove_cvref_t<T>;
static type st{};
return st.capacity();
}
// Disable std:string's SSO
// https://stackoverflow.com/questions/34788789/disable-stdstrings-sso
// std::string str;
// str.reserve(sizeof(str) + 1);
template<class String>
inline void disable_sso(String& str)
{
str.reserve(sso_buffer_size<typename detail::remove_cvref_t<String>>() + 1);
}
template<class Integer>
struct integer_add_sub_guard
{
integer_add_sub_guard(Integer& v) noexcept : v_(v) { ++v_; }
~integer_add_sub_guard() noexcept { --v_; }
Integer& v_;
};
// C++17 class template argument deduction guides
template<class Integer>
integer_add_sub_guard(Integer&)->integer_add_sub_guard<Integer>;
}
namespace asio2
{
enum class net_protocol : std::uint8_t
{
none = 0,
udp = 1,
tcp,
http,
websocket,
rpc,
mqtt,
tcps,
https,
websockets,
rpcs,
mqtts,
icmp,
serialport,
ws = websocket,
wss = websockets
};
enum class response_mode : std::uint8_t
{
automatic = 1,
manual,
};
}
// custom specialization of std::hash can be injected in namespace std
// see : struct hash<asio::ip::basic_endpoint<InternetProtocol>> in /asio/ip/basic_endpoint.hpp
#if !defined(ASIO_HAS_STD_HASH)
namespace std
{
template <>
struct hash<asio::ip::address_v4>
{
std::size_t operator()(const asio::ip::address_v4& addr) const ASIO_NOEXCEPT
{
return std::hash<unsigned int>()(addr.to_uint());
}
};
template <>
struct hash<asio::ip::address_v6>
{
std::size_t operator()(const asio::ip::address_v6& addr) const ASIO_NOEXCEPT
{
const asio::ip::address_v6::bytes_type bytes = addr.to_bytes();
std::size_t result = static_cast<std::size_t>(addr.scope_id());
combine_4_bytes(result, &bytes[0]);
combine_4_bytes(result, &bytes[4]);
combine_4_bytes(result, &bytes[8]);
combine_4_bytes(result, &bytes[12]);
return result;
}
private:
static void combine_4_bytes(std::size_t& seed, const unsigned char* bytes)
{
const std::size_t bytes_hash =
(static_cast<std::size_t>(bytes[0]) << 24) |
(static_cast<std::size_t>(bytes[1]) << 16) |
(static_cast<std::size_t>(bytes[2]) << 8) |
(static_cast<std::size_t>(bytes[3]));
seed ^= bytes_hash + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
template <>
struct hash<asio::ip::address>
{
std::size_t operator()(const asio::ip::address& addr) const ASIO_NOEXCEPT
{
return addr.is_v4()
? std::hash<asio::ip::address_v4>()(addr.to_v4())
: std::hash<asio::ip::address_v6>()(addr.to_v6());
}
};
template <typename InternetProtocol>
struct hash<asio::ip::basic_endpoint<InternetProtocol>>
{
std::size_t operator()(const asio::ip::basic_endpoint<InternetProtocol>& ep) const ASIO_NOEXCEPT
{
std::size_t hash1 = std::hash<asio::ip::address>()(ep.address());
std::size_t hash2 = std::hash<unsigned short>()(ep.port());
return hash1 ^ (hash2 + 0x9e3779b9 + (hash1 << 6) + (hash1 >> 2));
}
};
}
#endif
namespace asio2
{
namespace detail
{
template<class T>
struct current_object_result_t
{
using type = T&;
};
template<class T>
struct current_object_result_t<std::shared_ptr<T>>
{
using type = std::weak_ptr<T>&;
};
class [[maybe_unused]] external_linkaged_current_object
{
public:
template<class T>
[[maybe_unused]] static typename current_object_result_t<T>::type get() noexcept
{
if constexpr (detail::is_template_instance_of_v<std::shared_ptr, T>)
{
thread_local static std::weak_ptr<typename T::element_type> o{};
return o;
}
else
{
thread_local static T o{};
return o;
}
}
};
namespace internal_linkaged_current_object
{
template<class T>
[[maybe_unused]] static typename current_object_result_t<T>::type get() noexcept
{
if constexpr (detail::is_template_instance_of_v<std::shared_ptr, T>)
{
thread_local static std::weak_ptr<typename T::element_type> o{};
return o;
}
else
{
thread_local static T o{};
return o;
}
}
}
template<class T>
[[maybe_unused]] inline typename current_object_result_t<T>::type get_current_object() noexcept
{
return detail::external_linkaged_current_object::get<T>();
}
}
/**
* @brief Get the current caller object in the current thread.
* @tparam T - If the object is created on the stack such as "asio2::rpc_client client", the T can
* only be asio2::rpc_client& or asio2::rpc_client*
* If the object is created on the heap such as "std::shared_ptr<asio2::rpc_session>",
* the T can only be std::shared_ptr<asio2::rpc_session>
* @return The return type is same as the T.
*/
template<class T>
[[maybe_unused]] inline T get_current_caller() noexcept
{
if /**/ constexpr (detail::is_template_instance_of_v<std::shared_ptr, T>)
{
return detail::get_current_object<T>().lock();
}
else if constexpr (std::is_reference_v<T>)
{
return *detail::get_current_object<std::add_pointer_t<typename detail::remove_cvref_t<T>>>();
}
else
{
return detail::get_current_object<T>();
}
}
}
#endif // !__ASIO2_UTIL_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_FMT_HPP__
#define __ASIO2_FMT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <string_view>
#ifndef ASIO2_DISABLE_AUTO_HEADER_ONLY
#ifndef FMT_HEADER_ONLY
#define FMT_HEADER_ONLY
#endif
#endif
// used to compatible with the UE4 "check" macro
#pragma push_macro("check")
#undef check
#include <fmt/format.h>
#include <fmt/args.h>
#include <fmt/chrono.h>
#include <fmt/color.h>
#include <fmt/compile.h>
#include <fmt/os.h>
#include <fmt/ostream.h>
#include <fmt/printf.h>
#include <fmt/ranges.h>
#include <fmt/xchar.h>
// https://fmt.dev/latest/api.html#udt
// Custom format for MFC/ATL CString
#if defined(__AFXSTR_H__) || defined(__ATLSTR_H__)
#if __has_include(<afxstr.h>) || __has_include(<atlstr.h>)
template <>
struct fmt::formatter<CStringA, char>
{
template<typename FormatParseContext>
constexpr auto parse(FormatParseContext& ctx) -> decltype(ctx.begin())
{
// Parse the presentation format and store it in the formatter:
auto it = ctx.begin(), end = ctx.end();
// Check if reached the end of the range:
if (it != end && *it != '}') throw format_error("invalid format");
// Return an iterator past the end of the parsed range:
return it;
}
template <typename FormatContext>
auto format(const CStringA& s, FormatContext& ctx) -> decltype(ctx.out())
{
return format_to(ctx.out(), "{}", (LPCSTR)s);
}
};
// CStringA s;
// fmt::format(L"{}", s);
// above code will compile failed, beacuse the CStringA can be implicitly converted to const char*
// then then fmt::format(L"{}", (const char*)...); will compile failed.
template <>
struct fmt::formatter<CStringA, wchar_t>
{
template<typename FormatParseContext>
constexpr auto parse(FormatParseContext& ctx) -> decltype(ctx.begin())
{
// Parse the presentation format and store it in the formatter:
auto it = ctx.begin(), end = ctx.end();
// Check if reached the end of the range:
if (it != end && *it != '}') throw format_error("invalid format");
// Return an iterator past the end of the parsed range:
return it;
}
template <typename FormatContext>
auto format(const CStringA& s, FormatContext& ctx) -> decltype(ctx.out())
{
return format_to(ctx.out(), L"{}", (LPCWSTR)CStringW(s));
}
};
template <>
struct fmt::formatter<CStringW, char>
{
template<typename FormatParseContext>
constexpr auto parse(FormatParseContext& ctx) -> decltype(ctx.begin())
{
// Parse the presentation format and store it in the formatter:
auto it = ctx.begin(), end = ctx.end();
// Check if reached the end of the range:
if (it != end && *it != '}') throw format_error("invalid format");
// Return an iterator past the end of the parsed range:
return it;
}
template <typename FormatContext>
auto format(const CStringW& s, FormatContext& ctx) -> decltype(ctx.out())
{
return format_to(ctx.out(), "{}", (LPCSTR)CStringA(s));
}
};
template <>
struct fmt::formatter<CStringW, wchar_t>
{
template<typename FormatParseContext>
constexpr auto parse(FormatParseContext& ctx) -> decltype(ctx.begin())
{
// Parse the presentation format and store it in the formatter:
auto it = ctx.begin(), end = ctx.end();
// Check if reached the end of the range:
if (it != end && *it != '}') throw format_error("invalid format");
// Return an iterator past the end of the parsed range:
return it;
}
template <typename FormatContext>
auto format(const CStringW& s, FormatContext& ctx) -> decltype(ctx.out())
{
return format_to(ctx.out(), L"{}", (LPCWSTR)s);
}
};
#endif
#endif
// Custom format for wxWidgets wxString
// beacuse the wxString can be implicitly converted to const char* and const wchar_t*
// so the wxString can be use fmt::format("{}", wxString()); directly.
#if defined(_WX_WXSTRING_H__) && defined(ASIO2_ENABLE_WXSTRING_FORMATTER)
#if __has_include(<wx/string.h>)
template <>
struct fmt::formatter<wxString, char>
{
template<typename FormatParseContext>
constexpr auto parse(FormatParseContext& ctx) -> decltype(ctx.begin())
{
// Parse the presentation format and store it in the formatter:
auto it = ctx.begin(), end = ctx.end();
// Check if reached the end of the range:
if (it != end && *it != '}') throw format_error("invalid format");
// Return an iterator past the end of the parsed range:
return it;
}
template <typename FormatContext>
auto format(const wxString& s, FormatContext& ctx) -> decltype(ctx.out())
{
return format_to(ctx.out(), "{}", (const char*)s);
}
};
template <>
struct fmt::formatter<wxString, wchar_t>
{
template<typename FormatParseContext>
constexpr auto parse(FormatParseContext& ctx) -> decltype(ctx.begin())
{
// Parse the presentation format and store it in the formatter:
auto it = ctx.begin(), end = ctx.end();
// Check if reached the end of the range:
if (it != end && *it != '}') throw format_error("invalid format");
// Return an iterator past the end of the parsed range:
return it;
}
template <typename FormatContext>
auto format(const wxString& s, FormatContext& ctx) -> decltype(ctx.out())
{
return format_to(ctx.out(), L"{}", (const wchar_t*)s);
}
};
#endif
#endif
#pragma pop_macro("check")
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_FMT_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from https://github.com/kokke/tiny-AES-c
*/
#ifndef __ASIO2_AES_IMPL_HPP__
#define __ASIO2_AES_IMPL_HPP__
#include <cassert>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
#include <array>
#include <sstream>
namespace asio2
{
class aes
{
protected:
// state - array holding the intermediate results during decryption.
typedef uint8_t state_t[4][4];
// Block length in bytes - AES is 128b block only
static constexpr int AES_BLOCKLEN = 16;
public:
enum class mode_t
{
cbc,
ecb,
ctr,
//ocf, // not supported
//cfb, // not supported
};
public:
/*
* if key.size() <= 16, key will be resized to 16 and padded with '\0', the data block is 128 bit.
* if key.size() > 16 && <= 24, key will be resized to 24 and padded with '\0', the data block is 192 bit.
* if key.size() > 24, key will be resized to 32 and padded with '\0', the data block is 256 bit.
*/
explicit aes(std::string key, mode_t mode = mode_t::ecb) : key_(std::move(key)), mode_(mode)
{
init();
}
~aes()
{
}
aes(const aes & other) : key_(other.key_)
{
init();
}
aes & operator=(const aes & other)
{
key_ = other.key_;
init();
return (*this);
}
aes(aes && other) : key_(std::move(other.key_))
{
init();
}
aes & operator=(aes && other)
{
key_ = std::move(other.key_);
init();
return (*this);
}
mode_t mode() { return mode_; }
mode_t set_mode() { return mode_; }
aes & mode(mode_t mode) { mode_ = mode; return (*this); }
aes & get_mode(mode_t mode) { mode_ = mode; return (*this); }
aes & iv(uint8_t iv[AES_BLOCKLEN]) { memcpy(&Iv_[0], iv, AES_BLOCKLEN); return (*this); }
/*
* note : if msg contains '\0',there may be a wrong result when decrypt
*/
std::string encrypt(std::string msg)
{
if (msg.empty())
return std::string{};
if ((msg.size() % AES_BLOCKLEN) != 0)
{
msg.resize(msg.size() + AES_BLOCKLEN - (msg.size() % AES_BLOCKLEN));
}
switch (mode_)
{
case mode_t::cbc: return encrypt_with_cbc(std::move(msg));
case mode_t::ecb: return encrypt_with_ecb(std::move(msg));
case mode_t::ctr: return encrypt_with_ctr(std::move(msg));
}
return std::string{};
}
std::string decrypt(std::string msg)
{
if (msg.empty() || (msg.size() % AES_BLOCKLEN) != 0)
return std::string{};
std::string s{};
switch (mode_)
{
case mode_t::cbc: s = decrypt_with_cbc(std::move(msg)); break;
case mode_t::ecb: s = decrypt_with_ecb(std::move(msg)); break;
case mode_t::ctr: s = decrypt_with_ctr(std::move(msg)); break;
}
while (!s.empty() && s.back() == '\0')
s.erase(s.size() - 1);
return s;
}
protected:
std::string encrypt_with_cbc(std::string msg)
{
AES_init_ctx((const uint8_t*)key_.data());
AES_CBC_encrypt_buffer((uint8_t*)msg.data(), uint32_t(msg.size()));
return msg;
}
std::string decrypt_with_cbc(std::string msg)
{
AES_init_ctx((const uint8_t*)key_.data());
AES_CBC_decrypt_buffer((uint8_t*)msg.data(), uint32_t(msg.size()));
return msg;
}
std::string encrypt_with_ecb(std::string msg)
{
AES_init_ctx((const uint8_t*)key_.data());
uint8_t * buf = (uint8_t*)msg.data();
for (std::size_t i = 0; i < msg.size(); i += AES_BLOCKLEN)
{
AES_ECB_encrypt(buf);
buf += AES_BLOCKLEN;
}
return msg;
}
std::string decrypt_with_ecb(std::string msg)
{
AES_init_ctx((const uint8_t*)key_.data());
uint8_t * buf = (uint8_t*)msg.data();
for (std::size_t i = 0; i < msg.size(); i += AES_BLOCKLEN)
{
AES_ECB_decrypt(buf);
buf += AES_BLOCKLEN;
}
return msg;
}
std::string encrypt_with_ctr(std::string msg)
{
AES_init_ctx((const uint8_t*)key_.data());
AES_CTR_xcrypt_buffer((uint8_t*)msg.data(), uint32_t(msg.size()));
return msg;
}
std::string decrypt_with_ctr(std::string msg)
{
AES_init_ctx((const uint8_t*)key_.data());
AES_CTR_xcrypt_buffer((uint8_t*)msg.data(), uint32_t(msg.size()));
return msg;
}
protected:
void init()
{
if (key_.size() <= std::size_t(16)) // 128/8
{
key_.resize(16);
Nk = 4; // The number of 32 bit words in a key.
Nr = 10; // The number of rounds in AES Cipher.
RoundKey_.resize(176);
}
else if (key_.size() <= std::size_t(24)) // 192/8
{
key_.resize(24);
Nk = 6;
Nr = 12;
RoundKey_.resize(208);
}
else// 256/8
{
key_.resize(32);
Nk = 8;
Nr = 14;
RoundKey_.resize(240);
}
}
void AES_init_ctx(const uint8_t* key)
{
KeyExpansion(&RoundKey_[0], key);
}
void AES_init_ctx_iv(const uint8_t* key, const uint8_t* iv)
{
KeyExpansion(&RoundKey_[0], key);
memcpy(&Iv_[0], iv, AES_BLOCKLEN);
}
void AES_ctx_set_iv(const uint8_t* iv)
{
memcpy(&Iv_[0], iv, AES_BLOCKLEN);
}
void AES_ECB_encrypt(uint8_t* buf)
{
// The next function call encrypts the PlainText with the Key using AES algorithm.
Cipher((state_t*)buf, &RoundKey_[0]);
}
void AES_ECB_decrypt(uint8_t* buf)
{
// The next function call decrypts the PlainText with the Key using AES algorithm.
InvCipher((state_t*)buf, &RoundKey_[0]);
}
void AES_CBC_encrypt_buffer(uint8_t* buf, uint32_t length)
{
uint32_t i;
uint8_t *iv = &Iv_[0];
for (i = 0; i < length; i += AES_BLOCKLEN)
{
XorWithIv(buf, iv);
Cipher((state_t*)buf, &RoundKey_[0]);
iv = buf;
buf += AES_BLOCKLEN;
}
/* store Iv in ctx for next call */
memcpy(&Iv_[0], iv, AES_BLOCKLEN);
}
void AES_CBC_decrypt_buffer(uint8_t* buf, uint32_t length)
{
uint32_t i;
uint8_t storeNextIv[AES_BLOCKLEN];
for (i = 0; i < length; i += AES_BLOCKLEN)
{
memcpy(storeNextIv, buf, AES_BLOCKLEN);
InvCipher((state_t*)buf, &RoundKey_[0]);
XorWithIv(buf, &Iv_[0]);
memcpy(&Iv_[0], storeNextIv, AES_BLOCKLEN);
buf += AES_BLOCKLEN;
}
}
void AES_CTR_xcrypt_buffer(uint8_t* buf, uint32_t length)
{
uint8_t buffer[AES_BLOCKLEN];
unsigned i;
int bi;
for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi)
{
if (bi == AES_BLOCKLEN) /* we need to regen xor compliment in buffer */
{
memcpy(buffer, &Iv_[0], AES_BLOCKLEN);
Cipher((state_t*)buffer, &RoundKey_[0]);
/* Increment Iv and handle overflow */
for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi)
{
/* inc will overflow */
if (Iv_[bi] == 255)
{
Iv_[bi] = uint8_t(0);
continue;
}
Iv_[bi] = uint8_t(Iv_[bi] + uint8_t(1));
break;
}
bi = 0;
}
buf[i] = (buf[i] ^ buffer[bi]);
}
}
void XorWithIv(uint8_t* buf, const uint8_t* iv)
{
uint8_t i;
for (i = 0; i < AES_BLOCKLEN; ++i) // The block in AES is always 128bit no matter the key size
{
buf[i] ^= iv[i];
}
}
inline uint8_t Multiply(uint8_t x, uint8_t y)
{
return (uint8_t((((y & 1) * x) ^
((y>>1 & 1) * xtime(x)) ^
((y>>2 & 1) * xtime(xtime(x))) ^
((y>>3 & 1) * xtime(xtime(xtime(x)))) ^
((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))))); /* this last call to xtime() can be omitted */
}
// This function adds the round key to state.
// The round key is added to the state by an XOR function.
void AddRoundKey(uint8_t round, state_t* state, const uint8_t* RoundKey)
{
uint8_t i,j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
(*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j];
}
}
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
void SubBytes(state_t* state)
{
uint8_t i, j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
(*state)[j][i] = getSBoxValue((*state)[j][i]);
}
}
}
// The ShiftRows() function shifts the rows in the state to the left.
// Each row is shifted with different offset.
// Offset = Row number. So the first row is not shifted.
void ShiftRows(state_t* state)
{
uint8_t temp;
// Rotate first row 1 columns to left
temp = (*state)[0][1];
(*state)[0][1] = (*state)[1][1];
(*state)[1][1] = (*state)[2][1];
(*state)[2][1] = (*state)[3][1];
(*state)[3][1] = temp;
// Rotate second row 2 columns to left
temp = (*state)[0][2];
(*state)[0][2] = (*state)[2][2];
(*state)[2][2] = temp;
temp = (*state)[1][2];
(*state)[1][2] = (*state)[3][2];
(*state)[3][2] = temp;
// Rotate third row 3 columns to left
temp = (*state)[0][3];
(*state)[0][3] = (*state)[3][3];
(*state)[3][3] = (*state)[2][3];
(*state)[2][3] = (*state)[1][3];
(*state)[1][3] = temp;
}
inline uint8_t xtime(uint8_t x)
{
return (uint8_t(((x<<1) ^ (((x>>7) & 1) * 0x1b))));
}
// MixColumns function mixes the columns of the state matrix
void MixColumns(state_t* state)
{
uint8_t i;
uint8_t Tmp, Tm, t;
for (i = 0; i < 4; ++i)
{
t = (*state)[i][0];
Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ;
Tm = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm); (*state)[i][0] ^= Tm ^ Tmp ;
Tm = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm); (*state)[i][1] ^= Tm ^ Tmp ;
Tm = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm); (*state)[i][2] ^= Tm ^ Tmp ;
Tm = (*state)[i][3] ^ t ; Tm = xtime(Tm); (*state)[i][3] ^= Tm ^ Tmp ;
}
}
// MixColumns function mixes the columns of the state matrix.
// The method used to multiply may be difficult to understand for the inexperienced.
// Please use the references to gain more information.
void InvMixColumns(state_t* state)
{
int i;
uint8_t a, b, c, d;
for (i = 0; i < 4; ++i)
{
a = (*state)[i][0];
b = (*state)[i][1];
c = (*state)[i][2];
d = (*state)[i][3];
(*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);
(*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);
(*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);
(*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);
}
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
void InvSubBytes(state_t* state)
{
uint8_t i, j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
(*state)[j][i] = getSBoxInvert((*state)[j][i]);
}
}
}
void InvShiftRows(state_t* state)
{
uint8_t temp;
// Rotate first row 1 columns to right
temp = (*state)[3][1];
(*state)[3][1] = (*state)[2][1];
(*state)[2][1] = (*state)[1][1];
(*state)[1][1] = (*state)[0][1];
(*state)[0][1] = temp;
// Rotate second row 2 columns to right
temp = (*state)[0][2];
(*state)[0][2] = (*state)[2][2];
(*state)[2][2] = temp;
temp = (*state)[1][2];
(*state)[1][2] = (*state)[3][2];
(*state)[3][2] = temp;
// Rotate third row 3 columns to right
temp = (*state)[0][3];
(*state)[0][3] = (*state)[1][3];
(*state)[1][3] = (*state)[2][3];
(*state)[2][3] = (*state)[3][3];
(*state)[3][3] = temp;
}
inline uint8_t getSBoxValue(uint8_t num)
{
return sbox[num];
}
inline uint8_t getSBoxInvert(uint8_t num)
{
return rsbox[num];
}
// This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states.
void KeyExpansion(uint8_t* RoundKey, const uint8_t* Key)
{
unsigned i, j, k;
uint8_t tempa[4]; // Used for the column/row operations
// The first round key is the key itself.
for (i = 0; i < Nk; ++i)
{
RoundKey[(i * 4) + 0] = Key[(i * 4) + 0];
RoundKey[(i * 4) + 1] = Key[(i * 4) + 1];
RoundKey[(i * 4) + 2] = Key[(i * 4) + 2];
RoundKey[(i * 4) + 3] = Key[(i * 4) + 3];
}
// All other round keys are found from the previous round keys.
for (i = Nk; i < Nb * (Nr + 1); ++i)
{
{
k = (i - 1) * 4;
tempa[0] = RoundKey[k + 0];
tempa[1] = RoundKey[k + 1];
tempa[2] = RoundKey[k + 2];
tempa[3] = RoundKey[k + 3];
}
if (i % Nk == 0)
{
// This function shifts the 4 bytes in a word to the left once.
// [a0,a1,a2,a3] becomes [a1,a2,a3,a0]
// Function RotWord()
{
const uint8_t u8tmp = tempa[0];
tempa[0] = tempa[1];
tempa[1] = tempa[2];
tempa[2] = tempa[3];
tempa[3] = u8tmp;
}
// SubWord() is a function that takes a four-byte input word and
// applies the S-box to each of the four bytes to produce an output word.
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
tempa[0] = tempa[0] ^ Rcon[i / Nk];
}
if (Nk == 8) // AES256
{
if (i % Nk == 4)
{
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
}
}
j = i * 4; k = (i - Nk) * 4;
RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0];
RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1];
RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2];
RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3];
}
}
// Cipher is the main function that encrypts the PlainText.
void Cipher(state_t* state, const uint8_t* RoundKey)
{
uint8_t round = 0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(0, state, RoundKey);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr rounds are executed in the loop below.
// Last one without MixColumns()
for (round = 1; ; ++round)
{
SubBytes(state);
ShiftRows(state);
if (round == Nr) {
break;
}
MixColumns(state);
AddRoundKey(round, state, RoundKey);
}
// Add round key to last round
AddRoundKey(uint8_t(Nr), state, RoundKey);
}
void InvCipher(state_t* state, const uint8_t* RoundKey)
{
uint8_t round = 0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(uint8_t(Nr), state, RoundKey);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr rounds are executed in the loop below.
// Last one without InvMixColumn()
for (round = uint8_t(Nr - 1); ; --round)
{
InvShiftRows(state);
InvSubBytes(state);
AddRoundKey(round, state, RoundKey);
if (round == 0) {
break;
}
InvMixColumns(state);
}
}
protected:
std::string key_;
mode_t mode_ = mode_t::ecb;
// The number of columns comprising a state in AES. This is a constant in AES. Value=4
unsigned int Nb = 4;
unsigned int Nk = 4; // The number of 32 bit words in a key.
unsigned int Nr = 10; // The number of rounds in AES Cipher.
std::vector<uint8_t> RoundKey_{};
std::array<uint8_t, AES_BLOCKLEN> Iv_{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
// The lookup-tables are marked const so they can be placed in read-only storage instead of RAM
// The numbers below can be computed dynamically trading ROM for RAM -
// This can be useful in (embedded) bootloader applications, where ROM is often limited.
const uint8_t sbox[256] =
{
//0 1 2 3 4 5 6 7 8 9 A B C D E F
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
const uint8_t rsbox[256] =
{
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};
// The round constant word array, Rcon[i], contains the values given by
// x to the power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)
const uint8_t Rcon[11] =
{
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36
};
};
}
#endif // !__ASIO2_AES_IMPL_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_SOLARIS_H
#define BHO_PREDEF_OS_SOLARIS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_SOLARIS`
http://en.wikipedia.org/wiki/Solaris_Operating_Environment[Solaris] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `sun` | {predef_detection}
| `+__sun+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_SOLARIS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(sun) || defined(__sun) \
)
# undef BHO_OS_SOLARIS
# define BHO_OS_SOLARIS BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_SOLARIS
# define BHO_OS_SOLARIS_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_SOLARIS_NAME "Solaris"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_SOLARIS,BHO_OS_SOLARIS_NAME)
<file_sep>#include <asio2/tcp/tcp_server.hpp>
// how to use the match_role, see : https://blog.csdn.net/zhllxt/article/details/127670983
// the byte 1 head (1 bytes) : #
// the byte 2 length (1 bytes) : the body length
// the byte 3... body (n bytes) : the body content
class match_role
{
public:
explicit match_role(char c) : c_(c) {}
// The first member of the
// return value is an iterator marking one-past-the-end of the bytes that have
// been consumed by the match function.This iterator is used to calculate the
// begin parameter for any subsequent invocation of the match condition.The
// second member of the return value is true if a match has been found, false
// otherwise.
template <typename Iterator>
std::pair<Iterator, bool> operator()(Iterator begin, Iterator end) const
{
Iterator p = begin;
while (p != end)
{
// how to convert the Iterator to char*
[[maybe_unused]] const char * buf = &(*p);
// eg : How to close illegal clients
if (*p != c_)
{
// method 1:
// call the session stop function directly, you need add the init function, see below.
session_ptr_->stop();
break;
// method 2:
// return the matching success here and then determine the number of bytes received
// in the on_recv callback function, if it is 0, we close the connection in on_recv.
//return std::pair(begin, true); // head character is not #, return and kill the client
}
p++;
if (p == end) break;
int length = std::uint8_t(*p); // get content length
p++;
if (p == end) break;
if (end - p >= length)
return std::pair(p + length, true);
break;
}
return std::pair(begin, false);
}
// the asio2 framework will call this function immediately after the session is created,
// you can save the session pointer into a member variable, or do something else.
void init(std::shared_ptr<asio2::tcp_session>& session_ptr)
{
session_ptr_ = session_ptr;
}
private:
char c_;
// note : use a shared_ptr to save the session does not cause circular reference.
std::shared_ptr<asio2::tcp_session> session_ptr_;
};
#ifdef ASIO_STANDALONE
namespace asio
#else
namespace boost::asio
#endif
{
template <> struct is_match_condition<match_role> : public std::true_type {};
}
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8026";
asio2::tcp_server server;
server.bind_recv([&](auto & session_ptr, std::string_view data)
{
// how to close the illegal client, see : https://blog.csdn.net/zhllxt/article/details/127670983
if (data.size() == 0)
{
printf("close illegal client : %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port());
session_ptr->stop();
return;
}
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
// this is just a demo to show :
// even if we force one packet data to be sent twice,
// but the client must recvd whole packet once
session_ptr->async_send(data.substr(0, data.size() / 2));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
session_ptr->async_send(data.substr(data.size() / 2));
// of course you can sent the whole data once
//session_ptr->async_send(data);
}).bind_start([&]()
{
printf("start tcp server match role : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
printf("stop tcp server match role : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.start(host, port, match_role('#'));
while (std::getchar() != '\n');
server.stop();
return 0;
}
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_C_ZOS_H
#define BHO_PREDEF_LIBRARY_C_ZOS_H
#include <asio2/bho/predef/library/c/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_C_ZOS`
z/OS libc Standard C library.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__LIBREL__+` | {predef_detection}
| `+__LIBREL__+` | V.R.P
| `+__TARGET_LIB__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_LIB_C_ZOS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__LIBREL__)
# undef BHO_LIB_C_ZOS
# if !defined(BHO_LIB_C_ZOS) && defined(__LIBREL__)
# define BHO_LIB_C_ZOS BHO_PREDEF_MAKE_0X_VRRPPPP(__LIBREL__)
# endif
# if !defined(BHO_LIB_C_ZOS) && defined(__TARGET_LIB__)
# define BHO_LIB_C_ZOS BHO_PREDEF_MAKE_0X_VRRPPPP(__TARGET_LIB__)
# endif
# if !defined(BHO_LIB_C_ZOS)
# define BHO_LIB_C_ZOS BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_LIB_C_ZOS
# define BHO_LIB_C_ZOS_AVAILABLE
#endif
#define BHO_LIB_C_ZOS_NAME "z/OS"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_C_ZOS,BHO_LIB_C_ZOS_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_SESSION_PERSISTENCE_HPP__
#define __ASIO2_MQTT_SESSION_PERSISTENCE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <unordered_map>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class session_t, class args_t>
class mqtt_session_persistence
{
friend session_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using self = mqtt_session_persistence<session_t, args_t>;
/**
* @brief constructor
*/
mqtt_session_persistence()
{
}
/**
* @brief destructor
*/
~mqtt_session_persistence() = default;
public:
/**
* @brief add a mqtt session
*/
template<class StringT>
inline self& push_mqtt_session(StringT&& clientid, std::shared_ptr<session_t> session_ptr)
{
asio2::unique_locker guard(this->session_persistence_mutex_);
this->mqtt_sessions_map_[detail::to_string(std::forward<StringT>(clientid))] = std::move(session_ptr);
return (*this);
}
/**
* @brief find the mqtt session by client id
*/
inline std::shared_ptr<session_t> find_mqtt_session(const std::string& clientid)
{
asio2::shared_locker guard(this->session_persistence_mutex_);
auto iter = this->mqtt_sessions_map_.find(clientid);
return iter == this->mqtt_sessions_map_.end() ? nullptr : iter->second;
}
/**
* @brief find the mqtt session by client id
*/
inline std::shared_ptr<session_t> find_mqtt_session(const std::string_view& clientid)
{
return this->find_mqtt_session(std::string(clientid));
}
/**
* @brief remove the mqtt session by client id
*/
inline bool erase_mqtt_session(const std::string& clientid)
{
asio2::unique_locker guard(this->session_persistence_mutex_);
return this->mqtt_sessions_map_.erase(clientid) > 0;
}
/**
* @brief remove the mqtt session by client id
*/
inline bool erase_mqtt_session(const std::string_view& clientid)
{
return this->erase_mqtt_session(std::string(clientid));
}
/**
* @brief remove the mqtt session by client id and session itself
*/
inline bool erase_mqtt_session(const std::string& clientid, session_t* p)
{
asio2::unique_locker guard(this->session_persistence_mutex_);
auto iter = this->mqtt_sessions_map_.find(clientid);
if (iter != this->mqtt_sessions_map_.end())
{
if (iter->second.get() == p)
{
this->mqtt_sessions_map_.erase(iter);
return true;
}
}
return false;
}
/**
* @brief remove the mqtt session by client id and session itself
*/
inline bool erase_mqtt_session(const std::string_view& clientid, session_t* p)
{
return this->erase_mqtt_session(std::string(clientid), p);
}
/**
* @brief remove all mqtt sessions
*/
inline self& clear_mqtt_sessions()
{
asio2::unique_locker guard(this->session_persistence_mutex_);
this->mqtt_sessions_map_.clear();
return (*this);
}
protected:
/// use rwlock to make thread safe
mutable asio2::shared_mutexer session_persistence_mutex_;
///
std::unordered_map<std::string, std::shared_ptr<session_t>> mqtt_sessions_map_ ASIO2_GUARDED_BY(session_persistence_mutex_);
};
}
#endif // !__ASIO2_MQTT_SESSION_PERSISTENCE_HPP__
<file_sep>/*
Copyright <NAME> 2013-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_BLACKFIN_H
#define BHO_PREDEF_ARCHITECTURE_BLACKFIN_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_BLACKFIN`
Blackfin Processors from Analog Devices.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__bfin__+` | {predef_detection}
| `+__BFIN__+` | {predef_detection}
| `bfin` | {predef_detection}
| `BFIN` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_BLACKFIN BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__bfin__) || defined(__BFIN__) || \
defined(bfin) || defined(BFIN)
# undef BHO_ARCH_BLACKFIN
# define BHO_ARCH_BLACKFIN BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_BLACKFIN
# define BHO_ARCH_BLACKFIN_AVAILABLE
#endif
#if BHO_ARCH_BLACKFIN
# undef BHO_ARCH_WORD_BITS_16
# define BHO_ARCH_WORD_BITS_16 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_BLACKFIN_NAME "Blackfin"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_BLACKFIN,BHO_ARCH_BLACKFIN_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SILENCE_TIMER_COMPONENT_HPP__
#define __ASIO2_SILENCE_TIMER_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <chrono>
#include <asio2/base/iopool.hpp>
#include <asio2/base/log.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class silence_timer_cp
{
public:
/**
* @brief constructor
*/
explicit silence_timer_cp(io_t & io) : silence_timer_(io.context())
{
this->silence_timer_canceled_.clear();
}
/**
* @brief destructor
*/
~silence_timer_cp() = default;
public:
/**
* @brief get silence timeout value
*/
inline std::chrono::steady_clock::duration get_silence_timeout() const noexcept
{
return this->silence_timeout_;
}
/**
* @brief set silence timeout value
*/
template<class Rep, class Period>
inline derived_t & set_silence_timeout(std::chrono::duration<Rep, Period> duration) noexcept
{
if (duration > std::chrono::duration_cast<
std::chrono::duration<Rep, Period>>((std::chrono::steady_clock::duration::max)()))
this->silence_timeout_ = (std::chrono::steady_clock::duration::max)();
else
this->silence_timeout_ = duration;
return static_cast<derived_t&>(*this);
}
protected:
template<class Rep, class Period>
inline void _post_silence_timer(std::chrono::duration<Rep, Period> duration,
std::shared_ptr<derived_t> this_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = std::move(this_ptr), duration]() mutable
{
derived_t& derive = static_cast<derived_t&>(*this);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_stop_silence_timer_called_ == false);
#endif
// reset the "canceled" flag to false, see reconnect_timer_cp.hpp -> _make_reconnect_timer
this->silence_timer_canceled_.clear();
// start the timer of check silence timeout
if (duration > std::chrono::duration<Rep, Period>::zero())
{
this->silence_timer_.expires_after(duration);
this->silence_timer_.async_wait(
[&derive, this_ptr = std::move(this_ptr)](const error_code & ec) mutable
{
derive._handle_silence_timer(ec, std::move(this_ptr));
});
}
}));
}
inline void _handle_silence_timer(const error_code & ec, std::shared_ptr<derived_t> this_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT((!ec) || ec == asio::error::operation_aborted);
// ec maybe zero when timer_canceled_ is true.
if (ec == asio::error::operation_aborted || this->silence_timer_canceled_.test_and_set())
return;
this->silence_timer_canceled_.clear();
// silence duration seconds not exceed the silence timeout,post a timer
// event agagin to avoid this session shared_ptr object disappear.
std::chrono::system_clock::duration silence = derive.get_silence_duration();
if (silence < this->silence_timeout_)
{
derive._post_silence_timer(this->silence_timeout_ - silence, std::move(this_ptr));
}
else
{
// silence timeout has elasped,but has't data trans,don't post
// a timer event again,so this session, shared_ptr will disappear
// and the object will be destroyed automatically after this handler returns.
set_last_error(asio::error::timed_out);
derive._do_disconnect(asio::error::timed_out, std::move(this_ptr));
}
}
inline void _stop_silence_timer()
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.dispatch([this]() mutable
{
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_silence_timer_called_ = true;
#endif
this->silence_timer_canceled_.test_and_set();
detail::cancel_timer(this->silence_timer_);
});
}
protected:
/// timer for session silence time out
asio::steady_timer silence_timer_;
/// Why use this flag, beacuase the ec param maybe zero when the timer callback is
/// called after the timer cancel function has called already.
std::atomic_flag silence_timer_canceled_;
/// if there has no data transfer for a long time,the session will be disconnect
std::chrono::steady_clock::duration silence_timeout_ = std::chrono::milliseconds(tcp_silence_timeout);
#if defined(_DEBUG) || defined(DEBUG)
bool is_stop_silence_timer_called_ = false;
#endif
};
}
#endif // !__ASIO2_SILENCE_TIMER_COMPONENT_HPP__
<file_sep>//
// ipv6_header.hpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 <NAME> (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef __ASIO2_IPV6_HEADER_HPP__
#define __ASIO2_IPV6_HEADER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <algorithm>
#include <asio2/external/asio.hpp>
// Packet header for IPv6.
//
// The wire format of an IPv6 header is:
//
// The 'ECN' is 2 bits
//
// +-------+---------+---+---------+------------------------------+ ---
// | | | E | | ^
// |version| DS | C | flow label | |
// | (4) | (6) | N | (20) | |
// +-------+---------+---+---------+---------------+--------------+ |
// | | | | |
// | payload length | next header | hop limit | |
// | (16) | (8) | (8) | |
// +---------------+---------------+------------------------------+ 40 bytes
// | | |
// | source IPv6 address | |
// | (128) | |
// +--------------------------------------------------------------+ |
// | | |
// | destination IPv6 address | |
// | (128) | v
// +--------------------------------------------------------------+ ---
namespace asio2::detail
{
class ipv6_header
{
public:
ipv6_header()
{
std::fill(rep_, rep_ + sizeof(rep_), static_cast<unsigned char>(0));
}
inline unsigned char version() const { return (rep_[0] >> 4) & 0xF; }
inline unsigned short identification() const { return decode(4, 5); }
inline unsigned char next_header() const { return rep_[6]; }
inline unsigned char hop_limit() const { return rep_[7]; }
inline asio::ip::address_v6 source_address() const
{
asio::ip::address_v6::bytes_type bytes =
{
{
rep_[8], rep_[9], rep_[10], rep_[11],
rep_[12], rep_[13], rep_[14], rep_[15],
rep_[16], rep_[17], rep_[18], rep_[19],
rep_[20], rep_[21], rep_[22], rep_[23]
}
};
return asio::ip::address_v6(bytes);
}
inline asio::ip::address_v6 destination_address() const
{
asio::ip::address_v6::bytes_type bytes =
{
{
rep_[24], rep_[25], rep_[26], rep_[27],
rep_[28], rep_[29], rep_[30], rep_[31],
rep_[32], rep_[33], rep_[34], rep_[35],
rep_[36], rep_[37], rep_[38], rep_[39]
}
};
return asio::ip::address_v6(bytes);
}
friend std::istream& operator>>(std::istream& is, ipv6_header& header)
{
is.read(reinterpret_cast<char*>(header.rep_), 40);
if (header.version() != 6)
is.setstate(std::ios::failbit);
return is;
}
private:
inline unsigned short decode(int a, int b) const
{
return (unsigned short)((rep_[a] << 8) + rep_[b]);
}
//struct IPv6hdr {
// unsigned int ver : 4;
// unsigned int traf_class : 8;
// unsigned int flow_lab : 20;
// unsigned int length : 16;
// unsigned int next_header : 8;
// unsigned int hop_limit : 8;
// unsigned char src_addr[16];
// unsigned char dest_addr[16];
//};
unsigned char rep_[40];
};
}
#endif // __ASIO2_IPV6_HEADER_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_GCC_H
#define BHO_PREDEF_COMPILER_GCC_H
/* Other compilers that emulate this one need to be detected first. */
#include <asio2/bho/predef/compiler/clang.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_GNUC`
http://en.wikipedia.org/wiki/GNU_Compiler_Collection[Gnu GCC C/{CPP}] compiler.
Version number available as major, minor, and patch (if available).
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__GNUC__+` | {predef_detection}
| `+__GNUC__+`, `+__GNUC_MINOR__+`, `+__GNUC_PATCHLEVEL__+` | V.R.P
| `+__GNUC__+`, `+__GNUC_MINOR__+` | V.R.0
|===
*/ // end::reference[]
#define BHO_COMP_GNUC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__GNUC__)
# if !defined(BHO_COMP_GNUC_DETECTION) && defined(__GNUC_PATCHLEVEL__)
# define BHO_COMP_GNUC_DETECTION \
BHO_VERSION_NUMBER(__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__)
# endif
# if !defined(BHO_COMP_GNUC_DETECTION)
# define BHO_COMP_GNUC_DETECTION \
BHO_VERSION_NUMBER(__GNUC__,__GNUC_MINOR__,0)
# endif
#endif
#ifdef BHO_COMP_GNUC_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_GNUC_EMULATED BHO_COMP_GNUC_DETECTION
# else
# undef BHO_COMP_GNUC
# define BHO_COMP_GNUC BHO_COMP_GNUC_DETECTION
# endif
# define BHO_COMP_GNUC_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_GNUC_NAME "Gnu GCC C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_GNUC,BHO_COMP_GNUC_NAME)
#ifdef BHO_COMP_GNUC_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_GNUC_EMULATED,BHO_COMP_GNUC_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* referenced from boost/smart_ptr/detail/spinlock_std_atomic.hpp
*/
#ifndef __ASIO2_SPIN_LOCK_HPP__
#define __ASIO2_SPIN_LOCK_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <atomic>
#include <thread>
namespace asio2
{
class spin_lock
{
public:
spin_lock() noexcept
{
v_.clear();
}
bool try_lock() noexcept
{
return !v_.test_and_set(std::memory_order_acquire);
}
void lock() noexcept
{
for (unsigned k = 0; !try_lock(); ++k)
{
if (k < 16)
{
std::this_thread::yield();
}
else if (k < 32)
{
std::this_thread::sleep_for(std::chrono::milliseconds(0));
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
}
void unlock() noexcept
{
v_.clear(std::memory_order_release);
}
public:
std::atomic_flag v_;
};
}
#endif // !__ASIO2_SPIN_LOCK_HPP__
<file_sep># [indeterminate]
* Upgrade the asio library to version 1.18.2
* Upgrade the beast library to version 318 (boost-1.77.0)
* Upgrade the fmt library to version 8.0.1
* Add CMake to build the example projects
* Add mqtt, support mqtt v3.1 v3.1.1 v5.0
* Change the "_fire_init, _fire_start, _fire_stop" triggered thread from thread main to thread 0.
* Change the rpc's "call" interface function, before if it is called in the communication thread, it will do nothing, now it will degenerates into async_call and the return value is empty.
* Change the file "asio2/base/selector.hpp" to "asio2/external/asio.hpp and asio2/external/beast.hpp", used to separate asio and beast header file, previously "included tcp_lient.hpp" will contain both asio and beast, but now "included tcp_lient.hpp" will only contain asio.
* Change the serial port component which named "scp" to "serial_port".
* Modify "push_event, next_event" function, to optimized the problem where session_ptr would be copied multiple times.
* Modify "post, dispatch" function in post_cp.hpp, add "derive.selfptr()" to ensure that the asio::post callback function must hold the session_ptr.
* Split the original asynchronous function "send" into "send" and "async_send" two functions. Now "send" function means synchronous sending, "async_send" means asynchronous sending (you can find the "send" in your code and replace it with "async_send" directly). Now the return value of the "send" function is the number of bytes of data sent (formerly bool), The return value of "async_send" is void. If the synchronous function "send" is called in the communication thread, it will degenerate into an asynchronous function "async_send";
* Modify the behavior of the async_send function with the callback parameter, whenever async_send function called fails, such as an exception, the callback will be called. In previous versions, the callback was called only when write data failed.
* Modify the http::request and http::response in the http callback function to http::web_request and http::web_response, This purpose is to be compatible with boost (you can find http::request in your code and directly replace it with http::web_request. The same is for response. For details, please refer to example/http code example).
* Remove the "asio::error_code ec" parameter in all callback functions, for example: it used to be bind_start([](asio::error_code ec){}); now it's bind_start([](){}); Now you need to use asio2::get_last_error(); function to determine whether there is an error; Modified interfaces include: bind_start,bind_stop,bind_connect,bind_disconnect and async_call of rpc callback functions;
* Remove the error_code parameters in several functions, mainly include http_client::execute,ping::execute,http::make_request,http::make_response, and so on..., now you need to use asio2::get_last_error() to determine whether an error has occurred;
* Remove "thread_local static error_code ec_ignore;" in asio2/base/error.hpp.
* Resolve compiling errors under "Visual Studio 2017 - Windows XP (v141_xp)", changed the std::shared_mutex to asio2_shared_mutex marco.
* Fixed bug : after call server.stop(); in some cases, the server still accept session and the session can "recv send data" normaly. This will cause the server to never exit.
* Fixed bug : in asio2/base/error.hpp : thread_local static error_code ec_last; In vs2017 and some cases, this maybe cause crash before the "main" function.
* fixed bug : The reconnect_timer will be invalid when "client.start(...);client.stop();client.start(...);".
* fixed bug : the _fire_init() notify is not called always in thread 0.
* fixed bug : Incorrect parsing of filename and content_type in asio2/http/multipart.hpp.
* fixed bug : asio2/util/ini.hpp, When the exe file name does not contain dot "." , The automatically generated ini file name is incorrect.
* fixed bug : when call "start" with some exception, the "state" will be "starting", this will cause "start" failed next time forever.
* fixed bug : it will cause crash when call "client.start" multi times, all "ssl client" and "websocket client" will be affected by this bug, This is because multithreading reads and writes "ws_stream_".
* fixed bug : The code error traversing "http_router's wildcard_routers_" causes crash.
* fixed bug : When the timer is stopped immediately after it is started in the io_context thread, the timer will stop fails.
* fixed bug : If user has called "http::response.defer()" in the recv callback, it maybe cause crash if the session has disconnected before the "defer" has executed, beacuse the "rep_" was destroyed already at this time.
* fixed bug : If user has called "http::response.defer()" in the recv callback, and the client has not a "keep_alive" option, the response will can not be send to the client correctly.
* fixed bug : If user has called "http::response.defer()" in the recv callback, the variable "req_" maybe read write in two threads at the same time, and this maybe cause crash.
* fixed bug : it might find a callback function that does not match the id of rdc component.
* fixed bug : in some cases, after client.stop(), the client.is_stopped() maybe false.
* Fixed the problem where kcp server and client did not send fin frame correctly.
* Fixed the problem where the endian of the KCP handshake data header was not handled correctly.
* Fixed problem : when the client.stop is called, and at this time the async_send is called in another thread, the async_send maybe has unexpected behavior (e.g. async_send's callback is not called).
* Fixed unnecessary memory allocation problems in allocator to reduce the number of memory allocation. Now all timers do not use customized allocator to allocate memory, but use asio to allocate memory automatically.
* Various code fixes and improvements.
* Other general enhancements.
# 2020-12-23 version 2.7:
* Add remote data call ability.
* Other general enhancements.
# 2020-09-24 version 2.6:
* Fixed a bug in the connect_timeout_cp class that caused the program to crash.
* Fixed a bug in the ws_stream_cp class that causes program assertions to fail under debug mode.
* Fixed a bug in the rpc module that caused the program to crash after receiving illegal data.
* Rewrote the rpc_call_cp class code to support chained calls.
* Rewrote the api of http and websocket class.
* Rewrote the example code.
* Fixed and optimized the code for auto reconnection.
* A standalone version of Beast was added to support headonly http and websocket capabilities,now all functionality is no longer dependent on the Boost library.
* Rename the timeout function of rpc_client and rpc_session class to default_timeout function.
* Fixed compile warnings and errors under clang. Compiled under msvc(vs2017 vs2019) gcc8.2.0 clang10.
* Add event_guard class to enhance the reliability of event handle.
* Remove some class, the files is : httpws_server.hpp,httpws_session.hpp,httpwss_server.hpphttpwss_session.hpp;
* Various code fixes and improvements.
* Upgrade the asio library to version 1.16.1
* Upgrade the beast library to version 290 (boost-1.73.0)
* Upgrade the cereal library to version 1.3.0
* Upgrade the fmt library to version 7.0.3
# 2020-06-28 version 2.5:
* Improved SSL and certificate loading capabilities.
* Fix url_decode bug.
* Enhanced user_data() function.
* Other general enhancements.
# 2020-04-28 version 2.4:
* Add call and async_call for rpc_server.
* Add async call version without callback function.
* Other general enhancements.
* Bug fix : Fix the rpc bug of calling parameters is raw pointer or object refrence.
# 2020-01-10 version 2.3:
* Add automatic reconnection mechanism in the client when disconnection occurs.
* Bug fix : Fix the problem that data cannot be sent when the client is restarted in some cases(By adding event queue mechanism).
# 2019-11-02 version 2.2:
* Change internal send mode from synchronous to asynchronous.
# 2019-06-28 version 2.1:
* Fixed some bugs.
# 2019-06-04 version 2.0:
* ##### [BIG Update!!!]
* Rewrite all code with template metaprogramming mode.
* Version 1.x code will no longer be maintained.
# 2018-04-12 version 1.4:
* Fixed some bugs in session_mgr_t class.
* Adjust some other code.
# 2018-01-24 version 1.3:
* Replace boost::asio with asio standalone to avoid conflicts when use boost and asio2 at the same time.
* Adjust and optimize some other code.
# 2018-01-06 version 1.2:
* fixed bug : sender and session has't post close notify to listener when closed.
* Redesign the sender code.
# 2018-01-02 version 1.1:
* Upgrade the boost (asio) version to 1.66.0
* Changed the parameters of the listening interface to reference
* Modified the SSL certificate setting function, many functions need to be invoked before, now only one function needs to be called
* Optimizes a lot of internal code
# 2017-10-27 version 1.0:
* Initial release.
<file_sep>/*
* Copyright (C) 2017 <NAME>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_C_CLOUDABI_H
#define BHO_PREDEF_LIBRARY_C_CLOUDABI_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
#include <asio2/bho/predef/library/c/_prefix.h>
#if defined(__CloudABI__)
#include <stddef.h>
#endif
/* tag::reference[]
= `BHO_LIB_C_CLOUDABI`
https://github.com/NuxiNL/cloudlibc[cloudlibc] - CloudABI's standard C library.
Version number available as major, and minor.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__cloudlibc__+` | {predef_detection}
| `+__cloudlibc_major__+`, `+__cloudlibc_minor__+` | V.R.0
|===
*/ // end::reference[]
#define BHO_LIB_C_CLOUDABI BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__cloudlibc__)
# undef BHO_LIB_C_CLOUDABI
# define BHO_LIB_C_CLOUDABI \
BHO_VERSION_NUMBER(__cloudlibc_major__,__cloudlibc_minor__,0)
#endif
#if BHO_LIB_C_CLOUDABI
# define BHO_LIB_C_CLOUDABI_AVAILABLE
#endif
#define BHO_LIB_C_CLOUDABI_NAME "cloudlibc"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_C_CLOUDABI,BHO_LIB_C_CLOUDABI_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_LINUX_H
#define BHO_PREDEF_OS_LINUX_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_LINUX`
http://en.wikipedia.org/wiki/Linux[Linux] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `linux` | {predef_detection}
| `+__linux+` | {predef_detection}
| `+__linux__+` | {predef_detection}
| `+__gnu_linux__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_LINUX BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(linux) || defined(__linux) || \
defined(__linux__) || defined(__gnu_linux__) \
)
# undef BHO_OS_LINUX
# define BHO_OS_LINUX BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_LINUX
# define BHO_OS_LINUX_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_LINUX_NAME "Linux"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_LINUX,BHO_OS_LINUX_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_VACPP_H
#define BHO_PREDEF_LIBRARY_STD_VACPP_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_IBM`
http://www.ibm.com/software/awdtools/xlcpp/[IBM VACPP Standard {CPP}] library.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__IBMCPP__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_LIB_STD_IBM BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__IBMCPP__)
# undef BHO_LIB_STD_IBM
# define BHO_LIB_STD_IBM BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_LIB_STD_IBM
# define BHO_LIB_STD_IBM_AVAILABLE
#endif
#define BHO_LIB_STD_IBM_NAME "IBM VACPP"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_IBM,BHO_LIB_STD_IBM_NAME)
<file_sep>// (C) Copyright <NAME> 2001.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Modena C++ standard library (comes with KAI C++)
#if !defined(MSIPL_COMPILE_H)
# include <asio2/bho/config/no_tr1/utility.hpp>
# if !defined(__MSIPL_COMPILE_H)
# error "This is not the Modena C++ library!"
# endif
#endif
#ifndef MSIPL_NL_TYPES
#define BHO_NO_STD_MESSAGES
#endif
#ifndef MSIPL_WCHART
#define BHO_NO_STD_WSTRING
#endif
// C++0x headers not yet implemented
//
# define BHO_NO_CXX11_HDR_ARRAY
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_HDR_CODECVT
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_FORWARD_LIST
# define BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_RANDOM
# define BHO_NO_CXX11_HDR_RATIO
# define BHO_NO_CXX11_HDR_REGEX
# define BHO_NO_CXX11_HDR_SYSTEM_ERROR
# define BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_HDR_TUPLE
# define BHO_NO_CXX11_HDR_TYPE_TRAITS
# define BHO_NO_CXX11_HDR_TYPEINDEX
# define BHO_NO_CXX11_HDR_UNORDERED_MAP
# define BHO_NO_CXX11_HDR_UNORDERED_SET
# define BHO_NO_CXX11_NUMERIC_LIMITS
# define BHO_NO_CXX11_ALLOCATOR
# define BHO_NO_CXX11_POINTER_TRAITS
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
# define BHO_NO_CXX11_SMART_PTR
# define BHO_NO_CXX11_HDR_FUNCTIONAL
# define BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_STD_ALIGN
# define BHO_NO_CXX11_ADDRESSOF
# define BHO_NO_CXX11_HDR_EXCEPTION
#if defined(__has_include)
#if !__has_include(<shared_mutex>)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#elif __cplusplus < 201402
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#else
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
// C++14 features
# define BHO_NO_CXX14_STD_EXCHANGE
// C++17 features
# define BHO_NO_CXX17_STD_APPLY
# define BHO_NO_CXX17_STD_INVOKE
# define BHO_NO_CXX17_ITERATOR_TRAITS
#define BHO_STDLIB "Modena C++ standard library"
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_SGI_MIPSPRO_H
#define BHO_PREDEF_COMPILER_SGI_MIPSPRO_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_SGI`
http://en.wikipedia.org/wiki/MIPSpro[SGI MIPSpro] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__sgi+` | {predef_detection}
| `sgi` | {predef_detection}
| `+_SGI_COMPILER_VERSION+` | V.R.P
| `+_COMPILER_VERSION+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_SGI BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__sgi) || defined(sgi)
# if !defined(BHO_COMP_SGI_DETECTION) && defined(_SGI_COMPILER_VERSION)
# define BHO_COMP_SGI_DETECTION BHO_PREDEF_MAKE_10_VRP(_SGI_COMPILER_VERSION)
# endif
# if !defined(BHO_COMP_SGI_DETECTION) && defined(_COMPILER_VERSION)
# define BHO_COMP_SGI_DETECTION BHO_PREDEF_MAKE_10_VRP(_COMPILER_VERSION)
# endif
# if !defined(BHO_COMP_SGI_DETECTION)
# define BHO_COMP_SGI_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_COMP_SGI_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_SGI_EMULATED BHO_COMP_SGI_DETECTION
# else
# undef BHO_COMP_SGI
# define BHO_COMP_SGI BHO_COMP_SGI_DETECTION
# endif
# define BHO_COMP_SGI_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_SGI_NAME "SGI MIPSpro"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_SGI,BHO_COMP_SGI_NAME)
#ifdef BHO_COMP_SGI_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_SGI_EMULATED,BHO_COMP_SGI_NAME)
#endif
<file_sep>#ifndef BHO_MP11_BIND_HPP_INCLUDED
#define BHO_MP11_BIND_HPP_INCLUDED
// Copyright 2017, 2018 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/mp11/algorithm.hpp>
#include <asio2/bho/mp11/utility.hpp>
#include <cstddef>
namespace bho
{
namespace mp11
{
// mp_bind_front
template<template<class...> class F, class... T> struct mp_bind_front
{
// the indirection through mp_defer works around the language inability
// to expand U... into a fixed parameter list of an alias template
template<class... U> using fn = typename mp_defer<F, T..., U...>::type;
};
template<class Q, class... T> using mp_bind_front_q = mp_bind_front<Q::template fn, T...>;
// mp_bind_back
template<template<class...> class F, class... T> struct mp_bind_back
{
template<class... U> using fn = typename mp_defer<F, U..., T...>::type;
};
template<class Q, class... T> using mp_bind_back_q = mp_bind_back<Q::template fn, T...>;
// mp_arg
template<std::size_t I> struct mp_arg
{
template<class... T> using fn = mp_at_c<mp_list<T...>, I>;
};
using _1 = mp_arg<0>;
using _2 = mp_arg<1>;
using _3 = mp_arg<2>;
using _4 = mp_arg<3>;
using _5 = mp_arg<4>;
using _6 = mp_arg<5>;
using _7 = mp_arg<6>;
using _8 = mp_arg<7>;
using _9 = mp_arg<8>;
// mp_bind
template<template<class...> class F, class... T> struct mp_bind;
namespace detail
{
template<class V, class... T> struct eval_bound_arg
{
using type = V;
};
template<std::size_t I, class... T> struct eval_bound_arg<mp_arg<I>, T...>
{
using type = typename mp_arg<I>::template fn<T...>;
};
template<template<class...> class F, class... U, class... T> struct eval_bound_arg<mp_bind<F, U...>, T...>
{
using type = typename mp_bind<F, U...>::template fn<T...>;
};
template<template<class...> class F, class... U, class... T> struct eval_bound_arg<mp_bind_front<F, U...>, T...>
{
using type = typename mp_bind_front<F, U...>::template fn<T...>;
};
template<template<class...> class F, class... U, class... T> struct eval_bound_arg<mp_bind_back<F, U...>, T...>
{
using type = typename mp_bind_back<F, U...>::template fn<T...>;
};
} // namespace detail
template<template<class...> class F, class... T> struct mp_bind
{
#if BHO_MP11_WORKAROUND( BHO_MP11_MSVC, == 1915 )
private:
template<class... U> struct _f { using type = F<typename detail::eval_bound_arg<T, U...>::type...>; };
public:
template<class... U> using fn = typename _f<U...>::type;
#else
template<class... U> using fn = F<typename detail::eval_bound_arg<T, U...>::type...>;
#endif
};
template<class Q, class... T> using mp_bind_q = mp_bind<Q::template fn, T...>;
} // namespace mp11
} // namespace bho
#endif // #ifndef BHO_MP11_BIND_HPP_INCLUDED
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_BUFFER_WRAP_HPP__
#define __ASIO2_BUFFER_WRAP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstddef>
#include <limits>
#include <memory>
#include <type_traits>
#include <asio2/external/asio.hpp>
namespace asio2
{
namespace detail
{
static std::size_t constexpr min_size = 512;
template<class, class = std::void_t<>>
struct buffer_has_limit : std::false_type {};
template<class T>
struct buffer_has_limit<T, std::void_t<decltype(T(std::size_t(0)))>> : std::true_type {};
template<class, class = std::void_t<>>
struct buffer_has_max_size : std::false_type {};
template<class T>
struct buffer_has_max_size<T, std::void_t<decltype(std::declval<T>().max_size())>> : std::true_type {};
//template<typename T>
//struct buffer_has_limit
//{
//private:
// template<typename U>
// static auto check(bool) -> decltype(U(std::size_t(0)), std::true_type());
// template<typename U>
// static std::false_type check(...);
//public:
// static constexpr bool value = std::is_same_v<decltype(check<T>(true)), std::true_type>;
//};
//template<typename T>
//struct buffer_has_max_size
//{
//private:
// template<typename U>
// static auto check(bool) -> decltype(std::declval<U>().max_size(), std::true_type());
// template<typename U>
// static std::false_type check(...);
//public:
// static constexpr bool value = std::is_same_v<decltype(check<T>(true)), std::true_type>;
//};
// send callback indirect
struct callback_helper
{
template<class F>
typename std::enable_if_t<std::is_same_v<decltype(std::declval<F>()(
std::size_t(0)), std::true_type()), std::true_type>>
static inline call(F& f, std::size_t bytes_sent)
{
f(bytes_sent);
}
template<class F>
typename std::enable_if_t<std::is_same_v<decltype(std::declval<F>()(),
std::true_type()), std::true_type>>
static inline call(F& f, std::size_t)
{
f();
}
};
struct empty_buffer
{
using size_type = std::size_t;
inline size_type size () const noexcept { return 0; }
inline size_type max_size() const noexcept { return 0; }
inline size_type capacity() const noexcept { return 0; }
inline auto data () noexcept { return asio::buffer(asio::const_buffer ()); }
inline auto prepare (size_type) noexcept { return asio::buffer(asio::mutable_buffer()); }
inline void commit (size_type) noexcept {}
inline void consume (size_type) noexcept {}
};
template<class B>
struct proxy_buffer
{
using size_type = std::size_t;
proxy_buffer() noexcept {}
proxy_buffer(size_type) noexcept {}
inline size_type size () const noexcept { return b_->size ( ); }
inline size_type max_size() const noexcept { return b_->max_size( ); }
inline size_type capacity() const noexcept { return b_->capacity( ); }
inline auto data () noexcept { return b_->data ( ); }
inline auto prepare (size_type n) noexcept { return b_->prepare (n); }
inline void commit (size_type n) noexcept { b_->commit (n); }
inline void consume (size_type n) noexcept { b_->consume (n); }
inline void bind_buffer(B* b) { b_ = b; }
B* b_ = nullptr;
};
}
template<class buffer_t, bool has_limit = detail::buffer_has_limit<buffer_t>::value>
class buffer_wrap;
template<class buffer_t>
class buffer_wrap<buffer_t, true> : public buffer_t
{
public:
using buffer_type = buffer_t;
using buffer_t::buffer_t;
using size_type = std::size_t;
buffer_wrap() = default;
~buffer_wrap() = default;
buffer_wrap(size_type max) : buffer_t(max) {}
buffer_wrap(size_type pre, size_type max) : buffer_t(max), pre_(pre)
{
buffer_t::prepare(this->pre_);
}
buffer_wrap(buffer_wrap&& other) = default;
buffer_wrap(buffer_wrap const& other) = default;
buffer_wrap& operator=(buffer_wrap&& other) = default;
buffer_wrap& operator=(buffer_wrap const& other) = default;
inline buffer_t & base() noexcept { return (*this); }
inline buffer_t const& base() const noexcept { return (*this); }
inline size_type pre_size() const noexcept { return this->pre_; }
inline size_type max_size() const noexcept
{
if constexpr (detail::buffer_has_max_size<buffer_t>::value)
return buffer_t::max_size();
else
return (std::numeric_limits<size_type>::max)();
}
inline buffer_wrap& pre_size(size_type size) noexcept { this->pre_ = size; return (*this); }
inline buffer_wrap& max_size(size_type ) noexcept { return (*this); }
inline std::string_view data_view() noexcept
{
auto databuf = this->data();
return std::string_view{ reinterpret_cast<
std::string_view::const_pointer>(databuf.data()), databuf.size() };
}
protected:
size_type pre_ = detail::min_size;
};
template<class buffer_t>
class buffer_wrap<buffer_t, false> : public buffer_t
{
public:
using buffer_type = buffer_t;
using buffer_t::buffer_t;
using size_type = std::size_t;
buffer_wrap() = default;
~buffer_wrap() = default;
buffer_wrap(size_type max) : buffer_t(), max_(max) {}
buffer_wrap(size_type pre, size_type max) : buffer_t(), pre_(pre), max_(max)
{
buffer_t::prepare(this->pre_);
}
buffer_wrap(buffer_wrap&& other) = default;
buffer_wrap(buffer_wrap const& other) = default;
buffer_wrap& operator=(buffer_wrap&& other) = default;
buffer_wrap& operator=(buffer_wrap const& other) = default;
inline buffer_t & base() noexcept { return (*this); }
inline buffer_t const& base() const noexcept { return (*this); }
inline size_type pre_size() const noexcept { return this->pre_; }
inline size_type max_size() const noexcept
{
if constexpr (detail::buffer_has_max_size<buffer_t>::value)
return buffer_t::max_size();
else
return this->max_;
}
inline buffer_wrap& pre_size(size_type size) noexcept { this->pre_ = size; return (*this); }
inline buffer_wrap& max_size(size_type size) noexcept { this->max_ = size; return (*this); }
inline std::string_view data_view() noexcept
{
auto databuf = this->data();
return std::string_view{ reinterpret_cast<
std::string_view::const_pointer>(databuf.data()), databuf.size() };
}
protected:
size_type pre_ = detail::min_size; // prepare size
size_type max_ = (std::numeric_limits<size_type>::max)();
};
template<class B>
class buffer_wrap<detail::proxy_buffer<B>, true> : public detail::proxy_buffer<B>
{
public:
using proxy = detail::proxy_buffer<B>;
using buffer_type = B;
using detail::proxy_buffer<B>::proxy_buffer;
using size_type = std::size_t;
buffer_wrap() = default;
~buffer_wrap() = default;
buffer_wrap(size_type max) : proxy(max) {}
buffer_wrap(size_type pre, size_type max) : proxy(max), pre_(pre)
{
}
buffer_wrap(buffer_wrap&& other) = default;
buffer_wrap(buffer_wrap const& other) = default;
buffer_wrap& operator=(buffer_wrap&& other) = default;
buffer_wrap& operator=(buffer_wrap const& other) = default;
inline buffer_type & base() noexcept { return (*this->b_); }
inline buffer_type const& base() const noexcept { return (*this->b_); }
inline size_type pre_size() const noexcept { return this->pre_; }
inline size_type max_size() const noexcept
{
if constexpr (detail::buffer_has_max_size<proxy>::value)
return proxy::max_size();
else
return (std::numeric_limits<size_type>::max)();
}
inline buffer_wrap& pre_size(size_type size) noexcept { this->pre_ = size; return (*this); }
inline buffer_wrap& max_size(size_type ) noexcept { return (*this); }
inline std::string_view data_view() noexcept
{
auto databuf = this->data();
return std::string_view{ reinterpret_cast<
std::string_view::const_pointer>(databuf.data()), databuf.size() };
}
protected:
size_type pre_ = detail::min_size;
};
template<class B>
class buffer_wrap<detail::proxy_buffer<B>, false> : public detail::proxy_buffer<B>
{
public:
using proxy = detail::proxy_buffer<B>;
using buffer_type = B;
using detail::proxy_buffer<B>::proxy_buffer;
using size_type = std::size_t;
buffer_wrap() = default;
~buffer_wrap() = default;
buffer_wrap(size_type max) : proxy(), max_(max) {}
buffer_wrap(size_type pre, size_type max) : proxy(), pre_(pre), max_(max)
{
}
buffer_wrap(buffer_wrap&& other) = default;
buffer_wrap(buffer_wrap const& other) = default;
buffer_wrap& operator=(buffer_wrap&& other) = default;
buffer_wrap& operator=(buffer_wrap const& other) = default;
inline buffer_type & base() noexcept { return (*this->b_); }
inline buffer_type const& base() const noexcept { return (*this->b_); }
inline size_type pre_size() const noexcept { return this->pre_; }
inline size_type max_size() const noexcept
{
if constexpr (detail::buffer_has_max_size<proxy>::value)
return proxy::max_size();
else
return this->max_;
}
inline buffer_wrap& pre_size(size_type size) noexcept { this->pre_ = size; return (*this); }
inline buffer_wrap& max_size(size_type size) noexcept { this->max_ = size; return (*this); }
inline std::string_view data_view() noexcept
{
auto databuf = this->data();
return std::string_view{ reinterpret_cast<
std::string_view::const_pointer>(databuf.data()), databuf.size() };
}
protected:
size_type pre_ = detail::min_size; // prepare size
size_type max_ = (std::numeric_limits<size_type>::max)();
};
template<>
class buffer_wrap<detail::empty_buffer, true> : public detail::empty_buffer
{
public:
using buffer_type = detail::empty_buffer;
using size_type = std::size_t;
buffer_wrap() = default;
~buffer_wrap() = default;
buffer_wrap(size_type ) noexcept {}
buffer_wrap(size_type, size_type) noexcept {}
buffer_wrap(buffer_wrap&& other) = default;
buffer_wrap(buffer_wrap const& other) = default;
buffer_wrap& operator=(buffer_wrap&& other) = default;
buffer_wrap& operator=(buffer_wrap const& other) = default;
inline detail::empty_buffer & base() noexcept { return (*this); }
inline detail::empty_buffer const& base() const noexcept { return (*this); }
inline size_type pre_size( ) const noexcept { return 0; }
inline size_type max_size( ) const noexcept { return 0; }
inline buffer_wrap& pre_size(size_type) noexcept { return (*this); }
inline buffer_wrap& max_size(size_type) noexcept { return (*this); }
inline std::string_view data_view() noexcept
{
auto databuf = this->data();
return std::string_view{ reinterpret_cast<
std::string_view::const_pointer>(databuf.data()), databuf.size() };
}
};
template<>
class buffer_wrap<detail::empty_buffer, false> : public detail::empty_buffer
{
public:
using buffer_type = detail::empty_buffer;
using size_type = std::size_t;
buffer_wrap() = default;
~buffer_wrap() = default;
buffer_wrap(size_type ) noexcept {}
buffer_wrap(size_type, size_type) noexcept {}
buffer_wrap(buffer_wrap&& other) = default;
buffer_wrap(buffer_wrap const& other) = default;
buffer_wrap& operator=(buffer_wrap&& other) = default;
buffer_wrap& operator=(buffer_wrap const& other) = default;
inline detail::empty_buffer & base() noexcept { return (*this); }
inline detail::empty_buffer const& base() const noexcept { return (*this); }
inline size_type pre_size( ) const noexcept { return 0; }
inline size_type max_size( ) const noexcept { return 0; }
inline buffer_wrap& pre_size(size_type) noexcept { return (*this); }
inline buffer_wrap& max_size(size_type) noexcept { return (*this); }
inline std::string_view data_view() noexcept
{
auto databuf = this->data();
return std::string_view{ reinterpret_cast<
std::string_view::const_pointer>(databuf.data()), databuf.size() };
}
};
}
#endif // !__ASIO2_BUFFER_WRAP_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_CONNECT_TIME_COMPONENT_HPP__
#define __ASIO2_CONNECT_TIME_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <chrono>
namespace asio2::detail
{
template<class derived_t, class args_t>
class connect_time_cp
{
public:
/**
* @brief constructor
*/
connect_time_cp() = default;
/**
* @brief destructor
*/
~connect_time_cp() = default;
connect_time_cp(connect_time_cp&&) noexcept = default;
connect_time_cp(connect_time_cp const&) = default;
connect_time_cp& operator=(connect_time_cp&&) noexcept = default;
connect_time_cp& operator=(connect_time_cp const&) = default;
public:
/**
* @brief get build connection time
*/
inline std::chrono::time_point<std::chrono::system_clock> get_connect_time() const noexcept
{
return this->connect_time_;
}
/**
* @brief reset build connection time to system_clock::now()
*/
inline derived_t & reset_connect_time() noexcept
{
this->connect_time_ = std::chrono::system_clock::now();
return (static_cast<derived_t &>(*this));
}
/**
* @brief get connection duration of std::chrono::duration
*/
inline std::chrono::system_clock::duration get_connect_duration() const noexcept
{
return std::chrono::duration_cast<std::chrono::system_clock::duration>(
std::chrono::system_clock::now() - this->connect_time_);
}
protected:
/// build connection time
decltype(std::chrono::system_clock::now()) connect_time_ = std::chrono::system_clock::now();
};
}
#endif // !__ASIO2_CONNECT_TIME_COMPONENT_HPP__
<file_sep>// (C) Copyright <NAME> 2001.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Revision History:
// 27 Feb 2001 <NAME>
// Initial checkin.
#ifndef BHO_ITERATOR_FUNCTION_OUTPUT_ITERATOR_HPP
#define BHO_ITERATOR_FUNCTION_OUTPUT_ITERATOR_HPP
#include <iterator>
namespace bho {
namespace iterators {
template <class UnaryFunction>
class function_output_iterator {
typedef function_output_iterator self;
public:
typedef std::output_iterator_tag iterator_category;
typedef void value_type;
typedef void difference_type;
typedef void pointer;
typedef void reference;
explicit function_output_iterator() {}
explicit function_output_iterator(const UnaryFunction& f)
: m_f(f) {}
struct output_proxy {
output_proxy(UnaryFunction& f) : m_f(f) { }
template <class T> output_proxy& operator=(const T& value) {
m_f(value);
return *this;
}
UnaryFunction& m_f;
};
output_proxy operator*() { return output_proxy(m_f); }
self& operator++() { return *this; }
self& operator++(int) { return *this; }
private:
UnaryFunction m_f;
};
template <class UnaryFunction>
inline function_output_iterator<UnaryFunction>
make_function_output_iterator(const UnaryFunction& f = UnaryFunction()) {
return function_output_iterator<UnaryFunction>(f);
}
} // namespace iterators
using iterators::function_output_iterator;
using iterators::make_function_output_iterator;
} // namespace bho
#endif // BHO_ITERATOR_FUNCTION_OUTPUT_ITERATOR_HPP
<file_sep>/*
Copyright <NAME> 2011-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_CONVEX_H
#define BHO_PREDEF_ARCHITECTURE_CONVEX_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_CONVEX`
http://en.wikipedia.org/wiki/Convex_Computer[Convex Computer] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__convex__+` | {predef_detection}
| `+__convex_c1__+` | 1.0.0
| `+__convex_c2__+` | 2.0.0
| `+__convex_c32__+` | 3.2.0
| `+__convex_c34__+` | 3.4.0
| `+__convex_c38__+` | 3.8.0
|===
*/ // end::reference[]
#define BHO_ARCH_CONVEX BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__convex__)
# undef BHO_ARCH_CONVEX
# if !defined(BHO_ARCH_CONVEX) && defined(__convex_c1__)
# define BHO_ARCH_CONVEX BHO_VERSION_NUMBER(1,0,0)
# endif
# if !defined(BHO_ARCH_CONVEX) && defined(__convex_c2__)
# define BHO_ARCH_CONVEX BHO_VERSION_NUMBER(2,0,0)
# endif
# if !defined(BHO_ARCH_CONVEX) && defined(__convex_c32__)
# define BHO_ARCH_CONVEX BHO_VERSION_NUMBER(3,2,0)
# endif
# if !defined(BHO_ARCH_CONVEX) && defined(__convex_c34__)
# define BHO_ARCH_CONVEX BHO_VERSION_NUMBER(3,4,0)
# endif
# if !defined(BHO_ARCH_CONVEX) && defined(__convex_c38__)
# define BHO_ARCH_CONVEX BHO_VERSION_NUMBER(3,8,0)
# endif
# if !defined(BHO_ARCH_CONVEX)
# define BHO_ARCH_CONVEX BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_CONVEX
# define BHO_ARCH_CONVEX_AVAILABLE
#endif
#if BHO_ARCH_CONVEX
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_CONVEX_NAME "Convex Computer"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_CONVEX,BHO_ARCH_CONVEX_NAME)
<file_sep>#include <asio2/tcp/tcp_server.hpp>
class svr_listener
{
public:
void on_recv(std::shared_ptr<asio2::tcp_session>& session_ptr, std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
// this is just a demo to show :
// even if we force one packet data to be sent twice,
// but the client must recvd whole packet once
session_ptr->async_send(data.substr(0, data.size() / 2));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
session_ptr->async_send(data.substr(data.size() / 2));
}
void on_connect(std::shared_ptr<asio2::tcp_session>& session_ptr)
{
session_ptr->no_delay(true);
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}
void on_disconnect(std::shared_ptr<asio2::tcp_session>& session_ptr)
{
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
}
void on_start(asio2::tcp_server& server)
{
printf("start tcp server character : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}
void on_stop(asio2::tcp_server& server)
{
printf("stop tcp server character : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}
};
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8025";
asio2::tcp_server server;
svr_listener listener;
// bind member function
server
.bind_recv (&svr_listener::on_recv , listener) // by reference
.bind_connect (&svr_listener::on_connect , &listener) // by pointer
.bind_disconnect(&svr_listener::on_disconnect, &listener)
.bind_start (std::bind(&svr_listener::on_start, &listener, std::ref(server))) // use std::bind
.bind_stop ( &svr_listener::on_stop , listener, std::ref(server)); // not use std::bind
// Split data with a single character
//server.start(host, port, '\n');
// Split data with string
server.start(host, port, "\r\n");
while (std::getchar() != '\n');
return 0;
}
<file_sep># 基于c++和asio的网络编程框架asio2教程基础篇:1、基本概念和使用说明
由于asio2没有写技术文档,因此打算写几篇文章介绍一下如何使用它,主要是针对新手。
## 1、asio2如何使用?
- asio2这个框架的使用很简单,以VS2017举例:**在VS2017的项目上点右键 - 属性 - C/C++ - 常规 - 附加包含目录,将asio2-master/3rd和asio2-master/include这两个目录添加进去(假定你在github下载的是master分支的压缩包),然后在你的源代码中#include <asio2/asio2.hpp>即可开始使用了**
- 在/asio2/example目录下有大量的示例代码,支持cmake,可使用cmake生成visual studio的解决方案后,直接用visual studio打开去看示例即可。
- 关于asio库的使用方法,网上能搜到大量的文章和代码,这里不介绍了。我主要是通过看boost\libs\asio\example下的官方示例来学习asio的。
## 2、asio2是什么?
- asio2是在C++17基础上,基于asio库进行二次封装,编写的一个网络编程的框架,目的是想降低对asio本身使用的难度。
## 3、为什么不直接使用asio?为什么要做asio2?
- 因为asio“是一个库,而不是一个框架”,直接使用asio库的话,就要使用它的很多的API,要处理很多细节,所以这里才进行二次包装,又做了一个“框架”,目的就是把他的各种API再包装一遍,使用起来更简单,代码量大大减少,否则直接使用asio要考虑的细节就会多很多。
## 4、直接使用asio和使用asio2有什么区别?
- 我觉得区别主要还是在于使用asio的话需要自己去做这些工作:“在程序退出时,连接如何正常关闭,如何保证未发送完的数据一定是在发送之后程序才会退出”,也就是说程序如何优雅的退出这个问题。
- 看起来这个功能似乎不难做,但还是花了我大量时间去思考和试验。使用asio2的话就不需要再考虑这些问题了,比如使用tcp,那么构造一个tcp_server对象,然后直接调用tcp_server.start()启动服务,退出时直接调用tcp_server.stop()关闭服务即可,所有的连接正常关闭,数据发送,资源释放等这些问题,都不需要你再去考虑了。在tcp_server.stop()函数结束之前,会确保上面的这些问题完美处理之后,stop()函数才会结束的(stop()函数是阻塞的,假如有1千个连接,会一直阻塞到这个1千个连接都正常关闭了才会结束阻塞)。
## 5、asio2有什么优点?
- 除了上面第2条所说的优雅的退出之外,其它的优点大概有以下这些:
- 接口比较简单,主要有start-启动服务,stop-停止服务,bind_recv-绑定接收数据的回调函数,bind_connect-绑定连接成功的回调函数,......等等。
- 支持tcp,udp,http,websocket,rpc,ssl,串口等,而且形成了统一的接口,也就是这些组件的接口函数基本都一样。
- header-only,不需要单独去编译,只要包含一下头文件,就可以用了。(我个人对非header only而是需要编译的库深恶痛绝,跟非header-only的库需要配置各种编译选项等一系列问题相比,我觉得header-only的编译慢点完全不是问题)
## 6、asio2有什么缺点?
- 只支持C++,且只支持C++17以上(包含C++17)。
- 纯异步的,对同步支持非常不好。(asio2这个框架只针对大部分的通用情形去考虑的)
## 7、asio2的实现思路
- 大致思路就是使用C++的CRTP模板技术,和多重派生,使用多个小模块拼接组合成一个完整组件的方式(看代码中tcp,udp,http,websocket,rpc,ssl这些组件都是通过继承多个类来完成的),减少代码量。
- 相比virtual,使用CRTP的好处是效率更高一些,缺点是源码看起来更晦涩难懂了。
- 关于CRTP编译期多态和virtual运行期多态的效率可以看看这个评测:[https://eli.thegreenplace.net/2013/12/05/the-cost-of-dynamic-virtual-calls-vs-static-crtp-dispatch-in-c/
](https://eli.thegreenplace.net/2013/12/05/the-cost-of-dynamic-virtual-calls-vs-static-crtp-dispatch-in-c/)
## 8、关于asio2的头文件路径包含的详细说明
解压github下载的asio2压缩包之后,里面有3rd,include,test,example等文件夹,其中3rd文件夹包含了asio,cereal,fmt等一些开源库,asio2的代码需要用到这些开源库;include文件夹里面又包含了一个asio2文件夹,这个asio2文件夹是真正的asio2的相关代码;test文件夹是性能测试和单元测试相关的代码;example文件夹是各种使用示例代码;
最新版本的asio2代码可以使用cmake直接生成vs的解决方案等,打开vs解决方案即可直接编译,不需要任何其它额外设置(至于cmake如何使用,不会的话自己网络搜索)。
如果你对vs项目的头文件路径包含不熟悉,你可以直接参考cmake生成的vs解决方案里的头文件路径包含是如何设置的。
通常,如果你建立了自己的项目的vs解决方案(而不是使用的asio2里的cmake生成的解决方案),那么你需要在你的vs头文件路径包含中添加以下两项(假定你在github下载的是master分支的压缩包):asio2-master/3rd和asio2-master/include
如果你对项目头文件路径包含很熟悉,比如你有你自己的第三方库目录(比如你习惯把你自己用到的第三方库都放在这个目录下),那么你只需要把asio2-master/3rd里面的全部文件(是asio2-master/3rd里面的文件而不是asio2-master/3rd这个目录本身),和asio2-master/include里面的全部文件,放到你自己的第三方库目录即可。
## 9、在DLL中使用asio2的注意事项
#### 1、不能在Windows DLL中直接声明一个asio2的server或client对象,会导致死锁。
比如像下面这样在dllmain.cpp中直接声明了一个asio2全局对象:
```cpp
asio2::tcp_client client;
```
这就会导致在DLL的入口函数DllMain中出现死锁,死锁的原因是std::thread引起的,参考asio2/util/thread_pool.hpp开头的说明
需要用下面的方式,即声明一个指针,然后自己在DLL中做一个导出函数如Init(),在EXE中手动调用你的DLL中的导出函数Init();
然后在Init()中创建指针。如:
```cpp
// 在dllmain.cpp先声明一个全局的指针对象
std::shared_ptr<asio2::tcp_client> client;
```
```cpp
// 这是你dll中的导出函数Init
void Init()
{
client = std::make_shared<asio2::tcp_client>();
}
```
// 然后在你的EXE中手动调用这个Init导出函数即可。
#### 2、不能在Windows Dll的DLL_PROCESS_DETACH块中调用asio2的server或client对象的stop函数,会导致stop函数永远阻塞无法返回。
原因是由于在DLL_PROCESS_DETACH时,通过PostQueuedCompletionStatus投递的IOCP事件永远得不到执行。
解决办法依然是自己在DLL中做一个导出函数如Uninit(),在EXE中手动调用你的DLL中的导出函数Uninit();在Uninit函数中调用对象的stop函数;如:
```cpp
// 这是你dll中的导出函数Uninit
void Uninit()
{
client->stop();
}
```
## 项目地址:
github : [https://github.com/zhllxt/asio2](https://github.com/zhllxt/asio2)
码云 : [https://gitee.com/zhllxt/asio2](https://gitee.com/zhllxt/asio2)
### 最后编辑于2022-06-23
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_BORLAND_H
#define BHO_PREDEF_COMPILER_BORLAND_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_BORLAND`
http://en.wikipedia.org/wiki/C_plus_plus_builder[Borland {CPP}] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__BORLANDC__+` | {predef_detection}
| `+__CODEGEARC__+` | {predef_detection}
| `+__BORLANDC__+` | V.R.P
| `+__CODEGEARC__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_BORLAND BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__BORLANDC__) || defined(__CODEGEARC__)
# if !defined(BHO_COMP_BORLAND_DETECTION) && (defined(__CODEGEARC__))
# define BHO_COMP_BORLAND_DETECTION BHO_PREDEF_MAKE_0X_VVRP(__CODEGEARC__)
# endif
# if !defined(BHO_COMP_BORLAND_DETECTION)
# define BHO_COMP_BORLAND_DETECTION BHO_PREDEF_MAKE_0X_VVRP(__BORLANDC__)
# endif
#endif
#ifdef BHO_COMP_BORLAND_DETECTION
# define BHO_COMP_BORLAND_AVAILABLE
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_BORLAND_EMULATED BHO_COMP_BORLAND_DETECTION
# else
# undef BHO_COMP_BORLAND
# define BHO_COMP_BORLAND BHO_COMP_BORLAND_DETECTION
# endif
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_BORLAND_NAME "Borland C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_BORLAND,BHO_COMP_BORLAND_NAME)
#ifdef BHO_COMP_BORLAND_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_BORLAND_EMULATED,BHO_COMP_BORLAND_NAME)
#endif
<file_sep>//
// bho/assert.hpp - BHO_ASSERT(expr)
// BHO_ASSERT_MSG(expr, msg)
// BHO_VERIFY(expr)
// BHO_VERIFY_MSG(expr, msg)
// BHO_ASSERT_IS_VOID
//
// Copyright (c) 2001, 2002 <NAME> and Multi Media Ltd.
// Copyright (c) 2007, 2014 <NAME>
// Copyright (c) <NAME> 2011
// Copyright (c) 2015 <NAME>
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// Note: There are no include guards. This is intentional.
//
// See http://www.boost.org/libs/assert/assert.html for documentation.
//
//
// Stop inspect complaining about use of 'assert':
//
// boostinspect:naassert_macro
//
//
// BHO_ASSERT, BHO_ASSERT_MSG, BHO_ASSERT_IS_VOID
//
#undef BHO_ASSERT
#undef BHO_ASSERT_MSG
#undef BHO_ASSERT_IS_VOID
#if defined(BHO_DISABLE_ASSERTS) || ( defined(BHO_ENABLE_ASSERT_DEBUG_HANDLER) && defined(NDEBUG) )
# define BHO_ASSERT(expr) ((void)0)
# define BHO_ASSERT_MSG(expr, msg) ((void)0)
# define BHO_ASSERT_IS_VOID
#elif defined(BHO_ENABLE_ASSERT_HANDLER) || ( defined(BHO_ENABLE_ASSERT_DEBUG_HANDLER) && !defined(NDEBUG) )
#include <asio2/bho/config.hpp> // for BHO_LIKELY
#include <asio2/bho/current_function.hpp>
namespace bho
{
void assertion_failed(char const * expr, char const * function, char const * file, long line); // user defined
void assertion_failed_msg(char const * expr, char const * msg, char const * function, char const * file, long line); // user defined
} // namespace bho
#define BHO_ASSERT(expr) (BHO_LIKELY(!!(expr))? ((void)0): ::bho::assertion_failed(#expr, BHO_CURRENT_FUNCTION, __FILE__, __LINE__))
#define BHO_ASSERT_MSG(expr, msg) (BHO_LIKELY(!!(expr))? ((void)0): ::bho::assertion_failed_msg(#expr, msg, BHO_CURRENT_FUNCTION, __FILE__, __LINE__))
#else
# include <assert.h> // .h to support old libraries w/o <cassert> - effect is the same
# define BHO_ASSERT(expr) assert(expr)
# define BHO_ASSERT_MSG(expr, msg) assert((expr)&&(msg))
#if defined(NDEBUG)
# define BHO_ASSERT_IS_VOID
#endif
#endif
//
// BHO_VERIFY, BHO_VERIFY_MSG
//
#undef BHO_VERIFY
#undef BHO_VERIFY_MSG
#if defined(BHO_DISABLE_ASSERTS) || ( !defined(BHO_ENABLE_ASSERT_HANDLER) && defined(NDEBUG) )
# define BHO_VERIFY(expr) ((void)(expr))
# define BHO_VERIFY_MSG(expr, msg) ((void)(expr))
#else
# define BHO_VERIFY(expr) BHO_ASSERT(expr)
# define BHO_VERIFY_MSG(expr, msg) BHO_ASSERT_MSG(expr,msg)
#endif
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> dot <EMAIL> at g<EMAIL> dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_VERSION_HPP
#define BHO_BEAST_VERSION_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/config.hpp>
/* BEAST_VERSION
Identifies the API version of Beast.
This is a simple integer that is incremented by one every
time a set of code changes is merged to the develop branch.
*/
#define BHO_BEAST_VERSION 322
#define BHO_BEAST_VERSION_STRING "Boost.Beast/" BHO_STRINGIZE(BHO_BEAST_VERSION)
#ifndef BEAST_VERSION
# define BEAST_VERSION BHO_BEAST_VERSION
#endif
#ifndef BEAST_VERSION_STRING
# define BEAST_VERSION_STRING BHO_BEAST_VERSION_STRING
#endif
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_SERVER_HPP__
#define __ASIO2_HTTP_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/http/http_session.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
template<class derived_t, class session_t>
class http_server_impl_t
: public tcp_server_impl_t<derived_t, session_t>
, public http_router_t <session_t, typename session_t::args_type>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
public:
using super = tcp_server_impl_t <derived_t, session_t>;
using self = http_server_impl_t<derived_t, session_t>;
using session_type = session_t;
public:
/**
* @brief constructor
*/
template<class... Args>
explicit http_server_impl_t(Args&&... args)
: super(std::forward<Args>(args)...)
{
}
/**
* @brief destructor
*/
~http_server_impl_t()
{
this->stop();
}
/**
* @brief start the server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param service - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& service, Args&&... args)
{
return this->derived()._do_start(std::forward<String>(host), std::forward<StrOrInt>(service),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
public:
/**
* @brief bind recv listener
* @param fun - a user defined callback function
* Function signature : void(std::shared_ptr<asio2::http_session>& session_ptr,
* http::web_request& req, http::web_response& rep)
* or : void(http::web_request& req, http::web_response& rep)
*/
template<class F, class ...C>
inline derived_t & bind_recv(F&& fun, C&&... obj)
{
if constexpr (detail::is_template_callable_v<F,
std::shared_ptr<session_t>&, http::web_request&, http::web_response&>)
{
this->is_arg0_session_ = true;
this->listener_.bind(event_type::recv, observer_t<std::shared_ptr<session_t>&,
http::web_request&, http::web_response&>(std::forward<F>(fun), std::forward<C>(obj)...));
}
else
{
this->is_arg0_session_ = false;
this->listener_.bind(event_type::recv, observer_t<
http::web_request&, http::web_response&>(std::forward<F>(fun), std::forward<C>(obj)...));
}
return (this->derived());
}
/**
* @brief bind websocket upgrade listener
* @param fun - a user defined callback function
* Function signature : void(std::shared_ptr<asio2::http_session>& session_ptr)
*/
template<class F, class ...C>
inline derived_t & bind_upgrade(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::upgrade, observer_t<std::shared_ptr<session_t>&>
(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<typename... Args>
inline std::shared_ptr<session_t> _make_session(Args&&... args)
{
return super::_make_session(std::forward<Args>(args)..., *this,
this->root_directory_, this->is_arg0_session_, this->support_websocket_);
}
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
{
// can not use std::move(this_ptr), beacuse after handle stop with std::move(this_ptr),
// this object maybe destroyed, then call "this" will crash.
super::_handle_stop(ec, this_ptr);
this->derived().dispatch([this]() mutable
{
// clear the http cache
this->http_cache_.clear();
});
}
protected:
bool is_arg0_session_ = false;
};
}
namespace asio2
{
template<class derived_t, class session_t>
using http_server_impl_t = detail::http_server_impl_t<derived_t, session_t>;
template<class session_t>
class http_server_t : public detail::http_server_impl_t<http_server_t<session_t>, session_t>
{
public:
using detail::http_server_impl_t<http_server_t<session_t>, session_t>::http_server_impl_t;
};
using http_server = http_server_t<http_session>;
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
template<class session_t>
class http_rate_server_t : public asio2::http_server_impl_t<http_rate_server_t<session_t>, session_t>
{
public:
using asio2::http_server_impl_t<http_rate_server_t<session_t>, session_t>::http_server_impl_t;
};
using http_rate_server = http_rate_server_t<http_rate_session>;
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTP_SERVER_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SHARED_MTX_HPP__
#define __ASIO2_SHARED_MTX_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <mutex>
#include <shared_mutex>
// https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
// https://stackoverflow.com/questions/33608378/clang-thread-safety-annotation-and-shared-capabilities
// when compiled with "Visual Studio 2017 - Windows XP (v141_xp)"
// there is hasn't shared_mutex
#ifndef ASIO2_HAS_SHARED_MUTEX
#if defined(_MSC_VER)
#if defined(_HAS_SHARED_MUTEX)
#if _HAS_SHARED_MUTEX
#define ASIO2_HAS_SHARED_MUTEX 1
#define asio2_shared_mutex std::shared_mutex
#define asio2_shared_lock std::shared_lock
#define asio2_unique_lock std::unique_lock
#else
#define ASIO2_HAS_SHARED_MUTEX 0
#define asio2_shared_mutex std::mutex
#define asio2_shared_lock std::lock_guard
#define asio2_unique_lock std::lock_guard
#endif
#else
#define ASIO2_HAS_SHARED_MUTEX 1
#define asio2_shared_mutex std::shared_mutex
#define asio2_shared_lock std::shared_lock
#define asio2_unique_lock std::unique_lock
#endif
#else
#define ASIO2_HAS_SHARED_MUTEX 1
#define asio2_shared_mutex std::shared_mutex
#define asio2_shared_lock std::shared_lock
#define asio2_unique_lock std::unique_lock
#endif
#endif
// Enable thread safety attributes only with clang.
// The attributes can be safely erased when compiling with other compilers.
#if defined(__clang__) && (!defined(SWIG))
#define ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
#else
#define ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op
#endif
#define ASIO2_CAPABILITY(x) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
#define ASIO2_SCOPED_CAPABILITY \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
#define ASIO2_GUARDED_BY(x) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
#define ASIO2_PT_GUARDED_BY(x) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
#define ASIO2_ACQUIRED_BEFORE(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
#define ASIO2_ACQUIRED_AFTER(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
#define ASIO2_REQUIRES(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
#define ASIO2_REQUIRES_SHARED(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__))
#define ASIO2_ACQUIRE(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
#define ASIO2_ACQUIRE_SHARED(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__))
#define ASIO2_RELEASE(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
#define ASIO2_RELEASE_SHARED(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
#define ASIO2_RELEASE_GENERIC(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(release_generic_capability(__VA_ARGS__))
#define ASIO2_TRY_ACQUIRE(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
#define ASIO2_TRY_ACQUIRE_SHARED(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__))
#define ASIO2_EXCLUDES(...) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
#define ASIO2_ASSERT_CAPABILITY(x) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x))
#define ASIO2_ASSERT_SHARED_CAPABILITY(x) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x))
#define ASIO2_RETURN_CAPABILITY(x) \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
#define ASIO2_NO_THREAD_SAFETY_ANALYSIS \
ASIO2_THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
namespace asio2
{
// Defines an annotated interface for mutexes.
// These methods can be implemented to use any internal mutex implementation.
class ASIO2_CAPABILITY("mutex") shared_mutexer
{
public:
inline asio2_shared_mutex& native_handle() { return mutex_; }
// Good software engineering practice dictates that mutexes should be private members,
// because the locking mechanism used by a thread-safe class is part of its internal
// implementation. However, private mutexes can sometimes leak into the public interface
// of a class. Thread safety attributes follow normal C++ access restrictions, so if is
// a private member of , then it is an error to write in an attribute.mucc.mu
private:
mutable asio2_shared_mutex mutex_;
};
// shared_locker is an RAII class that acquires a mutex in its constructor, and
// releases it in its destructor.
class ASIO2_SCOPED_CAPABILITY shared_locker
{
public:
// Acquire mutex in shared mode, implicitly acquire *this and associate it with mutex.
explicit shared_locker(shared_mutexer& m) ASIO2_ACQUIRE_SHARED(m) : lock_(m.native_handle()) {}
// Release *this and all associated mutexes, if they are still held.
// There is no warning if the scope was already unlocked before.
// Note: can't use ASIO2_RELEASE_SHARED
// @see: https://stackoverflow.com/questions/33608378/clang-thread-safety-annotation-and-shared-capabilities
~shared_locker() ASIO2_RELEASE()
{
}
private:
asio2_shared_lock<asio2_shared_mutex> lock_;
};
// unique_locker is an RAII class that acquires a mutex in its constructor, and
// releases it in its destructor.
class ASIO2_SCOPED_CAPABILITY unique_locker
{
public:
// Acquire mutex, implicitly acquire *this and associate it with mutex.
explicit unique_locker(shared_mutexer& m) ASIO2_ACQUIRE(m) : lock_(m.native_handle()) {}
// Release *this and all associated mutexes, if they are still held.
// There is no warning if the scope was already unlocked before.
~unique_locker() ASIO2_RELEASE()
{
}
private:
asio2_unique_lock<asio2_shared_mutex> lock_;
};
}
#endif // !__ASIO2_SHARED_MTX_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_DIGNUS_H
#define BHO_PREDEF_COMPILER_DIGNUS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_SYSC`
http://www.dignus.com/dcxx/[Dignus Systems/{CPP}] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__SYSC__+` | {predef_detection}
| `+__SYSC_VER__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_SYSC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__SYSC__)
# define BHO_COMP_SYSC_DETECTION BHO_PREDEF_MAKE_10_VRRPP(__SYSC_VER__)
#endif
#ifdef BHO_COMP_SYSC_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_SYSC_EMULATED BHO_COMP_SYSC_DETECTION
# else
# undef BHO_COMP_SYSC
# define BHO_COMP_SYSC BHO_COMP_SYSC_DETECTION
# endif
# define BHO_COMP_SYSC_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_SYSC_NAME "Dignus Systems/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_SYSC,BHO_COMP_SYSC_NAME)
#ifdef BHO_COMP_SYSC_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_SYSC_EMULATED,BHO_COMP_SYSC_NAME)
#endif
<file_sep>#include <asio2/tcp/tcp_server.hpp>
decltype(std::chrono::steady_clock::now()) time1 = std::chrono::steady_clock::now();
decltype(std::chrono::steady_clock::now()) time2 = std::chrono::steady_clock::now();
std::atomic<std::size_t> recvd_bytes = 0;
bool first = true;
int main()
{
asio2::tcp_server server;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session>& session_ptr, std::string_view data)
{
if (first)
{
first = false;
time1 = std::chrono::steady_clock::now();
time2 = std::chrono::steady_clock::now();
}
recvd_bytes += data.size();
decltype(std::chrono::steady_clock::now()) time3 = std::chrono::steady_clock::now();
auto sec = std::chrono::duration_cast<std::chrono::seconds>(time3 - time2).count();
if (sec > 1)
{
time2 = time3;
sec = std::chrono::duration_cast<std::chrono::seconds>(time3 - time1).count();
double speed = (double)recvd_bytes / (double)sec / double(1024) / double(1024);
printf("%.1lf MByte/Sec connection_count:%zu\n", speed, server.get_session_count());
}
session_ptr->async_send(asio::buffer(data)); // no allocate memory
//session_ptr->async_send(data); // allocate memory
});
if (!server.start("0.0.0.0", "18081"))
printf("start failed: %s\n", asio2::last_error_msg().data());
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_C_UC_H
#define BHO_PREDEF_LIBRARY_C_UC_H
#include <asio2/bho/predef/library/c/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_C_UC`
http://en.wikipedia.org/wiki/Uclibc[uClibc] Standard C library.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__UCLIBC__+` | {predef_detection}
| `+__UCLIBC_MAJOR__+`, `+__UCLIBC_MINOR__+`, `+__UCLIBC_SUBLEVEL__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_LIB_C_UC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__UCLIBC__)
# undef BHO_LIB_C_UC
# define BHO_LIB_C_UC BHO_VERSION_NUMBER(\
__UCLIBC_MAJOR__,__UCLIBC_MINOR__,__UCLIBC_SUBLEVEL__)
#endif
#if BHO_LIB_C_UC
# define BHO_LIB_C_UC_AVAILABLE
#endif
#define BHO_LIB_C_UC_NAME "uClibc"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_C_UC,BHO_LIB_C_UC_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_CEREAL_HPP__
#define __ASIO2_CEREAL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#if defined(_MSC_VER)
# pragma warning(disable:4389) // Signed / unsigned mismatch
# pragma warning(disable:4018) // Signed / unsigned mismatch
#endif
#include <sstream>
#ifndef CEREAL_RAPIDJSON_NAMESPACE
#define CEREAL_RAPIDJSON_NAMESPACE cereal::rapidjson
#endif
#ifndef CEREAL_RAPIDJSON_NAMESPACE_BEGIN
#define CEREAL_RAPIDJSON_NAMESPACE_BEGIN namespace CEREAL_RAPIDJSON_NAMESPACE {
#endif
#ifndef CEREAL_RAPIDJSON_NAMESPACE_END
#define CEREAL_RAPIDJSON_NAMESPACE_END }
#endif
#include <cereal/cereal.hpp>
#include <cereal/types/array.hpp>
#include <cereal/types/atomic.hpp>
#include <cereal/types/bitset.hpp>
#include <cereal/types/chrono.hpp>
#include <cereal/types/complex.hpp>
#include <cereal/types/deque.hpp>
#include <cereal/types/forward_list.hpp>
#include <cereal/types/functional.hpp>
#include <cereal/types/list.hpp>
#include <cereal/types/map.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/types/optional.hpp>
#include <cereal/types/polymorphic.hpp>
#include <cereal/types/queue.hpp>
#include <cereal/types/set.hpp>
#include <cereal/types/stack.hpp>
#include <cereal/types/string.hpp>
#include <cereal/types/tuple.hpp>
#include <cereal/types/unordered_map.hpp>
#include <cereal/types/unordered_set.hpp>
#include <cereal/types/utility.hpp>
#include <cereal/types/valarray.hpp>
#include <cereal/types/variant.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/archives/portable_binary.hpp>
namespace cereal
{
using binary_oarchive = BinaryOutputArchive;
using binary_iarchive = BinaryInputArchive;
using json_oarchive = JSONOutputArchive;
using json_iarchive = JSONInputArchive;
using xml_oarchive = XMLOutputArchive;
using xml_iarchive = XMLInputArchive;
using pbinary_oarchive = PortableBinaryOutputArchive;
using pbinary_iarchive = PortableBinaryInputArchive;
using exception = Exception;
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_CEREAL_HPP__
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2003.
// (C) Copyright <NAME> 2007.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Rogue Wave std lib:
#define BHO_RW_STDLIB 1
#if !defined(__STD_RWCOMPILER_H__) && !defined(_RWSTD_VER)
# include <asio2/bho/config/no_tr1/utility.hpp>
# if !defined(__STD_RWCOMPILER_H__) && !defined(_RWSTD_VER)
# error This is not the Rogue Wave standard library
# endif
#endif
//
// figure out a consistent version number:
//
#ifndef _RWSTD_VER
# define BHO_RWSTD_VER 0x010000
#elif _RWSTD_VER < 0x010000
# define BHO_RWSTD_VER (_RWSTD_VER << 8)
#else
# define BHO_RWSTD_VER _RWSTD_VER
#endif
#ifndef _RWSTD_VER
# define BHO_STDLIB "Rogue Wave standard library version (Unknown version)"
#elif _RWSTD_VER < 0x04010200
# define BHO_STDLIB "Rogue Wave standard library version " BHO_STRINGIZE(_RWSTD_VER)
#else
# ifdef _RWSTD_VER_STR
# define BHO_STDLIB "Apache STDCXX standard library version " _RWSTD_VER_STR
# else
# define BHO_STDLIB "Apache STDCXX standard library version " BHO_STRINGIZE(_RWSTD_VER)
# endif
#endif
//
// Prior to version 2.2.0 the primary template for std::numeric_limits
// does not have compile time constants, even though specializations of that
// template do:
//
#if BHO_RWSTD_VER < 0x020200
# define BHO_NO_LIMITS_COMPILE_TIME_CONSTANTS
#endif
// Sun CC 5.5 patch 113817-07 adds long long specialization, but does not change the
// library version number (http://sunsolve6.sun.com/search/document.do?assetkey=1-21-113817):
#if BHO_RWSTD_VER <= 0x020101 && (!defined(__SUNPRO_CC) || (__SUNPRO_CC < 0x550))
# define BHO_NO_LONG_LONG_NUMERIC_LIMITS
# endif
//
// Borland version of numeric_limits lacks __int64 specialisation:
//
#ifdef BHO_BORLANDC
# define BHO_NO_MS_INT64_NUMERIC_LIMITS
#endif
//
// No std::iterator if it can't figure out default template args:
//
#if defined(_RWSTD_NO_SIMPLE_DEFAULT_TEMPLATES) || defined(RWSTD_NO_SIMPLE_DEFAULT_TEMPLATES) || (BHO_RWSTD_VER < 0x020000)
# define BHO_NO_STD_ITERATOR
#endif
//
// No iterator traits without partial specialization:
//
#if defined(_RWSTD_NO_CLASS_PARTIAL_SPEC) || defined(RWSTD_NO_CLASS_PARTIAL_SPEC)
# define BHO_NO_STD_ITERATOR_TRAITS
#endif
//
// Prior to version 2.0, std::auto_ptr was buggy, and there were no
// new-style iostreams, and no conformant std::allocator:
//
#if (BHO_RWSTD_VER < 0x020000)
# define BHO_NO_AUTO_PTR
# define BHO_NO_STRINGSTREAM
# define BHO_NO_STD_ALLOCATOR
# define BHO_NO_STD_LOCALE
#endif
//
// No template iterator constructors without member template support:
//
#if defined(RWSTD_NO_MEMBER_TEMPLATES) || defined(_RWSTD_NO_MEMBER_TEMPLATES)
# define BHO_NO_TEMPLATED_ITERATOR_CONSTRUCTORS
#endif
//
// RW defines _RWSTD_ALLOCATOR if the allocator is conformant and in use
// (the or _HPACC_ part is a hack - the library seems to define _RWSTD_ALLOCATOR
// on HP aCC systems even though the allocator is in fact broken):
//
#if !defined(_RWSTD_ALLOCATOR) || (defined(__HP_aCC) && __HP_aCC <= 33100)
# define BHO_NO_STD_ALLOCATOR
#endif
//
// If we have a std::locale, we still may not have std::use_facet:
//
#if defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE) && !defined(BHO_NO_STD_LOCALE)
# define BHO_NO_STD_USE_FACET
# define BHO_HAS_TWO_ARG_USE_FACET
#endif
//
// There's no std::distance prior to version 2, or without
// partial specialization support:
//
#if (BHO_RWSTD_VER < 0x020000) || defined(_RWSTD_NO_CLASS_PARTIAL_SPEC)
#define BHO_NO_STD_DISTANCE
#endif
//
// Some versions of the rogue wave library don't have assignable
// OutputIterators:
//
#if BHO_RWSTD_VER < 0x020100
# define BHO_NO_STD_OUTPUT_ITERATOR_ASSIGN
#endif
//
// Disable BHO_HAS_LONG_LONG when the library has no support for it.
//
#if !defined(_RWSTD_LONG_LONG) && defined(BHO_HAS_LONG_LONG)
# undef BHO_HAS_LONG_LONG
#endif
//
// check that on HP-UX, the proper RW library is used
//
#if defined(__HP_aCC) && !defined(_HP_NAMESPACE_STD)
# error "Boost requires Standard RW library. Please compile and link with -AA"
#endif
//
// Define macros specific to RW V2.2 on HP-UX
//
#if defined(__HP_aCC) && (BHO_RWSTD_VER == 0x02020100)
# ifndef __HP_TC1_MAKE_PAIR
# define __HP_TC1_MAKE_PAIR
# endif
# ifndef _HP_INSTANTIATE_STD2_VL
# define _HP_INSTANTIATE_STD2_VL
# endif
#endif
#if _RWSTD_VER < 0x05000000
# define BHO_NO_CXX11_HDR_ARRAY
#endif
// type_traits header is incomplete:
# define BHO_NO_CXX11_HDR_TYPE_TRAITS
//
// C++0x headers not yet implemented
//
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_HDR_CODECVT
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_FORWARD_LIST
# define BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_RANDOM
# define BHO_NO_CXX11_HDR_RATIO
# define BHO_NO_CXX11_HDR_REGEX
# define BHO_NO_CXX11_HDR_SYSTEM_ERROR
# define BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_HDR_TUPLE
# define BHO_NO_CXX11_HDR_TYPEINDEX
# define BHO_NO_CXX11_HDR_UNORDERED_MAP
# define BHO_NO_CXX11_HDR_UNORDERED_SET
# define BHO_NO_CXX11_NUMERIC_LIMITS
# define BHO_NO_CXX11_ALLOCATOR
# define BHO_NO_CXX11_POINTER_TRAITS
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
# define BHO_NO_CXX11_SMART_PTR
# define BHO_NO_CXX11_HDR_FUNCTIONAL
# define BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_STD_ALIGN
# define BHO_NO_CXX11_ADDRESSOF
# define BHO_NO_CXX11_HDR_EXCEPTION
#if defined(__has_include)
#if !__has_include(<shared_mutex>)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#elif __cplusplus < 201402
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#else
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
// C++14 features
# define BHO_NO_CXX14_STD_EXCHANGE
// C++17 features
# define BHO_NO_CXX17_STD_APPLY
# define BHO_NO_CXX17_STD_INVOKE
# define BHO_NO_CXX17_ITERATOR_TRAITS
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_AOP_SUBSCRIBE_HPP__
#define __ASIO2_MQTT_AOP_SUBSCRIBE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class caller_t, class args_t>
class mqtt_aop_subscribe
{
friend caller_t;
protected:
template<class Message>
inline mqtt::v5::properties_set _check_subscribe_properties(error_code& ec, Message& msg)
{
using message_type = typename detail::remove_cvref_t<Message>;
if constexpr (std::is_same_v<message_type, mqtt::v5::subscribe>)
{
// Get subscription identifier
mqtt::v5::subscription_identifier* sub_id =
msg.properties().template get_if<mqtt::v5::subscription_identifier>();
if (sub_id)
{
// The Subscription Identifier can have the value of 1 to 268,435,455.
// It is a Protocol Error if the Subscription Identifier has a value of 0
auto v = sub_id->value();
if (v < 1 || v > 268435455)
{
ASIO2_ASSERT(false);
ec = mqtt::make_error_code(mqtt::error::protocol_error);
}
else
{
std::ignore = true;
}
}
return msg.properties();
}
else
{
return {};
}
}
// must be server
template<class Message, class Response, bool IsClient = args_t::is_client>
inline std::enable_if_t<!IsClient, void>
_before_subscribe_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type = typename detail::remove_cvref_t<Message>;
bool is_v5 = std::is_same_v<message_type, mqtt::v5::subscribe>;
// A SUBACK and UNSUBACK MUST contain the Packet Identifier that was used in the
// corresponding SUBSCRIBE and UNSUBSCRIBE packet respectively [MQTT-2.2.1-6].
rep.packet_id(msg.packet_id());
// subscription properties
mqtt::v5::properties_set props = _check_subscribe_properties(ec, msg);
for (mqtt::subscription& sub : msg.subscriptions().data())
{
// Reason Codes
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901178
// error, the session will be disconnect a later
if (sub.topic_filter().empty())
{
ec = mqtt::make_error_code(mqtt::error::topic_filter_invalid);
rep.add_reason_codes(detail::to_underlying(is_v5 ?
mqtt::error::topic_filter_invalid : mqtt::error::unspecified_error));
continue;
}
mqtt::qos_type qos = sub.qos();
// error, the session will be disconnect a later
if (!mqtt::is_valid_qos(qos))
{
ec = mqtt::make_error_code(mqtt::error::unspecified_error);
rep.add_reason_codes(detail::to_underlying(mqtt::error::unspecified_error));
continue;
}
// not error, but not supported, and the session will not be disconnect
if (detail::to_underlying(qos) > caller->maximum_qos())
{
ec = mqtt::make_error_code(mqtt::error::qos_not_supported);
rep.add_reason_codes(detail::to_underlying(is_v5 ?
mqtt::error::quota_exceeded : mqtt::error::unspecified_error));
continue;
}
// not error, and supported too
rep.add_reason_codes(detail::to_underlying(qos));
typename caller_t::subnode_type node{ caller_ptr, sub, std::move(props) };
std::string_view share_name = node.share_name();
std::string_view topic_filter = node.topic_filter();
if (!share_name.empty())
{
caller->shared_targets().insert(caller_ptr, share_name, topic_filter);
}
bool inserted = caller->subs_map().insert_or_assign(
topic_filter, caller->client_id(), std::move(node)).second;
mqtt::retain_handling_type rh = sub.retain_handling();
if /**/ (rh == mqtt::retain_handling_type::send)
{
_send_retained_messages(caller_ptr, caller, sub);
}
else if (rh == mqtt::retain_handling_type::send_only_new_subscription)
{
if (inserted)
{
_send_retained_messages(caller_ptr, caller, sub);
}
}
}
}
template<class Message, class Response, bool IsClient = args_t::is_client>
inline std::enable_if_t<IsClient, void>
_before_subscribe_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
ASIO2_ASSERT(false && "client should't recv the subscribe message");
}
inline void _send_retained_messages(
std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::subscription& sub)
{
detail::ignore_unused(caller_ptr, caller, sub);
// use push_event to ensure the publish message is sent to clients must after mqtt
// response is sent already.
caller->push_event(
[caller_ptr, caller, sub = std::move(sub), topic_filter = std::string{ sub.topic_filter() }]
(event_queue_guard<caller_t> g) mutable
{
detail::ignore_unused(g);
mqtt::v5::properties_set props;
caller->retained_messages().find(topic_filter, [caller_ptr, caller, &sub, &props]
(mqtt::rmnode& node) mutable
{
std::visit([caller_ptr, caller, &sub, &props](auto& pub) mutable
{
using T = asio2::detail::remove_cvref_t<decltype(pub)>;
if constexpr (mqtt::is_publish_message<T>())
{
caller->_send_publish_to_subscriber(caller_ptr, sub, props, pub);
}
else
{
ASIO2_ASSERT(false);
}
}, node.message.base());
});
});
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::subscribe& msg, mqtt::v3::suback& rep)
{
if (_before_subscribe_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::subscribe& msg, mqtt::v4::suback& rep)
{
if (_before_subscribe_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::subscribe& msg, mqtt::v5::suback& rep)
{
if (_before_subscribe_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::subscribe& msg, mqtt::v3::suback& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::subscribe& msg, mqtt::v4::suback& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::subscribe& msg, mqtt::v5::suback& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
};
}
#endif // !__ASIO2_MQTT_AOP_SUBSCRIBE_HPP__
<file_sep>// (C) Copyright <NAME> 2001.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Greenhills C++ compiler setup:
#define BHO_COMPILER "Greenhills C++ version " BHO_STRINGIZE(__ghs)
#include <asio2/bho/config/compiler/common_edg.hpp>
//
// versions check:
// we don't support Greenhills prior to version 0:
#if __ghs < 0
# error "Compiler not supported or configured - please reconfigure"
#endif
//
// last known and checked version is 0:
#if (__ghs > 0)
# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown compiler version - please run the configure tests and report the results"
# endif
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_CLIENT_HPP__
#define __ASIO2_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdint>
#include <memory>
#include <chrono>
#include <atomic>
#include <string>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/log.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/object.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/base/detail/ecs.hpp>
#include <asio2/base/impl/thread_id_cp.hpp>
#include <asio2/base/impl/connect_time_cp.hpp>
#include <asio2/base/impl/alive_time_cp.hpp>
#include <asio2/base/impl/user_data_cp.hpp>
#include <asio2/base/impl/socket_cp.hpp>
#include <asio2/base/impl/connect_cp.hpp>
#include <asio2/base/impl/shutdown_cp.hpp>
#include <asio2/base/impl/close_cp.hpp>
#include <asio2/base/impl/disconnect_cp.hpp>
#include <asio2/base/impl/user_timer_cp.hpp>
#include <asio2/base/impl/post_cp.hpp>
#include <asio2/base/impl/connect_timeout_cp.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
#include <asio2/base/impl/condition_event_cp.hpp>
#include <asio2/base/impl/reconnect_timer_cp.hpp>
#include <asio2/base/impl/send_cp.hpp>
#include <asio2/component/rdc/rdc_call_cp.hpp>
#include <asio2/component/socks/socks5_client.hpp>
namespace asio2
{
class client
{
public:
inline constexpr static bool is_session() noexcept { return false; }
inline constexpr static bool is_client () noexcept { return true ; }
inline constexpr static bool is_server () noexcept { return false; }
};
}
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
template<class derived_t, class args_t>
class client_impl_t
: public asio2::client
, public object_t <derived_t >
, public iopool_cp <derived_t, args_t>
, public thread_id_cp <derived_t, args_t>
, public event_queue_cp <derived_t, args_t>
, public user_data_cp <derived_t, args_t>
, public connect_time_cp <derived_t, args_t>
, public alive_time_cp <derived_t, args_t>
, public socket_cp <derived_t, args_t>
, public connect_cp <derived_t, args_t>
, public shutdown_cp <derived_t, args_t>
, public close_cp <derived_t, args_t>
, public disconnect_cp <derived_t, args_t>
, public reconnect_timer_cp <derived_t, args_t>
, public user_timer_cp <derived_t, args_t>
, public connect_timeout_cp <derived_t, args_t>
, public send_cp <derived_t, args_t>
, public post_cp <derived_t, args_t>
, public condition_event_cp <derived_t, args_t>
, public rdc_call_cp <derived_t, args_t>
, public socks5_client_impl <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
public:
using super = object_t <derived_t >;
using self = client_impl_t<derived_t, args_t>;
using iopoolcp = iopool_cp <derived_t, args_t>;
using args_type = args_t;
using key_type = std::size_t;
using buffer_type = typename args_t::buffer_t;
using send_cp<derived_t, args_t>::send;
using send_cp<derived_t, args_t>::async_send;
public:
/**
* @brief constructor
* @throws maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
template<class ThreadCountOrScheduler, class ...Args>
explicit client_impl_t(
std::size_t init_buf_size,
std::size_t max_buf_size,
ThreadCountOrScheduler&& tcos,
Args&&... args
)
: super()
, iopool_cp <derived_t, args_t>(std::forward<ThreadCountOrScheduler>(tcos))
, event_queue_cp <derived_t, args_t>()
, user_data_cp <derived_t, args_t>()
, connect_time_cp <derived_t, args_t>()
, alive_time_cp <derived_t, args_t>()
, socket_cp <derived_t, args_t>(iopoolcp::_get_io(0).context(), std::forward<Args>(args)...)
, connect_cp <derived_t, args_t>()
, shutdown_cp <derived_t, args_t>()
, close_cp <derived_t, args_t>()
, disconnect_cp <derived_t, args_t>()
, reconnect_timer_cp <derived_t, args_t>()
, user_timer_cp <derived_t, args_t>()
, connect_timeout_cp <derived_t, args_t>()
, send_cp <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp <derived_t, args_t>()
, rdc_call_cp <derived_t, args_t>()
, rallocator_()
, wallocator_()
, listener_ ()
, io_ (iopoolcp::_get_io(0))
, buffer_ (init_buf_size, max_buf_size)
{
#if defined(ASIO2_ENABLE_LOG)
#if defined(ASIO2_ALLOCATOR_STORAGE_SIZE)
static_assert(decltype(rallocator_)::storage_size == ASIO2_ALLOCATOR_STORAGE_SIZE);
static_assert(decltype(wallocator_)::storage_size == ASIO2_ALLOCATOR_STORAGE_SIZE);
#endif
#endif
}
/**
* @brief destructor
*/
~client_impl_t()
{
}
/**
* @brief start the client
*/
inline bool start() noexcept
{
ASIO2_ASSERT(this->io_.running_in_this_thread());
this->stopped_ = false;
return true;
}
/**
* @brief async start the client
*/
inline bool async_start() noexcept
{
ASIO2_ASSERT(this->io_.running_in_this_thread());
this->stopped_ = false;
return true;
}
/**
* @brief stop the client
*/
inline void stop()
{
ASIO2_ASSERT(this->io_.running_in_this_thread());
// can't use post, we need ensure when the derived stop is called, the chain
// must be executed completed.
this->derived().dispatch([this]() mutable
{
// close reconnect timer
this->_stop_reconnect_timer();
// close connect timeout timer
this->_stop_connect_timeout_timer();
// close user custom timers
this->_dispatch_stop_all_timers();
// close all posted timed tasks
this->_dispatch_stop_all_timed_events();
// close all async_events
this->notify_all_condition_events();
// can't use push event to close the socket, beacuse when used with websocket,
// the websocket's async_close will be called, and the chain will passed into
// the async_close, but the async_close will cause the chain interrupted, and
// we don't know when the async_close will be completed, if another push event
// was called during async_close executing, then here push event will after
// the another event in the queue.
// clear recv buffer
this->buffer().consume(this->buffer().size());
// destroy user data, maybe the user data is self shared_ptr, if
// don't destroy it, will cause loop refrence.
// read/write user data in other thread which is not the io_context
// thread maybe cause crash.
this->user_data_.reset();
// destroy the ecs
this->ecs_.reset();
//
this->reset_life_id();
//
this->stopped_ = true;
});
}
/**
* @brief check whether the client is started
*/
inline bool is_started()
{
return (this->state_ == state_t::started && this->socket().is_open());
}
/**
* @brief check whether the client is stopped
*/
inline bool is_stopped()
{
return (this->state_ == state_t::stopped && !this->socket().is_open() && this->stopped_);
}
/**
* @brief get this object hash key
*/
inline key_type hash_key() const noexcept
{
return reinterpret_cast<key_type>(this);
}
/**
* @brief get the buffer object refrence
*/
inline buffer_wrap<buffer_type> & buffer() noexcept { return this->buffer_; }
/**
* @brief get the io object refrence
*/
inline io_t & io() noexcept { return this->io_; }
/**
* @brief set the default remote call timeout for rpc/rdc
*/
template<class Rep, class Period>
inline derived_t & set_default_timeout(std::chrono::duration<Rep, Period> duration) noexcept
{
this->rc_timeout_ = duration;
return (this->derived());
}
/**
* @brief get the default remote call timeout for rpc/rdc
*/
inline std::chrono::steady_clock::duration get_default_timeout() noexcept
{
return this->rc_timeout_;
}
protected:
/**
* @brief get the recv/read allocator object refrence
*/
inline auto & rallocator() noexcept { return this->rallocator_; }
/**
* @brief get the send/write allocator object refrence
*/
inline auto & wallocator() noexcept { return this->wallocator_; }
inline listener_t & listener() noexcept { return this->listener_; }
inline std::atomic<state_t> & state () noexcept { return this->state_; }
inline const char* life_id () noexcept { return this->life_id_.get(); }
inline void reset_life_id () noexcept { this->life_id_ = std::make_unique<char>(); }
protected:
/// The memory to use for handler-based custom memory allocation. used fo recv/read.
handler_memory<std::true_type , assizer<args_t>> rallocator_;
/// The memory to use for handler-based custom memory allocation. used fo send/write.
handler_memory<std::false_type, assizer<args_t>> wallocator_;
/// listener
listener_t listener_;
/// The io_context wrapper used to handle the connect/recv/send event.
io_t & io_;
/// buffer
buffer_wrap<buffer_type> buffer_;
/// state
std::atomic<state_t> state_ = state_t::stopped;
/// Remote call (rpc/rdc) response timeout.
std::chrono::steady_clock::duration rc_timeout_ = std::chrono::milliseconds(http_execute_timeout);
/// the pointer of ecs_t
std::shared_ptr<ecs_base> ecs_;
/// client has two status:
/// 1. completely stopped.
/// 2. disconnected but not stopped, the timer or other event are running.
bool stopped_ = true;
/// Whether the async_read... is called.
bool reading_ = false;
/// Used to solve this problem:
///
/// client_ptr->bind_connect([client_ptr]()
/// {
/// client_ptr->async_send(...);
/// });
///
/// client_ptr->post([client_ptr]()
/// {
/// client_ptr->stop();
/// client_ptr->start(...);
///
/// client_ptr->stop();
/// client_ptr->start(...);
/// });
///
/// We wanted is :
///
/// stop event
/// start event
/// async send event
/// stop event
/// start event
/// async send event
///
/// but beacuse the async send will push event into the event queue, so the
/// event queue will be like this:
///
/// stop event
/// start event
/// stop event
/// start event
/// async send event
/// async send event
///
/// the async send will be called twice for the last time started client.
std::unique_ptr<char> life_id_ = std::make_unique<char>();
#if defined(_DEBUG) || defined(DEBUG)
std::atomic<int> post_send_counter_ = 0;
std::atomic<int> post_recv_counter_ = 0;
#endif
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_CLIENT_HPP__
<file_sep>/*
Copyright <NAME> 2015
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_HARDWARE_SIMD_X86_H
#define BHO_PREDEF_HARDWARE_SIMD_X86_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/hardware/simd/x86/versions.h>
/* tag::reference[]
= `BHO_HW_SIMD_X86`
The SIMD extension for x86 (*if detected*).
Version number depends on the most recent detected extension.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__SSE__+` | {predef_detection}
| `+_M_X64+` | {predef_detection}
| `_M_IX86_FP >= 1` | {predef_detection}
| `+__SSE2__+` | {predef_detection}
| `+_M_X64+` | {predef_detection}
| `_M_IX86_FP >= 2` | {predef_detection}
| `+__SSE3__+` | {predef_detection}
| `+__SSSE3__+` | {predef_detection}
| `+__SSE4_1__+` | {predef_detection}
| `+__SSE4_2__+` | {predef_detection}
| `+__AVX__+` | {predef_detection}
| `+__FMA__+` | {predef_detection}
| `+__AVX2__+` | {predef_detection}
|===
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__SSE__+` | BHO_HW_SIMD_X86_SSE_VERSION
| `+_M_X64+` | BHO_HW_SIMD_X86_SSE_VERSION
| `_M_IX86_FP >= 1` | BHO_HW_SIMD_X86_SSE_VERSION
| `+__SSE2__+` | BHO_HW_SIMD_X86_SSE2_VERSION
| `+_M_X64+` | BHO_HW_SIMD_X86_SSE2_VERSION
| `_M_IX86_FP >= 2` | BHO_HW_SIMD_X86_SSE2_VERSION
| `+__SSE3__+` | BHO_HW_SIMD_X86_SSE3_VERSION
| `+__SSSE3__+` | BHO_HW_SIMD_X86_SSSE3_VERSION
| `+__SSE4_1__+` | BHO_HW_SIMD_X86_SSE4_1_VERSION
| `+__SSE4_2__+` | BHO_HW_SIMD_X86_SSE4_2_VERSION
| `+__AVX__+` | BHO_HW_SIMD_X86_AVX_VERSION
| `+__FMA__+` | BHO_HW_SIMD_X86_FMA3_VERSION
| `+__AVX2__+` | BHO_HW_SIMD_X86_AVX2_VERSION
|===
*/ // end::reference[]
#define BHO_HW_SIMD_X86 BHO_VERSION_NUMBER_NOT_AVAILABLE
#undef BHO_HW_SIMD_X86
#if !defined(BHO_HW_SIMD_X86) && defined(__MIC__)
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_MIC_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && defined(__AVX2__)
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_AVX2_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && defined(__AVX__)
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_AVX_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && defined(__FMA__)
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_FMA_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && defined(__SSE4_2__)
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_SSE4_2_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && defined(__SSE4_1__)
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_SSE4_1_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && defined(__SSSE3__)
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_SSSE3_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && defined(__SSE3__)
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_SSE3_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && (defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2))
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_SSE2_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && (defined(__SSE__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 1))
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_SSE_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86) && defined(__MMX__)
# define BHO_HW_SIMD_X86 BHO_HW_SIMD_X86_MMX_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86)
# define BHO_HW_SIMD_X86 BHO_VERSION_NUMBER_NOT_AVAILABLE
#else
# define BHO_HW_SIMD_X86_AVAILABLE
#endif
#define BHO_HW_SIMD_X86_NAME "x86 SIMD"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_HW_SIMD_X86, BHO_HW_SIMD_X86_NAME)
<file_sep>#ifndef BHO_CORE_TYPEINFO_HPP_INCLUDED
#define BHO_CORE_TYPEINFO_HPP_INCLUDED
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
// core::typeinfo, BHO_CORE_TYPEID
//
// Copyright 2007, 2014 <NAME>
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <asio2/bho/config.hpp>
#if defined( BHO_NO_TYPEID )
#include <asio2/bho/current_function.hpp>
#include <functional>
#include <cstring>
namespace bho
{
namespace core
{
class typeinfo
{
private:
typeinfo( typeinfo const& );
typeinfo& operator=( typeinfo const& );
char const * name_;
void (*lib_id_)();
public:
typeinfo( char const * name, void (*lib_id)() ): name_( name ), lib_id_( lib_id )
{
}
bool operator==( typeinfo const& rhs ) const
{
#if ( defined(_WIN32) || defined(__CYGWIN__) ) && ( defined(__GNUC__) || defined(__clang__) ) && !defined(BHO_DISABLE_CURRENT_FUNCTION)
return lib_id_ == rhs.lib_id_? this == &rhs: std::strcmp( name_, rhs.name_ ) == 0;
#else
return this == &rhs;
#endif
}
bool operator!=( typeinfo const& rhs ) const
{
return !( *this == rhs );
}
bool before( typeinfo const& rhs ) const
{
#if ( defined(_WIN32) || defined(__CYGWIN__) ) && ( defined(__GNUC__) || defined(__clang__) ) && !defined(BHO_DISABLE_CURRENT_FUNCTION)
return lib_id_ == rhs.lib_id_? std::less< typeinfo const* >()( this, &rhs ): std::strcmp( name_, rhs.name_ ) < 0;
#else
return std::less< typeinfo const* >()( this, &rhs );
#endif
}
char const* name() const
{
return name_;
}
};
inline char const * demangled_name( core::typeinfo const & ti )
{
return ti.name();
}
} // namespace core
namespace detail
{
template<class T> struct BHO_SYMBOL_VISIBLE core_typeid_
{
static bho::core::typeinfo ti_;
static char const * name()
{
return BHO_CURRENT_FUNCTION;
}
};
BHO_SYMBOL_VISIBLE inline void core_typeid_lib_id()
{
}
template<class T> bho::core::typeinfo core_typeid_< T >::ti_( core_typeid_< T >::name(), &core_typeid_lib_id );
template<class T> struct core_typeid_< T & >: core_typeid_< T >
{
};
template<class T> struct core_typeid_< T const >: core_typeid_< T >
{
};
template<class T> struct core_typeid_< T volatile >: core_typeid_< T >
{
};
template<class T> struct core_typeid_< T const volatile >: core_typeid_< T >
{
};
} // namespace detail
} // namespace bho
#define BHO_CORE_TYPEID(T) (bho::detail::core_typeid_<T>::ti_)
#else
#include <asio2/bho/core/demangle.hpp>
#include <typeinfo>
namespace bho
{
namespace core
{
#if defined( BHO_NO_STD_TYPEINFO )
typedef ::type_info typeinfo;
#else
typedef std::type_info typeinfo;
#endif
inline std::string demangled_name( core::typeinfo const & ti )
{
return core::demangle( ti.name() );
}
} // namespace core
} // namespace bho
#define BHO_CORE_TYPEID(T) typeid(T)
#endif
#endif // #ifndef BHO_CORE_TYPEINFO_HPP_INCLUDED
<file_sep>#include <asio2/tcp/tcp_server.hpp>
void on_recv(std::shared_ptr<asio2::tcp_session>& session_ptr, std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}
void on_connect(std::shared_ptr<asio2::tcp_session>& session_ptr)
{
session_ptr->no_delay(true);
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}
void on_disconnect(std::shared_ptr<asio2::tcp_session>& session_ptr)
{
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
}
void on_start(asio2::tcp_server& server)
{
printf("start tcp server dgram : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}
void on_stop(asio2::tcp_server& server)
{
printf("stop tcp server dgram : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8027";
// Specify the "max recv buffer size" to avoid malicious packets, if some client
// sent data packets size is too long to the "max recv buffer size", then the
// client will be disconnect automatic .
asio2::tcp_server server(
512, // the initialize recv buffer size :
1024, // the max recv buffer size :
4 // the thread count :
);
// bind global function
server
.bind_recv (on_recv) // use global function
.bind_connect (on_connect)
.bind_disconnect(on_disconnect)
.bind_start (std::bind(on_start, std::ref(server))) // use std::bind
.bind_stop ( on_stop , std::ref(server)); // not use std::bind
server.start(host, port, asio2::use_dgram); // dgram tcp
while (std::getchar() != '\n');
server.stop();
return 0;
}
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_SUNPRO_H
#define BHO_PREDEF_COMPILER_SUNPRO_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_SUNPRO`
http://en.wikipedia.org/wiki/Oracle_Solaris_Studio[Oracle Solaris Studio] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__SUNPRO_CC+` | {predef_detection}
| `+__SUNPRO_C+` | {predef_detection}
| `+__SUNPRO_CC+` | V.R.P
| `+__SUNPRO_C+` | V.R.P
| `+__SUNPRO_CC+` | VV.RR.P
| `+__SUNPRO_C+` | VV.RR.P
|===
*/ // end::reference[]
#define BHO_COMP_SUNPRO BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__SUNPRO_CC) || defined(__SUNPRO_C)
# if !defined(BHO_COMP_SUNPRO_DETECTION) && defined(__SUNPRO_CC)
# if (__SUNPRO_CC < 0x5100)
# define BHO_COMP_SUNPRO_DETECTION BHO_PREDEF_MAKE_0X_VRP(__SUNPRO_CC)
# else
# define BHO_COMP_SUNPRO_DETECTION BHO_PREDEF_MAKE_0X_VVRRP(__SUNPRO_CC)
# endif
# endif
# if !defined(BHO_COMP_SUNPRO_DETECTION) && defined(__SUNPRO_C)
# if (__SUNPRO_C < 0x5100)
# define BHO_COMP_SUNPRO_DETECTION BHO_PREDEF_MAKE_0X_VRP(__SUNPRO_C)
# else
# define BHO_COMP_SUNPRO_DETECTION BHO_PREDEF_MAKE_0X_VVRRP(__SUNPRO_C)
# endif
# endif
# if !defined(BHO_COMP_SUNPRO_DETECTION)
# define BHO_COMP_SUNPRO_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_COMP_SUNPRO_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_SUNPRO_EMULATED BHO_COMP_SUNPRO_DETECTION
# else
# undef BHO_COMP_SUNPRO
# define BHO_COMP_SUNPRO BHO_COMP_SUNPRO_DETECTION
# endif
# define BHO_COMP_SUNPRO_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_SUNPRO_NAME "Oracle Solaris Studio"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_SUNPRO,BHO_COMP_SUNPRO_NAME)
#ifdef BHO_COMP_SUNPRO_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_SUNPRO_EMULATED,BHO_COMP_SUNPRO_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* chinese : http://mqtt.p2hp.com/mqtt-5-0
* english : https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_PROTOCOL_V5_HPP__
#define __ASIO2_MQTT_PROTOCOL_V5_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/mqtt/core.hpp>
namespace asio2::mqtt::v5
{
static constexpr std::uint8_t version_number = asio2::detail::to_underlying(mqtt::version::v5);
/**
* Property
*
* A Property consists of an Identifier which defines its usage and data type, followed by a value.
* The Identifier is encoded as a Variable Byte Integer. A Control Packet which contains an Identifier
* which is not valid for its packet type, or contains a value not of the specified data type, is a
* Malformed Packet. If received, use a CONNACK or DISCONNECT packet with Reason Code 0x81 (Malformed Packet)
* as described in section 4.13 Handling errors. There is no significance in the order of Properties with
* different Identifiers.
*
* Although the Property Identifier is defined as a Variable Byte Integer, in this version of the
* specification all of the Property Identifiers are one byte long.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901027
*/
enum class property_type : std::int32_t
{
payload_format_indicator = 1, // Byte
message_expiry_interval = 2, // Four Byte Integer
content_type = 3, // UTF-8 Encoded String
response_topic = 8, // UTF-8 Encoded String
correlation_data = 9, // Binary Data
subscription_identifier = 11, // Variable Byte Integer
session_expiry_interval = 17, // Four Byte Integer
assigned_client_identifier = 18, // UTF-8 Encoded String
server_keep_alive = 19, // Two Byte Integer
authentication_method = 21, // UTF-8 Encoded String
authentication_data = 22, // Binary Data
request_problem_information = 23, // Byte
will_delay_interval = 24, // Four Byte Integer
request_response_information = 25, // Byte
response_information = 26, // UTF-8 Encoded String
server_reference = 28, // UTF-8 Encoded String
reason_string = 31, // UTF-8 Encoded String
receive_maximum = 33, // Two Byte Integer
topic_alias_maximum = 34, // Two Byte Integer
topic_alias = 35, // Two Byte Integer
maximum_qos = 36, // Byte
retain_available = 37, // Byte
user_property = 38, // UTF-8 String Pair
maximum_packet_size = 39, // Four Byte Integer
wildcard_subscription_available = 40, // Byte
subscription_identifier_available = 41, // Byte
shared_subscription_available = 42, // Byte
};
}
namespace asio2::mqtt
{
template<typename = void>
inline constexpr std::string_view to_string(v5::property_type type)
{
using namespace std::string_view_literals;
switch (type)
{
case v5::property_type::payload_format_indicator : return "payload_format_indicator"sv;
case v5::property_type::message_expiry_interval : return "message_expiry_interval"sv;
case v5::property_type::content_type : return "content_type"sv;
case v5::property_type::response_topic : return "response_topic"sv;
case v5::property_type::correlation_data : return "correlation_data"sv;
case v5::property_type::subscription_identifier : return "subscription_identifier"sv;
case v5::property_type::session_expiry_interval : return "session_expiry_interval"sv;
case v5::property_type::assigned_client_identifier : return "assigned_client_identifier"sv;
case v5::property_type::server_keep_alive : return "server_keep_alive"sv;
case v5::property_type::authentication_method : return "authentication_method"sv;
case v5::property_type::authentication_data : return "authentication_data"sv;
case v5::property_type::request_problem_information : return "request_problem_information"sv;
case v5::property_type::will_delay_interval : return "will_delay_interval"sv;
case v5::property_type::request_response_information : return "request_response_information"sv;
case v5::property_type::response_information : return "response_information"sv;
case v5::property_type::server_reference : return "server_reference"sv;
case v5::property_type::reason_string : return "reason_string"sv;
case v5::property_type::receive_maximum : return "receive_maximum"sv;
case v5::property_type::topic_alias_maximum : return "topic_alias_maximum"sv;
case v5::property_type::topic_alias : return "topic_alias"sv;
case v5::property_type::maximum_qos : return "maximum_qos"sv;
case v5::property_type::retain_available : return "retain_available"sv;
case v5::property_type::user_property : return "user_property"sv;
case v5::property_type::maximum_packet_size : return "maximum_packet_size"sv;
case v5::property_type::wildcard_subscription_available : return "wildcard_subscription_available"sv;
case v5::property_type::subscription_identifier_available : return "subscription_identifier_available"sv;
case v5::property_type::shared_subscription_available : return "shared_subscription_available"sv;
}
return ""sv;
};
}
namespace asio2::mqtt::v5
{
// forward declared
template<class> struct property_ops;
// forward declared
class properties_set;
/**
* A Property consists of an Identifier which defines its usage and data type, followed by a value.
* The Identifier is encoded as a Variable Byte Integer.
* A Control Packet which contains an Identifier which is not valid for its packet type, or contains
* a value not of the specified data type, is a Malformed Packet. If received, use a CONNACK or
* DISCONNECT packet with Reason Code 0x81 (Malformed Packet) as described in section 4.13 Handling
* errors. There is no significance in the order of Properties with different Identifiers.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901029
*/
template<property_type T>
struct basic_property
{
template<class> friend struct property_ops; friend class properties_set;
inline variable_byte_integer::value_type id() { return id_.value(); }
inline constexpr property_type type() { return T; }
inline constexpr std::string_view name() { return mqtt::to_string(T); }
protected:
// Property Identifier
// Although the Property Identifier is defined as a Variable Byte Integer, in this version of the
// specification all of the Property Identifiers are one byte long.
variable_byte_integer id_{ asio2::detail::to_underlying(T) };
};
/**
* Payload Format Indicator
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063
*/
template<class derived_t>
struct property_ops
{
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline derived_t& serialize(Container& buffer)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.id_ .serialize(buffer);
derive.value_.serialize(buffer);
return (derive);
}
inline derived_t& deserialize(std::string_view& data)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.id_ .deserialize(data);
derive.value_.deserialize(data);
return (derive);
}
inline std::size_t required_size()
{
derived_t& derive = static_cast<derived_t&>(*this);
return (derive.id_.required_size() + derive.value_.required_size());
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Properties
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901027
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Payload Format Indicator
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063
*/
struct payload_format_indicator
: public basic_property<property_type::payload_format_indicator>
, public property_ops<payload_format_indicator>
{
// template<class> friend struct property_ops; friend class properties_set;
// can't use the code previous line, it will cause compile error under gcc 8.2.0.
friend struct property_ops<payload_format_indicator>; friend class properties_set;
enum class format : std::uint8_t
{
binary,
string
};
payload_format_indicator() = default;
payload_format_indicator(format v) : value_(asio2::detail::to_underlying(v)) {}
/**
* 0 (0x00) Indicates that the Will Message is unspecified bytes.
* 1 (0x01) Indicates that the Will Message is UTF-8 Encoded Character Data.
*/
payload_format_indicator(std::uint8_t v) : value_(v) {}
inline one_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by the value of the Payload Format Indicator, either of: 0 or 1
one_byte_integer value_{};
};
/**
* Message Expiry Interval
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901112
*/
struct message_expiry_interval
: public basic_property<property_type::message_expiry_interval>
, public property_ops<message_expiry_interval>
{
friend struct property_ops<message_expiry_interval>; friend class properties_set;
message_expiry_interval() = default;
message_expiry_interval(std::uint32_t v) : value_(v) {}
inline four_byte_integer::value_type value() { return value_.value(); }
protected:
// The Four Byte value is the lifetime of the Application Message in seconds.
four_byte_integer value_{};
};
/**
* Content Type
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901118
*/
struct content_type
: public basic_property<property_type::content_type>
, public property_ops<content_type>
{
friend struct property_ops<content_type>; friend class properties_set;
content_type() = default;
template<class String, std::enable_if_t<asio2::detail::is_character_string_v<String>, int> = 0>
explicit content_type(String&& v) : value_(std::forward<String>(v)) {}
inline utf8_string::view_type value() { return value_.data_view(); }
protected:
// Followed by a UTF-8 Encoded String describing the content of the Application Message.
// The Content Type MUST be a UTF-8 Encoded String as defined in section 1.5.4 [MQTT-3.3.2-19].
// It is a Protocol Error to include the Content Type more than once.The value of the Content Type
// is defined by the sending and receiving application.
utf8_string value_{};
};
/**
* Response Topic
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901114
*/
struct response_topic
: public basic_property<property_type::response_topic>
, public property_ops<response_topic>
{
friend struct property_ops<response_topic>; friend class properties_set;
response_topic() = default;
template<class String, std::enable_if_t<asio2::detail::is_character_string_v<String>, int> = 0>
response_topic(String&& v) : value_(std::forward<String>(v)) {}
inline utf8_string::view_type value() { return value_.data_view(); }
protected:
// Followed by a UTF-8 Encoded String which is used as the Topic Name for a response message.
// The Response Topic MUST be a UTF-8 Encoded String as defined in section 1.5.4 [MQTT-3.3.2-13].
// The Response Topic MUST NOT contain wildcard characters [MQTT-3.3.2-14].
// It is a Protocol Error to include the Response Topic more than once.
// The presence of a Response Topic identifies the Message as a Request.
utf8_string value_{};
};
/**
* Correlation Data
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901115
*/
struct correlation_data
: public basic_property<property_type::correlation_data>
, public property_ops<correlation_data>
{
friend struct property_ops<correlation_data>; friend class properties_set;
correlation_data() = default;
template<class String, std::enable_if_t<asio2::detail::is_character_string_v<String>, int> = 0>
correlation_data(String&& v) : value_(std::forward<String>(v)) {}
inline binary_data::view_type value() { return value_.data_view(); }
protected:
// Followed by Binary Data.
// The Correlation Data is used by the sender of the Request Message to identify which request the
// Response Message is for when it is received.
// It is a Protocol Error to include Correlation Data more than once.
// If the Correlation Data is not present, the Requester does not require any correlation data.
// The Server MUST send the Correlation Data unaltered to all subscribers receiving the Application
// Message[MQTT - 3.3.2 - 16].
// The value of the Correlation Data only has meaning to the sender of the Request Message and
// receiver of the Response Message.
binary_data value_{};
};
/**
* Subscription Identifier
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901166
*/
struct subscription_identifier
: public basic_property<property_type::subscription_identifier>
, public property_ops<subscription_identifier>
{
friend struct property_ops<subscription_identifier>; friend class properties_set;
subscription_identifier() = default;
subscription_identifier(std::int32_t v) : value_(v) {}
inline variable_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Variable Byte Integer representing the identifier of the subscription.
// The Subscription Identifier can have the value of 1 to 268,435,455.
// It is a Protocol Error if the Subscription Identifier has a value of 0.
// It is a Protocol Error to include the Subscription Identifier more than once.
variable_byte_integer value_{};
};
/**
* Session Expiry Interval
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901048
*/
struct session_expiry_interval
: public basic_property<property_type::session_expiry_interval>
, public property_ops<session_expiry_interval>
{
friend struct property_ops<session_expiry_interval>; friend class properties_set;
session_expiry_interval() = default;
session_expiry_interval(std::uint32_t v) : value_(v) {}
inline four_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by the Four Byte Integer representing the Session Expiry Interval in seconds.
// It is a Protocol Error to include the Session Expiry Interval more than once.
four_byte_integer value_{};
};
/**
* Assigned Client Identifier
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901087
*/
struct assigned_client_identifier
: public basic_property<property_type::assigned_client_identifier>
, public property_ops<assigned_client_identifier>
{
friend struct property_ops<assigned_client_identifier>; friend class properties_set;
assigned_client_identifier() = default;
template<class String, std::enable_if_t<asio2::detail::is_character_string_v<String>, int> = 0>
assigned_client_identifier(String&& v) : value_(std::forward<String>(v)) {}
inline utf8_string::view_type value() { return value_.data_view(); }
protected:
// Followed by the UTF-8 string which is the Assigned Client Identifier.
// It is a Protocol Error to include the Assigned Client Identifier more than once.
utf8_string value_{};
};
/**
* Server Keep Alive
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901094
*/
struct server_keep_alive
: public basic_property<property_type::server_keep_alive>
, public property_ops<server_keep_alive>
{
friend struct property_ops<server_keep_alive>; friend class properties_set;
server_keep_alive() = default;
server_keep_alive(std::uint16_t v) : value_(v) {}
inline two_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Two Byte Integer with the Keep Alive time assigned by the Server.
// If the Server sends a Server Keep Alive on the CONNACK packet, the Client MUST use this value
// instead of the Keep Alive value the Client sent on CONNECT [MQTT-3.2.2-21].
// If the Server does not send the Server Keep Alive, the Server MUST use the Keep Alive value
// set by the Client on CONNECT [MQTT-3.2.2-22].
// It is a Protocol Error to include the Server Keep Alive more than once.
two_byte_integer value_{};
};
/**
* Authentication Method
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901055
*/
struct authentication_method
: public basic_property<property_type::authentication_method>
, public property_ops<authentication_method>
{
friend struct property_ops<authentication_method>; friend class properties_set;
authentication_method() = default;
template<class String, std::enable_if_t<asio2::detail::is_character_string_v<String>, int> = 0>
authentication_method(String&& v) : value_(std::forward<String>(v)) {}
inline utf8_string::view_type value() { return value_.data_view(); }
protected:
// Followed by a UTF-8 Encoded String containing the name of the authentication method used
// for extended authentication .
// It is a Protocol Error to include Authentication Method more than once.
// If Authentication Method is absent, extended authentication is not performed.Refer to section 4.12.
utf8_string value_{};
};
/**
* Authentication Data
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901056
*/
struct authentication_data
: public basic_property<property_type::authentication_data>
, public property_ops<authentication_data>
{
friend struct property_ops<authentication_data>; friend class properties_set;
authentication_data() = default;
template<class String, std::enable_if_t<asio2::detail::is_character_string_v<String>, int> = 0>
authentication_data(String&& v) : value_(std::forward<String>(v)) {}
inline binary_data::view_type value() { return value_.data_view(); }
protected:
// Followed by Binary Data containing authentication data.
// It is a Protocol Error to include Authentication Data if there is no Authentication Method.
// It is a Protocol Error to include Authentication Data more than once.
binary_data value_{};
};
/**
* Request Problem Information
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901053
*/
struct request_problem_information
: public basic_property<property_type::request_problem_information>
, public property_ops<request_problem_information>
{
friend struct property_ops<request_problem_information>; friend class properties_set;
request_problem_information() = default;
request_problem_information(std::uint8_t v) : value_(v) {}
inline one_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Byte with a value of either 0 or 1.
// It is a Protocol Error to include Request Problem Information more than once, or to have a
// value other than 0 or 1. If the Request Problem Information is absent, the value of 1 is used.
one_byte_integer value_{};
};
/**
* Will Delay Interval
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901062
*/
struct will_delay_interval
: public basic_property<property_type::will_delay_interval>
, public property_ops<will_delay_interval>
{
friend struct property_ops<will_delay_interval>; friend class properties_set;
will_delay_interval() = default;
will_delay_interval(std::uint32_t v) : value_(v) {}
inline four_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by the Four Byte Integer representing the Will Delay Interval in seconds.
// It is a Protocol Error to include the Will Delay Interval more than once.
// If the Will Delay Interval is absent, the default value is 0 and there is no delay before the
// Will Message is published.
four_byte_integer value_{};
};
/**
* Request Response Information
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901052
*/
struct request_response_information
: public basic_property<property_type::request_response_information>
, public property_ops<request_response_information>
{
friend struct property_ops<request_response_information>; friend class properties_set;
request_response_information() = default;
request_response_information(std::uint8_t v) : value_(v) {}
inline one_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Byte with a value of either 0 or 1.
// It is Protocol Error to include the Request Response Information more than once, or to have a
// value other than 0 or 1. If the Request Response Information is absent, the value of 0 is used.
one_byte_integer value_{};
};
/**
* Response Information
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901095
*/
struct response_information
: public basic_property<property_type::response_information>
, public property_ops<response_information>
{
friend struct property_ops<response_information>; friend class properties_set;
response_information() = default;
template<class String, std::enable_if_t<asio2::detail::is_character_string_v<String>, int> = 0>
response_information(String&& v) : value_(std::forward<String>(v)) {}
inline utf8_string::view_type value() { return value_.data_view(); }
protected:
// Followed by a UTF-8 Encoded String which is used as the basis for creating a Response Topic.
// The way in which the Client creates a Response Topic from the Response Information is not
// defined by this specification. It is a Protocol Error to include the Response Information
// more than once.
utf8_string value_{};
};
/**
* Server Reference
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901214
*/
struct server_reference
: public basic_property<property_type::server_reference>
, public property_ops<server_reference>
{
friend struct property_ops<server_reference>; friend class properties_set;
server_reference() = default;
template<class String, std::enable_if_t<asio2::detail::is_character_string_v<String>, int> = 0>
server_reference(String&& v) : value_(std::forward<String>(v)) {}
inline utf8_string::view_type value() { return value_.data_view(); }
protected:
// Followed by a UTF-8 Encoded String which can be used by the Client to identify another Server to use.
// It is a Protocol Error to include the Server Reference more than once.
utf8_string value_{};
};
/**
* Reason String
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901089
*/
struct reason_string
: public basic_property<property_type::reason_string>
, public property_ops<reason_string>
{
friend struct property_ops<reason_string>; friend class properties_set;
reason_string() = default;
template<class String, std::enable_if_t<asio2::detail::is_character_string_v<String>, int> = 0>
reason_string(String&& v) : value_(std::forward<String>(v)) {}
inline utf8_string::view_type value() { return value_.data_view(); }
protected:
// Followed by the UTF-8 Encoded String representing the reason associated with this response.
// This Reason String is a human readable string designed for diagnostics and SHOULD NOT be
// parsed by the Client.
utf8_string value_{};
};
/**
* Receive Maximum
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901049
*/
struct receive_maximum
: public basic_property<property_type::receive_maximum>
, public property_ops<receive_maximum>
{
friend struct property_ops<receive_maximum>; friend class properties_set;
receive_maximum() = default;
receive_maximum(std::uint16_t v) : value_(v) {}
inline two_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by the Two Byte Integer representing the Receive Maximum value.
// It is a Protocol Error to include the Receive Maximum value more than once or for it to have the value 0.
two_byte_integer value_{};
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901051
*/
struct topic_alias_maximum
: public basic_property<property_type::topic_alias_maximum>
, public property_ops<topic_alias_maximum>
{
friend struct property_ops<topic_alias_maximum>; friend class properties_set;
topic_alias_maximum() = default;
topic_alias_maximum(std::uint16_t v) : value_(v) {}
inline two_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by the Two Byte Integer representing the Topic Alias Maximum value.
// It is a Protocol Error to include the Topic Alias Maximum value more than once.
// If the Topic Alias Maximum property is absent, the default value is 0.
two_byte_integer value_{};
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901113
*/
struct topic_alias
: public basic_property<property_type::topic_alias>
, public property_ops<topic_alias>
{
friend struct property_ops<topic_alias>; friend class properties_set;
topic_alias() = default;
topic_alias(std::uint16_t v) : value_(v) {}
inline two_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by the Two Byte integer representing the Topic Alias value.
// It is a Protocol Error to include the Topic Alias value more than once.
two_byte_integer value_{};
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901084
*/
struct maximum_qos
: public basic_property<property_type::maximum_qos>
, public property_ops<maximum_qos>
{
friend struct property_ops<maximum_qos>; friend class properties_set;
maximum_qos() = default;
maximum_qos(std::uint8_t v) : value_(v) {}
inline one_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Byte with a value of either 0 or 1.
// It is a Protocol Error to include Maximum QoS more than once, or to have a value other than 0 or 1.
// If the Maximum QoS is absent, the Client uses a Maximum QoS of 2.
one_byte_integer value_{};
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901085
*/
struct retain_available
: public basic_property<property_type::retain_available>
, public property_ops<retain_available>
{
friend struct property_ops<retain_available>; friend class properties_set;
retain_available() = default;
retain_available(std::uint8_t v) : value_(v) {}
inline one_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Byte field.
// If present, this byte declares whether the Server supports retained messages.
// A value of 0 means that retained messages are not supported.
// A value of 1 means retained messages are supported.
// If not present, then retained messages are supported.
// It is a Protocol Error to include Retain Available more than once or to use a value other than 0 or 1.
one_byte_integer value_{};
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901054
*/
struct user_property
: public basic_property<property_type::user_property>
, public property_ops<user_property>
{
friend struct property_ops<user_property>; friend class properties_set;
user_property() = default;
template<class String1, class String2,
std::enable_if_t<
asio2::detail::is_character_string_v<String1>&&
asio2::detail::is_character_string_v<String2>, int> = 0>
user_property(String1&& k, String2&& v) : value_(std::forward<String1>(k), std::forward<String2>(v)) {}
inline utf8_string_pair::view_type value() { return { value_.key_view(), value_.val_view() }; }
protected:
// Followed by a UTF-8 String Pair.
utf8_string_pair value_{};
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901050
*/
struct maximum_packet_size
: public basic_property<property_type::maximum_packet_size>
, public property_ops<maximum_packet_size>
{
friend struct property_ops<maximum_packet_size>; friend class properties_set;
maximum_packet_size() = default;
maximum_packet_size(std::uint32_t v) : value_(v) {}
inline four_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Four Byte Integer representing the Maximum Packet Size the Client is willing to accept.
// If the Maximum Packet Size is not present, no limit on the packet size is imposed beyond the
// limitations in the protocol as a result of the remaining length encoding and the protocol header sizes.
four_byte_integer value_{};
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901091
*/
struct wildcard_subscription_available
: public basic_property<property_type::wildcard_subscription_available>
, public property_ops<wildcard_subscription_available>
{
friend struct property_ops<wildcard_subscription_available>; friend class properties_set;
wildcard_subscription_available() = default;
wildcard_subscription_available(std::uint8_t v) : value_(v) {}
inline one_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Byte field.
// If present, this byte declares whether the Server supports Wildcard Subscriptions.
// A value is 0 means that Wildcard Subscriptions are not supported.
// A value of 1 means Wildcard Subscriptions are supported.
// If not present, then Wildcard Subscriptions are supported.
// It is a Protocol Error to include the Wildcard Subscription Available more than once or to
// send a value other than 0 or 1.
one_byte_integer value_{};
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901092
*/
struct subscription_identifier_available
: public basic_property<property_type::subscription_identifier_available>
, public property_ops<subscription_identifier_available>
{
friend struct property_ops<subscription_identifier_available>; friend class properties_set;
subscription_identifier_available() = default;
subscription_identifier_available(std::uint8_t v) : value_(v) {}
inline one_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Byte field.
// If present, this byte declares whether the Server supports Subscription Identifiers.
// A value is 0 means that Subscription Identifiers are not supported.
// A value of 1 means Subscription Identifiers are supported.
// If not present, then Subscription Identifiers are supported.
// It is a Protocol Error to include the Subscription Identifier Available more than once, or to
// send a value other than 0 or 1.
one_byte_integer value_{};
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901093
*/
struct shared_subscription_available
: public basic_property<property_type::shared_subscription_available>
, public property_ops<shared_subscription_available>
{
friend struct property_ops<shared_subscription_available>; friend class properties_set;
shared_subscription_available() = default;
shared_subscription_available(std::uint8_t v) : value_(v) {}
inline one_byte_integer::value_type value() { return value_.value(); }
protected:
// Followed by a Byte field.
// If present, this byte declares whether the Server supports Shared Subscriptions.
// A value is 0 means that Shared Subscriptions are not supported.
// A value of 1 means Shared Subscriptions are supported.
// If not present, then Shared Subscriptions are supported.
// It is a Protocol Error to include the Shared Subscription Available more than once or to
// send a value other than 0 or 1.
one_byte_integer value_{};
};
using property_variant = std::variant<
v5::payload_format_indicator ,
v5::message_expiry_interval ,
v5::content_type ,
v5::response_topic ,
v5::correlation_data ,
v5::subscription_identifier ,
v5::session_expiry_interval ,
v5::assigned_client_identifier ,
v5::server_keep_alive ,
v5::authentication_method ,
v5::authentication_data ,
v5::request_problem_information ,
v5::will_delay_interval ,
v5::request_response_information ,
v5::response_information ,
v5::server_reference ,
v5::reason_string ,
v5::receive_maximum ,
v5::topic_alias_maximum ,
v5::topic_alias ,
v5::maximum_qos ,
v5::retain_available ,
v5::user_property ,
v5::maximum_packet_size ,
v5::wildcard_subscription_available ,
v5::subscription_identifier_available ,
v5::shared_subscription_available
>;
template<typename T>
inline constexpr bool is_v5_property() noexcept
{
using type = asio2::detail::remove_cvref_t<T>;
if constexpr (
std::is_same_v<type, v5::payload_format_indicator > ||
std::is_same_v<type, v5::message_expiry_interval > ||
std::is_same_v<type, v5::content_type > ||
std::is_same_v<type, v5::response_topic > ||
std::is_same_v<type, v5::correlation_data > ||
std::is_same_v<type, v5::subscription_identifier > ||
std::is_same_v<type, v5::session_expiry_interval > ||
std::is_same_v<type, v5::assigned_client_identifier > ||
std::is_same_v<type, v5::server_keep_alive > ||
std::is_same_v<type, v5::authentication_method > ||
std::is_same_v<type, v5::authentication_data > ||
std::is_same_v<type, v5::request_problem_information > ||
std::is_same_v<type, v5::will_delay_interval > ||
std::is_same_v<type, v5::request_response_information > ||
std::is_same_v<type, v5::response_information > ||
std::is_same_v<type, v5::server_reference > ||
std::is_same_v<type, v5::reason_string > ||
std::is_same_v<type, v5::receive_maximum > ||
std::is_same_v<type, v5::topic_alias_maximum > ||
std::is_same_v<type, v5::topic_alias > ||
std::is_same_v<type, v5::maximum_qos > ||
std::is_same_v<type, v5::retain_available > ||
std::is_same_v<type, v5::user_property > ||
std::is_same_v<type, v5::maximum_packet_size > ||
std::is_same_v<type, v5::wildcard_subscription_available > ||
std::is_same_v<type, v5::subscription_identifier_available > ||
std::is_same_v<type, v5::shared_subscription_available >
)
{
return true;
}
else
{
return false;
}
}
class property : public property_variant
{
public:
using super = property_variant;
property()
{
}
template<class T, std::enable_if_t<is_v5_property<T>(), int> = 0>
property(T&& v) : property_variant(std::forward<T>(v))
{
}
template<class T, std::enable_if_t<is_v5_property<T>(), int> = 0>
property& operator=(T&& v)
{
this->base() = std::forward<T>(v);
return (*this);
}
property(property&&) noexcept = default;
property(property const&) = default;
property& operator=(property&&) noexcept = default;
property& operator=(property const&) = default;
template<class T, std::enable_if_t<is_v5_property<T>(), int> = 0>
operator T&()
{
return std::get<T>(this->base());
}
template<class T, std::enable_if_t<is_v5_property<T>(), int> = 0>
operator const T&()
{
return std::get<T>(this->base());
}
template<class T, std::enable_if_t<is_v5_property<T>(), int> = 0>
operator T*() noexcept
{
return std::get_if<T>(std::addressof(this->base()));
}
template<class T, std::enable_if_t<is_v5_property<T>(), int> = 0>
operator const T*() noexcept
{
return std::get_if<T>(std::addressof(this->base()));
}
// this overload will cause compile error on gcc, see mqtt/message.hpp operator T()
//template<class T, std::enable_if_t<is_v5_property<T>(), int> = 0>
//operator T()
//{
// return std::get<T>(this->base());
//}
inline variable_byte_integer::value_type id()
{
variable_byte_integer::value_type r = 0;
if (this->base().index() != std::variant_npos)
{
asio2::clear_last_error();
r = std::visit([](auto& prop) mutable { return prop.id(); }, this->base());
}
else
{
asio2::set_last_error(asio::error::no_data);
}
return r;
}
inline property_type type()
{
property_type r = static_cast<property_type>(0);
if (this->base().index() != std::variant_npos)
{
asio2::clear_last_error();
r = std::visit([](auto& prop) mutable { return prop.type(); }, this->base());
}
else
{
asio2::set_last_error(asio::error::no_data);
}
return r;
}
inline std::string_view name()
{
std::string_view r{};
if (this->base().index() != std::variant_npos)
{
asio2::clear_last_error();
r = std::visit([](auto& prop) mutable { return prop.name(); }, this->base());
}
else
{
asio2::set_last_error(asio::error::no_data);
}
return r;
}
/// Returns the base variant of the message
inline super const& base() const noexcept { return *this; }
/// Returns the base variant of the message
inline super& base() noexcept { return *this; }
/// Returns the base variant of the message
inline super const& variant() const noexcept { return *this; }
/// Returns the base variant of the message
inline super& variant() noexcept { return *this; }
/**
* @brief Checks if the variant holds anyone of the alternative Types...
*/
template<class... Types>
inline bool has() noexcept
{
return (std::holds_alternative<Types>(this->base()) || ...);
}
/**
* @brief Checks if the variant holds anyone of the alternative Types...
*/
template<class... Types>
inline bool holds() noexcept
{
return (std::holds_alternative<Types>(this->base()) || ...);
}
/**
* @brief If this holds the alternative T, returns a pointer to the value stored in the variant.
* Otherwise, returns a null pointer value.
*/
template<class T>
inline std::add_pointer_t<T> get_if() noexcept
{
return std::get_if<T>(std::addressof(this->base()));
}
/**
* @brief If this holds the alternative T, returns a reference to the value stored in the variant.
* Otherwise, throws std::bad_variant_access.
*/
template<class T>
inline T& get()
{
return std::get<T>(this->base());
}
protected:
};
template<class... Args>
static constexpr bool is_property() noexcept
{
if constexpr (sizeof...(Args) == std::size_t(0))
return false;
else
return ((
std::is_same_v<asio2::detail::remove_cvref_t<Args>, v5::property> ||
is_v5_property<asio2::detail::remove_cvref_t<Args>>()) && ...);
}
/**
* The set of Properties is composed of a Property Length followed by the Properties.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901027
*/
class properties_set
{
public:
properties_set() = default;
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit properties_set(Properties&&... Props)
{
set(std::forward<Properties>(Props)...);
}
properties_set(properties_set&&) noexcept = default;
properties_set(properties_set const&) = default;
properties_set& operator=(properties_set&&) noexcept = default;
properties_set& operator=(properties_set const&) = default;
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
inline properties_set& set(Properties&&... Props)
{
data_.clear();
(data_.emplace_back(std::forward<Properties>(Props)), ...);
update_length();
return (*this);
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
inline properties_set& add(Properties&&... Props)
{
(data_.emplace_back(std::forward<Properties>(Props)), ...);
update_length();
return (*this);
}
template<class Propertie, std::enable_if_t<is_property<Propertie>(), int> = 0>
inline properties_set& erase(Propertie&& Prop)
{
for (auto it = data_.begin(); it != data_.end();)
{
std::visit([this, &it, &Prop](auto&& prop) mutable
{
asio2::detail::ignore_unused(this, it, Prop);
using T1 = std::decay_t<decltype(Prop)>;
using T2 = std::decay_t<decltype(prop)>;
if constexpr (std::is_same_v<T1, T2>)
it = data_.erase(it);
else
++it;
}, (*it).base());
}
update_length();
return (*this);
}
template<class Propertie, std::enable_if_t<is_property<Propertie>(), int> = 0>
inline properties_set& erase()
{
for (auto it = data_.begin(); it != data_.end();)
{
std::visit([this, &it](auto&& prop) mutable
{
using T1 = std::decay_t<Propertie>;
using T2 = std::decay_t<decltype(prop)>;
if constexpr (std::is_same_v<T1, T2>)
it = data_.erase(it);
else
++it;
}, (*it).base());
}
update_length();
return (*this);
}
inline properties_set& clear() noexcept
{
data_.clear();
update_length();
return (*this);
}
inline std::size_t required_size()
{
return (length_.required_size() + length_.value());
}
inline std::size_t count() noexcept
{
return data_.size();
}
/**
* @brief Checks if the properties holds the alternative property T.
*/
template<class T>
inline bool has() noexcept
{
for (auto& v : data_)
{
if (std::holds_alternative<T>(v))
return true;
}
return false;
}
template<class T>
inline std::add_pointer_t<T> get_if() noexcept
{
for (auto& v : data_)
{
if (auto pval = std::get_if<T>(std::addressof(v)))
return pval;
}
return nullptr;
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline properties_set& serialize(Container& buffer)
{
update_length();
length_.serialize(buffer);
for (auto& v : data_)
{
std::visit([&buffer](auto& prop) mutable { prop.serialize(buffer); }, v.base());
}
return (*this);
}
inline properties_set& deserialize(std::string_view& data)
{
asio2::clear_last_error();
length_.deserialize(data);
if (asio2::get_last_error())
{
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
return (*this);
}
std::int32_t length = length_.value();
std::string_view props_data = data.substr(0, length);
data.remove_prefix(length);
while (!props_data.empty())
{
variable_byte_integer id{};
id.deserialize(props_data);
if (asio2::get_last_error())
{
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
return (*this);
}
// It is a Protocol Error to include the Session Expiry Interval more than once.
for (auto& prop : data_)
{
if (prop.id() == id)
{
asio2::set_last_error(mqtt::make_error_code(mqtt::error::protocol_error));
break;
}
}
switch (static_cast<property_type>(id.value()))
{
case property_type::payload_format_indicator : data_.emplace_back(payload_format_indicator {}); break;
case property_type::message_expiry_interval : data_.emplace_back(message_expiry_interval {}); break;
case property_type::content_type : data_.emplace_back(content_type {}); break;
case property_type::response_topic : data_.emplace_back(response_topic {}); break;
case property_type::correlation_data : data_.emplace_back(correlation_data {}); break;
case property_type::subscription_identifier : data_.emplace_back(subscription_identifier {}); break;
case property_type::session_expiry_interval : data_.emplace_back(session_expiry_interval {}); break;
case property_type::assigned_client_identifier : data_.emplace_back(assigned_client_identifier {}); break;
case property_type::server_keep_alive : data_.emplace_back(server_keep_alive {}); break;
case property_type::authentication_method : data_.emplace_back(authentication_method {}); break;
case property_type::authentication_data : data_.emplace_back(authentication_data {}); break;
case property_type::request_problem_information : data_.emplace_back(request_problem_information {}); break;
case property_type::will_delay_interval : data_.emplace_back(will_delay_interval {}); break;
case property_type::request_response_information : data_.emplace_back(request_response_information {}); break;
case property_type::response_information : data_.emplace_back(response_information {}); break;
case property_type::server_reference : data_.emplace_back(server_reference {}); break;
case property_type::reason_string : data_.emplace_back(reason_string {}); break;
case property_type::receive_maximum : data_.emplace_back(receive_maximum {}); break;
case property_type::topic_alias_maximum : data_.emplace_back(topic_alias_maximum {}); break;
case property_type::topic_alias : data_.emplace_back(topic_alias {}); break;
case property_type::maximum_qos : data_.emplace_back(maximum_qos {}); break;
case property_type::retain_available : data_.emplace_back(retain_available {}); break;
case property_type::user_property : data_.emplace_back(user_property {}); break;
case property_type::maximum_packet_size : data_.emplace_back(maximum_packet_size {}); break;
case property_type::wildcard_subscription_available : data_.emplace_back(wildcard_subscription_available {}); break;
case property_type::subscription_identifier_available : data_.emplace_back(subscription_identifier_available{}); break;
case property_type::shared_subscription_available : data_.emplace_back(shared_subscription_available {}); break;
default:
// A Control Packet which contains an Identifier which is not valid for its packet type,
// or contains a value not of the specified data type, is a Malformed Packet. If received,
// use a CONNACK or DISCONNECT packet with Reason Code 0x81 (Malformed Packet) as described
// in section 4.13 Handling errors.
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
return (*this);
}
std::visit([&props_data](auto& prop) mutable
{
prop.value_.deserialize(props_data);
}, data_.back().base());
// aboved deserialize maybe failed.
if (asio2::get_last_error())
{
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
return (*this);
}
}
return (*this);
}
inline std::vector<property>& data() { return data_; }
inline properties_set& update_length()
{
std::size_t size = 0;
for (auto& v : data_)
{
size += std::visit([](auto& prop) mutable { return prop.required_size(); }, v.base());
}
length_ = static_cast<std::int32_t>(size);
return (*this);
}
/**
* function signature : void(auto& prop)
*/
template<class Function>
inline properties_set& for_each(Function&& f)
{
for (auto& v : data_)
{
std::visit([&f](auto& prop) mutable { f(prop); }, v.base());
}
return (*this);
}
protected:
// The Property Length is encoded as a Variable Byte Integer.
// The Property Length does not include the bytes used to encode itself, but includes the
// length of the Properties.
// If there are no properties, this MUST be indicated by including a Property Length of zero [MQTT-2.2.2-1].
variable_byte_integer length_{};
// propertie list
std::vector<property> data_ {};
};
namespace detail
{
template<class derived_t>
struct reason_string_ops
{
inline bool has_reason_string()
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.properties().template has<v5::reason_string>();
}
inline std::string_view reason_string()
{
derived_t& derive = static_cast<derived_t&>(*this);
v5::reason_string* prs = derive.properties().template get_if<v5::reason_string>();
return (prs ? prs->value() : std::string_view{});
}
};
}
/**
* CONNECT - Connection Request
*
* After a Network Connection is established by a Client to a Server, the first packet sent from the
* Client to the Server MUST be a CONNECT packet [MQTT-3.1.0-1].
*
* A Client can only send the CONNECT packet once over a Network Connection. The Server MUST process
* a second CONNECT packet sent from a Client as a Protocol Error and close the Network Connection [MQTT-3.1.0-2].
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901033
*/
class connect : public fixed_header<version_number>
{
public:
connect() : fixed_header(control_packet_type::connect)
{
update_remain_length();
}
connect(utf8_string::value_type clientid) : fixed_header(control_packet_type::connect)
{
client_id(std::move(clientid));
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline connect& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
protocol_name_ .serialize(buffer);
protocol_version_ .serialize(buffer);
connect_flags_.byte .serialize(buffer);
keep_alive_ .serialize(buffer);
properties_ .serialize(buffer);
client_id_ .serialize(buffer);
if (will_props_ ) will_props_ ->serialize(buffer);
if (will_topic_ ) will_topic_ ->serialize(buffer);
if (will_payload_) will_payload_->serialize(buffer);
if (username_ ) username_ ->serialize(buffer);
if (password_ ) password_ ->serialize(buffer);
return (*this);
}
inline connect& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
protocol_name_ .deserialize(data);
protocol_version_ .deserialize(data);
connect_flags_.byte .deserialize(data);
keep_alive_ .deserialize(data);
properties_ .deserialize(data);
client_id_ .deserialize(data);
if (has_will())
{
properties_set will_props{};
will_props.deserialize(data);
will_props_ = std::move(will_props);
utf8_string will_topic{};
will_topic.deserialize(data);
will_topic_ = std::move(will_topic);
binary_data will_payload{};
will_payload.deserialize(data);
will_payload_ = std::move(will_payload);
}
if (has_username())
{
utf8_string username{};
username.deserialize(data);
username_ = std::move(username);
}
if (has_password())
{
binary_data password{};
password.deserialize(data);
password_ = std::move(password);
}
update_remain_length();
return (*this);
}
inline std::uint8_t protocol_version() { return (protocol_version_ ); }
inline bool clean_start () { return (connect_flags_.bits.clean_start ); }
inline bool clean_session () { return (connect_flags_.bits.clean_start ); }
inline bool has_will () { return (connect_flags_.bits.will_flag ); }
inline qos_type will_qos () { return static_cast<qos_type>(connect_flags_.bits.will_qos ); }
inline bool will_retain () { return (connect_flags_.bits.will_retain ); }
inline bool has_password () { return (connect_flags_.bits.password_flag); }
inline bool has_username () { return (connect_flags_.bits.username_flag); }
inline connect& clean_start (bool v) { connect_flags_.bits.clean_start = v; return (*this); }
inline connect& clean_session (bool v) { connect_flags_.bits.clean_start = v; return (*this); }
inline two_byte_integer::value_type keep_alive () { return keep_alive_ .value() ; }
inline properties_set& properties () { return properties_ ; }
inline utf8_string::view_type client_id () { return client_id_ .data_view(); }
inline properties_set& will_properties () { return will_props_ .value() ; }
inline utf8_string::view_type will_topic () { return will_topic_ ? will_topic_ ->data_view() : ""; }
inline binary_data::view_type will_payload () { return will_payload_ ? will_payload_->data_view() : ""; }
inline utf8_string::view_type username () { return username_ ? username_ ->data_view() : ""; }
inline binary_data::view_type password () { return password_ ? password_ ->data_view() : ""; }
inline connect& keep_alive(two_byte_integer::value_type v)
{
keep_alive_ = std::move(v);
return (*this);
}
template<class String>
inline connect& client_id(String&& v)
{
client_id_ = std::forward<String>(v);
update_remain_length();
return (*this);
}
template<class String>
inline connect& username(String&& v)
{
username_ = std::forward<String>(v);
connect_flags_.bits.username_flag = true;
update_remain_length();
return (*this);
}
inline connect& password(binary_data::value_type v)
{
password_ = std::move(v);
connect_flags_.bits.password_flag = true;
update_remain_length();
return (*this);
}
template<class... Properties>
inline connect& properties(Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
template<class String1, class String2, class QosOrInt, class... Properties>
inline connect& will_attributes(String1&& topic, String2&& payload, QosOrInt qos,
bool retain, Properties&&... Props)
{
will_props_ = properties_set{ std::forward<Properties>(Props)... };
will_topic_ = std::forward<String1>(topic);
will_payload_ = std::forward<String2>(payload);
connect_flags_.bits.will_flag = true;
connect_flags_.bits.will_qos = static_cast<std::uint8_t>(qos);
connect_flags_.bits.will_retain = retain;
update_remain_length();
return (*this);
}
inline bool has_will () const noexcept { return will_props_.has_value(); }
inline bool has_username () const noexcept { return username_ .has_value(); }
inline bool has_password () const noexcept { return password_ .has_value(); }
inline connect& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ protocol_name_ .required_size()
+ protocol_version_ .required_size()
+ connect_flags_.byte .required_size()
+ keep_alive_ .required_size()
+ properties_ .required_size()
+ client_id_ .required_size()
+ (will_props_ ? will_props_ ->required_size() : 0)
+ (will_topic_ ? will_topic_ ->required_size() : 0)
+ (will_payload_ ? will_payload_->required_size() : 0)
+ (username_ ? username_ ->required_size() : 0)
+ (password_ ? password_ ->required_size() : 0)
);
return (*this);
}
protected:
// The Protocol Name is a UTF-8 Encoded String that represents the protocol name "MQTT".
// The string, its offset and length will not be changed by future versions of the MQTT specification.
utf8_string protocol_name_{ "MQTT" };
// The one byte unsigned value that represents the revision level of the protocol used by the Client.
// The value of the Protocol Version field for version 5.0 of the protocol is 5 (0x05).
one_byte_integer protocol_version_{ 0x05 };
union
{
one_byte_integer byte{ 0 }; // all connect flags
#if ASIO2_ENDIAN_BIG_BYTE
struct
{
bool username_flag : 1; // <NAME> Flag
bool password_flag : 1; // Password Flag
bool will_retain : 1; // will retain setting
std::uint8_t will_qos : 2; // will QoS value
bool will_flag : 1; // will flag
bool clean_start : 1; // Clean Start flag
std::uint8_t reserved : 1; // unused
} bits;
#else
struct
{
std::uint8_t reserved : 1; // unused
bool clean_start : 1; // Clean Start flag
bool will_flag : 1; // will flag
std::uint8_t will_qos : 2; // will QoS value
bool will_retain : 1; // will retain setting
bool password_flag : 1; // Password Flag
bool username_flag : 1; // User Name Flag
} bits;
#endif
} connect_flags_{}; // connect flags byte
// The Keep Alive is a Two Byte Integer which is a time interval measured in seconds.
// Default to 60 seconds
two_byte_integer keep_alive_ { 60 };
// CONNECT Properties
properties_set properties_ {};
// The Client Identifier (ClientID) identifies the Client to the Server.
// Each Client connecting to the Server has a unique ClientID.
utf8_string client_id_ {};
// If the Will Flag is set to 1, the Will Properties is the next field in the Payload.
std::optional<properties_set> will_props_ {};
// If the Will Flag is set to 1, the Will Topic is the next field in the Payload.
std::optional<utf8_string> will_topic_ {};
// If the Will Flag is set to 1 the Will Payload is the next field in the Payload.
std::optional<binary_data> will_payload_{};
// If the User Name Flag is set to 1, the User Name is the next field in the Payload.
std::optional<utf8_string> username_ {};
// If the Password Flag is set to 1, the Password is the next field in the Payload.
std::optional<binary_data> password_ {};
};
/**
* CONNACK - Connect acknowledgement
*
* The CONNACK packet is the packet sent by the Server in response to a CONNECT packet received from a Client.
* The Server MUST send a CONNACK with a 0x00 (Success) Reason Code before sending any Packet other than AUTH [MQTT-3.2.0-1].
* The Server MUST NOT send more than one CONNACK in a Network Connection [MQTT-3.2.0-2].
* If the Client does not receive a CONNACK packet from the Server within a reasonable amount of time,
* the Client SHOULD close the Network Connection.
* A "reasonable" amount of time depends on the type of application and the communications infrastructure.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901074
*/
class connack : public fixed_header<version_number>, public detail::reason_string_ops<connack>
{
public:
connack() : fixed_header(control_packet_type::connack)
{
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit connack(bool session_present, std::uint8_t reason_code, Properties&&... Props)
: fixed_header(control_packet_type::connack)
, reason_code_(reason_code)
, properties_(std::forward<Properties>(Props)...)
{
connack_flags_.bits.session_present = session_present;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline connack& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
connack_flags_.byte .serialize(buffer);
reason_code_ .serialize(buffer);
properties_ .serialize(buffer);
return (*this);
}
inline connack& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
connack_flags_.byte .deserialize(data);
reason_code_ .deserialize(data);
properties_ .deserialize(data);
update_remain_length();
return (*this);
}
inline bool session_present() { return connack_flags_.bits.session_present; }
inline mqtt::error reason_code () { return static_cast<mqtt::error>(reason_code_.value()); }
inline properties_set& properties () { return properties_ ; }
inline connack & session_present(bool v) { connack_flags_.bits.session_present = v; return (*this); }
inline connack & reason_code (std::uint8_t v) { reason_code_ = v; return (*this); }
inline connack & reason_code (mqtt::error v)
{ reason_code_ = asio2::detail::to_underlying(v); return (*this); }
template<class... Properties>
inline connack & properties(Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
inline connack& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ connack_flags_.byte .required_size()
+ reason_code_ .required_size()
+ properties_ .required_size()
);
return (*this);
}
protected:
union
{
one_byte_integer byte{ 0 }; // all connack flags
#if ASIO2_ENDIAN_BIG_BYTE
struct
{
std::uint8_t reserved : 7;
bool session_present : 1; // session found on the server?
} bits;
#else
struct
{
bool session_present : 1; // session found on the server?
std::uint8_t reserved : 7;
} bits;
#endif
} connack_flags_{}; // connack flags
// Byte 2 in the Variable Header is the Connect Reason Code.
one_byte_integer reason_code_{ 0 };
// CONNACK Properties
properties_set properties_ { };
};
/**
* PUBLISH - Publish message
*
* A PUBLISH packet is sent from a Client to a Server or from a Server to a Client to transport an Application Message.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901100
*/
class publish : public fixed_header<version_number>
{
public:
publish() : fixed_header(control_packet_type::publish)
{
update_remain_length();
}
template<class String1, class String2, class QosOrInt, std::enable_if_t<
asio2::detail::is_character_string_v<String1>, int> = 0>
explicit publish(String1&& topic_name, String2&& payload, QosOrInt qos,
bool dup = false, bool retain = false)
: fixed_header(control_packet_type::publish)
, topic_name_ (std::forward<String1>(topic_name))
, payload_ (std::forward<String2>(payload ))
{
type_and_flags_.bits.dup = dup;
type_and_flags_.bits.qos = static_cast<std::uint8_t>(qos);
type_and_flags_.bits.retain = retain;
update_remain_length();
}
template<class String1, class String2, class QosOrInt, std::enable_if_t<
asio2::detail::is_character_string_v<String1>, int> = 0>
explicit publish(std::uint16_t pid, String1&& topic_name, String2&& payload, QosOrInt qos,
bool dup = false, bool retain = false)
: fixed_header(control_packet_type::publish)
, topic_name_ (std::forward<String1>(topic_name))
, packet_id_ (pid)
, payload_ (std::forward<String2>(payload ))
{
type_and_flags_.bits.dup = dup;
type_and_flags_.bits.qos = static_cast<std::uint8_t>(qos);
type_and_flags_.bits.retain = retain;
ASIO2_ASSERT(type_and_flags_.bits.qos > std::uint8_t(0));
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline publish& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
// The Packet Identifier field is only present in PUBLISH packets where the QoS level is 1 or 2.
// A PUBLISH packet MUST NOT contain a Packet Identifier if its QoS value is set to 0
if ((type_and_flags_.bits.qos == std::uint8_t(0) && packet_id_.has_value()) ||
(type_and_flags_.bits.qos > std::uint8_t(0) && !packet_id_.has_value()))
{
ASIO2_ASSERT(false);
asio2::set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
}
topic_name_.serialize(buffer);
if (type_and_flags_.bits.qos > std::uint8_t(0) && packet_id_.has_value())
{
packet_id_->serialize(buffer);
}
properties_.serialize(buffer);
payload_ .serialize(buffer);
return (*this);
}
inline publish& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
topic_name_.deserialize(data);
if (type_and_flags_.bits.qos == 1 || type_and_flags_.bits.qos == 2)
{
two_byte_integer packet_id{};
packet_id.deserialize(data);
packet_id_ = packet_id;
}
properties_.deserialize(data);
payload_ .deserialize(data);
update_remain_length();
return (*this);
}
inline bool dup () { return (type_and_flags_.bits.dup ); }
inline qos_type qos () { return static_cast<qos_type>(type_and_flags_.bits.qos ); }
inline bool retain() { return (type_and_flags_.bits.retain); }
inline publish & dup (bool v) { type_and_flags_.bits.dup = v; return (*this); }
template<class QosOrInt>
inline publish & qos (QosOrInt v) { type_and_flags_.bits.qos = static_cast<std::uint8_t>(v); return (*this); }
inline publish & retain(bool v) { type_and_flags_.bits.retain = v; return (*this); }
inline utf8_string::view_type topic_name() { return topic_name_.data_view(); }
inline two_byte_integer::value_type packet_id () { return packet_id_ ? packet_id_->value() : 0; }
inline properties_set& properties() { return properties_ ; }
inline application_message::view_type payload () { return payload_.data_view() ; }
inline publish & packet_id (std::uint16_t v) { packet_id_ = v ; return (*this); }
template<class String>
inline publish & topic_name(String&& v) { topic_name_ = std::forward<String>(v); update_remain_length(); return (*this); }
template<class String>
inline publish & payload (String&& v) { payload_ = std::forward<String>(v); update_remain_length(); return (*this); }
template<class... Properties>
inline publish & properties(Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
inline bool has_packet_id() const noexcept { return packet_id_.has_value(); }
inline publish& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ topic_name_.required_size()
+ (packet_id_ ? packet_id_->required_size() : 0)
+ properties_.required_size()
+ payload_ .required_size()
);
return (*this);
}
protected:
// The Topic Name identifies the information channel to which Payload data is published.
utf8_string topic_name_{};
// The Packet Identifier field is only present in PUBLISH packets where the QoS level is 1 or 2.
// a Two Byte Integer Packet Identifier.
std::optional<two_byte_integer> packet_id_ {};
// PUBLISH Properties
properties_set properties_{};
// The Payload contains the Application Message that is being published.
// The content and format of the data is application specific.
// The length of the Payload can be calculated by subtracting the length of the Variable Header
// from the Remaining Length field that is in the Fixed Header.
// It is valid for a PUBLISH packet to contain a zero length Payload.
application_message payload_ {};
};
/**
* PUBACK - Publish acknowledgement
*
* A PUBACK packet is the response to a PUBLISH packet with QoS 1.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901121
*/
class puback : public fixed_header<version_number>, public detail::reason_string_ops<puback>
{
public:
puback() : fixed_header(control_packet_type::puback)
{
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit puback(std::uint16_t packet_id, std::uint8_t reason_code, Properties&&... Props)
: fixed_header(control_packet_type::puback)
, packet_id_ (packet_id)
, reason_code_(reason_code)
, properties_ (std::forward<Properties>(Props)...)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline puback& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
reason_code_.serialize(buffer);
properties_ .serialize(buffer);
return (*this);
}
inline puback& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
// The Reason Code and Property Length can be omitted if the Reason Code is 0x00 (Success)
// and there are no Properties. In this case the PUBACK has a Remaining Length of 2.
packet_id_ .deserialize(data);
if (!data.empty())
{
reason_code_.deserialize(data);
// If the Remaining Length is less than 4 there is no Property Length and the value of 0 is used.
if (!data.empty())
properties_.deserialize(data);
}
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline std::uint8_t reason_code() { return reason_code_.value() ; }
inline properties_set& properties () { return properties_ ; }
inline puback & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline puback & reason_code(std::uint8_t v) { reason_code_ = v; return (*this); }
template<class... Properties>
inline puback & properties (Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
inline puback& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ reason_code_.required_size()
+ properties_ .required_size()
);
return (*this);
}
protected:
// The Variable Header of the PUBACK Packet contains the following fields in the order:
// Packet Identifier from the PUBLISH packet that is being acknowledged, PUBACK Reason Code,
// Property Length, and the Properties. The rules for encoding Properties are described in section 2.2.2.
two_byte_integer packet_id_ {};
// Byte 3 in the Variable Header is the PUBACK Reason Code.
// If the Remaining Length is 2, then there is no Reason Code and the value of 0x00 (Success) is used.
one_byte_integer reason_code_{ 0 };
// PUBACK Properties
properties_set properties_{};
};
/**
* PUBREC - Publish received (QoS 2 delivery part 1)
*
* A PUBREC packet is the response to a PUBLISH packet with QoS 2.
* It is the second packet of the QoS 2 protocol exchange.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901131
*/
class pubrec : public fixed_header<version_number>, public detail::reason_string_ops<pubrec>
{
public:
pubrec() : fixed_header(control_packet_type::pubrec)
{
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit pubrec(std::uint16_t packet_id, std::uint8_t reason_code, Properties&&... Props)
: fixed_header(control_packet_type::pubrec)
, packet_id_ (packet_id)
, reason_code_(reason_code)
, properties_ (std::forward<Properties>(Props)...)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pubrec& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
reason_code_.serialize(buffer);
properties_ .serialize(buffer);
return (*this);
}
inline pubrec& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
// The Reason Code and Property Length can be omitted if the Reason Code is 0x00 (Success)
// and there are no Properties. In this case the PUBREC has a Remaining Length of 2.
packet_id_ .deserialize(data);
if (!data.empty())
{
reason_code_.deserialize(data);
// If the Remaining Length is less than 4 there is no Property Length and the value of 0 is used.
if (!data.empty())
properties_.deserialize(data);
}
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline std::uint8_t reason_code() { return reason_code_.value() ; }
inline properties_set& properties () { return properties_ ; }
inline pubrec & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline pubrec & reason_code(std::uint8_t v) { reason_code_ = v; return (*this); }
template<class... Properties>
inline pubrec & properties (Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
inline pubrec& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ reason_code_.required_size()
+ properties_ .required_size()
);
return (*this);
}
protected:
// The Variable Header of the PUBREC Packet consists of the following fields in the order:
// the Packet Identifier from the PUBLISH packet that is being acknowledged, PUBREC Reason Code,
// and Properties. The rules for encoding Properties are described in section 2.2.2.
two_byte_integer packet_id_ {};
// Byte 3 in the Variable Header is the PUBREC Reason Code.
// If the Remaining Length is 2, then the Publish Reason Code has the value 0x00 (Success).
one_byte_integer reason_code_{ 0 };
// PUBREC Properties
properties_set properties_{};
};
/**
* PUBREL - Publish release (QoS 2 delivery part 2)
*
* A PUBREL packet is the response to a PUBREC packet.
* It is the third packet of the QoS 2 protocol exchange.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901141
*/
class pubrel : public fixed_header<version_number>, public detail::reason_string_ops<pubrel>
{
public:
pubrel() : fixed_header(control_packet_type::pubrel)
{
// Bits 3,2,1 and 0 of the Fixed Header in the PUBREL packet are reserved and MUST be
// set to 0,0,1 and 0 respectively.
// The Server MUST treat any other value as malformed and close the Network Connection [MQTT-3.6.1-1].
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit pubrel(std::uint16_t packet_id, std::uint8_t reason_code, Properties&&... Props)
: fixed_header(control_packet_type::pubrel)
, packet_id_ (packet_id)
, reason_code_(reason_code)
, properties_ (std::forward<Properties>(Props)...)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pubrel& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
reason_code_.serialize(buffer);
properties_ .serialize(buffer);
return (*this);
}
inline pubrel& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
// The Reason Code and Property Length can be omitted if the Reason Code is 0x00 (Success)
// and there are no Properties. In this case the PUBREL has a Remaining Length of 2.
packet_id_ .deserialize(data);
if (!data.empty())
{
reason_code_.deserialize(data);
// If the Remaining Length is less than 4 there is no Property Length and the value of 0 is used.
if (!data.empty())
properties_.deserialize(data);
}
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline std::uint8_t reason_code() { return reason_code_.value() ; }
inline properties_set& properties () { return properties_ ; }
inline pubrel & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline pubrel & reason_code(std::uint8_t v) { reason_code_ = v; return (*this); }
template<class... Properties>
inline pubrel & properties (Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
inline pubrel& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ reason_code_.required_size()
+ properties_ .required_size()
);
return (*this);
}
protected:
// The Variable Header of the PUBREL Packet contains the following fields in the order:
// the Packet Identifier from the PUBREC packet that is being acknowledged, PUBREL Reason Code,
// and Properties. The rules for encoding Properties are described in section 2.2.2.
two_byte_integer packet_id_ {};
// Byte 3 in the Variable Header is the PUBREL Reason Code.
// If the Remaining Length is 2, the value of 0x00 (Success) is used.
one_byte_integer reason_code_{ 0 };
// PUBREL Properties
properties_set properties_{};
};
/**
* PUBCOMP - Publish complete (QoS 2 delivery part 3)
*
* The PUBCOMP packet is the response to a PUBREL packet.
* It is the fourth and final packet of the QoS 2 protocol exchange.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901151
*/
class pubcomp : public fixed_header<version_number>, public detail::reason_string_ops<pubcomp>
{
public:
pubcomp() : fixed_header(control_packet_type::pubcomp)
{
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit pubcomp(std::uint16_t packet_id, std::uint8_t reason_code, Properties&&... Props)
: fixed_header(control_packet_type::pubcomp)
, packet_id_ (packet_id)
, reason_code_(reason_code)
, properties_ (std::forward<Properties>(Props)...)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pubcomp& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
reason_code_.serialize(buffer);
properties_ .serialize(buffer);
return (*this);
}
inline pubcomp& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
// The Reason Code and Property Length can be omitted if the Reason Code is 0x00 (Success)
// and there are no Properties. In this case the PUBCOMP has a Remaining Length of 2.
packet_id_ .deserialize(data);
if (!data.empty())
{
reason_code_.deserialize(data);
// If the Remaining Length is less than 4 there is no Property Length and the value of 0 is used.
if (!data.empty())
properties_.deserialize(data);
}
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline std::uint8_t reason_code() { return reason_code_.value() ; }
inline properties_set& properties () { return properties_ ; }
inline pubcomp & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
inline pubcomp & reason_code(std::uint8_t v) { reason_code_ = v; return (*this); }
template<class... Properties>
inline pubcomp & properties (Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
inline pubcomp& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ reason_code_.required_size()
+ properties_ .required_size()
);
return (*this);
}
protected:
// The Variable Header of the PUBCOMP Packet contains the following fields in the order:
// Packet Identifier from the PUBREL packet that is being acknowledged, PUBCOMP Reason Code,
// and Properties. The rules for encoding Properties are described in section 2.2.2.
two_byte_integer packet_id_ {};
// Byte 3 in the Variable Header is the PUBCOMP Reason Code.
// If the Remaining Length is 2, then the value 0x00 (Success) is used.
one_byte_integer reason_code_{ 0 };
// PUBCOMP Properties
properties_set properties_{};
};
/**
* SUBSCRIBE - Subscribe request
*
* The SUBSCRIBE packet is sent from the Client to the Server to create one or more Subscriptions.
* Each Subscription registers a Client's interest in one or more Topics.
* The Server sends PUBLISH packets to the Client to forward Application Messages that were published
* to Topics that match these Subscriptions.
* The SUBSCRIBE packet also specifies (for each Subscription) the maximum QoS with which the Server
* can send Application Messages to the Client.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901161
*/
class subscribe : public fixed_header<version_number>
{
public:
subscribe() : fixed_header(control_packet_type::subscribe)
{
// Bits 3,2,1 and 0 of the Fixed Header of the SUBSCRIBE packet are reserved and MUST be
// set to 0,0,1 and 0 respectively. The Server MUST treat any other value as malformed and
// close the Network Connection [MQTT-3.8.1-1].
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit subscribe(std::uint16_t packet_id, Properties&&... Props)
: fixed_header(control_packet_type::subscribe)
, packet_id_ (packet_id)
, properties_ (std::forward<Properties>(Props)...)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline subscribe& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
properties_ .serialize(buffer);
subscriptions_.serialize(buffer);
return (*this);
}
inline subscribe& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
properties_ .deserialize(data);
subscriptions_.deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline properties_set & properties () { return properties_ ; }
inline subscriptions_set& subscriptions() { return subscriptions_ ; }
inline subscribe & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Properties>
inline subscribe & properties (Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
template<class... Subscriptions>
inline subscribe& add_subscriptions(Subscriptions&&... Subscripts)
{
subscriptions_.add(std::forward<Subscriptions>(Subscripts)...);
update_remain_length();
return (*this);
}
inline subscribe& erase_subscription(std::string_view topic_filter)
{
subscriptions_.erase(topic_filter);
update_remain_length();
return (*this);
}
inline subscribe& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ properties_ .required_size()
+ subscriptions_.required_size()
);
return (*this);
}
protected:
// The Variable Header of the SUBSCRIBE Packet contains the following fields in the order:
// Packet Identifier, and Properties.
two_byte_integer packet_id_ {};
// SUBSCRIBE Properties
properties_set properties_ {};
// The Payload of a SUBSCRIBE packet contains a list of Topic Filters indicating the Topics
// to which the Client wants to subscribe. The Topic Filters MUST be a UTF-8 Encoded String
// [MQTT-3.8.3-1]. Each Topic Filter is followed by a Subscription Options byte.
subscriptions_set subscriptions_{};
};
/**
* SUBACK - Subscribe acknowledgement
*
* A SUBACK packet is sent by the Server to the Client to confirm receipt and processing of a SUBSCRIBE packet.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901171
*/
class suback : public fixed_header<version_number>
{
public:
suback() : fixed_header(control_packet_type::suback)
{
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit suback(std::uint16_t packet_id, Properties&&... Props)
: fixed_header(control_packet_type::suback)
, packet_id_ (packet_id)
, properties_ (std::forward<Properties>(Props)...)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline suback& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
properties_ .serialize(buffer);
reason_codes_ .serialize(buffer);
return (*this);
}
inline suback& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
properties_ .deserialize(data);
reason_codes_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline properties_set & properties () { return properties_ ; }
inline one_byte_integer_set & reason_codes () { return reason_codes_ ; }
inline suback & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Properties>
inline suback & properties (Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
template<class... Integers>
inline suback& add_reason_codes(Integers... Ints)
{
reason_codes_.add(static_cast<one_byte_integer::value_type>(Ints)...);
update_remain_length();
return (*this);
}
inline suback& erase_reason_code(std::size_t index)
{
reason_codes_.erase(index);
update_remain_length();
return (*this);
}
inline suback& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ properties_ .required_size()
+ reason_codes_ .required_size()
);
return (*this);
}
protected:
// The Variable Header of the SUBACK Packet contains the following fields in the order:
// the Packet Identifier from the SUBSCRIBE Packet that is being acknowledged, and Properties.
two_byte_integer packet_id_ {};
// SUBACK Properties
properties_set properties_ {};
// The Payload contains a list of Reason Codes. Each Reason Code corresponds to a Topic Filter
// in the SUBSCRIBE packet being acknowledged. The order of Reason Codes in the SUBACK packet
// MUST match the order of Topic Filters in the SUBSCRIBE packet [MQTT-3.9.3-1].
one_byte_integer_set reason_codes_{};
};
/**
* UNSUBSCRIBE - Unsubscribe request
*
* An UNSUBSCRIBE packet is sent by the Client to the Server, to unsubscribe from topics.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901179
*/
class unsubscribe : public fixed_header<version_number>
{
public:
unsubscribe() : fixed_header(control_packet_type::unsubscribe)
{
// Bits 3,2,1 and 0 of the Fixed Header of the UNSUBSCRIBE packet are reserved and MUST
// be set to 0,0,1 and 0 respectively. The Server MUST treat any other value as malformed
// and close the Network Connection [MQTT-3.10.1-1].
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
template<class... Strings>
explicit unsubscribe(std::uint16_t packet_id, Strings&&... topic_filters)
: fixed_header (control_packet_type::unsubscribe)
, packet_id_ (packet_id)
, topic_filters_(std::forward<Strings>(topic_filters)...)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit unsubscribe(std::uint16_t packet_id, Properties&&... Props)
: fixed_header(control_packet_type::unsubscribe)
, packet_id_ (packet_id)
, properties_ (std::forward<Properties>(Props)...)
{
type_and_flags_.reserved.bit1 = 1;
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline unsubscribe& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
properties_ .serialize(buffer);
topic_filters_.serialize(buffer);
return (*this);
}
inline unsubscribe& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
properties_ .deserialize(data);
topic_filters_.deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline properties_set & properties () { return properties_ ; }
inline utf8_string_set & topic_filters() { return topic_filters_ ; }
inline unsubscribe & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Properties>
inline unsubscribe & properties (Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
template<class... Strings>
inline unsubscribe& add_topic_filters(Strings&&... Strs)
{
topic_filters_.add(std::forward<Strings>(Strs)...);
update_remain_length();
return (*this);
}
inline unsubscribe& erase_topic_filter(std::string_view topic_filter)
{
topic_filters_.erase(topic_filter);
update_remain_length();
return (*this);
}
inline unsubscribe& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ properties_ .required_size()
+ topic_filters_.required_size()
);
return (*this);
}
protected:
// The Variable Header of the UNSUBSCRIBE Packet contains the following fields in the order:
// Packet Identifier, and Properties.
two_byte_integer packet_id_ {};
// UNSUBSCRIBE Properties
properties_set properties_ {};
// The Payload for the UNSUBSCRIBE packet contains the list of Topic Filters that the Client
// wishes to unsubscribe from. The Topic Filters in an UNSUBSCRIBE packet MUST be UTF-8
// Encoded Strings [MQTT-3.10.3-1] as defined in section 1.5.4, packed contiguously.
// The Payload of an UNSUBSCRIBE packet MUST contain at least one Topic Filter[MQTT - 3.10.3 - 2].
// An UNSUBSCRIBE packet with no Payload is a Protocol Error.Refer to section 4.13 for
// information about handling errors.
utf8_string_set topic_filters_{};
};
/**
* UNSUBACK - Unsubscribe acknowledgement
*
* The UNSUBACK packet is sent by the Server to the Client to confirm receipt of an UNSUBSCRIBE packet.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901187
*/
class unsuback : public fixed_header<version_number>
{
public:
unsuback() : fixed_header(control_packet_type::unsuback)
{
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit unsuback(std::uint16_t packet_id, Properties&&... Props)
: fixed_header(control_packet_type::unsuback)
, packet_id_ (packet_id)
, properties_ (std::forward<Properties>(Props)...)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline unsuback& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
packet_id_ .serialize(buffer);
properties_ .serialize(buffer);
reason_codes_ .serialize(buffer);
return (*this);
}
inline unsuback& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
packet_id_ .deserialize(data);
properties_ .deserialize(data);
reason_codes_ .deserialize(data);
update_remain_length();
return (*this);
}
inline two_byte_integer::value_type packet_id () { return packet_id_ .value() ; }
inline properties_set & properties () { return properties_ ; }
inline one_byte_integer_set & reason_codes () { return reason_codes_ ; }
inline unsuback & packet_id (std::uint16_t v) { packet_id_ = v; return (*this); }
template<class... Properties>
inline unsuback & properties (Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
template<class... Integers>
inline unsuback& add_reason_codes(Integers... Ints)
{
reason_codes_.add(static_cast<one_byte_integer::value_type>(Ints)...);
update_remain_length();
return (*this);
}
inline unsuback& erase_reason_code(std::size_t index)
{
reason_codes_.erase(index);
update_remain_length();
return (*this);
}
inline unsuback& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ packet_id_ .required_size()
+ properties_ .required_size()
+ reason_codes_ .required_size()
);
return (*this);
}
protected:
// The Variable Header of the UNSUBACK Packet the following fields in the order:
// the Packet Identifier from the UNSUBSCRIBE Packet that is being acknowledged, and Properties.
two_byte_integer packet_id_ {};
// UNSUBACK Properties
properties_set properties_ {};
// The Payload contains a list of Reason Codes.
// Each Reason Code corresponds to a Topic Filter in the UNSUBSCRIBE packet being acknowledged.
one_byte_integer_set reason_codes_{};
};
/**
* PINGREQ - PING request
*
* The PINGREQ packet is sent from a Client to the Server.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901195
*/
class pingreq : public fixed_header<version_number>
{
public:
pingreq() : fixed_header(control_packet_type::pingreq)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pingreq& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
return (*this);
}
inline pingreq& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
update_remain_length();
return (*this);
}
inline pingreq& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
);
return (*this);
}
protected:
// The PINGREQ packet has no Variable Header.
// The PINGREQ packet has no Payload.
};
/**
* PINGRESP - PING response
*
* A PINGRESP Packet is sent by the Server to the Client in response to a PINGREQ packet.
* It indicates that the Server is alive.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901200
*/
class pingresp : public fixed_header<version_number>
{
public:
pingresp() : fixed_header(control_packet_type::pingresp)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline pingresp& serialize(Container& buffer)
{
fixed_header::serialize(buffer);
return (*this);
}
inline pingresp& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
update_remain_length();
return (*this);
}
inline pingresp& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
);
return (*this);
}
protected:
// The PINGRESP packet has no Variable Header.
// The PINGRESP packet has no Payload.
};
/**
* DISCONNECT - Disconnect notification
*
* The DISCONNECT packet is the final MQTT Control Packet sent from the Client or the Server.
* It indicates the reason why the Network Connection is being closed.
* The Client or Server MAY send a DISCONNECT packet before closing the Network Connection.
* If the Network Connection is closed without the Client first sending a DISCONNECT packet
* with Reason Code 0x00 (Normal disconnection) and the Connection has a Will Message, the
* Will Message is published. Refer to section 3.1.2.5 for further details.
* A Server MUST NOT send a DISCONNECT until after it has sent a CONNACK with Reason Code of
* less than 0x80 [MQTT-3.14.0-1].
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901205
*/
class disconnect : public fixed_header<version_number>, public detail::reason_string_ops<disconnect>
{
public:
disconnect() : fixed_header(control_packet_type::disconnect)
{
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit disconnect(std::uint8_t reason_code, Properties&&... Props)
: fixed_header(control_packet_type::disconnect)
, reason_code_(reason_code)
, properties_(std::forward<Properties>(Props)...)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline disconnect& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
reason_code_ .serialize(buffer);
properties_ .serialize(buffer);
return (*this);
}
inline disconnect& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
// If the Remaining Length is less than 1 the value of 0x00 (Normal disconnection) is used.
if (!data.empty())
{
reason_code_ .deserialize(data);
properties_ .deserialize(data);
}
update_remain_length();
return (*this);
}
inline std::uint8_t reason_code () { return reason_code_.value() ; }
inline properties_set& properties () { return properties_ ; }
inline disconnect & reason_code (std::uint8_t v) { reason_code_ = v; return (*this); }
template<class... Properties>
inline disconnect & properties(Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
inline disconnect& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ reason_code_ .required_size()
+ properties_ .required_size()
);
return (*this);
}
protected:
// The Variable Header of the DISCONNECT Packet contains the following fields in the order:
// Disconnect Reason Code, and Properties.
// Byte 1 in the Variable Header is the Disconnect Reason Code.
// If the Remaining Length is less than 1 the value of 0x00 (Normal disconnection) is used.
one_byte_integer reason_code_{ 0 };
// DISCONNECT Properties
properties_set properties_ { };
// The DISCONNECT packet has no Payload.
};
/**
* AUTH - Authentication exchange
*
* An AUTH packet is sent from Client to Server or Server to Client as part of an extended
* authentication exchange, such as challenge / response authentication.
* It is a Protocol Error for the Client or Server to send an AUTH packet if the CONNECT packet
* did not contain the same Authentication Method.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901217
*/
class auth : public fixed_header<version_number>, public detail::reason_string_ops<auth>
{
public:
auth() : fixed_header(control_packet_type::auth)
{
update_remain_length();
}
template<class... Properties, std::enable_if_t<is_property<Properties...>(), int> = 0>
explicit auth(std::uint8_t reason_code, Properties&&... Props)
: fixed_header(control_packet_type::auth)
, reason_code_(reason_code)
, properties_(std::forward<Properties>(Props)...)
{
update_remain_length();
}
inline std::size_t required_size()
{
return (fixed_header::required_size() + fixed_header::remain_length());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline auth& serialize(Container& buffer)
{
update_remain_length();
fixed_header::serialize(buffer);
reason_code_ .serialize(buffer);
properties_ .serialize(buffer);
return (*this);
}
inline auth& deserialize(std::string_view& data)
{
fixed_header::deserialize(data);
// The Reason Code and Property Length can be omitted if the Reason Code is 0x00 (Success)
// and there are no Properties. In this case the AUTH has a Remaining Length of 0.
if (!data.empty())
{
reason_code_ .deserialize(data);
properties_ .deserialize(data);
}
update_remain_length();
return (*this);
}
inline std::uint8_t reason_code () { return reason_code_.value() ; }
inline properties_set& properties () { return properties_ ; }
inline auth & reason_code (std::uint8_t v) { reason_code_ = v; return (*this); }
template<class... Properties>
inline auth & properties(Properties&&... Props)
{
properties_.set(std::forward<Properties>(Props)...);
update_remain_length();
return (*this);
}
inline auth& update_remain_length()
{
remain_length_ = static_cast<std::int32_t>(0
+ reason_code_ .required_size()
+ properties_ .required_size()
);
return (*this);
}
protected:
// The Variable Header of the AUTH Packet contains the following fields in the order:
// Authenticate Reason Code, and Properties.
// Byte 0 in the Variable Header is the Authenticate Reason Code.
// The values for the one byte unsigned Authenticate Reason Code field are shown below.
// The sender of the AUTH Packet MUST use one of the Authenticate Reason Codes [MQTT-3.15.2-1].
// 0-Success 24-Continue authentication 25-Re-authenticate
// The Reason Code and Property Length can be omitted if the Reason Code is 0x00 (Success)
// and there are no Properties. In this case the AUTH has a Remaining Length of 0.
one_byte_integer reason_code_{ 0 };
// AUTH Properties
properties_set properties_ { };
// The AUTH packet has no Payload.
};
}
namespace asio2::mqtt
{
template<typename message_type>
inline constexpr bool is_v5_message()
{
using type = asio2::detail::remove_cvref_t<message_type>;
if constexpr (
std::is_same_v<type, mqtt::v5::connect > ||
std::is_same_v<type, mqtt::v5::connack > ||
std::is_same_v<type, mqtt::v5::publish > ||
std::is_same_v<type, mqtt::v5::puback > ||
std::is_same_v<type, mqtt::v5::pubrec > ||
std::is_same_v<type, mqtt::v5::pubrel > ||
std::is_same_v<type, mqtt::v5::pubcomp > ||
std::is_same_v<type, mqtt::v5::subscribe > ||
std::is_same_v<type, mqtt::v5::suback > ||
std::is_same_v<type, mqtt::v5::unsubscribe > ||
std::is_same_v<type, mqtt::v5::unsuback > ||
std::is_same_v<type, mqtt::v5::pingreq > ||
std::is_same_v<type, mqtt::v5::pingresp > ||
std::is_same_v<type, mqtt::v5::disconnect > ||
std::is_same_v<type, mqtt::v5::auth > )
{
return true;
}
else
{
return false;
}
}
}
#endif // !__ASIO2_MQTT_PROTOCOL_V5_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_TCP_STREAM_HPP__
#define __ASIO2_TCP_STREAM_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/basic_stream.hpp>
namespace asio2
{
/** A TCP/IP stream socket with timeouts and a polymorphic executor.
@see basic_stream
*/
template<class RatePolicy = unlimited_rate_policy>
using tcp_stream = basic_stream<asio::ip::tcp, asio::any_io_executor, RatePolicy>;
}
#endif // !__ASIO2_TCP_STREAM_HPP__
<file_sep>//
// https://github.com/lisyarus/movable_function
//
// bench (Intel(R) Core(TM) i5-4590 CPU @ 3.30GHz, RAM 8.00 GB)
//
// Assign light lambda (std::function) took 2.03859s
// Assign light lambda (function) took 0.201078s
// Call light lambda (std::function) took 0.206337s
// Call light lambda (function) took 0.18224s
// counter = 200000000
// Assign heavy lambda (std::function) took 15.1772s
// Assign heavy lambda (function) took 13.9959s
// Call heavy lambda (std::function) took 0.200089s
// Call heavy lambda (function) took 0.17089s
// counter = 200000000
// Assign function pointer (std::function) took 1.83542s
// Assign function pointer (function) took 0.200447s
// Call function pointer (std::function) took 0.199261s
// Call function pointer (function) took 0.226355s
// global_counter = 200000000
// Assign pointer to member (std::function) took 1.88201s
// Assign pointer to member (function) took 0.225137s
// Call pointer to member (std::function) took 0.196708s
// Call pointer to member (function) took 0.225984s
// x.counter = 200000000
//
#ifndef __ASIO2_FUNCTION_HPP__
#define __ASIO2_FUNCTION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <type_traits>
#include <memory>
#include <functional>
#include <asio2/config.hpp>
#include <asio2/base/log.hpp>
namespace asio2::detail
{
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
template<typename = void>
inline void log_function_storage_size(bool is_stack, std::size_t size)
{
static std::mutex mtx;
static std::map<std::size_t, std::size_t> stack_map;
static std::map<std::size_t, std::size_t> heaps_map;
std::lock_guard guard(mtx);
if (is_stack)
stack_map[size]++;
else
heaps_map[size]++;
static auto t1 = std::chrono::steady_clock::now();
auto t2 = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(t2 - t1).count() > 60)
{
t1 = std::chrono::steady_clock::now();
std::string str;
str += "\n";
str += "function storage size test: ";
if /**/ constexpr (sizeof(void*) == sizeof(std::uint64_t))
str += "x64";
else if constexpr (sizeof(void*) == sizeof(std::uint32_t))
str += "x86";
else
str += std::to_string(sizeof(void*)) + "bit";
str += ", ";
#if defined(_DEBUG) || defined(DEBUG)
str += "Debug";
#else
str += "Release";
#endif
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
str += ", SSL";
#endif
#if ASIO2_OS_LINUX || ASIO2_OS_UNIX
str += ", linux";
#elif ASIO2_OS_WINDOWS
str += ", windows";
#elif ASIO2_OS_MACOS
str += ", macos";
#endif
str += "\n";
str += "------------------------------------------------------------\n";
str += "stack_map\n";
for (auto [len, num] : stack_map)
{
str += " ";
str += std::to_string(len); str += " : ";
str += std::to_string(num); str += "\n";
}
str += "heaps_map\n";
for (auto [len, num] : heaps_map)
{
str += " ";
str += std::to_string(len); str += " : ";
str += std::to_string(num); str += "\n";
}
str += "------------------------------------------------------------\n";
str += "\n";
ASIO2_LOG_FATAL("{}", str);
}
}
#endif
}
namespace asio2::detail
{
template<class args_t>
struct function_size_traits
{
template<class, class = void>
struct has_member_size : std::false_type {};
template<class T>
struct has_member_size<T, std::void_t<decltype(T::function_storage_size)>> : std::true_type {};
static constexpr std::size_t calc()
{
if constexpr (has_member_size<args_t>::value)
{
return args_t::function_storage_size;
}
else
{
return 0;
}
}
static constexpr std::size_t value = calc();
};
template <typename Signature, std::size_t StorageSize = 0>
struct function;
template <typename R, typename ... Args, std::size_t StorageSize>
struct function<R(Args...), StorageSize>
{
private:
static constexpr std::size_t get_storage_size() noexcept
{
#ifdef ASIO2_FUNCTION_STORAGE_SIZE
// if the user defined a custom function storage size, use it.
return std::size_t(ASIO2_FUNCTION_STORAGE_SIZE);
#else
if constexpr (StorageSize >= sizeof(void*) && StorageSize <= std::size_t(1024))
{
return StorageSize;
}
else
{
if constexpr (sizeof(void*) == sizeof(std::uint32_t))
return (sizeof(void*) * 10);
else
return (sizeof(void*) * 7);
}
#endif
}
static constexpr std::size_t storage_size = get_storage_size();
static constexpr std::size_t storage_align = alignof(void*);
template <typename T>
struct uses_static_storage
: std::bool_constant<true
&& sizeof (T) <= storage_size
&& alignof(T) <= storage_align
&& ((storage_align % alignof(T)) == 0)
&& std::is_nothrow_move_constructible_v<T>
>
{};
public:
using signature = R(Args...);
function() noexcept = default;
template <typename F>
function(F && f)
{
assign(std::forward<F>(f));
}
function (function && other) noexcept
{
vtable_ = other.vtable_;
if (vtable_)
vtable_->move(std::addressof(other.storage_), std::addressof(storage_));
other.reset();
}
function & operator = (function && other) noexcept
{
if (this == &other)
return *this;
reset();
vtable_ = other.vtable_;
if (vtable_)
vtable_->move(std::addressof(other.storage_), std::addressof(storage_));
other.reset();
return *this;
}
function (function const &) = delete;
function & operator = (function const &) = delete;
~function()
{
reset();
}
// operator = (F && f) has strong exception guarantree:
// if the assignment throws, the function remains unchanged
template <typename F>
std::enable_if_t<uses_static_storage<std::decay_t<F>>::value, function &>
operator = (F && f)
{
reset();
assign(std::forward<F>(f));
return *this;
}
template <typename F>
std::enable_if_t<!uses_static_storage<std::decay_t<F>>::value, function &>
operator = (F && f)
{
function(std::forward<F>(f)).swap(*this);
return *this;
}
explicit operator bool() const
{
return static_cast<bool>(vtable_);
}
template <typename ... Args1>
R operator()(Args1 && ... args) const
{
if (!vtable_)
throw std::bad_function_call();
return vtable_->call(const_cast<void *>(static_cast<void const *>(&storage_)), std::forward<Args1>(args)...);
}
void reset()
{
if (!vtable_) return;
vtable_->destroy(&storage_);
vtable_ = nullptr;
}
void swap(function & other) noexcept
{
std::swap(*this, other);
}
private:
std::aligned_storage_t<storage_size, storage_align> storage_;
struct vtable
{
using move_func = void(*)(void *, void *);
using destroy_func = void(*)(void *);
using call_func = R(*)(void *, Args&& ...);
move_func move;
destroy_func destroy;
call_func call;
};
vtable * vtable_ = nullptr;
template <typename F>
void assign(F && f)
{
using T = std::decay_t<F>;
if constexpr (uses_static_storage<T>::value)
{
new (reinterpret_cast<T *>(&storage_)) T(std::move(f));
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
log_function_storage_size(true, sizeof(T));
#endif
static vtable m = {
[](void * src, void * dst){ new (reinterpret_cast<T*>(dst)) T(std::move(*reinterpret_cast<T*>(src))); },
[](void * src){ reinterpret_cast<T*>(src)->~T(); },
[](void * src, Args&& ... args) -> R { return std::invoke(*reinterpret_cast<T*>(src), static_cast<Args&&>(args)...); }
};
vtable_ = &m;
}
else
{
*reinterpret_cast<T**>(&storage_) = new T(std::move(f));
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
log_function_storage_size(false, sizeof(T));
#endif
static vtable m = {
[](void * src, void * dst){ *reinterpret_cast<T**>(dst) = *reinterpret_cast<T**>(src); *reinterpret_cast<T**>(src) = nullptr; },
[](void * src){ delete *reinterpret_cast<T**>(src); },
[](void * src, Args&& ... args) -> R { return std::invoke(**reinterpret_cast<T**>(src), static_cast<Args&&>(args)...); }
};
vtable_ = &m;
}
}
};
}
#endif // !__ASIO2_FUNCTION_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_HTTPS_CLIENT_HPP__
#define __ASIO2_HTTPS_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <fstream>
#include <asio2/base/detail/push_options.hpp>
#include <asio2/http/http_client.hpp>
#include <asio2/http/https_execute.hpp>
#include <asio2/http/https_download.hpp>
#include <asio2/tcp/impl/ssl_stream_cp.hpp>
#include <asio2/tcp/impl/ssl_context_cp.hpp>
namespace asio2::detail
{
struct template_args_https_client : public template_args_http_client
{
// Used to remove inherited http_client_impl_t::execute and http_client_impl_t::download
static constexpr bool http_execute_download_enabled = false;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class derived_t, class args_t = template_args_https_client>
class https_client_impl_t
: public ssl_context_cp <derived_t, args_t>
, public http_client_impl_t <derived_t, args_t>
, public ssl_stream_cp <derived_t, args_t>
, public https_execute_impl <derived_t, args_t>
, public https_download_impl<derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using super = http_client_impl_t <derived_t, args_t>;
using self = https_client_impl_t<derived_t, args_t>;
using args_type = args_t;
using body_type = typename args_t::body_t;
using buffer_type = typename args_t::buffer_t;
using ssl_context_comp = ssl_context_cp<derived_t, args_t>;
using ssl_stream_comp = ssl_stream_cp <derived_t, args_t>;
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
template<class... Args>
explicit https_client_impl_t(
asio::ssl::context::method method = asio::ssl::context::sslv23,
Args&&... args
)
: ssl_context_comp(method)
, super(std::forward<Args>(args)...)
, ssl_stream_comp(this->io_, *this, asio::ssl::stream_base::client)
{
}
/**
* @brief destructor
*/
~https_client_impl_t()
{
this->stop();
}
/**
* @brief get the stream object refrence
*/
inline typename ssl_stream_comp::ssl_stream_type & stream() noexcept
{
return this->derived().ssl_stream();
}
public:
/**
* @brief bind ssl handshake listener
* @param fun - a user defined callback function
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_handshake(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::handshake,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<typename C>
inline void _do_init(std::shared_ptr<ecs_t<C>>& ecs)
{
super::_do_init(ecs);
this->derived()._ssl_init(ecs, this->socket_, *this);
}
template<typename DeferEvent>
inline void _post_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_LOG_DEBUG("https_client::_post_shutdown: {} {}", ec.value(), ec.message());
this->derived()._ssl_stop(this_ptr, defer_event
{
[this, ec, this_ptr, e = chain.move_event()] (event_queue_guard<derived_t> g) mutable
{
super::_post_shutdown(ec, std::move(this_ptr), defer_event(std::move(e), std::move(g)));
}, chain.move_guard()
});
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
set_last_error(ec);
derived_t& derive = this->derived();
if (ec)
{
return derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
derive._ssl_start(this_ptr, ecs, this->socket_, *this);
derive._post_handshake(std::move(this_ptr), std::move(ecs), std::move(chain));
}
inline void _fire_handshake(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_handshake must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
detail::ignore_unused(this_ptr);
this->listener_.notify(event_type::handshake);
}
protected:
};
}
namespace asio2
{
using https_client_args = detail::template_args_https_client;
template<class derived_t, class args_t>
using https_client_impl_t = detail::https_client_impl_t<derived_t, args_t>;
template<class derived_t>
class https_client_t : public detail::https_client_impl_t<derived_t, detail::template_args_https_client>
{
public:
using detail::https_client_impl_t<derived_t, detail::template_args_https_client>::https_client_impl_t;
};
class https_client : public https_client_t<https_client>
{
public:
using https_client_t<https_client>::https_client_t;
};
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct https_rate_client_args : public https_client_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
template<class derived_t>
class https_rate_client_t : public asio2::https_client_impl_t<derived_t, https_rate_client_args>
{
public:
using asio2::https_client_impl_t<derived_t, https_rate_client_args>::https_client_impl_t;
};
class https_rate_client : public asio2::https_rate_client_t<https_rate_client>
{
public:
using asio2::https_rate_client_t<https_rate_client>::https_rate_client_t;
};
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTPS_CLIENT_HPP__
#endif
<file_sep>// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2001.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// config for libstdc++ v3
// not much to go in here:
#define BHO_GNU_STDLIB 1
#ifdef __GLIBCXX__
#define BHO_STDLIB "GNU libstdc++ version " BHO_STRINGIZE(__GLIBCXX__)
#else
#define BHO_STDLIB "GNU libstdc++ version " BHO_STRINGIZE(__GLIBCPP__)
#endif
#if !defined(_GLIBCPP_USE_WCHAR_T) && !defined(_GLIBCXX_USE_WCHAR_T)
# define BHO_NO_CWCHAR
# define BHO_NO_CWCTYPE
# define BHO_NO_STD_WSTRING
# define BHO_NO_STD_WSTREAMBUF
#endif
#if defined(__osf__) && !defined(_REENTRANT) \
&& ( defined(_GLIBCXX_HAVE_GTHR_DEFAULT) || defined(_GLIBCPP_HAVE_GTHR_DEFAULT) )
// GCC 3 on Tru64 forces the definition of _REENTRANT when any std lib header
// file is included, therefore for consistency we define it here as well.
# define _REENTRANT
#endif
#ifdef __GLIBCXX__ // gcc 3.4 and greater:
# if defined(_GLIBCXX_HAVE_GTHR_DEFAULT) \
|| defined(_GLIBCXX__PTHREADS) \
|| defined(_GLIBCXX_HAS_GTHREADS) \
|| defined(_WIN32) \
|| defined(_AIX) \
|| defined(__HAIKU__)
//
// If the std lib has thread support turned on, then turn it on in Boost
// as well. We do this because some gcc-3.4 std lib headers define _REENTANT
// while others do not...
//
# define BHO_HAS_THREADS
# else
# define BHO_DISABLE_THREADS
# endif
#elif defined(__GLIBCPP__) \
&& !defined(_GLIBCPP_HAVE_GTHR_DEFAULT) \
&& !defined(_GLIBCPP__PTHREADS)
// disable thread support if the std lib was built single threaded:
# define BHO_DISABLE_THREADS
#endif
#if (defined(linux) || defined(__linux) || defined(__linux__)) && defined(__arm__) && defined(_GLIBCPP_HAVE_GTHR_DEFAULT)
// linux on arm apparently doesn't define _REENTRANT
// so just turn on threading support whenever the std lib is thread safe:
# define BHO_HAS_THREADS
#endif
#if !defined(_GLIBCPP_USE_LONG_LONG) \
&& !defined(_GLIBCXX_USE_LONG_LONG)\
&& defined(BHO_HAS_LONG_LONG)
// May have been set by compiler/*.hpp, but "long long" without library
// support is useless.
# undef BHO_HAS_LONG_LONG
#endif
// Apple doesn't seem to reliably defined a *unix* macro
#if !defined(CYGWIN) && ( defined(__unix__) \
|| defined(__unix) \
|| defined(unix) \
|| defined(__APPLE__) \
|| defined(__APPLE) \
|| defined(APPLE))
# include <unistd.h>
#endif
#ifndef __VXWORKS__ // VxWorks uses Dinkum, not GNU STL with GCC
#if defined(__GLIBCXX__) || (defined(__GLIBCPP__) && __GLIBCPP__>=20020514) // GCC >= 3.1.0
# define BHO_STD_EXTENSION_NAMESPACE __gnu_cxx
# define BHO_HAS_SLIST
# define BHO_HAS_HASH
# define BHO_SLIST_HEADER <ext/slist>
# if !defined(__GNUC__) || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3)
# define BHO_HASH_SET_HEADER <ext/hash_set>
# define BHO_HASH_MAP_HEADER <ext/hash_map>
# else
# define BHO_HASH_SET_HEADER <backward/hash_set>
# define BHO_HASH_MAP_HEADER <backward/hash_map>
# endif
#endif
#endif
#if defined(__has_include)
#if defined(BHO_HAS_HASH)
#if !__has_include(BHO_HASH_SET_HEADER) || (__GNUC__ >= 10)
#undef BHO_HAS_HASH
#undef BHO_HAS_SET_HEADER
#undef BHO_HAS_MAP_HEADER
#endif
#if !__has_include(BHO_SLIST_HEADER)
#undef BHO_HAS_SLIST
#undef BHO_HAS_SLIST_HEADER
#endif
#endif
#endif
//
// Decide whether we have C++11 support turned on:
//
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103)
# define BHO_LIBSTDCXX11
#endif
//
// Decide which version of libstdc++ we have, normally
// libstdc++ C++0x support is detected via __GNUC__, __GNUC_MINOR__, and possibly
// __GNUC_PATCHLEVEL__ at the suggestion of <NAME>, one of the libstdc++
// developers. He also commented:
//
// "I'm not sure how useful __GLIBCXX__ is for your purposes, for instance in
// GCC 4.2.4 it is set to 20080519 but in GCC 4.3.0 it is set to 20080305.
// Although 4.3.0 was released earlier than 4.2.4, it has better C++0x support
// than any release in the 4.2 series."
//
// Another resource for understanding libstdc++ features is:
// http://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#manual.intro.status.standard.200x
//
// However, using the GCC version number fails when the compiler is clang since this
// only ever claims to emulate GCC-4.2, see https://svn.boost.org/trac/bho/ticket/7473
// for a long discussion on this issue. What we can do though is use clang's __has_include
// to detect the presence of a C++11 header that was introduced with a specific GCC release.
// We still have to be careful though as many such headers were buggy and/or incomplete when
// first introduced, so we only check for headers that were fully featured from day 1, and then
// use that to infer the underlying GCC version:
//
#ifdef __clang__
#if __has_include(<compare>)
# define BHO_LIBSTDCXX_VERSION 100100
#elif __has_include(<memory_resource>)
# define BHO_LIBSTDCXX_VERSION 90100
#elif __has_include(<charconv>)
# define BHO_LIBSTDCXX_VERSION 80100
#elif __has_include(<variant>)
# define BHO_LIBSTDCXX_VERSION 70100
#elif __has_include(<experimental/memory_resource>)
# define BHO_LIBSTDCXX_VERSION 60100
#elif __has_include(<experimental/any>)
# define BHO_LIBSTDCXX_VERSION 50100
#elif __has_include(<shared_mutex>)
# define BHO_LIBSTDCXX_VERSION 40900
#elif __has_include(<ext/cmath>)
# define BHO_LIBSTDCXX_VERSION 40800
#elif __has_include(<scoped_allocator>)
# define BHO_LIBSTDCXX_VERSION 40700
#elif __has_include(<typeindex>)
# define BHO_LIBSTDCXX_VERSION 40600
#elif __has_include(<future>)
# define BHO_LIBSTDCXX_VERSION 40500
#elif __has_include(<ratio>)
# define BHO_LIBSTDCXX_VERSION 40400
#elif __has_include(<array>)
# define BHO_LIBSTDCXX_VERSION 40300
#endif
//
// If BHO_HAS_FLOAT128 is set, now that we know the std lib is libstdc++3, check to see if the std lib is
// configured to support this type. If not disable it:
//
#if defined(BHO_HAS_FLOAT128) && !defined(_GLIBCXX_USE_FLOAT128)
# undef BHO_HAS_FLOAT128
#endif
#if (BHO_LIBSTDCXX_VERSION >= 100000) && defined(BHO_HAS_HASH)
//
// hash_set/hash_map deprecated and have terminal bugs:
//
#undef BHO_HAS_HASH
#undef BHO_HAS_SET_HEADER
#undef BHO_HAS_MAP_HEADER
#endif
#if (BHO_LIBSTDCXX_VERSION >= 100000) && defined(BHO_HAS_HASH)
//
// hash_set/hash_map deprecated and have terminal bugs:
//
#undef BHO_HAS_HASH
#undef BHO_HAS_SET_HEADER
#undef BHO_HAS_MAP_HEADER
#endif
#if (BHO_LIBSTDCXX_VERSION < 50100)
// libstdc++ does not define this function as it's deprecated in C++11, but clang still looks for it,
// defining it here is a terrible cludge, but should get things working:
extern "C" char *gets (char *__s);
#endif
//
// clang is unable to parse some GCC headers, add those workarounds here:
//
#if BHO_LIBSTDCXX_VERSION < 50000
# define BHO_NO_CXX11_HDR_REGEX
#endif
//
// GCC 4.7.x has no __cxa_thread_atexit which
// thread_local objects require for cleanup:
//
#if BHO_LIBSTDCXX_VERSION < 40800
# define BHO_NO_CXX11_THREAD_LOCAL
#endif
//
// Early clang versions can handle <chrono>, not exactly sure which versions
// but certainly up to clang-3.8 and gcc-4.6:
//
#if (__clang_major__ < 5)
# if BHO_LIBSTDCXX_VERSION < 40800
# define BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_CHRONO
# endif
#endif
//
// GCC 4.8 and 9 add working versions of <atomic> and <regex> respectively.
// However, we have no test for these as the headers were present but broken
// in early GCC versions.
//
#endif
#if defined(__SUNPRO_CC) && (__SUNPRO_CC >= 0x5130) && (__cplusplus >= 201103L)
//
// Oracle Solaris compiler uses it's own verison of libstdc++ but doesn't
// set __GNUC__
//
#if __SUNPRO_CC >= 0x5140
#define BHO_LIBSTDCXX_VERSION 50100
#else
#define BHO_LIBSTDCXX_VERSION 40800
#endif
#endif
#if !defined(BHO_LIBSTDCXX_VERSION)
# define BHO_LIBSTDCXX_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
// std::auto_ptr isn't provided with _GLIBCXX_DEPRECATED=0 (GCC 4.5 and earlier)
// or _GLIBCXX_USE_DEPRECATED=0 (GCC 4.6 and later).
#if defined(BHO_LIBSTDCXX11)
# if BHO_LIBSTDCXX_VERSION < 40600
# if !_GLIBCXX_DEPRECATED
# define BHO_NO_AUTO_PTR
# endif
# elif !_GLIBCXX_USE_DEPRECATED
# define BHO_NO_AUTO_PTR
# define BHO_NO_CXX98_BINDERS
# endif
#endif
// C++0x headers in GCC 4.3.0 and later
//
#if (BHO_LIBSTDCXX_VERSION < 40300) || !defined(BHO_LIBSTDCXX11)
# define BHO_NO_CXX11_HDR_ARRAY
# define BHO_NO_CXX11_HDR_TUPLE
# define BHO_NO_CXX11_HDR_UNORDERED_MAP
# define BHO_NO_CXX11_HDR_UNORDERED_SET
# define BHO_NO_CXX11_HDR_FUNCTIONAL
#endif
// C++0x headers in GCC 4.4.0 and later
//
#if (BHO_LIBSTDCXX_VERSION < 40400) || !defined(BHO_LIBSTDCXX11)
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_FORWARD_LIST
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_RATIO
# define BHO_NO_CXX11_HDR_SYSTEM_ERROR
# define BHO_NO_CXX11_SMART_PTR
# define BHO_NO_CXX11_HDR_EXCEPTION
#else
# define BHO_HAS_TR1_COMPLEX_INVERSE_TRIG
# define BHO_HAS_TR1_COMPLEX_OVERLOADS
#endif
// C++0x features in GCC 4.5.0 and later
//
#if (BHO_LIBSTDCXX_VERSION < 40500) || !defined(BHO_LIBSTDCXX11)
# define BHO_NO_CXX11_NUMERIC_LIMITS
# define BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_RANDOM
#endif
// C++0x features in GCC 4.6.0 and later
//
#if (BHO_LIBSTDCXX_VERSION < 40600) || !defined(BHO_LIBSTDCXX11)
# define BHO_NO_CXX11_HDR_TYPEINDEX
# define BHO_NO_CXX11_ADDRESSOF
# define BHO_NO_CXX17_ITERATOR_TRAITS
#endif
// C++0x features in GCC 4.7.0 and later
//
#if (BHO_LIBSTDCXX_VERSION < 40700) || !defined(BHO_LIBSTDCXX11)
// Note that although <chrono> existed prior to 4.7, "steady_clock" is spelled "monotonic_clock"
// so 4.7.0 is the first truly conforming one.
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_ALLOCATOR
# define BHO_NO_CXX11_POINTER_TRAITS
#endif
// C++0x features in GCC 4.8.0 and later
//
#if (BHO_LIBSTDCXX_VERSION < 40800) || !defined(BHO_LIBSTDCXX11)
// Note that although <atomic> existed prior to gcc 4.8 it was largely unimplemented for many types:
# define BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_HDR_THREAD
#endif
// C++0x features in GCC 4.9.0 and later
//
#if (BHO_LIBSTDCXX_VERSION < 40900) || !defined(BHO_LIBSTDCXX11)
// Although <regex> is present and compilable against, the actual implementation is not functional
// even for the simplest patterns such as "\d" or "[0-9]". This is the case at least in gcc up to 4.8, inclusively.
# define BHO_NO_CXX11_HDR_REGEX
#endif
#if (BHO_LIBSTDCXX_VERSION < 40900) || (__cplusplus <= 201103)
# define BHO_NO_CXX14_STD_EXCHANGE
#endif
//
// C++0x features in GCC 5.1 and later
//
#if (BHO_LIBSTDCXX_VERSION < 50100) || !defined(BHO_LIBSTDCXX11)
# define BHO_NO_CXX11_HDR_TYPE_TRAITS
# define BHO_NO_CXX11_HDR_CODECVT
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
# define BHO_NO_CXX11_STD_ALIGN
#endif
//
// C++17 features in GCC 7.1 and later
//
#if (BHO_LIBSTDCXX_VERSION < 70100) || (__cplusplus <= 201402L)
# define BHO_NO_CXX17_STD_INVOKE
# define BHO_NO_CXX17_STD_APPLY
# define BHO_NO_CXX17_HDR_OPTIONAL
# define BHO_NO_CXX17_HDR_STRING_VIEW
# define BHO_NO_CXX17_HDR_VARIANT
#endif
#if defined(__has_include)
#if !__has_include(<shared_mutex>)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#elif __cplusplus <= 201103
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
//
// <execution> has a dependency to Intel's thread building blocks:
// unless these are installed seperately, including <execution> leads
// to inscrutable errors inside libstdc++'s own headers.
//
#if (BHO_LIBSTDCXX_VERSION < 100100)
#if !__has_include(<tbb/tbb.h>)
#define BHO_NO_CXX17_HDR_EXECUTION
#endif
#endif
#elif __cplusplus < 201402 || (BHO_LIBSTDCXX_VERSION < 40900) || !defined(BHO_LIBSTDCXX11)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#if BHO_LIBSTDCXX_VERSION < 100100
//
// The header may be present but is incomplete:
//
# define BHO_NO_CXX17_HDR_CHARCONV
#endif
#if BHO_LIBSTDCXX_VERSION < 110000
//
// Header <bit> may be present but lacks std::bit_cast:
//
#define BHO_NO_CXX20_HDR_BIT
#endif
#ifndef __cpp_impl_coroutine
# define BHO_NO_CXX20_HDR_COROUTINE
#endif
//
// These next defines are mostly for older clang versions with a newer libstdc++ :
//
#if !defined(__cpp_lib_concepts)
#if !defined(BHO_NO_CXX20_HDR_COMPARE)
# define BHO_NO_CXX20_HDR_COMPARE
#endif
#if !defined(BHO_NO_CXX20_HDR_CONCEPTS)
# define BHO_NO_CXX20_HDR_CONCEPTS
#endif
#if !defined(BHO_NO_CXX20_HDR_SPAN)
# define BHO_NO_CXX20_HDR_SPAN
#endif
#if !defined(BHO_NO_CXX20_HDR_RANGES)
# define BHO_NO_CXX20_HDR_RANGES
#endif
#endif
//
// Headers not present on Solaris with the Oracle compiler:
#if defined(__SUNPRO_CC) && (__SUNPRO_CC < 0x5140)
#define BHO_NO_CXX11_HDR_FUTURE
#define BHO_NO_CXX11_HDR_FORWARD_LIST
#define BHO_NO_CXX11_HDR_ATOMIC
// shared_ptr is present, but is not convertible to bool
// which causes all kinds of problems especially in Boost.Thread
// but probably elsewhere as well.
#define BHO_NO_CXX11_SMART_PTR
#endif
#if (!defined(_GLIBCXX_HAS_GTHREADS) || !defined(_GLIBCXX_USE_C99_STDINT_TR1))
// Headers not always available:
# ifndef BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# endif
# ifndef BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_MUTEX
# endif
# ifndef BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_HDR_THREAD
# endif
# ifndef BHO_NO_CXX14_HDR_SHARED_MUTEX
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
# endif
#endif
#if (!defined(_GTHREAD_USE_MUTEX_TIMEDLOCK) || (_GTHREAD_USE_MUTEX_TIMEDLOCK == 0)) && !defined(BHO_NO_CXX11_HDR_MUTEX)
// Timed mutexes are not always available:
# define BHO_NO_CXX11_HDR_MUTEX
#endif
// --- end ---
<file_sep>/*
Copyright <NAME> 2020-2021
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OTHER_WORD_SIZE_H
#define BHO_PREDEF_OTHER_WORD_SIZE_H
#include <asio2/bho/predef/architecture.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_WORD_BITS`
Detects the native word size, in bits, for the current architecture. There are
two types of macros for this detection:
* `BHO_ARCH_WORD_BITS`, gives the number of word size bits
(16, 32, 64).
* `BHO_ARCH_WORD_BITS_16`, `BHO_ARCH_WORD_BITS_32`, and
`BHO_ARCH_WORD_BITS_64`, indicate when the given word size is
detected.
They allow for both single checks and direct use of the size in code.
NOTE: The word size is determined manually on each architecture. Hence use of
the `wordsize.h` header will also include all the architecture headers.
*/ // end::reference[]
#if !defined(BHO_ARCH_WORD_BITS_64)
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_NOT_AVAILABLE
#elif !defined(BHO_ARCH_WORD_BITS)
# define BHO_ARCH_WORD_BITS 64
#endif
#if !defined(BHO_ARCH_WORD_BITS_32)
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_NOT_AVAILABLE
#elif !defined(BHO_ARCH_WORD_BITS)
# define BHO_ARCH_WORD_BITS 32
#endif
#if !defined(BHO_ARCH_WORD_BITS_16)
# define BHO_ARCH_WORD_BITS_16 BHO_VERSION_NUMBER_NOT_AVAILABLE
#elif !defined(BHO_ARCH_WORD_BITS)
# define BHO_ARCH_WORD_BITS 16
#endif
#if !defined(BHO_ARCH_WORD_BITS)
# define BHO_ARCH_WORD_BITS 0
#endif
#define BHO_ARCH_WORD_BITS_NAME "Word Bits"
#define BHO_ARCH_WORD_BITS_16_NAME "16-bit Word Size"
#define BHO_ARCH_WORD_BITS_32_NAME "32-bit Word Size"
#define BHO_ARCH_WORD_BITS_64_NAME "64-bit Word Size"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_WORD_BITS,BHO_ARCH_WORD_BITS_NAME)
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_WORD_BITS_16,BHO_ARCH_WORD_BITS_16_NAME)
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_WORD_BITS_32,BHO_ARCH_WORD_BITS_32_NAME)
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_WORD_BITS_64,BHO_ARCH_WORD_BITS_64_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RPC_RECV_OP_HPP__
#define __ASIO2_RPC_RECV_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/ecs.hpp>
#include <asio2/rpc/detail/rpc_serialization.hpp>
#include <asio2/rpc/detail/rpc_protocol.hpp>
#include <asio2/rpc/detail/rpc_invoker.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class rpc_recv_op
{
public:
/**
* @brief constructor
*/
rpc_recv_op() noexcept {}
/**
* @brief destructor
*/
~rpc_recv_op() = default;
protected:
inline void _rpc_handle_failed_request(rpc::error e, rpc_serializer& sr, rpc_header& head)
{
if (head.id() != static_cast<rpc_header::id_type>(0))
{
derived_t& derive = static_cast<derived_t&>(*this);
error_code ec = rpc::make_error_code(e);
sr.reset();
sr << head;
sr << ec;
derive.async_send(sr.str());
}
}
template<typename C>
void _rpc_handle_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
detail::ignore_unused(ecs);
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.is_started());
rpc_serializer & sr = derive.serializer_;
rpc_deserializer & dr = derive.deserializer_;
rpc_header & head = derive.header_;
try
{
dr.reset(data);
dr >> head;
}
catch (cereal::exception const&)
{
derive._do_disconnect(rpc::make_error_code(rpc::error::illegal_data), this_ptr);
return;
}
// bug fixed : illegal data being parsed into string object fails to allocate
// memory due to excessively long data
catch (std::bad_alloc const&)
{
derive._do_disconnect(rpc::make_error_code(rpc::error::illegal_data), this_ptr);
return;
}
catch (std::exception const&)
{
derive._do_disconnect(rpc::make_error_code(rpc::error::unspecified_error), this_ptr);
return;
}
if /**/ (head.is_request())
{
head.type(rpc_type_rep);
sr.reset();
sr << head;
auto fn = derive._invoker().find(head.name());
if (fn)
{
// async - return true, sync - return false
// call this function will deserialize data, so it maybe throw some exception,
// and it will call user function inner, the user function maybe throw some
// exception also.
try
{
if ((*fn)(this_ptr, std::addressof(derive), sr, dr))
return;
}
catch (cereal::exception const&)
{
derive._rpc_handle_failed_request(rpc::error::invalid_argument, sr, head);
return;
}
catch (system_error const&)
{
derive._rpc_handle_failed_request(rpc::error::unspecified_error, sr, head);
return;
}
catch (std::exception const&)
{
derive._rpc_handle_failed_request(rpc::error::unspecified_error, sr, head);
return;
}
// The number of parameters passed in when calling rpc function exceeds
// the number of parameters of local function
if (head.id() != static_cast<rpc_header::id_type>(0))
{
if (dr.buffer().in_avail() == 0)
{
derive.async_send(sr.str());
}
else
{
derive._rpc_handle_failed_request(rpc::error::invalid_argument, sr, head);
}
}
}
else
{
if (head.id() != static_cast<rpc_header::id_type>(0))
{
error_code ec = rpc::make_error_code(rpc::error::not_found);
sr << ec;
derive.async_send(sr.str());
}
}
}
else if (head.is_response())
{
auto iter = derive.reqs_.find(head.id());
if (iter != derive.reqs_.end())
{
std::function<void(error_code, std::string_view)>& cb = iter->second;
cb(rpc::make_error_code(rpc::error::success), data);
}
}
else
{
derive._do_disconnect(rpc::make_error_code(rpc::error::no_data), this_ptr);
}
}
protected:
};
}
#endif // !__ASIO2_RPC_RECV_OP_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_TRAITS_HPP__
#define __ASIO2_HTTP_TRAITS_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/http/request.hpp>
#include <asio2/http/response.hpp>
namespace asio2::detail
{
template<class Proxy>
struct http_proxy_checker
{
static constexpr bool value = true
&& (!std::is_same_v<detail::remove_cvref_t<Proxy>, error_code>)
&& (!detail::can_convert_to_http_request_v<detail::remove_cvref_t<Proxy>>)
&& (!detail::is_character_string_v<detail::remove_cvref_t<Proxy>>)
;
};
template<class T>
inline constexpr bool http_proxy_checker_v = http_proxy_checker<detail::remove_cvref_t<T>>::value;
template<class args_t>
struct is_http_execute_download_enabled
{
template<class, class = void>
struct has_member_enabled : std::false_type {};
template<class T>
struct has_member_enabled<T, std::void_t<decltype(T::http_execute_download_enabled)>> : std::true_type {};
static constexpr bool value()
{
if constexpr (has_member_enabled<args_t>::value)
{
return args_t::http_execute_download_enabled;
}
else
{
return true;
}
}
};
template<class args_t>
struct is_https_execute_download_enabled
{
template<class, class = void>
struct has_member_enabled : std::false_type {};
template<class T>
struct has_member_enabled<T, std::void_t<decltype(T::https_execute_download_enabled)>> : std::true_type {};
static constexpr bool value()
{
if constexpr (has_member_enabled<args_t>::value)
{
return args_t::https_execute_download_enabled;
}
else
{
return true;
}
}
};
}
#endif // !__ASIO2_HTTP_TRAITS_HPP__
<file_sep>#include "unit_test.hpp"
#include <asio2/config.hpp>
#ifndef ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR
#define ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR
#endif
#include <asio2/base/timer.hpp>
void timer_enable_error_test()
{
#if !defined(ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR)
ASIO2_CHECK(false);
#endif
ASIO2_TEST_BEGIN_LOOP(test_loop_times / 50);
#define diff 100ll
asio2::timer timer1;
int c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0;
int e1 = 0, e2 = 0, e3 = 0, e4 = 0, e5 = 0, e6 = 0;
auto t1 = std::chrono::high_resolution_clock::now();
timer1.start_timer(1, 100, [&c1, &t1, &e1]() mutable
{
if (asio2::get_last_error())
{
e1 = 1;
return;
}
c1++;
ASIO2_CHECK(!asio2::get_last_error());
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t1).count() - 100);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= diff);
t1 = std::chrono::high_resolution_clock::now();
});
auto t2 = std::chrono::high_resolution_clock::now();
timer1.start_timer("id2", 530, 9, [&c2, &t2, &e2]() mutable
{
if (asio2::get_last_error())
{
e2 = 1;
return;
}
c2++;
ASIO2_CHECK(!asio2::get_last_error());
auto elapse2 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t2).count() - 500);
ASIO2_CHECK_VALUE(elapse2, elapse2 <= diff);
t2 = std::chrono::high_resolution_clock::now();
});
auto t3 = std::chrono::high_resolution_clock::now();
timer1.start_timer(3, std::chrono::milliseconds(1100), [&c3, &t3, &e3]() mutable
{
if (asio2::get_last_error())
{
e3 = 1;
return;
}
c3++;
ASIO2_CHECK(!asio2::get_last_error());
auto elapse3 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t3).count() - 1100);
ASIO2_CHECK_VALUE(elapse3, elapse3 <= diff);
t3 = std::chrono::high_resolution_clock::now();
});
auto t4 = std::chrono::high_resolution_clock::now();
timer1.start_timer(4, std::chrono::milliseconds(600), 7, [&c4, &t4, &e4]() mutable
{
if (asio2::get_last_error())
{
e4 = 1;
return;
}
c4++;
ASIO2_CHECK(!asio2::get_last_error());
auto elapse4 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t4).count() - 600);
ASIO2_CHECK_VALUE(elapse4, elapse4 <= diff);
t4 = std::chrono::high_resolution_clock::now();
});
bool f5 = true;
auto t5 = std::chrono::high_resolution_clock::now();
timer1.start_timer(5, std::chrono::milliseconds(1000), std::chrono::milliseconds(2300), [&c5, &t5, &f5, &e5]() mutable
{
if (asio2::get_last_error())
{
e5 = 1;
return;
}
c5++;
ASIO2_CHECK(!asio2::get_last_error());
if (f5)
{
f5 = false;
auto elapse5 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t5).count() - 2300);
ASIO2_CHECK_VALUE(elapse5, elapse5 <= diff);
}
else
{
auto elapse5 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t5).count() - 1000);
ASIO2_CHECK_VALUE(elapse5, elapse5 <= diff);
}
t5 = std::chrono::high_resolution_clock::now();
});
bool f6 = true;
auto t6 = std::chrono::high_resolution_clock::now();
timer1.start_timer(6, std::chrono::milliseconds(400), 6, std::chrono::milliseconds(2200), [&c6, &t6, &f6, &e6]() mutable
{
if (asio2::get_last_error())
{
e6 = 1;
return;
}
c6++;
ASIO2_CHECK(!asio2::get_last_error());
if (f6)
{
f6 = false;
auto elapse6 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t6).count() - 2200);
ASIO2_CHECK_VALUE(elapse6, elapse6 <= diff);
}
else
{
auto elapse6 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t6).count() - 400);
ASIO2_CHECK_VALUE(elapse6, elapse6 <= diff);
}
t6 = std::chrono::high_resolution_clock::now();
});
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
// The actual timeout of the timer is about 10 milliseconds more than the preset timeout,
// but at here we use 15 milliseconds to ensure the value is within the range
ASIO2_CHECK_VALUE(c1, c1 >= (5000 - (5000 / 100 * 15)) / 100 && c1 <= 5000 / 100);
ASIO2_CHECK_VALUE(c2, c2 == 9);
ASIO2_CHECK_VALUE(c3, c3 >= 4 && c3 < 5);
ASIO2_CHECK_VALUE(c4, c4 == 7);
ASIO2_CHECK_VALUE(c5, c5 >= 3 && c5 < 4);
ASIO2_CHECK_VALUE(c6, c6 == 6);
if (c2 == 9)
{
ASIO2_CHECK(!timer1.is_timer_exists("id2"));
}
if (c4 == 7)
{
ASIO2_CHECK(!timer1.is_timer_exists(4));
}
if (c6 == 6)
{
ASIO2_CHECK(!timer1.is_timer_exists(6));
}
timer1.stop_all_timers();
ASIO2_CHECK(!timer1.is_timer_exists(1));
ASIO2_CHECK(!timer1.is_timer_exists("id2"));
ASIO2_CHECK(!timer1.is_timer_exists(2));
ASIO2_CHECK(!timer1.is_timer_exists(3));
ASIO2_CHECK(!timer1.is_timer_exists(4));
ASIO2_CHECK(!timer1.is_timer_exists(5));
ASIO2_CHECK(!timer1.is_timer_exists(6));
ASIO2_CHECK(e1 == 1);
if (c2 == 9)
ASIO2_CHECK(e2 == 0);
else
ASIO2_CHECK(e2 == 1);
ASIO2_CHECK(e3 == 1);
if (c4 == 7)
ASIO2_CHECK(e4 == 0);
else
ASIO2_CHECK(e4 == 1);
ASIO2_CHECK(e5 == 1);
if (c6 == 6)
ASIO2_CHECK(e6 == 0);
else
ASIO2_CHECK(e6 == 1);
//---------------------------------------------------------------------------------------------
asio2::timer timer2;
int b1 = -1, b2 = -1, b3 = -1, b4 = -1;
timer2.stop_timer(1/*1*/);
timer2.start_timer(1, std::chrono::milliseconds(500), [&]()/*2*/
{
/*10*/
ASIO2_CHECK(asio2::get_last_error());
if (asio2::get_last_error())
{
ASIO2_CHECK(true); // must run to here
b1 = 0;
return;
}
ASIO2_CHECK(false); // can't run to here
b1 = 1;
timer2.stop_timer(1); // can't run to here
});
timer2.stop_timer(1/*3*/);
timer2.start_timer(1, std::chrono::milliseconds(500), [&]()/*4*/
{
/*11*/
ASIO2_CHECK(asio2::get_last_error());
if (asio2::get_last_error())
{
ASIO2_CHECK(true); // must run to here
b2 = 0;
ASIO2_CHECK(b1 == 0);
return;
}
ASIO2_CHECK(false); // can't run to here
b2 = 1;
timer2.stop_timer(1); // can't run to here
});
timer2.post([&]()/*5*/
{
timer2.stop_timer(1/*6*/);
timer2.start_timer(1, std::chrono::milliseconds(500), [&]()/*7*/
{
/*12*/
ASIO2_CHECK(asio2::get_last_error());
if (asio2::get_last_error())
{
ASIO2_CHECK(true); // must run to here
b3 = 0;
ASIO2_CHECK(b1 == 0 && b2 == 0);
return;
}
ASIO2_CHECK(false); // can't run to here
b3 = 1;
timer2.stop_timer(1); // can't run to here
});
timer2.stop_timer(1/*8*/);
timer2.start_timer(1, std::chrono::milliseconds(50), [&]()/*9*/
{
/*13*/
if (asio2::get_last_error())
{
ASIO2_CHECK(b1 == 0 && b2 == 0 && b3 == 0 && b4 == 1); // must run to here second
b4 = 0;
return;
}
/*14*/
ASIO2_CHECK(b1 == 0 && b2 == 0 && b3 == 0 && b4 == -1); // must run to here first
b4 = 1;
timer2.stop_timer(1);
});
});
while (b4 != 0)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK(!timer2.is_timer_exists(1));
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"timer_enable_error",
ASIO2_TEST_CASE(timer_enable_error_test)
)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_EKOPATH_H
#define BHO_PREDEF_COMPILER_EKOPATH_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_PATH`
http://en.wikipedia.org/wiki/PathScale[EKOpath] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__PATHCC__+` | {predef_detection}
| `+__PATHCC__+`, `+__PATHCC_MINOR__+`, `+__PATHCC_PATCHLEVEL__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_PATH BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__PATHCC__)
# define BHO_COMP_PATH_DETECTION \
BHO_VERSION_NUMBER(__PATHCC__,__PATHCC_MINOR__,__PATHCC_PATCHLEVEL__)
#endif
#ifdef BHO_COMP_PATH_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_PATH_EMULATED BHO_COMP_PATH_DETECTION
# else
# undef BHO_COMP_PATH
# define BHO_COMP_PATH BHO_COMP_PATH_DETECTION
# endif
# define BHO_COMP_PATH_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_PATH_NAME "EKOpath"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_PATH,BHO_COMP_PATH_NAME)
#ifdef BHO_COMP_PATH_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_PATH_EMULATED,BHO_COMP_PATH_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* https://www.ietf.org/rfc/rfc1867.txt
* https://tools.ietf.org/html/rfc1867#section-7
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_MULTIPART_HPP__
#define __ASIO2_HTTP_MULTIPART_HPP__
#include <asio2/base/detail/push_options.hpp>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <list>
#include <map>
#include <string>
#include <string_view>
#include <algorithm>
#include <type_traits>
#include <asio2/external/asio.hpp>
#include <asio2/external/beast.hpp>
#include <asio2/external/throw_exception.hpp>
#include <asio2/util/string.hpp>
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::http
#else
namespace boost::beast::http
#endif
{
#define LF '\n'
#define CR '\r'
#define CRLF "\r\n"
template<class String>
class basic_multipart_field
{
public:
/// Constructor
basic_multipart_field() = default;
/// Constructor
basic_multipart_field(basic_multipart_field&&) noexcept = default;
/// Constructor
basic_multipart_field(basic_multipart_field const&) = default;
/// Assignment
basic_multipart_field& operator=(basic_multipart_field&&) noexcept = default;
/// Assignment
basic_multipart_field& operator=(basic_multipart_field const&) = default;
inline const String& content_disposition () { return content_disposition_ ; }
inline const String& name () { return name_ ; }
inline const String& value () { return value_ ; }
inline const String& content_type () { return content_type_ ; }
inline const String& filename () { return filename_ ; }
inline const String& content_transfer_encoding() { return content_transfer_encoding_; }
inline const String& get_content_disposition () { return content_disposition_ ; }
inline const String& get_name () { return name_ ; }
inline const String& get_value () { return value_ ; }
inline const String& get_content_type () { return content_type_ ; }
inline const String& get_filename () { return filename_ ; }
inline const String& get_content_transfer_encoding() { return content_transfer_encoding_; }
inline const String& content_disposition () const { return content_disposition_ ; }
inline const String& name () const { return name_ ; }
inline const String& value () const { return value_ ; }
inline const String& content_type () const { return content_type_ ; }
inline const String& filename () const { return filename_ ; }
inline const String& content_transfer_encoding() const { return content_transfer_encoding_; }
inline const String& get_content_disposition () const { return content_disposition_ ; }
inline const String& get_name () const { return name_ ; }
inline const String& get_value () const { return value_ ; }
inline const String& get_content_type () const { return content_type_ ; }
inline const String& get_filename () const { return filename_ ; }
inline const String& get_content_transfer_encoding() const { return content_transfer_encoding_; }
template<class Str> inline basic_multipart_field& content_disposition (Str&& v) { content_disposition_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& name (Str&& v) { name_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& value (Str&& v) { value_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& content_type (Str&& v) { content_type_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& filename (Str&& v) { filename_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& content_transfer_encoding(Str&& v) { content_transfer_encoding_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& set_content_disposition (Str&& v) { content_disposition_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& set_name (Str&& v) { name_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& set_value (Str&& v) { value_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& set_content_type (Str&& v) { content_type_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& set_filename (Str&& v) { filename_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_field& set_content_transfer_encoding(Str&& v) { content_transfer_encoding_ = std::forward<Str>(v); return (*this); }
inline bool is_empty()
{
return (
content_disposition_ .empty() &&
name_ .empty() &&
value_ .empty() &&
content_type_ .empty() &&
filename_ .empty() &&
content_transfer_encoding_.empty() );
}
inline bool empty()
{
return this->is_empty();
}
protected:
String content_disposition_;
String name_;
String value_;
String content_type_;
String filename_;
String content_transfer_encoding_;
};
using multipart_field = basic_multipart_field<std::string>;
template<class String>
class basic_multipart_fields
{
public:
/// Constructor
basic_multipart_fields() = default;
/// Constructor
basic_multipart_fields(basic_multipart_fields&&) = default;
/// Constructor
basic_multipart_fields(basic_multipart_fields const&) = default;
/// Assignment
basic_multipart_fields& operator=(basic_multipart_fields&&) = default;
/// Assignment
basic_multipart_fields& operator=(basic_multipart_fields const&) = default;
using const_iterator = typename std::list<basic_multipart_field<String>>::const_iterator;
using iterator = typename std::list<basic_multipart_field<String>>::iterator;
inline const String& boundary() { return boundary_; }
inline const String& boundary() const { return boundary_; }
inline const String& get_boundary() { return boundary_; }
inline const String& get_boundary() const { return boundary_; }
template<class Str> inline basic_multipart_fields& boundary(Str&& v) { boundary_ = std::forward<Str>(v); return (*this); }
template<class Str> inline basic_multipart_fields& set_boundary(Str&& v) { boundary_ = std::forward<Str>(v); return (*this); }
/** Returns the value for a field, or throws an exception.
If more than one field with the specified name exists, the
first field defined by insertion order is returned.
@throws std::out_of_range if the field is not found.
*/
inline const basic_multipart_field<String>& at(const String& name)
{
auto it = find(name);
if (it == cend())
ASIO2_THROW_EXCEPTION(std::out_of_range{ "field not found" });
return (*it);
}
/*
* Returns the value by name, or `""` if it does not exist.
*/
inline const basic_multipart_field<String>& operator[](const String& name)
{
auto it = find(name);
if (it == cend())
return dummy_;
return (*it);
}
/// Return a const iterator to the beginning of the field sequence.
inline iterator begin() noexcept
{
return list_.begin();
}
/// Return a const iterator to the end of the field sequence.
inline iterator end() noexcept
{
return list_.end();
}
/// Return a const iterator to the beginning of the field sequence.
inline const_iterator begin() const noexcept
{
return list_.begin();
}
/// Return a const iterator to the end of the field sequence.
inline const_iterator end() const noexcept
{
return list_.end();
}
/// Return a const iterator to the beginning of the field sequence.
inline const_iterator cbegin() const noexcept
{
return list_.cbegin();
}
/// Return a const iterator to the end of the field sequence.
inline const_iterator cend() const noexcept
{
return list_.cend();
}
/*
* Remove all fields from the container
*/
inline void clear() noexcept
{
set_.clear();
list_.clear();
}
/*
* Insert a field.
*/
template<class String1, class String2>
inline iterator insert(String1&& name, String2&& value)
{
basic_multipart_field<String> field;
field.name (std::forward<String1>(name ));
field.value(std::forward<String2>(value));
auto iter = set_.emplace(field.name(), std::addressof(field));
auto itel = list_.insert(std::next(list_.begin(), std::distance(set_.begin(), iter)), std::move(field));
iter->second = itel.operator->();
return itel;
}
/*
* Insert a field.
*/
inline iterator insert(basic_multipart_field<String> field)
{
auto iter = set_.emplace(field.name(), std::addressof(field));
auto itel = list_.insert(std::next(list_.begin(), std::distance(set_.begin(), iter)), std::move(field));
iter->second = itel.operator->();
return itel;
}
/*
* Set a field value, removing any other instances of that field.
*/
template<class String1, class String2>
inline iterator set(String1&& name, String2&& value)
{
basic_multipart_field<String> field;
field.name (std::forward<String1>(name ));
field.value(std::forward<String2>(value));
erase(field.name());
auto iter = set_.emplace(field.name(), std::addressof(field));
auto itel = list_.insert(std::next(list_.begin(), std::distance(set_.begin(), iter)), std::move(field));
iter->second = itel.operator->();
return itel;
}
/*
* Remove a field.
*/
inline const_iterator erase(const_iterator pos)
{
auto next = pos;
auto iter = set_.erase(std::next(set_.begin(), std::distance(list_.cbegin(), pos)));
auto itel = list_.erase(pos);
return (++next);
}
/*
* Remove all fields with the specified name.
*/
inline std::size_t erase(const String& name)
{
auto result = set_.equal_range(name);
if (result.first == result.second)
return std::size_t(0);
list_.erase(std::next(list_.begin(), std::distance(set_.begin(), result.first)),
std::next(list_.begin(), std::distance(set_.begin(), result.second)));
set_.erase(result.first, result.second);
return std::distance(result.first, result.second);
}
//--------------------------------------------------------------------------
//
// Lookup
//
//--------------------------------------------------------------------------
/*
* Return the number of fields with the specified name.
*/
inline std::size_t count(const String& name) const
{
return set_.count(name);
}
/*
* Find the multipart field iterator by name.
*/
inline iterator find(const String& name)
{
auto it = set_.find(name);
if (it == set_.end())
return list_.end();
return std::next(list_.begin(), std::distance(set_.begin(), it));
}
/*
* Find the multipart field iterator by name.
*/
inline const_iterator find(const String& name) const
{
auto it = set_.find(name);
if (it == set_.end())
return list_.cend();
return std::next(list_.cbegin(), std::distance(set_.begin(), it));
}
/*
* Returns a range of iterators to the fields with the specified name.
*/
inline std::pair<const_iterator, const_iterator> equal_range(const String& name) const
{
auto result = set_.equal_range(name);
if (result.first == result.second)
return { list_.cend(), list_.cend() };
return {
std::next(list_.cbegin(),std::distance(set_.begin(),result.first)),
std::next(list_.cbegin(),std::distance(set_.begin(),result.second)) };
}
protected:
String boundary_;
std::list<basic_multipart_field<String>> list_;
std::multimap<String, basic_multipart_field<String>*> set_;
inline static basic_multipart_field<String> dummy_{};
};
using multipart_fields = basic_multipart_fields<std::string>;
/*
* Convert a multipart fields to a string.
*/
template<class String>
inline std::string to_string(const basic_multipart_fields<String>& fields)
{
std::string body;
std::string::size_type size = 0;
for (auto it = fields.begin(); it != fields.end(); ++it)
{
size += fields.boundary().size() + 2 + 2;
size += it->content_disposition ().size() + 22;
size += it->name ().size() + 10;
size += it->value ().size() + 4;
size += it->content_type ().size() + (it->content_type ().empty() ? 0 : 16);
size += it->filename ().size() + (it->filename ().empty() ? 0 : 12);
size += it->content_transfer_encoding().size() + (it->content_transfer_encoding().empty() ? 0 : 29);
}
body.reserve(size + fields.boundary().size() + 2 + 2 + 2);
for (auto it = fields.begin(); it != fields.end(); ++it)
{
body += "--";
body += fields.boundary();
body += CRLF;
body += "Content-Disposition: ";
body += it->content_disposition();
if (!it->name().empty())
{
body += "; ";
body += "name=\"";
body += it->name();
body += "\"";
}
if (!it->filename().empty())
{
body += "; ";
body += "filename=\"";
body += it->filename();
body += "\"";
}
body += CRLF;
if (!it->content_type().empty())
{
body += "Content-Type: ";
body += it->content_type();
body += CRLF;
}
if (!it->content_transfer_encoding().empty())
{
body += "Content-Transfer-Encoding: ";
body += it->content_transfer_encoding();
body += CRLF;
}
body += CRLF;
if (!it->value().empty())
{
body += it->value();
}
body += CRLF;
}
body += "--";
body += fields.boundary();
body += "--";
body += CRLF;
return body;
}
/// Write the text for a multipart fields to an output stream.
template<class String>
inline std::ostream& operator<<(std::ostream& os, const basic_multipart_fields<String>& fields)
{
return os << to_string(fields);
}
namespace multipart_parser
{
template<class String>
inline bool parse_field(basic_multipart_field<String>& field, std::string_view content)
{
// 8 == "\r\n" "\r\n\r\n" "\r\n"
if (content.size() < 8)
return false;
// first 2 bytes must be "\r\n"
if (content.substr(0, 2) != CRLF)
return false;
// last 2 bytes must be "\r\n"
if (content.substr(content.size() - 2) != CRLF)
return false;
// remove the first "\r\n" and the last "\r\n"
content = content.substr(2, content.size() - 4);
// find the split of header and value
auto split = content.find("\r\n\r\n");
if (split == std::string_view::npos)
return false;
std::string_view header = content.substr(0, split);
std::string_view value = content.substr(split + 4);
std::string_view::size_type pos_row_1 = static_cast<std::string_view::size_type>( 0);
std::string_view::size_type pos_row_2 = static_cast<std::string_view::size_type>(-2);
for(;;)
{
pos_row_1 = pos_row_2 + 2;
pos_row_2 = header.find("\r\n", pos_row_1);
std::string_view header_row = header.substr(pos_row_1,
pos_row_2 == std::string_view::npos ? pos_row_2 : pos_row_2 - pos_row_1);
// find the header type name.
auto pos1 = header_row.find(':');
if (pos1 == std::string_view::npos)
return false;
// get the header type value.
std::string_view type = header_row.substr(0, pos1);
asio2::trim_both(type);
++pos1;
if /**/(beast::iequals(type, "Content-Disposition"))
{
auto pos2 = header_row.find(';', pos1);
std::string_view disposition = header_row.substr(pos1, pos2 == std::string_view::npos ? pos2 : pos2 - pos1);
asio2::trim_both(disposition);
field.content_disposition(disposition);
if (pos2 != std::string_view::npos)
{
std::string_view kvs = header_row.substr(pos2 + 1);
for (pos2 = 0;;)
{
auto pos3 = kvs.find(';', pos2);
std::string_view kv = kvs.substr(pos2, pos3 == std::string_view::npos ? pos3 : pos3 - pos2);
auto pos4 = kv.find('=');
if (pos4 == std::string_view::npos)
return false;
std::string_view k = kv.substr(0, pos4);
std::string_view v = kv.substr(pos4 + 1);
asio2::trim_both(k);
asio2::trim_both(v);
if (!v.empty() && v.front() == '\"') v.remove_prefix(1);
if (!v.empty() && v.back() == '\"') v.remove_suffix(1);
if /**/ (beast::iequals(k, "name"))
field.name(v);
else if (beast::iequals(k, "filename"))
field.filename(v);
if (pos3 == std::string_view::npos)
break;
pos2 = pos3 + 1;
}
}
}
else if (beast::iequals(type, "Content-Type"))
{
field.content_type(header_row.substr(pos1 + 1));
}
else if (beast::iequals(type, "Content-Transfer-Encoding"))
{
field.content_transfer_encoding(header_row.substr(pos1 + 1));
}
else
{
ASIO2_ASSERT(false);
}
if (pos_row_2 == std::string_view::npos)
break;
}
field.value(value);
return true;
}
}
template<class String = std::string>
basic_multipart_fields<String> multipart_parser_execute(std::string_view body, std::string_view boundary)
{
using namespace multipart_parser;
basic_multipart_fields<String> fields{};
fields.boundary(boundary);
std::string full_boundary{ "--" }; full_boundary += boundary;
std::string_view bound = full_boundary;
for (std::size_t i = 0; i < body.size();)
{
basic_multipart_field<String> field{};
// find first boundary
if (body.substr(i, bound.size()) != bound)
break;
i += bound.size();
// check whether is the end.
std::string_view tail = body.substr(i + 0, 2);
if (tail == "--")
{
i += 2;
if (i < body.size())
{
if (body[i] != CR)
break;
++i;
}
if (i < body.size())
{
if (body[i] != LF)
break;
++i;
}
break;
}
// find next boundary
auto next = body.find(bound, i);
if (next == std::string_view::npos)
break;
// field.
std::string_view field_content = body.substr(i, next - i);
if (!parse_field(field, field_content))
break;
fields.insert(std::move(field));
i = next;
}
return fields;
}
template<bool isRequest, class Body, class Fields, class String = std::string>
basic_multipart_fields<String> multipart_parser_execute(const http::message<isRequest, Body, Fields>& msg)
{
std::string_view type = msg[http::field::content_type];
std::size_t pos1 = asio2::ifind(type, "multipart/form-data");
if (pos1 == std::string_view::npos)
return {};
pos1 += 19; // std::strlen("multipart/form-data");
pos1 = asio2::ifind(type, "boundary", pos1);
if (pos1 == std::string_view::npos)
return {};
pos1 += 8; // std::strlen("boundary");
pos1 = type.find('=', pos1);
if (pos1 == std::string_view::npos)
return {};
pos1 += 1;
std::size_t pos2 = type.find_first_of("\r;", pos1);
std::string_view boundary = type.substr(pos1, pos2 == std::string_view::npos ? pos2 : pos2 - pos1);
return multipart_parser_execute<String>(msg.body(), boundary);
}
#undef CRLF
#undef LF
#undef CR
}
#include <asio2/base/detail/pop_options.hpp>
#endif
<file_sep>#ifndef BHO_MP11_DETAIL_MP_VOID_HPP_INCLUDED
#define BHO_MP11_DETAIL_MP_VOID_HPP_INCLUDED
// Copyright 2015-2017 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
namespace bho
{
namespace mp11
{
// mp_void<T...>
namespace detail
{
template<class... T> struct mp_void_impl
{
using type = void;
};
} // namespace detail
template<class... T> using mp_void = typename detail::mp_void_impl<T...>::type;
} // namespace mp11
} // namespace bho
#endif // #ifndef BHO_MP11_DETAIL_MP_VOID_HPP_INCLUDED
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_BEOS_H
#define BHO_PREDEF_OS_BEOS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_BEOS`
http://en.wikipedia.org/wiki/BeOS[BeOS] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__BEOS__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_BEOS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__BEOS__) \
)
# undef BHO_OS_BEOS
# define BHO_OS_BEOS BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_BEOS
# define BHO_OS_BEOS_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_BEOS_NAME "BeOS"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_BEOS,BHO_OS_BEOS_NAME)
<file_sep>// (C) Copyright <NAME> 2001 - 2002.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// IBM/Aix specific config options:
#define BHO_PLATFORM "IBM Aix"
#define BHO_HAS_UNISTD_H
#define BHO_HAS_NL_TYPES_H
#define BHO_HAS_NANOSLEEP
#define BHO_HAS_CLOCK_GETTIME
// This needs support in "asio2/bho/cstdint.hpp" exactly like FreeBSD.
// This platform has header named <inttypes.h> which includes all
// the things needed.
#define BHO_HAS_STDINT_H
// Threading API's:
#define BHO_HAS_PTHREADS
#define BHO_HAS_PTHREAD_DELAY_NP
#define BHO_HAS_SCHED_YIELD
//#define BHO_HAS_PTHREAD_YIELD
// boilerplate code:
#include <asio2/bho/config/detail/posix_features.hpp>
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_HTTP_HPP
#define BHO_BEAST_HTTP_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/beast/http/basic_dynamic_body.hpp>
#include <asio2/bho/beast/http/basic_file_body.hpp>
#include <asio2/bho/beast/http/basic_parser.hpp>
#include <asio2/bho/beast/http/buffer_body.hpp>
#include <asio2/bho/beast/http/chunk_encode.hpp>
#include <asio2/bho/beast/http/dynamic_body.hpp>
#include <asio2/bho/beast/http/empty_body.hpp>
#include <asio2/bho/beast/http/error.hpp>
#include <asio2/bho/beast/http/field.hpp>
#include <asio2/bho/beast/http/fields.hpp>
#include <asio2/bho/beast/http/file_body.hpp>
#include <asio2/bho/beast/http/message.hpp>
#include <asio2/bho/beast/http/parser.hpp>
#include <asio2/bho/beast/http/read.hpp>
#include <asio2/bho/beast/http/rfc7230.hpp>
#include <asio2/bho/beast/http/serializer.hpp>
#include <asio2/bho/beast/http/span_body.hpp>
#include <asio2/bho/beast/http/status.hpp>
#include <asio2/bho/beast/http/string_body.hpp>
#include <asio2/bho/beast/http/type_traits.hpp>
#include <asio2/bho/beast/http/vector_body.hpp>
#include <asio2/bho/beast/http/verb.hpp>
#include <asio2/bho/beast/http/write.hpp>
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Copyright <NAME> 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#if !defined(BHO_PREDEF_OS_H) || defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BHO_PREDEF_OS_H
#define BHO_PREDEF_OS_H
#endif
#include <asio2/bho/predef/os/aix.h>
#include <asio2/bho/predef/os/amigaos.h>
#include <asio2/bho/predef/os/beos.h>
#include <asio2/bho/predef/os/bsd.h>
#include <asio2/bho/predef/os/cygwin.h>
#include <asio2/bho/predef/os/haiku.h>
#include <asio2/bho/predef/os/hpux.h>
#include <asio2/bho/predef/os/irix.h>
#include <asio2/bho/predef/os/ios.h>
#include <asio2/bho/predef/os/linux.h>
#include <asio2/bho/predef/os/macos.h>
#include <asio2/bho/predef/os/os400.h>
#include <asio2/bho/predef/os/qnxnto.h>
#include <asio2/bho/predef/os/solaris.h>
#include <asio2/bho/predef/os/unix.h>
#include <asio2/bho/predef/os/vms.h>
#include <asio2/bho/predef/os/windows.h>
#endif
<file_sep>#include <asio2/udp/udp_client.hpp>
#include <iostream>
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8036";
asio2::udp_client client;
// Provide a kcp conv, If the conv is not provided, it will be generated by the server.
//client.set_kcp_conv(12);
client.bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n",
client.local_address().c_str(), client.local_port());
// has no error, it means connect success, we can send data at here
if (!asio2::get_last_error())
{
client.async_send("1<abcdefghijklmnopqrstovuxyz0123456789>");
}
}).bind_disconnect([]()
{
printf("disconnect : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_recv([&](std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
std::string s;
s += '<';
int len = 33 + std::rand() % (126 - 33);
for (int i = 0; i < len; i++)
{
s += (char)((std::rand() % 26) + 'a');
}
s += '>';
client.async_send(std::move(s));
}).bind_handshake([&]()
{
if (asio2::get_last_error())
printf("handshake failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("handshake success : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_init([&]()
{
// Specify the local port to which the socket is bind.
//asio::ip::udp::endpoint ep(asio::ip::udp::v4(), 1234);
//client.socket().bind(ep);
});
// to use kcp, the last param must be : asio2::use_kcp
client.async_start(host, port, asio2::use_kcp);
while (std::getchar() != '\n');
client.stop();
return 0;
}
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_SUPERH_H
#define BHO_PREDEF_ARCHITECTURE_SUPERH_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_SH`
http://en.wikipedia.org/wiki/SuperH[SuperH] architecture:
If available versions [1-5] are specifically detected.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__sh__+` | {predef_detection}
| `+__SH5__+` | 5.0.0
| `+__SH4__+` | 4.0.0
| `+__sh3__+` | 3.0.0
| `+__SH3__+` | 3.0.0
| `+__sh2__+` | 2.0.0
| `+__sh1__+` | 1.0.0
|===
*/ // end::reference[]
#define BHO_ARCH_SH BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__sh__)
# undef BHO_ARCH_SH
# if !defined(BHO_ARCH_SH) && (defined(__SH5__))
# define BHO_ARCH_SH BHO_VERSION_NUMBER(5,0,0)
# endif
# if !defined(BHO_ARCH_SH) && (defined(__SH4__))
# define BHO_ARCH_SH BHO_VERSION_NUMBER(4,0,0)
# endif
# if !defined(BHO_ARCH_SH) && (defined(__sh3__) || defined(__SH3__))
# define BHO_ARCH_SH BHO_VERSION_NUMBER(3,0,0)
# endif
# if !defined(BHO_ARCH_SH) && (defined(__sh2__))
# define BHO_ARCH_SH BHO_VERSION_NUMBER(2,0,0)
# endif
# if !defined(BHO_ARCH_SH) && (defined(__sh1__))
# define BHO_ARCH_SH BHO_VERSION_NUMBER(1,0,0)
# endif
# if !defined(BHO_ARCH_SH)
# define BHO_ARCH_SH BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_SH
# define BHO_ARCH_SH_AVAILABLE
#endif
#if BHO_ARCH_SH
# if BHO_ARCH_SH >= BHO_VERSION_NUMBER(5,0,0)
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
# elif BHO_ARCH_SH >= BHO_VERSION_NUMBER(3,0,0)
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
# else
# undef BHO_ARCH_WORD_BITS_16
# define BHO_ARCH_WORD_BITS_16 BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#define BHO_ARCH_SH_NAME "SuperH"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_SH,BHO_ARCH_SH_NAME)
<file_sep>// (C) Copyright <NAME> 2011
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// PathScale EKOPath C++ Compiler
#ifndef BHO_COMPILER
# define BHO_COMPILER "PathScale EKOPath C++ Compiler version " __PATHSCALE__
#endif
#if __PATHCC__ >= 6
// PathCC is based on clang, and supports the __has_*() builtins used
// to detect features in clang.hpp. Since the clang toolset is much
// better maintained, it is more convenient to reuse its definitions.
# include "asio2/bho/config/compiler/clang.hpp"
#elif __PATHCC__ >= 4
# define BHO_MSVC6_MEMBER_TEMPLATES
# define BHO_HAS_UNISTD_H
# define BHO_HAS_STDINT_H
# define BHO_HAS_SIGACTION
# define BHO_HAS_SCHED_YIELD
# define BHO_HAS_THREADS
# define BHO_HAS_PTHREADS
# define BHO_HAS_PTHREAD_YIELD
# define BHO_HAS_PTHREAD_MUTEXATTR_SETTYPE
# define BHO_HAS_PARTIAL_STD_ALLOCATOR
# define BHO_HAS_NRVO
# define BHO_HAS_NL_TYPES_H
# define BHO_HAS_NANOSLEEP
# define BHO_HAS_LONG_LONG
# define BHO_HAS_LOG1P
# define BHO_HAS_GETTIMEOFDAY
# define BHO_HAS_EXPM1
# define BHO_HAS_DIRENT_H
# define BHO_HAS_CLOCK_GETTIME
# define BHO_NO_CXX11_VARIADIC_TEMPLATES
# define BHO_NO_CXX11_UNICODE_LITERALS
# define BHO_NO_CXX11_TEMPLATE_ALIASES
# define BHO_NO_CXX11_STATIC_ASSERT
# define BHO_NO_SFINAE_EXPR
# define BHO_NO_CXX11_SFINAE_EXPR
# define BHO_NO_CXX11_SCOPED_ENUMS
# define BHO_NO_CXX11_RVALUE_REFERENCES
# define BHO_NO_CXX11_RANGE_BASED_FOR
# define BHO_NO_CXX11_RAW_LITERALS
# define BHO_NO_CXX11_NULLPTR
# define BHO_NO_CXX11_NUMERIC_LIMITS
# define BHO_NO_CXX11_NOEXCEPT
# define BHO_NO_CXX11_LAMBDAS
# define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
# define BHO_NO_MS_INT64_NUMERIC_LIMITS
# define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
# define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
# define BHO_NO_CXX11_DELETED_FUNCTIONS
# define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
# define BHO_NO_CXX11_DECLTYPE
# define BHO_NO_CXX11_DECLTYPE_N3276
# define BHO_NO_CXX11_CONSTEXPR
# define BHO_NO_COMPLETE_VALUE_INITIALIZATION
# define BHO_NO_CXX11_CHAR32_T
# define BHO_NO_CXX11_CHAR16_T
# define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
# define BHO_NO_CXX11_AUTO_DECLARATIONS
# define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
# define BHO_NO_CXX11_HDR_UNORDERED_SET
# define BHO_NO_CXX11_HDR_UNORDERED_MAP
# define BHO_NO_CXX11_HDR_TYPEINDEX
# define BHO_NO_CXX11_HDR_TUPLE
# define BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_HDR_SYSTEM_ERROR
# define BHO_NO_CXX11_HDR_REGEX
# define BHO_NO_CXX11_HDR_RATIO
# define BHO_NO_CXX11_HDR_RANDOM
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_FORWARD_LIST
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_CODECVT
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_USER_DEFINED_LITERALS
# define BHO_NO_CXX11_ALIGNAS
# define BHO_NO_CXX11_TRAILING_RESULT_TYPES
# define BHO_NO_CXX11_INLINE_NAMESPACES
# define BHO_NO_CXX11_REF_QUALIFIERS
# define BHO_NO_CXX11_FINAL
# define BHO_NO_CXX11_OVERRIDE
# define BHO_NO_CXX11_THREAD_LOCAL
# define BHO_NO_CXX11_UNRESTRICTED_UNION
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
#endif
<file_sep>#include "unit_test.hpp"
#include <asio2/util/ini.hpp>
#include <cmath>
#include <cstdlib>
void ini_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
asio2::ini ini;
std::error_code ec;
std::filesystem::resize_file(ini.filepath(), 0, ec);
ASIO2_CHECK(std::filesystem::path(ini.filepath()).filename().string() == "ini.ini");
ASIO2_CHECK(ini.get<bool>("number", "boolean", true ) == true );
ASIO2_CHECK(ini.get<bool>("number", "boolean", false) == false);
ASIO2_CHECK(ini.get< char>("number", "ichar", 'a') == 'a');
ASIO2_CHECK(ini.get<unsigned char>("number", "uchar", 250) == 250);
ASIO2_CHECK(ini.get<std:: int8_t>("number", "i8", 99) == 99);
ASIO2_CHECK(ini.get<std:: int8_t>("number", "i8", -99) == -99);
ASIO2_CHECK(ini.get<std::uint8_t>("number", "u8", 99) == 99);
ASIO2_CHECK(ini.get<std:: int16_t>("number", "i16", 9999) == 9999);
ASIO2_CHECK(ini.get<std:: int16_t>("number", "i16", -9999) == -9999);
ASIO2_CHECK(ini.get<std::uint16_t>("number", "u16", 9999) == 9999);
ASIO2_CHECK(ini.get<std:: int32_t>("number", "i32", 999999) == 999999);
ASIO2_CHECK(ini.get<std:: int32_t>("number", "i32", -999999) == -999999);
ASIO2_CHECK(ini.get<std::uint32_t>("number", "u32", 999999) == 999999);
ASIO2_CHECK(ini.get<std:: int64_t>("number", "i64", 9999999999ll ) == 9999999999ll );
ASIO2_CHECK(ini.get<std:: int64_t>("number", "i64", -9999999999ll ) == -9999999999ll );
ASIO2_CHECK(ini.get<std::uint64_t>("number", "u64", 9999999999llu) == 9999999999llu);
ASIO2_CHECK(std::fabs(ini.get<float >("number", "sf", 99.99f) - 99.99f) < 0.0001f);
ASIO2_CHECK(std::fabs(ini.get<double>("number", "df", 999.99 ) - 999.99 ) < 0.0001 );
ASIO2_CHECK(ini.get<std::size_t>("number", "su", 99999) == 99999);
ASIO2_CHECK(ini.get<std::string>("string", "str", "abc!=xyz") == "abc!=xyz");
//---------------------------------------------------------------------------------------------
ASIO2_CHECK(ini.get<bool>("", "boolean", true ) == true );
ASIO2_CHECK(ini.get<bool>("", "boolean", false) == false);
ASIO2_CHECK(ini.get< char>("", "ichar", 'a') == 'a');
ASIO2_CHECK(ini.get<unsigned char>("", "uchar", 250) == 250);
ASIO2_CHECK(ini.get<std:: int8_t>("", "i8", 99) == 99);
ASIO2_CHECK(ini.get<std:: int8_t>("", "i8", -99) == -99);
ASIO2_CHECK(ini.get<std::uint8_t>("", "u8", 99) == 99);
ASIO2_CHECK(ini.get<std:: int16_t>("", "i16", 9999) == 9999);
ASIO2_CHECK(ini.get<std:: int16_t>("", "i16", -9999) == -9999);
ASIO2_CHECK(ini.get<std::uint16_t>("", "u16", 9999) == 9999);
ASIO2_CHECK(ini.get<std:: int32_t>("", "i32", 999999) == 999999);
ASIO2_CHECK(ini.get<std:: int32_t>("", "i32", -999999) == -999999);
ASIO2_CHECK(ini.get<std::uint32_t>("", "u32", 999999) == 999999);
ASIO2_CHECK(ini.get<std:: int64_t>("", "i64", 9999999999ll ) == 9999999999ll );
ASIO2_CHECK(ini.get<std:: int64_t>("", "i64", -9999999999ll ) == -9999999999ll );
ASIO2_CHECK(ini.get<std::uint64_t>("", "u64", 9999999999llu) == 9999999999llu);
ASIO2_CHECK(std::fabs(ini.get<float >("", "sf", 99.99f) - 99.99f) < 0.0001f);
ASIO2_CHECK(std::fabs(ini.get<double>("", "df", 999.99 ) - 999.99 ) < 0.0001 );
ASIO2_CHECK(ini.get<std::size_t>("", "su", 99999) == 99999);
ASIO2_CHECK(ini.get<std::string>("", "str", "abc!=xyz") == "abc!=xyz");
//---------------------------------------------------------------------------------------------
bool boolean = ((loop % 2) == 0);
std::int8_t sign = (boolean ? 1 : -1);
char ichar = (std::rand() % (std::numeric_limits< char>::max)());
char uchar = (std::rand() % (std::numeric_limits<unsigned char>::max)());
std:: int8_t i8 = (std::rand() % (std::numeric_limits<std:: int8_t>::max)()) * sign;
std:: uint8_t u8 = (std::rand() % (std::numeric_limits<std:: uint8_t>::max)());
std:: int16_t i16 = (std::rand() % (std::numeric_limits<std:: int16_t>::max)()) * sign;
std::uint16_t u16 = (std::rand() % (std::numeric_limits<std::uint16_t>::max)());
std:: int32_t i32 = (std::rand() % (std::numeric_limits<std:: int32_t>::max)()) * sign;
std::uint32_t u32 = (std::rand() % (std::numeric_limits<std::uint32_t>::max)());
std:: int64_t i64 = (std::rand() % (std::numeric_limits<std:: int64_t>::max)()) * sign;
std::uint64_t u64 = (std::rand() % (std::numeric_limits<std::uint64_t>::max)());
std::size_t su = (std::rand() % (std::numeric_limits<std::size_t>::max)());
float sf = ( float(std::rand()) / float(RAND_MAX) / 2.0f) * float(sign);
double df = (double(std::rand()) / double(RAND_MAX) / 2.0f) * double(sign);
std::string str;
for (int i = std::rand() % 50 + 5; i >= 0; --i)
str += '!' + (std::rand() % (126 - 33));
//---------------------------------------------------------------------------------------------
ini.set("number", "boolean", boolean);
ASIO2_CHECK(ini.get<bool>("number", "boolean") == boolean);
ini.set("number", "boolean", "true");
ASIO2_CHECK(ini.get<bool>("number", "boolean") == true);
ini.set("number", "boolean", "false");
ASIO2_CHECK(ini.get<bool>("number", "boolean") == false);
ini.set("number", "ichar", ichar);
ASIO2_CHECK(ini.get<char>("number", "ichar") == ichar);
ini.set("number", "uchar", uchar);
ASIO2_CHECK(ini.get<char>("number", "uchar") == uchar);
ini.set("number", "i8", i8);
ASIO2_CHECK(ini.get<std::int8_t>("number", "i8") == i8);
ini.set("number", "u8", u8);
ASIO2_CHECK(ini.get<std::uint8_t>("number", "u8") == u8);
ini.set("number", "i16", i16);
ASIO2_CHECK(ini.get<std::int16_t>("number", "i16") == i16);
ini.set("number", "u16", u16);
ASIO2_CHECK(ini.get<std::uint16_t>("number", "u16") == u16);
ini.set("number", "i32", i32);
ASIO2_CHECK(ini.get<std::int32_t>("number", "i32") == i32);
ini.set("number", "u32", u32);
ASIO2_CHECK(ini.get<std::uint32_t>("number", "u32") == u32);
ini.set("number", "i64", i64);
ASIO2_CHECK(ini.get<std::int64_t>("number", "i64") == i64);
ini.set("number", "u64", u64);
ASIO2_CHECK(ini.get<std::uint64_t>("number", "u64") == u64);
ini.set("number", "su", su);
ASIO2_CHECK(ini.get<std::size_t>("number", "su") == su);
ini.set("number", "sf", sf);
ASIO2_CHECK(std::fabs(ini.get<float>("number", "sf") - sf) < 0.0001f);
ini.set("number", "df", df);
ASIO2_CHECK(std::fabs(ini.get<double>("number", "df") - df) < 0.0001);
ini.set("string", "str", str);
ASIO2_CHECK(ini.get<std::string>("string", "str") == str);
ini.set("number", "i32", "xyz");
ASIO2_CHECK(ini.get<std::int32_t>("number", "i32") == std::int32_t{});
ASIO2_CHECK(ini.get<std::string>("string", "no") == "");
//---------------------------------------------------------------------------------------------
ini.set("", "boolean", boolean);
ASIO2_CHECK(ini.get<bool>("", "boolean") == boolean);
ini.set("", "boolean", "true");
ASIO2_CHECK(ini.get<bool>("", "boolean") == true);
ini.set("", "boolean", "false");
ASIO2_CHECK(ini.get<bool>("", "boolean") == false);
ini.set("", "ichar", ichar);
ASIO2_CHECK(ini.get<char>("", "ichar") == ichar);
ini.set("", "uchar", uchar);
ASIO2_CHECK(ini.get<char>("", "uchar") == uchar);
ini.set("", "i8", i8);
ASIO2_CHECK(ini.get<std::int8_t>("", "i8") == i8);
ini.set("", "u8", u8);
ASIO2_CHECK(ini.get<std::uint8_t>("", "u8") == u8);
ini.set("", "i16", i16);
ASIO2_CHECK(ini.get<std::int16_t>("", "i16") == i16);
ini.set("", "u16", u16);
ASIO2_CHECK(ini.get<std::uint16_t>("", "u16") == u16);
ini.set("", "i32", i32);
ASIO2_CHECK(ini.get<std::int32_t>("", "i32") == i32);
ini.set("", "u32", u32);
ASIO2_CHECK(ini.get<std::uint32_t>("", "u32") == u32);
ini.set("", "i64", i64);
ASIO2_CHECK(ini.get<std::int64_t>("", "i64") == i64);
ini.set("", "u64", u64);
ASIO2_CHECK(ini.get<std::uint64_t>("", "u64") == u64);
ini.set("", "su", su);
ASIO2_CHECK(ini.get<std::size_t>("", "su") == su);
ini.set("", "sf", sf);
ASIO2_CHECK(std::fabs(ini.get<float>("", "sf") - sf) < 0.0001f);
ini.set("", "df", df);
ASIO2_CHECK(std::fabs(ini.get<double>("", "df") - df) < 0.0001);
ini.set("", "str", str);
ASIO2_CHECK(ini.get<std::string>("", "str") == str);
ini.set("", "i32", "xyz");
ASIO2_CHECK(ini.get<std::int32_t>("", "i32") == std::int32_t{});
ASIO2_CHECK(ini.get<std::string>("", "no") == "");
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"ini",
ASIO2_TEST_CASE(ini_test)
)
<file_sep>// (C) Copyright <NAME> 2006.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// GCC-XML C++ compiler setup:
# if !defined(__GCCXML_GNUC__) || ((__GCCXML_GNUC__ <= 3) && (__GCCXML_GNUC_MINOR__ <= 3))
# define BHO_NO_IS_ABSTRACT
# endif
//
// Threading support: Turn this on unconditionally here (except for
// those platforms where we can know for sure). It will get turned off again
// later if no threading API is detected.
//
#if !defined(__MINGW32__) && !defined(_MSC_VER) && !defined(linux) && !defined(__linux) && !defined(__linux__)
# define BHO_HAS_THREADS
#endif
//
// gcc has "long long"
//
#define BHO_HAS_LONG_LONG
// C++0x features:
//
# define BHO_NO_CXX11_CONSTEXPR
# define BHO_NO_CXX11_NULLPTR
# define BHO_NO_CXX11_TEMPLATE_ALIASES
# define BHO_NO_CXX11_DECLTYPE
# define BHO_NO_CXX11_DECLTYPE_N3276
# define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
# define BHO_NO_CXX11_RVALUE_REFERENCES
# define BHO_NO_CXX11_STATIC_ASSERT
# define BHO_NO_CXX11_VARIADIC_TEMPLATES
# define BHO_NO_CXX11_VARIADIC_MACROS
# define BHO_NO_CXX11_AUTO_DECLARATIONS
# define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
# define BHO_NO_CXX11_CHAR16_T
# define BHO_NO_CXX11_CHAR32_T
# define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
# define BHO_NO_CXX11_DELETED_FUNCTIONS
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_SCOPED_ENUMS
# define BHO_NO_SFINAE_EXPR
# define BHO_NO_CXX11_SFINAE_EXPR
# define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
# define BHO_NO_CXX11_LAMBDAS
# define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
# define BHO_NO_CXX11_RANGE_BASED_FOR
# define BHO_NO_CXX11_RAW_LITERALS
# define BHO_NO_CXX11_UNICODE_LITERALS
# define BHO_NO_CXX11_NOEXCEPT
# define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
# define BHO_NO_CXX11_USER_DEFINED_LITERALS
# define BHO_NO_CXX11_ALIGNAS
# define BHO_NO_CXX11_TRAILING_RESULT_TYPES
# define BHO_NO_CXX11_INLINE_NAMESPACES
# define BHO_NO_CXX11_REF_QUALIFIERS
# define BHO_NO_CXX11_FINAL
# define BHO_NO_CXX11_OVERRIDE
# define BHO_NO_CXX11_THREAD_LOCAL
# define BHO_NO_CXX11_UNRESTRICTED_UNION
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
#define BHO_COMPILER "GCC-XML C++ version " __GCCXML__
<file_sep>// (C) Copyright <NAME> 2002 - 2003.
// (C) Copyright <NAME> 2002 - 2003.
// (C) Copyright <NAME> 2002 - 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Comeau STL:
#if !defined(__LIBCOMO__)
# include <asio2/bho/config/no_tr1/utility.hpp>
# if !defined(__LIBCOMO__)
# error "This is not the Comeau STL!"
# endif
#endif
//
// std::streambuf<wchar_t> is non-standard
// NOTE: versions of libcomo prior to beta28 have octal version numbering,
// e.g. version 25 is 21 (dec)
#if __LIBCOMO_VERSION__ <= 22
# define BHO_NO_STD_WSTREAMBUF
#endif
#if (__LIBCOMO_VERSION__ <= 31) && defined(_WIN32)
#define BHO_NO_SWPRINTF
#endif
#if __LIBCOMO_VERSION__ >= 31
# define BHO_HAS_HASH
# define BHO_HAS_SLIST
#endif
// C++0x headers not yet implemented
//
# define BHO_NO_CXX11_HDR_ARRAY
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_HDR_CODECVT
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_EXCEPTION
# define BHO_NO_CXX11_HDR_FORWARD_LIST
# define BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_RANDOM
# define BHO_NO_CXX11_HDR_RATIO
# define BHO_NO_CXX11_HDR_REGEX
# define BHO_NO_CXX11_HDR_SYSTEM_ERROR
# define BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_HDR_TUPLE
# define BHO_NO_CXX11_HDR_TYPE_TRAITS
# define BHO_NO_CXX11_HDR_TYPEINDEX
# define BHO_NO_CXX11_HDR_UNORDERED_MAP
# define BHO_NO_CXX11_HDR_UNORDERED_SET
# define BHO_NO_CXX11_NUMERIC_LIMITS
# define BHO_NO_CXX11_ALLOCATOR
# define BHO_NO_CXX11_POINTER_TRAITS
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
# define BHO_NO_CXX11_SMART_PTR
# define BHO_NO_CXX11_HDR_FUNCTIONAL
# define BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_STD_ALIGN
# define BHO_NO_CXX11_ADDRESSOF
#if defined(__has_include)
#if !__has_include(<shared_mutex>)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#elif __cplusplus < 201402
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#else
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
// C++14 features
# define BHO_NO_CXX14_STD_EXCHANGE
// C++17 features
# define BHO_NO_CXX17_STD_APPLY
# define BHO_NO_CXX17_STD_INVOKE
# define BHO_NO_CXX17_ITERATOR_TRAITS
//
// Intrinsic type_traits support.
// The SGI STL has it's own __type_traits class, which
// has intrinsic compiler support with SGI's compilers.
// Whatever map SGI style type traits to boost equivalents:
//
#define BHO_HAS_SGI_TYPE_TRAITS
#define BHO_STDLIB "Comeau standard library " BHO_STRINGIZE(__LIBCOMO_VERSION__)
<file_sep>#include <asio2/http/http_client.hpp>
#include <iostream>
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8080";
asio2::socks5::option<asio2::socks5::method::anonymous>
sock5_option{ "127.0.0.1",10808 };
//asio2::socks5::option<asio2::socks5::method::anonymous, asio2::socks5::method::password>
// sock5_option{ "s5.doudouip.cn",1088,"zjww-1","aaa123" };
// download and save the file directly. // see ssl_http_client.cpp
// The file is in this directory: /asio2/example/bin/x64/100mb.test
asio2::http_client::download("http://cachefly.cachefly.net/100mb.test", "100mb.test");
std::string_view url = R"(http://www.baidu.com/cond?json={"qeury":"name like '%abc%'","id":1})";
std::string en = http::url_encode(url);
std::cout << en << std::endl;
std::string de = http::url_decode(en);
std::cout << de << std::endl;
auto path = asio2::http::url_to_path(url);
std::cout << path << std::endl;
auto query = asio2::http::url_to_query(url);
std::cout << query << std::endl;
auto rep21 = asio2::http_client::execute(url);
std::cout << rep21 << std::endl;
http::web_request req24 = http::make_request(url);
req24.set(http::field::user_agent, "Chrome");
auto rep26 = asio2::http_client::execute(req24);
std::cout << rep26 << std::endl;
asio2::http_client::execute("www.baidu.com", "80", "/", std::chrono::seconds(5));
asio2::http_client::execute("www.baidu.com", "80", "/", sock5_option);
// GET
auto req2 = http::make_request("GET / HTTP/1.1\r\nHost: 192.168.0.1\r\n\r\n");
auto rep2 = asio2::http_client::execute("www.baidu.com", "80", req2, std::chrono::seconds(3));
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep2 << std::endl;
// POST
auto req4 = http::make_request("POST / HTTP/1.1\r\nHost: 192.168.0.1\r\n\r\n");
auto rep4 = asio2::http_client::execute("www.baidu.com", "80", req4);
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep4 << std::endl;
// GET
http::web_request req6(http::verb::get, "/", 11);
req6.set(http::field::user_agent, "Chrome");
auto rep6 = asio2::http_client::execute("www.baidu.com", "80", req6, sock5_option);
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep6 << std::endl;
// POST
http::web_request req7;
req7.method(http::verb::post);
req7.target("/");
req7.set(http::field::user_agent, "Chrome");
req7.set(http::field::content_type, "text/html");
req7.body() = "Hello World.";
req7.prepare_payload();
auto rep7 = asio2::http_client::execute("www.baidu.com", "80", req7);
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep7 << std::endl;
// convert the response body to string
std::stringstream ss1;
ss1 << rep7.body();
std::cout << ss1.str() << std::endl;
// convert the whole response to string
std::stringstream ss2;
ss2 << rep7;
std::cout << ss2.str() << std::endl;
asio2::http_client client;
client.bind_recv([&](http::web_request& req, http::web_response& rep)
{
// print the whole response
std::cout << rep << std::endl;
// print the response body
std::cout << rep.body() << std::endl;
// convert the response body to string
std::stringstream ss;
ss << rep.body();
std::cout << ss.str() << std::endl;
// Remove all fields
req.clear();
req.set(http::field::user_agent, "Chrome");
req.set(http::field::content_type, "text/html");
req.method(http::verb::get);
req.keep_alive(true);
req.target("/get_user?name=abc");
req.body() = "Hello World.";
req.prepare_payload();
client.async_send(std::move(req));
}).bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n",
client.local_address().c_str(), client.local_port());
// connect success, send a request.
if (!asio2::get_last_error())
{
const char * msg = "GET / HTTP/1.1\r\n\r\n";
client.async_send(msg);
}
});
client.start(host, port/*, sock5_option*/);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
Copyright <NAME> 2015
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_HARDWARE_SIMD_X86_AMD_H
#define BHO_PREDEF_HARDWARE_SIMD_X86_AMD_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/hardware/simd/x86_amd/versions.h>
/* tag::reference[]
= `BHO_HW_SIMD_X86_AMD`
The SIMD extension for x86 (AMD) (*if detected*).
Version number depends on the most recent detected extension.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__SSE4A__+` | {predef_detection}
| `+__FMA4__+` | {predef_detection}
| `+__XOP__+` | {predef_detection}
| `BHO_HW_SIMD_X86` | {predef_detection}
|===
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__SSE4A__+` | BHO_HW_SIMD_X86_SSE4A_VERSION
| `+__FMA4__+` | BHO_HW_SIMD_X86_FMA4_VERSION
| `+__XOP__+` | BHO_HW_SIMD_X86_XOP_VERSION
| `BHO_HW_SIMD_X86` | BHO_HW_SIMD_X86
|===
NOTE: This predef includes every other x86 SIMD extensions and also has other
more specific extensions (FMA4, XOP, SSE4a). You should use this predef
instead of `BHO_HW_SIMD_X86` to test if those specific extensions have
been detected.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_AMD BHO_VERSION_NUMBER_NOT_AVAILABLE
// AMD CPUs also use x86 architecture. We first try to detect if any AMD
// specific extension are detected, if yes, then try to detect more recent x86
// common extensions.
#undef BHO_HW_SIMD_X86_AMD
#if !defined(BHO_HW_SIMD_X86_AMD) && defined(__XOP__)
# define BHO_HW_SIMD_X86_AMD BHO_HW_SIMD_X86_AMD_XOP_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86_AMD) && defined(__FMA4__)
# define BHO_HW_SIMD_X86_AMD BHO_HW_SIMD_X86_AMD_FMA4_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86_AMD) && defined(__SSE4A__)
# define BHO_HW_SIMD_X86_AMD BHO_HW_SIMD_X86_AMD_SSE4A_VERSION
#endif
#if !defined(BHO_HW_SIMD_X86_AMD)
# define BHO_HW_SIMD_X86_AMD BHO_VERSION_NUMBER_NOT_AVAILABLE
#else
// At this point, we know that we have an AMD CPU, we do need to check for
// other x86 extensions to determine the final version number.
# include <asio2/bho/predef/hardware/simd/x86.h>
# if BHO_HW_SIMD_X86 > BHO_HW_SIMD_X86_AMD
# undef BHO_HW_SIMD_X86_AMD
# define BHO_HW_SIMD_X86_AMD BHO_HW_SIMD_X86
# endif
# define BHO_HW_SIMD_X86_AMD_AVAILABLE
#endif
#define BHO_HW_SIMD_X86_AMD_NAME "x86 (AMD) SIMD"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_HW_SIMD_X86_AMD, BHO_HW_SIMD_X86_AMD_NAME)
<file_sep>#include "unit_test.hpp"
#include <asio2/base/detail/push_options.hpp>
#include <asio2/util/string.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/util/codecvt.hpp>
#include <sstream>
#include <fstream>
#include <asio2/base/detail/filesystem.hpp>
std::string ensure_char_pointer_valid(const char* p)
{
if (p && *p)
return p;
return {};
}
void codecvt_test()
{
#if defined(__cpp_lib_char8_t)
{
ASIO2_TEST_IOSTREAM << "LC_CTYPE: " << ensure_char_pointer_valid(std::getenv("LC_CTYPE")) << std::endl;
ASIO2_TEST_IOSTREAM << "LC_ALL : " << ensure_char_pointer_valid(std::getenv("LC_ALL")) << std::endl;
ASIO2_TEST_IOSTREAM << "LANG : " << ensure_char_pointer_valid(std::getenv("LANG")) << std::endl;
ASIO2_TEST_IOSTREAM << "get_system_locale : " << asio2::get_system_locale() << std::endl;
ASIO2_TEST_IOSTREAM << "get_codecvt_locale: " << asio2::get_codecvt_locale() << std::endl;
}
// wide char and ansi char convert
// if the locale has gbk envirment
if (asio2::get_codecvt_locale() == ".936")
{
auto* p = new asio2::codecvt_byname<wchar_t, char, std::mbstate_t>("chs");
std::wstring str;
str += 'H';
str += 'i';
str += ',';
str += 20320;
str += 22909;
str += 65281;
asio2::wstring_convert<asio2::codecvt<wchar_t, char, std::mbstate_t>> conv(p);
std::string narrowStr = conv.to_bytes(str);
std::wstring wideStr = conv.from_bytes(narrowStr);
ASIO2_CHECK(wideStr == str);
}
// wcstombs mbstowcs
{
std::wstring str;
str += 'H';
str += 'i';
str += ',';
str += 20320;
str += 22909;
str += 65281;
std::string mstr = asio2::wcstombs(str);
std::wstring wstr = asio2::mbstowcs(mstr);
ASIO2_CHECK(wstr == str);
}
// gbk_to_utf8 utf8_to_gbk
if (asio2::get_codecvt_locale() == ".936")
{
std::u8string utf8 = u8"z\u6c34\u6c49";
std::string g = asio2::utf8_to_gbk(utf8);
std::string u = asio2::gbk_to_utf8(g);
ASIO2_CHECK(u.size() == utf8.size());
for (std::size_t i = 0; i < u.size(); ++i)
{
ASIO2_CHECK(
static_cast<std::make_unsigned_t<char>>(u[i]) ==
static_cast<std::make_unsigned_t<char8_t>>(utf8[i]));
}
}
// https://en.cppreference.com/w/cpp/locale/codecvt_utf8
{
// UTF-8 data. The character U+1d10b, musical sign segno, does not fit in UCS-2
std::u8string utf8 = u8"z\u6c34\U0001d10b";
std::u16string u16 = u"z\u6c34\U0001d10b";
// the UTF-8 / UTF-16 standard conversion facet
asio2::wstring_convert<asio2::codecvt_utf8_utf16<char16_t, char8_t>, char16_t, char8_t> utf16conv;
std::u16string utf16 = utf16conv.from_bytes(utf8);
ASIO2_CHECK(u16 == utf16);
// the UTF-8 / UCS-2 standard conversion facet
asio2::wstring_convert<asio2::codecvt_utf8<char16_t, char8_t>, char16_t, char8_t> ucs2conv;
try
{
std::u16string ucs2 = ucs2conv.from_bytes(utf8);
ASIO2_CHECK(ucs2.size() == 3);
ASIO2_CHECK(ucs2[0] == 'z');
ASIO2_CHECK(ucs2[1] == 0x6c34);
ASIO2_CHECK(ucs2[2] == 0xd10b);
}
catch (const std::range_error&)
{
//std::u16string ucs2 = ucs2conv.from_bytes(utf8.substr(0, ucs2conv.converted()));
}
}
// https://en.cppreference.com/w/cpp/locale/codecvt_utf16
{
// UTF-16le data (if host system is little-endian)
char16_t utf16le[4] = { 0x007a, // latin small letter 'z' U+007a
0x6c34, // CJK ideograph "water" U+6c34
0xd834, 0xdd0b }; // musical sign segno U+1d10b
// store in a file
std::ofstream fout("text.txt");
fout.write(reinterpret_cast<char*>(utf16le), sizeof utf16le);
fout.close();
// open as a byte stream
std::wifstream fin("text.txt", std::ios::binary);
// apply facet
fin.imbue(std::locale(fin.getloc(),
new asio2::codecvt_utf16<wchar_t, char, 0x10ffff, asio2::little_endian>));
std::wstring str;
wchar_t c = 0;
for (; fin.get(c); str += c);
ASIO2_CHECK(str.size() == 3);
ASIO2_CHECK(str[0] == 0x7a);
ASIO2_CHECK(str[1] == 0x6c34);
if constexpr (sizeof(wchar_t) == 2)
ASIO2_CHECK(str[2] == 0xd10b); // chinese windows, why ?
else // sizeof(wchar_t) == 4
ASIO2_CHECK(str[2] == 0x1d10b); // wsl ubuntu
}
// https://en.cppreference.com/w/cpp/locale/codecvt_utf8_utf16
{
std::u8string u8 = u8"z\u00df\u6c34\U0001f34c";
std::u16string u16 = u"z\u00df\u6c34\U0001f34c";
// UTF-8 to UTF-16/char16_t
std::u16string u16_conv = asio2::wstring_convert<
asio2::codecvt_utf8_utf16<char16_t, char8_t>, char16_t, char8_t>{}.from_bytes(u8);
ASIO2_CHECK(u16 == u16_conv);
// UTF-16/char16_t to UTF-8
std::u8string u8_conv = asio2::wstring_convert<
asio2::codecvt_utf8_utf16<char16_t, char8_t>, char16_t, char8_t>{}.to_bytes(u16);
ASIO2_CHECK(u8 == u8_conv);
}
// https://en.cppreference.com/w/cpp/locale/wbuffer_convert/wbuffer_convert
if (asio2::get_codecvt_locale() == ".936")
{
const char* filepathutf8 = "../../codecvt_utf8.json";
const char* filepathgbk = "../../codecvt_gbk.json";
std::fstream fileutf8(filepathutf8, std::ios::in | std::ios::binary);
std::fstream filegbk(filepathgbk, std::ios::in | std::ios::binary);
if (fileutf8 && filegbk)
{
std::string contentutf8, contentgbk;
contentutf8.resize(std::filesystem::file_size(filepathutf8));
contentgbk.resize(std::filesystem::file_size(filepathgbk));
fileutf8.read(contentutf8.data(), contentutf8.size());
filegbk.read(contentgbk.data(), contentgbk.size());
// wrap a UTF-8 string stream in a UCS4 wbuffer_convert
std::stringbuf utf8buf(contentutf8); // or
// or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9f\x8d\x8c";
asio2::wbuffer_convert<asio2::codecvt_utf8<wchar_t>> conv_in(&utf8buf);
std::wistream ucsbuf(&conv_in);
std::ostringstream ucsout;
for (wchar_t c; ucsbuf.get(c); )
ucsout << std::hex << std::showbase << int(c) << '\n';
// wrap a UTF-8 aware std::cout in a UCS4 wbuffer_convert to output UCS4
asio2::wbuffer_convert<asio2::codecvt_utf8<wchar_t>> conv_out(ucsout.rdbuf());
std::wostream out(&conv_out);
out << L"z\u00df\u6c34\U0001f34c\n";
}
}
if (asio2::get_codecvt_locale() == ".936")
{
const char* filepathutf8 = "../../codecvt_utf8.json";
const char* filepathgbk = "../../codecvt_gbk.json";
std::fstream fileutf8(filepathutf8, std::ios::in | std::ios::binary);
std::fstream filegbk(filepathgbk, std::ios::in | std::ios::binary);
if (fileutf8 && filegbk)
{
std::string contentutf8, contentgbk;
contentutf8.resize(std::filesystem::file_size(filepathutf8));
contentgbk.resize(std::filesystem::file_size(filepathgbk));
fileutf8.read(contentutf8.data(), contentutf8.size());
filegbk.read(contentgbk.data(), contentgbk.size());
std::string g = asio2::utf8_to_gbk(contentutf8);
ASIO2_CHECK(g == contentgbk);
std::string u = asio2::gbk_to_utf8(contentgbk);
ASIO2_CHECK(u == contentutf8);
}
}
if (asio2::get_codecvt_locale() == ".936")
{
const char* filepathutf8 = "../../codecvt_utf8.json";
const char* filepathgbk = "../../codecvt_gbk.json";
std::fstream fileutf8(filepathutf8, std::ios::in | std::ios::binary);
std::fstream filegbk(filepathgbk, std::ios::in | std::ios::binary);
if (fileutf8 && filegbk)
{
std::string contentutf8, contentgbk;
contentutf8.resize(std::filesystem::file_size(filepathutf8));
contentgbk.resize(std::filesystem::file_size(filepathgbk));
fileutf8.read(contentutf8.data(), contentutf8.size());
filegbk.read(contentgbk.data(), contentgbk.size());
std::string g = asio2::utf8_to_locale(contentutf8);
ASIO2_CHECK(g == contentgbk);
std::string u = asio2::locale_to_utf8(contentgbk);
ASIO2_CHECK(u == contentutf8);
}
}
#else
{
ASIO2_TEST_IOSTREAM << "LC_CTYPE: " << ensure_char_pointer_valid(std::getenv("LC_CTYPE")) << std::endl;
ASIO2_TEST_IOSTREAM << "LC_ALL : " << ensure_char_pointer_valid(std::getenv("LC_ALL")) << std::endl;
ASIO2_TEST_IOSTREAM << "LANG : " << ensure_char_pointer_valid(std::getenv("LANG")) << std::endl;
ASIO2_TEST_IOSTREAM << "get_system_locale : " << asio2::get_system_locale() << std::endl;
ASIO2_TEST_IOSTREAM << "get_codecvt_locale: " << asio2::get_codecvt_locale() << std::endl;
}
// wide char and ansi char convert
// if the locale has gbk envirment
if (asio2::get_codecvt_locale() == ".936")
{
auto* p = new asio2::codecvt_byname<wchar_t, char, std::mbstate_t>("chs");
std::wstring str;
str += 'H';
str += 'i';
str += ',';
str += 20320;
str += 22909;
str += 65281;
asio2::wstring_convert<asio2::codecvt<wchar_t, char, std::mbstate_t>> conv(p);
std::string narrowStr = conv.to_bytes(str);
std::wstring wideStr = conv.from_bytes(narrowStr);
ASIO2_CHECK(wideStr == str);
}
// wcstombs mbstowcs
{
std::wstring str;
str += 'H';
str += 'i';
str += ',';
str += 20320;
str += 22909;
str += 65281;
std::string mstr = asio2::wcstombs(str);
std::wstring wstr = asio2::mbstowcs(mstr);
ASIO2_CHECK(wstr == str);
}
// gbk_to_utf8 utf8_to_gbk
if (asio2::get_codecvt_locale() == ".936")
{
std::string utf8 = u8"z\u6c34\u6c49";
std::string g = asio2::utf8_to_gbk(utf8);
std::string u = asio2::gbk_to_utf8(g);
ASIO2_CHECK(u == utf8);
}
// https://en.cppreference.com/w/cpp/locale/codecvt_utf8
{
// UTF-8 data. The character U+1d10b, musical sign segno, does not fit in UCS-2
std::string utf8 = u8"z\u6c34\U0001d10b";
std::u16string u16 = u"z\u6c34\U0001d10b";
// the UTF-8 / UTF-16 standard conversion facet
asio2::wstring_convert<asio2::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv;
std::u16string utf16 = utf16conv.from_bytes(utf8);
ASIO2_CHECK(u16 == utf16);
// the UTF-8 / UCS-2 standard conversion facet
asio2::wstring_convert<asio2::codecvt_utf8<char16_t>, char16_t> ucs2conv;
try
{
std::u16string ucs2 = ucs2conv.from_bytes(utf8);
ASIO2_CHECK(ucs2.size() == 3);
ASIO2_CHECK(ucs2[0] == 'z');
ASIO2_CHECK(ucs2[1] == 0x6c34);
ASIO2_CHECK(ucs2[2] == 0xd10b);
}
catch (const std::range_error&)
{
//std::u16string ucs2 = ucs2conv.from_bytes(utf8.substr(0, ucs2conv.converted()));
}
}
// https://en.cppreference.com/w/cpp/locale/codecvt_utf16
{
// UTF-16le data (if host system is little-endian)
char16_t utf16le[4] = { 0x007a, // latin small letter 'z' U+007a
0x6c34, // CJK ideograph "water" U+6c34
0xd834, 0xdd0b }; // musical sign segno U+1d10b
// store in a file
std::ofstream fout("text.txt");
fout.write(reinterpret_cast<char*>(utf16le), sizeof utf16le);
fout.close();
// open as a byte stream
std::wifstream fin("text.txt", std::ios::binary);
// apply facet
fin.imbue(std::locale(fin.getloc(),
new asio2::codecvt_utf16<wchar_t, char, 0x10ffff, asio2::little_endian>));
std::wstring str;
wchar_t c = 0;
for (; fin.get(c); str += c);
ASIO2_CHECK(str.size() == 3);
ASIO2_CHECK(str[0] == 0x7a);
ASIO2_CHECK(str[1] == 0x6c34);
if constexpr (sizeof(wchar_t) == 2)
ASIO2_CHECK_VALUE(str[2], str[2] == 0xd10b); // chinese windows, why ?
else // sizeof(wchar_t) == 4
ASIO2_CHECK_VALUE(str[2], str[2] == 0x1d10b); // wsl ubuntu
}
// https://en.cppreference.com/w/cpp/locale/codecvt_utf8_utf16
{
std::string u8 = u8"z\u00df\u6c34\U0001f34c";
std::u16string u16 = u"z\u00df\u6c34\U0001f34c";
// UTF-8 to UTF-16/char16_t
std::u16string u16_conv = asio2::wstring_convert<
asio2::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(u8);
ASIO2_CHECK(u16 == u16_conv);
// UTF-16/char16_t to UTF-8
std::string u8_conv = asio2::wstring_convert<
asio2::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(u16);
ASIO2_CHECK(u8 == u8_conv);
}
// https://en.cppreference.com/w/cpp/locale/wbuffer_convert/wbuffer_convert
{
// wrap a UTF-8 string stream in a UCS4 wbuffer_convert
std::stringbuf utf8buf(u8"z\u00df\u6c34\U0001f34c"); // or
// or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9f\x8d\x8c";
asio2::wbuffer_convert<asio2::codecvt_utf8<wchar_t>> conv_in(&utf8buf);
std::wistream ucsbuf(&conv_in);
for (wchar_t c; ucsbuf.get(c); )
std::cout << std::hex << std::showbase << c << '\n';
// wrap a UTF-8 aware std::cout in a UCS4 wbuffer_convert to output UCS4
asio2::wbuffer_convert<asio2::codecvt_utf8<wchar_t>> conv_out(std::cout.rdbuf());
std::wostream out(&conv_out);
out << L"z\u00df\u6c34\U0001f34c\n";
}
if (asio2::get_codecvt_locale() == ".936")
{
const char* filepathutf8 = "../../codecvt_utf8.json";
const char* filepathgbk = "../../codecvt_gbk.json";
std::fstream fileutf8(filepathutf8, std::ios::in | std::ios::binary);
std::fstream filegbk(filepathgbk, std::ios::in | std::ios::binary);
if (fileutf8 && filegbk)
{
std::string contentutf8, contentgbk;
contentutf8.resize(std::filesystem::file_size(filepathutf8));
contentgbk.resize(std::filesystem::file_size(filepathgbk));
fileutf8.read(contentutf8.data(), contentutf8.size());
filegbk.read(contentgbk.data(), contentgbk.size());
std::string g = asio2::utf8_to_gbk(contentutf8);
ASIO2_CHECK(g == contentgbk);
std::string u = asio2::gbk_to_utf8(contentgbk);
ASIO2_CHECK(u == contentutf8);
}
}
if (asio2::get_codecvt_locale() == ".936")
{
const char* filepathutf8 = "../../codecvt_utf8.json";
const char* filepathgbk = "../../codecvt_gbk.json";
std::fstream fileutf8(filepathutf8, std::ios::in | std::ios::binary);
std::fstream filegbk(filepathgbk, std::ios::in | std::ios::binary);
if (fileutf8 && filegbk)
{
std::string contentutf8, contentgbk;
contentutf8.resize(std::filesystem::file_size(filepathutf8));
contentgbk.resize(std::filesystem::file_size(filepathgbk));
fileutf8.read(contentutf8.data(), contentutf8.size());
filegbk.read(contentgbk.data(), contentgbk.size());
std::string g = asio2::utf8_to_locale(contentutf8);
ASIO2_CHECK(g == contentgbk);
std::string u = asio2::locale_to_utf8(contentgbk);
ASIO2_CHECK(u == contentutf8);
}
}
#endif
//ASIO2_TEST_BEGIN_LOOP(test_loop_times);
//ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"codecvt",
ASIO2_TEST_CASE(codecvt_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RECONNECT_TIMER_COMPONENT_HPP__
#define __ASIO2_RECONNECT_TIMER_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <chrono>
#include <asio2/base/iopool.hpp>
#include <asio2/base/log.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class reconnect_timer_cp
{
public:
/**
* @brief constructor
*/
reconnect_timer_cp() = default;
/**
* @brief destructor
*/
~reconnect_timer_cp() = default;
public:
/**
* @brief set the option of whether auto reconnect when disconnected, same as set_auto_reconnect
* @param enable - whether reconnect or not
*/
template<typename = void>
inline derived_t& auto_reconnect(bool enable) noexcept
{
return this->set_auto_reconnect(enable);
}
/**
* @brief set the option of whether auto reconnect when disconnected, same as set_auto_reconnect
* @param enable - whether reconnect or not
* @param delay - how long is the delay before reconnecting, when enalbe is
* false, the delay param is ignored
*/
template<class Rep, class Period>
inline derived_t& auto_reconnect(bool enable, std::chrono::duration<Rep, Period> delay) noexcept
{
return this->set_auto_reconnect(enable, std::move(delay));
}
/**
* @brief set the option of whether auto reconnect when disconnected
* @param enable - whether reconnect or not
*/
template<typename = void>
inline derived_t& set_auto_reconnect(bool enable) noexcept
{
this->reconnect_enable_ = enable;
return static_cast<derived_t&>(*this);
}
/**
* @brief set the option of whether auto reconnect when disconnected
* @param enable - whether reconnect or not
* @param delay - how long is the delay before reconnecting, when enalbe is
* false, the delay param is ignored
*/
template<class Rep, class Period>
inline derived_t& set_auto_reconnect(bool enable, std::chrono::duration<Rep, Period> delay) noexcept
{
this->reconnect_enable_ = enable;
if (delay > std::chrono::duration_cast<
std::chrono::duration<Rep, Period>>((std::chrono::steady_clock::duration::max)()))
this->reconnect_delay_ = (std::chrono::steady_clock::duration::max)();
else
this->reconnect_delay_ = delay;
return static_cast<derived_t&>(*this);
}
/**
* @brief get whether auto reconnect is enabled or not
*/
template<typename = void>
inline bool is_auto_reconnect() noexcept
{
return this->reconnect_enable_;
}
/**
* @brief get the delay before reconnecting, when enalbe is
*/
template<typename = void>
inline std::chrono::steady_clock::duration get_auto_reconnect_delay() noexcept
{
return this->reconnect_delay_;
}
protected:
template<class C>
inline void _make_reconnect_timer(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]() mutable
{
derived_t& derive = static_cast<derived_t&>(*this);
if (this->reconnect_timer_)
{
this->reconnect_timer_->cancel();
}
this->reconnect_timer_ = std::make_shared<safe_timer>(derive.io().context());
derive._post_reconnect_timer(std::move(this_ptr), std::move(ecs),
this->reconnect_timer_, (std::chrono::nanoseconds::max)()); // 292 yeas
}));
}
template<class Rep, class Period, class C>
inline void _post_reconnect_timer(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs,
std::shared_ptr<safe_timer> timer_ptr, std::chrono::duration<Rep, Period> delay)
{
derived_t& derive = static_cast<derived_t&>(*this);
#if defined(_DEBUG) || defined(DEBUG)
this->is_post_reconnect_timer_called_ = true;
ASIO2_ASSERT(this->is_stop_reconnect_timer_called_ == false);
#endif
// When goto timer callback, and execute the reconnect operation :
// call _start_connect -> _make_reconnect_timer -> a new timer is maked, and
// the prev timer will be canceled, then call _post_reconnect_timer, the prev
// timer will be enqueue to, this will cause the prev timer never be exit.
// so we check if timer_ptr is not equal the member variable reconnect_timer_,
// don't call async_wait again.
if (timer_ptr.get() != this->reconnect_timer_.get())
return;
safe_timer* ptimer = timer_ptr.get();
ptimer->timer.expires_after(delay);
ptimer->timer.async_wait(
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), timer_ptr = std::move(timer_ptr)]
(const error_code & ec) mutable
{
derive._handle_reconnect_timer(ec, std::move(this_ptr), std::move(ecs), std::move(timer_ptr));
});
}
template<class C>
inline void _handle_reconnect_timer(const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, std::shared_ptr<safe_timer> timer_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT((!ec) || ec == asio::error::operation_aborted);
// a new timer is maked, this is the prev timer, so return directly.
if (timer_ptr.get() != this->reconnect_timer_.get())
return;
// member variable timer should't be empty
if (!this->reconnect_timer_)
{
ASIO2_ASSERT(false);
return;
}
// current reconnect timer is canceled, so return directly
if (timer_ptr->canceled.test_and_set())
return;
timer_ptr->canceled.clear();
if (ec == asio::error::operation_aborted)
{
derive._post_reconnect_timer(
std::move(this_ptr), std::move(ecs), std::move(timer_ptr), this->reconnect_delay_);
}
else
{
if (this->reconnect_enable_)
{
derive.push_event(
[&derive, this_ptr, ecs, timer_ptr](event_queue_guard<derived_t> g) mutable
{
if (timer_ptr->canceled.test_and_set())
return;
timer_ptr->canceled.clear();
state_t expected = state_t::stopped;
if (derive.state_.compare_exchange_strong(expected, state_t::starting))
{
derive.template _start_connect<true>(
std::move(this_ptr), std::move(ecs), defer_event(std::move(g)));
}
});
}
derive._post_reconnect_timer(std::move(this_ptr), std::move(ecs),
std::move(timer_ptr), (std::chrono::nanoseconds::max)()); // 292 yeas
}
}
inline void _stop_reconnect_timer()
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.dispatch([this]() mutable
{
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_reconnect_timer_called_ = true;
#endif
if (this->reconnect_timer_)
{
this->reconnect_timer_->cancel();
}
});
}
inline void _wake_reconnect_timer()
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.dispatch([this]() mutable
{
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_post_reconnect_timer_called_ == true);
#endif
if (this->reconnect_enable_)
{
ASIO2_ASSERT(this->reconnect_timer_);
if (this->reconnect_timer_)
{
detail::cancel_timer(this->reconnect_timer_->timer);
}
}
});
}
protected:
/// timer for client reconnect
std::shared_ptr<safe_timer> reconnect_timer_;
/// if there has no data transfer for a long time,the session will be disconnect
std::chrono::steady_clock::duration reconnect_delay_ = std::chrono::seconds(1);
/// flag of whether reconnect when disconnect
bool reconnect_enable_ = true;
#if defined(_DEBUG) || defined(DEBUG)
bool is_stop_reconnect_timer_called_ = false;
bool is_post_reconnect_timer_called_ = false;
#endif
};
}
#endif // !__ASIO2_RECONNECT_TIMER_COMPONENT_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_GREENHILLS_H
#define BHO_PREDEF_COMPILER_GREENHILLS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_GHS`
http://en.wikipedia.org/wiki/Green_Hills_Software[Green Hills C/{CPP}] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__ghs+` | {predef_detection}
| `+__ghs__+` | {predef_detection}
| `+__GHS_VERSION_NUMBER__+` | V.R.P
| `+__ghs+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_GHS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__ghs) || defined(__ghs__)
# if !defined(BHO_COMP_GHS_DETECTION) && defined(__GHS_VERSION_NUMBER__)
# define BHO_COMP_GHS_DETECTION BHO_PREDEF_MAKE_10_VRP(__GHS_VERSION_NUMBER__)
# endif
# if !defined(BHO_COMP_GHS_DETECTION) && defined(__ghs)
# define BHO_COMP_GHS_DETECTION BHO_PREDEF_MAKE_10_VRP(__ghs)
# endif
# if !defined(BHO_COMP_GHS_DETECTION)
# define BHO_COMP_GHS_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_COMP_GHS_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_GHS_EMULATED BHO_COMP_GHS_DETECTION
# else
# undef BHO_COMP_GHS
# define BHO_COMP_GHS BHO_COMP_GHS_DETECTION
# endif
# define BHO_COMP_GHS_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_GHS_NAME "Green Hills C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_GHS,BHO_COMP_GHS_NAME)
#ifdef BHO_COMP_GHS_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_GHS_EMULATED,BHO_COMP_GHS_NAME)
#endif
<file_sep>//=====================================================================
//
// KCP - A Better ARQ Protocol Implementation
// skywind3000 (at) gmail.com, 2010-2011
//
// Features:
// + Average RTT reduce 30% - 40% vs traditional ARQ like tcp.
// + Maximum RTT reduce three times vs tcp.
// + Lightweight, distributed as a single source file.
//
//=====================================================================
#ifndef __IKCP_H__
#define __IKCP_H__
#define KCP_VERSION 107 // 1.7
#include <stddef.h>
#include <stdlib.h>
#include <assert.h>
namespace asio2::detail::kcp {
//=====================================================================
// 32BIT INTEGER DEFINITION
//=====================================================================
#ifndef __INTEGER_32_BITS__
#define __INTEGER_32_BITS__
#if defined(_WIN64) || defined(WIN64) || defined(__amd64__) || \
defined(__x86_64) || defined(__x86_64__) || defined(_M_IA64) || \
defined(_M_AMD64)
typedef unsigned int ISTDUINT32;
typedef int ISTDINT32;
#elif defined(_WIN32) || defined(WIN32) || defined(__i386__) || \
defined(__i386) || defined(_M_X86)
typedef unsigned long ISTDUINT32;
typedef long ISTDINT32;
#elif defined(__MACOS__)
typedef UInt32 ISTDUINT32;
typedef SInt32 ISTDINT32;
#elif defined(__APPLE__) && defined(__MACH__)
#include <sys/types.h>
typedef u_int32_t ISTDUINT32;
typedef int32_t ISTDINT32;
#elif defined(__BEOS__)
#include <sys/inttypes.h>
typedef u_int32_t ISTDUINT32;
typedef int32_t ISTDINT32;
#elif (defined(_MSC_VER) || defined(__BORLANDC__)) && (!defined(__MSDOS__))
typedef unsigned __int32 ISTDUINT32;
typedef __int32 ISTDINT32;
#elif defined(__GNUC__)
#include <stdint.h>
typedef uint32_t ISTDUINT32;
typedef int32_t ISTDINT32;
#else
typedef unsigned long ISTDUINT32;
typedef long ISTDINT32;
#endif
#endif
//=====================================================================
// Integer Definition
//=====================================================================
#ifndef __IINT8_DEFINED
#define __IINT8_DEFINED
typedef char IINT8;
#endif
#ifndef __IUINT8_DEFINED
#define __IUINT8_DEFINED
typedef unsigned char IUINT8;
#endif
#ifndef __IUINT16_DEFINED
#define __IUINT16_DEFINED
typedef unsigned short IUINT16;
#endif
#ifndef __IINT16_DEFINED
#define __IINT16_DEFINED
typedef short IINT16;
#endif
#ifndef __IINT32_DEFINED
#define __IINT32_DEFINED
typedef ISTDINT32 IINT32;
#endif
#ifndef __IUINT32_DEFINED
#define __IUINT32_DEFINED
typedef ISTDUINT32 IUINT32;
#endif
#ifndef __IINT64_DEFINED
#define __IINT64_DEFINED
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef __int64 IINT64;
#else
typedef long long IINT64;
#endif
#endif
#ifndef __IUINT64_DEFINED
#define __IUINT64_DEFINED
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 IUINT64;
#else
typedef unsigned long long IUINT64;
#endif
#endif
#ifndef INLINE
#if defined(__GNUC__)
#if (__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))
#define INLINE __inline__ __attribute__((always_inline))
#else
#define INLINE __inline__
#endif
#elif (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__WATCOMC__))
#define INLINE __inline
#else
#define INLINE
#endif
#endif
#if (!defined(__cplusplus)) && (!defined(inline))
#define inline INLINE
#endif
//=====================================================================
// QUEUE DEFINITION
//=====================================================================
#ifndef __IQUEUE_DEF__
#define __IQUEUE_DEF__
struct IQUEUEHEAD {
struct IQUEUEHEAD *next, *prev;
};
typedef struct IQUEUEHEAD iqueue_head;
//---------------------------------------------------------------------
// queue init
//---------------------------------------------------------------------
#define IQUEUE_HEAD_INIT(name) { &(name), &(name) }
#define IQUEUE_HEAD(name) \
struct IQUEUEHEAD name = IQUEUE_HEAD_INIT(name)
#define IQUEUE_INIT(ptr) ( \
(ptr)->next = (ptr), (ptr)->prev = (ptr))
#define IOFFSETOF(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define ICONTAINEROF(ptr, type, member) ( \
(type*)( ((char*)((type*)ptr)) - IOFFSETOF(type, member)) )
#define IQUEUE_ENTRY(ptr, type, member) ICONTAINEROF(ptr, type, member)
//---------------------------------------------------------------------
// queue operation
//---------------------------------------------------------------------
#define IQUEUE_ADD(node, head) ( \
(node)->prev = (head), (node)->next = (head)->next, \
(head)->next->prev = (node), (head)->next = (node))
#define IQUEUE_ADD_TAIL(node, head) ( \
(node)->prev = (head)->prev, (node)->next = (head), \
(head)->prev->next = (node), (head)->prev = (node))
#define IQUEUE_DEL_BETWEEN(p, n) ((n)->prev = (p), (p)->next = (n))
#define IQUEUE_DEL(entry) (\
(entry)->next->prev = (entry)->prev, \
(entry)->prev->next = (entry)->next, \
(entry)->next = 0, (entry)->prev = 0)
#define IQUEUE_DEL_INIT(entry) do { \
IQUEUE_DEL(entry); IQUEUE_INIT(entry); } while (0)
#define IQUEUE_IS_EMPTY(entry) ((entry) == (entry)->next)
#define iqueue_init IQUEUE_INIT
#define iqueue_entry IQUEUE_ENTRY
#define iqueue_add IQUEUE_ADD
#define iqueue_add_tail IQUEUE_ADD_TAIL
#define iqueue_del IQUEUE_DEL
#define iqueue_del_init IQUEUE_DEL_INIT
#define iqueue_is_empty IQUEUE_IS_EMPTY
#define IQUEUE_FOREACH(iterator, head, TYPE, MEMBER) \
for ((iterator) = iqueue_entry((head)->next, TYPE, MEMBER); \
&((iterator)->MEMBER) != (head); \
(iterator) = iqueue_entry((iterator)->MEMBER.next, TYPE, MEMBER))
#define iqueue_foreach(iterator, head, TYPE, MEMBER) \
IQUEUE_FOREACH(iterator, head, TYPE, MEMBER)
#define iqueue_foreach_entry(pos, head) \
for( (pos) = (head)->next; (pos) != (head) ; (pos) = (pos)->next )
#define __iqueue_splice(list, head) do { \
iqueue_head *first = (list)->next, *last = (list)->prev; \
iqueue_head *at = (head)->next; \
(first)->prev = (head), (head)->next = (first); \
(last)->next = (at), (at)->prev = (last); } while (0)
#define iqueue_splice(list, head) do { \
if (!iqueue_is_empty(list)) __iqueue_splice(list, head); } while (0)
#define iqueue_splice_init(list, head) do { \
iqueue_splice(list, head); iqueue_init(list); } while (0)
#ifdef _MSC_VER
#pragma warning(disable:4311)
#pragma warning(disable:4312)
#pragma warning(disable:4996)
#endif
#endif
//---------------------------------------------------------------------
// BYTE ORDER & ALIGNMENT
//---------------------------------------------------------------------
#ifndef IWORDS_BIG_ENDIAN
#ifdef _BIG_ENDIAN_
#if _BIG_ENDIAN_
#define IWORDS_BIG_ENDIAN 1
#endif
#endif
#ifndef IWORDS_BIG_ENDIAN
#if defined(__hppa__) || \
defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \
(defined(__MIPS__) && defined(__MIPSEB__)) || \
defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \
defined(__sparc__) || defined(__powerpc__) || \
defined(__mc68000__) || defined(__s390x__) || defined(__s390__)
#define IWORDS_BIG_ENDIAN 1
#endif
#endif
#ifndef IWORDS_BIG_ENDIAN
#define IWORDS_BIG_ENDIAN 0
#endif
#endif
#ifndef IWORDS_MUST_ALIGN
#if defined(__i386__) || defined(__i386) || defined(_i386_)
#define IWORDS_MUST_ALIGN 0
#elif defined(_M_IX86) || defined(_X86_) || defined(__x86_64__)
#define IWORDS_MUST_ALIGN 0
#elif defined(__amd64) || defined(__amd64__)
#define IWORDS_MUST_ALIGN 0
#else
#define IWORDS_MUST_ALIGN 1
#endif
#endif
//=====================================================================
// SEGMENT
//=====================================================================
struct IKCPSEG
{
struct IQUEUEHEAD node;
IUINT32 conv;
IUINT32 cmd;
IUINT32 frg;
IUINT32 wnd;
IUINT32 ts;
IUINT32 sn;
IUINT32 una;
IUINT32 len;
IUINT32 resendts;
IUINT32 rto;
IUINT32 fastack;
IUINT32 xmit;
char data[1];
};
//---------------------------------------------------------------------
// IKCPCB
//---------------------------------------------------------------------
struct IKCPCB
{
IUINT32 conv, mtu, mss, state;
IUINT32 snd_una, snd_nxt, rcv_nxt;
IUINT32 ts_recent, ts_lastack, ssthresh;
IINT32 rx_rttval, rx_srtt, rx_rto, rx_minrto;
IUINT32 snd_wnd, rcv_wnd, rmt_wnd, cwnd, probe;
IUINT32 current, interval, ts_flush, xmit;
IUINT32 nrcv_buf, nsnd_buf;
IUINT32 nrcv_que, nsnd_que;
IUINT32 nodelay, updated;
IUINT32 ts_probe, probe_wait;
IUINT32 dead_link, incr;
struct IQUEUEHEAD snd_queue;
struct IQUEUEHEAD rcv_queue;
struct IQUEUEHEAD snd_buf;
struct IQUEUEHEAD rcv_buf;
IUINT32 *acklist;
IUINT32 ackcount;
IUINT32 ackblock;
void *user;
char *buffer;
int fastresend;
int fastlimit;
int nocwnd, stream;
int logmask;
int (*output)(const char *buf, int len, struct IKCPCB *kcp, void *user);
void (*writelog)(const char *log, struct IKCPCB *kcp, void *user);
};
typedef struct IKCPCB ikcpcb;
#define IKCP_LOG_OUTPUT 1
#define IKCP_LOG_INPUT 2
#define IKCP_LOG_SEND 4
#define IKCP_LOG_RECV 8
#define IKCP_LOG_IN_DATA 16
#define IKCP_LOG_IN_ACK 32
#define IKCP_LOG_IN_PROBE 64
#define IKCP_LOG_IN_WINS 128
#define IKCP_LOG_OUT_DATA 256
#define IKCP_LOG_OUT_ACK 512
#define IKCP_LOG_OUT_PROBE 1024
#define IKCP_LOG_OUT_WINS 2048
//#ifdef __cplusplus
//extern "C" {
//#endif
namespace {
//---------------------------------------------------------------------
// interface
//---------------------------------------------------------------------
// create a new kcp control object, 'conv' must equal in two endpoint
// from the same connection. 'user' will be passed to the output callback
// output callback can be setup like this: 'kcp->output = my_udp_output'
ikcpcb* ikcp_create(IUINT32 conv, void *user);
// release kcp control object
void ikcp_release(ikcpcb *kcp);
// set output callback, which will be invoked by kcp
void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len,
ikcpcb *kcp, void *user));
// user/upper level recv: returns size, returns below zero for EAGAIN
int ikcp_recv(ikcpcb *kcp, char *buffer, int len);
// user/upper level send, returns below zero for error
int ikcp_send(ikcpcb *kcp, const char *buffer, int len);
// update state (call it repeatedly, every 10ms-100ms), or you can ask
// ikcp_check when to call it again (without ikcp_input/_send calling).
// 'current' - current timestamp in millisec.
void ikcp_update(ikcpcb *kcp, IUINT32 current);
// Determine when should you invoke ikcp_update:
// returns when you should invoke ikcp_update in millisec, if there
// is no ikcp_input/_send calling. you can call ikcp_update in that
// time, instead of call update repeatly.
// Important to reduce unnacessary ikcp_update invoking. use it to
// schedule ikcp_update (eg. implementing an epoll-like mechanism,
// or optimize ikcp_update when handling massive kcp connections)
IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current);
// when you received a low level packet (eg. UDP packet), call it
int ikcp_input(ikcpcb *kcp, const char *data, long size);
// flush pending data
void ikcp_flush(ikcpcb *kcp);
// check the size of next message in the recv queue
int ikcp_peeksize(const ikcpcb *kcp);
// change MTU size, default is 1400
int ikcp_setmtu(ikcpcb *kcp, int mtu);
// set maximum window size: sndwnd=32, rcvwnd=32 by default
int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd);
// get how many packet is waiting to be sent
int ikcp_waitsnd(const ikcpcb *kcp);
// fastest: ikcp_nodelay(kcp, 1, 20, 2, 1)
// nodelay: 0:disable(default), 1:enable
// interval: internal update timer interval in millisec, default is 100ms
// resend: 0:disable fast resend(default), 1:enable fast resend
// nc: 0:normal congestion control(default), 1:disable congestion control
int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc);
void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...);
// setup allocator
void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*));
// read conv
IUINT32 ikcp_getconv(const void *ptr);
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
//=====================================================================
// KCP BASIC
//=====================================================================
const IUINT32 IKCP_RTO_NDL = 30; // no delay min rto
const IUINT32 IKCP_RTO_MIN = 100; // normal min rto
const IUINT32 IKCP_RTO_DEF = 200;
const IUINT32 IKCP_RTO_MAX = 60000;
const IUINT32 IKCP_CMD_PUSH = 81; // cmd: push data
const IUINT32 IKCP_CMD_ACK = 82; // cmd: ack
const IUINT32 IKCP_CMD_WASK = 83; // cmd: window probe (ask)
const IUINT32 IKCP_CMD_WINS = 84; // cmd: window size (tell)
const IUINT32 IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK
const IUINT32 IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS
const IUINT32 IKCP_WND_SND = 32;
const IUINT32 IKCP_WND_RCV = 128; // must >= max fragment size
const IUINT32 IKCP_MTU_DEF = 1400;
const IUINT32 IKCP_ACK_FAST = 3;
const IUINT32 IKCP_INTERVAL = 100;
const IUINT32 IKCP_OVERHEAD = 24;
const IUINT32 IKCP_DEADLINK = 20;
const IUINT32 IKCP_THRESH_INIT = 2;
const IUINT32 IKCP_THRESH_MIN = 2;
const IUINT32 IKCP_PROBE_INIT = 7000; // 7 secs to probe window size
const IUINT32 IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window
const IUINT32 IKCP_FASTACK_LIMIT = 5; // max times to trigger fastack
//---------------------------------------------------------------------
// encode / decode
//---------------------------------------------------------------------
/* encode 8 bits unsigned int */
static inline char *ikcp_encode8u(char *p, unsigned char c)
{
*(unsigned char*)p++ = c;
return p;
}
/* decode 8 bits unsigned int */
static inline const char *ikcp_decode8u(const char *p, unsigned char *c)
{
*c = *(unsigned char*)p++;
return p;
}
/* encode 16 bits unsigned int (lsb) */
static inline char *ikcp_encode16u(char *p, unsigned short w)
{
#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
*(unsigned char*)(p + 0) = (w & 255);
*(unsigned char*)(p + 1) = (w >> 8);
#else
memcpy(p, &w, 2);
#endif
p += 2;
return p;
}
/* decode 16 bits unsigned int (lsb) */
static inline const char *ikcp_decode16u(const char *p, unsigned short *w)
{
#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
*w = *(const unsigned char*)(p + 1);
*w = *(const unsigned char*)(p + 0) + (*w << 8);
#else
memcpy(w, p, 2);
#endif
p += 2;
return p;
}
/* encode 32 bits unsigned int (lsb) */
static inline char *ikcp_encode32u(char *p, IUINT32 l)
{
#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
*(unsigned char*)(p + 0) = (unsigned char)((l >> 0) & 0xff);
*(unsigned char*)(p + 1) = (unsigned char)((l >> 8) & 0xff);
*(unsigned char*)(p + 2) = (unsigned char)((l >> 16) & 0xff);
*(unsigned char*)(p + 3) = (unsigned char)((l >> 24) & 0xff);
#else
memcpy(p, &l, 4);
#endif
p += 4;
return p;
}
/* decode 32 bits unsigned int (lsb) */
static inline const char *ikcp_decode32u(const char *p, IUINT32 *l)
{
#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
*l = *(const unsigned char*)(p + 3);
*l = *(const unsigned char*)(p + 2) + (*l << 8);
*l = *(const unsigned char*)(p + 1) + (*l << 8);
*l = *(const unsigned char*)(p + 0) + (*l << 8);
#else
memcpy(l, p, 4);
#endif
p += 4;
return p;
}
static inline IUINT32 _imin_(IUINT32 a, IUINT32 b) {
return a <= b ? a : b;
}
static inline IUINT32 _imax_(IUINT32 a, IUINT32 b) {
return a >= b ? a : b;
}
static inline IUINT32 _ibound_(IUINT32 lower, IUINT32 middle, IUINT32 upper)
{
return _imin_(_imax_(lower, middle), upper);
}
static inline long _itimediff(IUINT32 later, IUINT32 earlier)
{
return ((IINT32)(later - earlier));
}
//---------------------------------------------------------------------
// manage segment
//---------------------------------------------------------------------
typedef struct IKCPSEG IKCPSEG;
static void* (*ikcp_malloc_hook)(size_t) = NULL;
static void (*ikcp_free_hook)(void *) = NULL;
// internal malloc
static void* ikcp_malloc(size_t size) {
if (ikcp_malloc_hook)
return ikcp_malloc_hook(size);
return malloc(size);
}
// internal free
static void ikcp_free(void *ptr) {
if (ikcp_free_hook) {
ikcp_free_hook(ptr);
} else {
free(ptr);
}
}
// redefine allocator
void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*))
{
ikcp_malloc_hook = new_malloc;
ikcp_free_hook = new_free;
}
// allocate a new kcp segment
static IKCPSEG* ikcp_segment_new(ikcpcb *kcp, int size)
{
return (IKCPSEG*)ikcp_malloc(sizeof(IKCPSEG) + size);
}
// delete a segment
static void ikcp_segment_delete(ikcpcb *kcp, IKCPSEG *seg)
{
ikcp_free(seg);
}
// write log
void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...)
{
char buffer[1024];
va_list argptr;
if ((mask & kcp->logmask) == 0 || kcp->writelog == 0) return;
va_start(argptr, fmt);
vsprintf(buffer, fmt, argptr);
va_end(argptr);
kcp->writelog(buffer, kcp, kcp->user);
}
// check log mask
static int ikcp_canlog(const ikcpcb *kcp, int mask)
{
if ((mask & kcp->logmask) == 0 || kcp->writelog == NULL) return 0;
return 1;
}
// output segment
static int ikcp_output(ikcpcb *kcp, const void *data, int size)
{
assert(kcp);
assert(kcp->output);
if (ikcp_canlog(kcp, IKCP_LOG_OUTPUT)) {
ikcp_log(kcp, IKCP_LOG_OUTPUT, "[RO] %ld bytes", (long)size);
}
if (size == 0) return 0;
return kcp->output((const char*)data, size, kcp, kcp->user);
}
// output queue
void ikcp_qprint(const char *name, const struct IQUEUEHEAD *head)
{
#if 0
const struct IQUEUEHEAD *p;
printf("<%s>: [", name);
for (p = head->next; p != head; p = p->next) {
const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node);
printf("(%lu %d)", (unsigned long)seg->sn, (int)(seg->ts % 10000));
if (p->next != head) printf(",");
}
printf("]\n");
#endif
}
//---------------------------------------------------------------------
// create a new kcpcb
//---------------------------------------------------------------------
ikcpcb* ikcp_create(IUINT32 conv, void *user)
{
ikcpcb *kcp = (ikcpcb*)ikcp_malloc(sizeof(struct IKCPCB));
if (kcp == NULL) return NULL;
kcp->conv = conv;
kcp->user = user;
kcp->snd_una = 0;
kcp->snd_nxt = 0;
kcp->rcv_nxt = 0;
kcp->ts_recent = 0;
kcp->ts_lastack = 0;
kcp->ts_probe = 0;
kcp->probe_wait = 0;
kcp->snd_wnd = IKCP_WND_SND;
kcp->rcv_wnd = IKCP_WND_RCV;
kcp->rmt_wnd = IKCP_WND_RCV;
kcp->cwnd = 0;
kcp->incr = 0;
kcp->probe = 0;
kcp->mtu = IKCP_MTU_DEF;
kcp->mss = kcp->mtu - IKCP_OVERHEAD;
kcp->stream = 0;
kcp->buffer = (char*)ikcp_malloc((kcp->mtu + IKCP_OVERHEAD) * 3);
if (kcp->buffer == NULL) {
ikcp_free(kcp);
return NULL;
}
iqueue_init(&kcp->snd_queue);
iqueue_init(&kcp->rcv_queue);
iqueue_init(&kcp->snd_buf);
iqueue_init(&kcp->rcv_buf);
kcp->nrcv_buf = 0;
kcp->nsnd_buf = 0;
kcp->nrcv_que = 0;
kcp->nsnd_que = 0;
kcp->state = 0;
kcp->acklist = NULL;
kcp->ackblock = 0;
kcp->ackcount = 0;
kcp->rx_srtt = 0;
kcp->rx_rttval = 0;
kcp->rx_rto = IKCP_RTO_DEF;
kcp->rx_minrto = IKCP_RTO_MIN;
kcp->current = 0;
kcp->interval = IKCP_INTERVAL;
kcp->ts_flush = IKCP_INTERVAL;
kcp->nodelay = 0;
kcp->updated = 0;
kcp->logmask = 0;
kcp->ssthresh = IKCP_THRESH_INIT;
kcp->fastresend = 0;
kcp->fastlimit = IKCP_FASTACK_LIMIT;
kcp->nocwnd = 0;
kcp->xmit = 0;
kcp->dead_link = IKCP_DEADLINK;
kcp->output = NULL;
kcp->writelog = NULL;
return kcp;
}
//---------------------------------------------------------------------
// release a new kcpcb
//---------------------------------------------------------------------
void ikcp_release(ikcpcb *kcp)
{
assert(kcp);
if (kcp) {
IKCPSEG *seg;
while (!iqueue_is_empty(&kcp->snd_buf)) {
seg = iqueue_entry(kcp->snd_buf.next, IKCPSEG, node);
iqueue_del(&seg->node);
ikcp_segment_delete(kcp, seg);
}
while (!iqueue_is_empty(&kcp->rcv_buf)) {
seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node);
iqueue_del(&seg->node);
ikcp_segment_delete(kcp, seg);
}
while (!iqueue_is_empty(&kcp->snd_queue)) {
seg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node);
iqueue_del(&seg->node);
ikcp_segment_delete(kcp, seg);
}
while (!iqueue_is_empty(&kcp->rcv_queue)) {
seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node);
iqueue_del(&seg->node);
ikcp_segment_delete(kcp, seg);
}
if (kcp->buffer) {
ikcp_free(kcp->buffer);
}
if (kcp->acklist) {
ikcp_free(kcp->acklist);
}
kcp->nrcv_buf = 0;
kcp->nsnd_buf = 0;
kcp->nrcv_que = 0;
kcp->nsnd_que = 0;
kcp->ackcount = 0;
kcp->buffer = NULL;
kcp->acklist = NULL;
ikcp_free(kcp);
}
}
//---------------------------------------------------------------------
// set output callback, which will be invoked by kcp
//---------------------------------------------------------------------
void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len,
ikcpcb *kcp, void *user))
{
kcp->output = output;
}
//---------------------------------------------------------------------
// user/upper level recv: returns size, returns below zero for EAGAIN
//---------------------------------------------------------------------
int ikcp_recv(ikcpcb *kcp, char *buffer, int len)
{
struct IQUEUEHEAD *p;
int ispeek = (len < 0)? 1 : 0;
int peeksize;
int recover = 0;
IKCPSEG *seg;
assert(kcp);
if (iqueue_is_empty(&kcp->rcv_queue))
return -1;
if (len < 0) len = -len;
peeksize = ikcp_peeksize(kcp);
if (peeksize < 0)
return -2;
if (peeksize > len)
return -3;
if (kcp->nrcv_que >= kcp->rcv_wnd)
recover = 1;
// merge fragment
for (len = 0, p = kcp->rcv_queue.next; p != &kcp->rcv_queue; ) {
int fragment;
seg = iqueue_entry(p, IKCPSEG, node);
p = p->next;
if (buffer) {
memcpy(buffer, seg->data, seg->len);
buffer += seg->len;
}
len += seg->len;
fragment = seg->frg;
if (ikcp_canlog(kcp, IKCP_LOG_RECV)) {
ikcp_log(kcp, IKCP_LOG_RECV, "recv sn=%lu", (unsigned long)seg->sn);
}
if (ispeek == 0) {
iqueue_del(&seg->node);
ikcp_segment_delete(kcp, seg);
kcp->nrcv_que--;
}
if (fragment == 0)
break;
}
assert(len == peeksize);
// move available data from rcv_buf -> rcv_queue
while (! iqueue_is_empty(&kcp->rcv_buf)) {
seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node);
if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) {
iqueue_del(&seg->node);
kcp->nrcv_buf--;
iqueue_add_tail(&seg->node, &kcp->rcv_queue);
kcp->nrcv_que++;
kcp->rcv_nxt++;
} else {
break;
}
}
// fast recover
if (kcp->nrcv_que < kcp->rcv_wnd && recover) {
// ready to send back IKCP_CMD_WINS in ikcp_flush
// tell remote my window size
kcp->probe |= IKCP_ASK_TELL;
}
return len;
}
//---------------------------------------------------------------------
// peek data size
//---------------------------------------------------------------------
int ikcp_peeksize(const ikcpcb *kcp)
{
struct IQUEUEHEAD *p;
IKCPSEG *seg;
int length = 0;
assert(kcp);
if (iqueue_is_empty(&kcp->rcv_queue)) return -1;
seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node);
if (seg->frg == 0) return seg->len;
if (kcp->nrcv_que < seg->frg + 1) return -1;
for (p = kcp->rcv_queue.next; p != &kcp->rcv_queue; p = p->next) {
seg = iqueue_entry(p, IKCPSEG, node);
length += seg->len;
if (seg->frg == 0) break;
}
return length;
}
//---------------------------------------------------------------------
// user/upper level send, returns below zero for error
//---------------------------------------------------------------------
int ikcp_send(ikcpcb *kcp, const char *buffer, int len)
{
IKCPSEG *seg;
int count, i;
assert(kcp->mss > 0);
if (len < 0) return -1;
// append to previous segment in streaming mode (if possible)
if (kcp->stream != 0) {
if (!iqueue_is_empty(&kcp->snd_queue)) {
IKCPSEG *old = iqueue_entry(kcp->snd_queue.prev, IKCPSEG, node);
if (old->len < kcp->mss) {
int capacity = kcp->mss - old->len;
int extend = (len < capacity)? len : capacity;
seg = ikcp_segment_new(kcp, old->len + extend);
assert(seg);
if (seg == NULL) {
return -2;
}
iqueue_add_tail(&seg->node, &kcp->snd_queue);
memcpy(seg->data, old->data, old->len);
if (buffer) {
memcpy(seg->data + old->len, buffer, extend);
buffer += extend;
}
seg->len = old->len + extend;
seg->frg = 0;
len -= extend;
iqueue_del_init(&old->node);
ikcp_segment_delete(kcp, old);
}
}
if (len <= 0) {
return 0;
}
}
if (len <= (int)kcp->mss) count = 1;
else count = (len + kcp->mss - 1) / kcp->mss;
if (count >= (int)IKCP_WND_RCV) return -2;
if (count == 0) count = 1;
// fragment
for (i = 0; i < count; i++) {
int size = len > (int)kcp->mss ? (int)kcp->mss : len;
seg = ikcp_segment_new(kcp, size);
assert(seg);
if (seg == NULL) {
return -2;
}
if (buffer && len > 0) {
memcpy(seg->data, buffer, size);
}
seg->len = size;
seg->frg = (kcp->stream == 0)? (count - i - 1) : 0;
iqueue_init(&seg->node);
iqueue_add_tail(&seg->node, &kcp->snd_queue);
kcp->nsnd_que++;
if (buffer) {
buffer += size;
}
len -= size;
}
return 0;
}
//---------------------------------------------------------------------
// parse ack
//---------------------------------------------------------------------
static void ikcp_update_ack(ikcpcb *kcp, IINT32 rtt)
{
IINT32 rto = 0;
if (kcp->rx_srtt == 0) {
kcp->rx_srtt = rtt;
kcp->rx_rttval = rtt / 2;
} else {
long delta = rtt - kcp->rx_srtt;
if (delta < 0) delta = -delta;
kcp->rx_rttval = (3 * kcp->rx_rttval + delta) / 4;
kcp->rx_srtt = (7 * kcp->rx_srtt + rtt) / 8;
if (kcp->rx_srtt < 1) kcp->rx_srtt = 1;
}
rto = kcp->rx_srtt + _imax_(kcp->interval, 4 * kcp->rx_rttval);
kcp->rx_rto = _ibound_(kcp->rx_minrto, rto, IKCP_RTO_MAX);
}
static void ikcp_shrink_buf(ikcpcb *kcp)
{
struct IQUEUEHEAD *p = kcp->snd_buf.next;
if (p != &kcp->snd_buf) {
IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
kcp->snd_una = seg->sn;
} else {
kcp->snd_una = kcp->snd_nxt;
}
}
static void ikcp_parse_ack(ikcpcb *kcp, IUINT32 sn)
{
struct IQUEUEHEAD *p, *next;
if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0)
return;
for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) {
IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
next = p->next;
if (sn == seg->sn) {
iqueue_del(p);
ikcp_segment_delete(kcp, seg);
kcp->nsnd_buf--;
break;
}
if (_itimediff(sn, seg->sn) < 0) {
break;
}
}
}
static void ikcp_parse_una(ikcpcb *kcp, IUINT32 una)
{
struct IQUEUEHEAD *p, *next;
for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) {
IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
next = p->next;
if (_itimediff(una, seg->sn) > 0) {
iqueue_del(p);
ikcp_segment_delete(kcp, seg);
kcp->nsnd_buf--;
} else {
break;
}
}
}
static void ikcp_parse_fastack(ikcpcb *kcp, IUINT32 sn, IUINT32 ts)
{
struct IQUEUEHEAD *p, *next;
if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0)
return;
for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) {
IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
next = p->next;
if (_itimediff(sn, seg->sn) < 0) {
break;
}
else if (sn != seg->sn) {
#ifndef IKCP_FASTACK_CONSERVE
seg->fastack++;
#else
if (_itimediff(ts, seg->ts) >= 0)
seg->fastack++;
#endif
}
}
}
//---------------------------------------------------------------------
// ack append
//---------------------------------------------------------------------
static void ikcp_ack_push(ikcpcb *kcp, IUINT32 sn, IUINT32 ts)
{
size_t newsize = kcp->ackcount + 1;
IUINT32 *ptr;
if (newsize > kcp->ackblock) {
IUINT32 *acklist;
size_t newblock;
for (newblock = 8; newblock < newsize; newblock <<= 1);
acklist = (IUINT32*)ikcp_malloc(newblock * sizeof(IUINT32) * 2);
if (acklist == NULL) {
assert(acklist != NULL);
abort();
}
if (kcp->acklist != NULL) {
size_t x;
for (x = 0; x < kcp->ackcount; x++) {
acklist[x * 2 + 0] = kcp->acklist[x * 2 + 0];
acklist[x * 2 + 1] = kcp->acklist[x * 2 + 1];
}
ikcp_free(kcp->acklist);
}
kcp->acklist = acklist;
kcp->ackblock = newblock;
}
ptr = &kcp->acklist[kcp->ackcount * 2];
ptr[0] = sn;
ptr[1] = ts;
kcp->ackcount++;
}
static void ikcp_ack_get(const ikcpcb *kcp, int p, IUINT32 *sn, IUINT32 *ts)
{
if (sn) sn[0] = kcp->acklist[p * 2 + 0];
if (ts) ts[0] = kcp->acklist[p * 2 + 1];
}
//---------------------------------------------------------------------
// parse data
//---------------------------------------------------------------------
void ikcp_parse_data(ikcpcb *kcp, IKCPSEG *newseg)
{
struct IQUEUEHEAD *p, *prev;
IUINT32 sn = newseg->sn;
int repeat = 0;
if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) >= 0 ||
_itimediff(sn, kcp->rcv_nxt) < 0) {
ikcp_segment_delete(kcp, newseg);
return;
}
for (p = kcp->rcv_buf.prev; p != &kcp->rcv_buf; p = prev) {
IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
prev = p->prev;
if (seg->sn == sn) {
repeat = 1;
break;
}
if (_itimediff(sn, seg->sn) > 0) {
break;
}
}
if (repeat == 0) {
iqueue_init(&newseg->node);
iqueue_add(&newseg->node, p);
kcp->nrcv_buf++;
} else {
ikcp_segment_delete(kcp, newseg);
}
#if 0
ikcp_qprint("rcvbuf", &kcp->rcv_buf);
printf("rcv_nxt=%lu\n", kcp->rcv_nxt);
#endif
// move available data from rcv_buf -> rcv_queue
while (! iqueue_is_empty(&kcp->rcv_buf)) {
IKCPSEG *seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node);
if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) {
iqueue_del(&seg->node);
kcp->nrcv_buf--;
iqueue_add_tail(&seg->node, &kcp->rcv_queue);
kcp->nrcv_que++;
kcp->rcv_nxt++;
} else {
break;
}
}
#if 0
ikcp_qprint("queue", &kcp->rcv_queue);
printf("rcv_nxt=%lu\n", kcp->rcv_nxt);
#endif
#if 1
// printf("snd(buf=%d, queue=%d)\n", kcp->nsnd_buf, kcp->nsnd_que);
// printf("rcv(buf=%d, queue=%d)\n", kcp->nrcv_buf, kcp->nrcv_que);
#endif
}
//---------------------------------------------------------------------
// input data
//---------------------------------------------------------------------
int ikcp_input(ikcpcb *kcp, const char *data, long size)
{
IUINT32 prev_una = kcp->snd_una;
IUINT32 maxack = 0, latest_ts = 0;
int flag = 0;
if (ikcp_canlog(kcp, IKCP_LOG_INPUT)) {
ikcp_log(kcp, IKCP_LOG_INPUT, "[RI] %d bytes", (int)size);
}
if (data == NULL || (int)size < (int)IKCP_OVERHEAD) return -1;
while (1) {
IUINT32 ts, sn, len, una, conv;
IUINT16 wnd;
IUINT8 cmd, frg;
IKCPSEG *seg;
if (size < (int)IKCP_OVERHEAD) break;
data = ikcp_decode32u(data, &conv);
if (conv != kcp->conv) return -1;
data = ikcp_decode8u(data, &cmd);
data = ikcp_decode8u(data, &frg);
data = ikcp_decode16u(data, &wnd);
data = ikcp_decode32u(data, &ts);
data = ikcp_decode32u(data, &sn);
data = ikcp_decode32u(data, &una);
data = ikcp_decode32u(data, &len);
size -= IKCP_OVERHEAD;
if ((long)size < (long)len || (int)len < 0) return -2;
if (cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK &&
cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS)
return -3;
kcp->rmt_wnd = wnd;
ikcp_parse_una(kcp, una);
ikcp_shrink_buf(kcp);
if (cmd == IKCP_CMD_ACK) {
if (_itimediff(kcp->current, ts) >= 0) {
ikcp_update_ack(kcp, _itimediff(kcp->current, ts));
}
ikcp_parse_ack(kcp, sn);
ikcp_shrink_buf(kcp);
if (flag == 0) {
flag = 1;
maxack = sn;
latest_ts = ts;
} else {
if (_itimediff(sn, maxack) > 0) {
#ifndef IKCP_FASTACK_CONSERVE
maxack = sn;
latest_ts = ts;
#else
if (_itimediff(ts, latest_ts) > 0) {
maxack = sn;
latest_ts = ts;
}
#endif
}
}
if (ikcp_canlog(kcp, IKCP_LOG_IN_ACK)) {
ikcp_log(kcp, IKCP_LOG_IN_ACK,
"input ack: sn=%lu rtt=%ld rto=%ld", (unsigned long)sn,
(long)_itimediff(kcp->current, ts),
(long)kcp->rx_rto);
}
}
else if (cmd == IKCP_CMD_PUSH) {
if (ikcp_canlog(kcp, IKCP_LOG_IN_DATA)) {
ikcp_log(kcp, IKCP_LOG_IN_DATA,
"input psh: sn=%lu ts=%lu", (unsigned long)sn, (unsigned long)ts);
}
if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) < 0) {
ikcp_ack_push(kcp, sn, ts);
if (_itimediff(sn, kcp->rcv_nxt) >= 0) {
seg = ikcp_segment_new(kcp, len);
seg->conv = conv;
seg->cmd = cmd;
seg->frg = frg;
seg->wnd = wnd;
seg->ts = ts;
seg->sn = sn;
seg->una = una;
seg->len = len;
if (len > 0) {
memcpy(seg->data, data, len);
}
ikcp_parse_data(kcp, seg);
}
}
}
else if (cmd == IKCP_CMD_WASK) {
// ready to send back IKCP_CMD_WINS in ikcp_flush
// tell remote my window size
kcp->probe |= IKCP_ASK_TELL;
if (ikcp_canlog(kcp, IKCP_LOG_IN_PROBE)) {
ikcp_log(kcp, IKCP_LOG_IN_PROBE, "input probe");
}
}
else if (cmd == IKCP_CMD_WINS) {
// do nothing
if (ikcp_canlog(kcp, IKCP_LOG_IN_WINS)) {
ikcp_log(kcp, IKCP_LOG_IN_WINS,
"input wins: %lu", (unsigned long)(wnd));
}
}
else {
return -3;
}
data += len;
size -= len;
}
if (flag != 0) {
ikcp_parse_fastack(kcp, maxack, latest_ts);
}
if (_itimediff(kcp->snd_una, prev_una) > 0) {
if (kcp->cwnd < kcp->rmt_wnd) {
IUINT32 mss = kcp->mss;
if (kcp->cwnd < kcp->ssthresh) {
kcp->cwnd++;
kcp->incr += mss;
} else {
if (kcp->incr < mss) kcp->incr = mss;
kcp->incr += (mss * mss) / kcp->incr + (mss / 16);
if ((kcp->cwnd + 1) * mss <= kcp->incr) {
#if 1
kcp->cwnd = (kcp->incr + mss - 1) / ((mss > 0)? mss : 1);
#else
kcp->cwnd++;
#endif
}
}
if (kcp->cwnd > kcp->rmt_wnd) {
kcp->cwnd = kcp->rmt_wnd;
kcp->incr = kcp->rmt_wnd * mss;
}
}
}
return 0;
}
//---------------------------------------------------------------------
// ikcp_encode_seg
//---------------------------------------------------------------------
static char *ikcp_encode_seg(char *ptr, const IKCPSEG *seg)
{
ptr = ikcp_encode32u(ptr, seg->conv);
ptr = ikcp_encode8u(ptr, (IUINT8)seg->cmd);
ptr = ikcp_encode8u(ptr, (IUINT8)seg->frg);
ptr = ikcp_encode16u(ptr, (IUINT16)seg->wnd);
ptr = ikcp_encode32u(ptr, seg->ts);
ptr = ikcp_encode32u(ptr, seg->sn);
ptr = ikcp_encode32u(ptr, seg->una);
ptr = ikcp_encode32u(ptr, seg->len);
return ptr;
}
static int ikcp_wnd_unused(const ikcpcb *kcp)
{
if (kcp->nrcv_que < kcp->rcv_wnd) {
return kcp->rcv_wnd - kcp->nrcv_que;
}
return 0;
}
//---------------------------------------------------------------------
// ikcp_flush
//---------------------------------------------------------------------
void ikcp_flush(ikcpcb *kcp)
{
IUINT32 current = kcp->current;
char *buffer = kcp->buffer;
char *ptr = buffer;
int count, size, i;
IUINT32 resent, cwnd;
IUINT32 rtomin;
struct IQUEUEHEAD *p;
int change = 0;
int lost = 0;
IKCPSEG seg;
// 'ikcp_update' haven't been called.
if (kcp->updated == 0) return;
seg.conv = kcp->conv;
seg.cmd = IKCP_CMD_ACK;
seg.frg = 0;
seg.wnd = ikcp_wnd_unused(kcp);
seg.una = kcp->rcv_nxt;
seg.len = 0;
seg.sn = 0;
seg.ts = 0;
// flush acknowledges
count = kcp->ackcount;
for (i = 0; i < count; i++) {
size = (int)(ptr - buffer);
if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) {
ikcp_output(kcp, buffer, size);
ptr = buffer;
}
ikcp_ack_get(kcp, i, &seg.sn, &seg.ts);
ptr = ikcp_encode_seg(ptr, &seg);
}
kcp->ackcount = 0;
// probe window size (if remote window size equals zero)
if (kcp->rmt_wnd == 0) {
if (kcp->probe_wait == 0) {
kcp->probe_wait = IKCP_PROBE_INIT;
kcp->ts_probe = kcp->current + kcp->probe_wait;
}
else {
if (_itimediff(kcp->current, kcp->ts_probe) >= 0) {
if (kcp->probe_wait < IKCP_PROBE_INIT)
kcp->probe_wait = IKCP_PROBE_INIT;
kcp->probe_wait += kcp->probe_wait / 2;
if (kcp->probe_wait > IKCP_PROBE_LIMIT)
kcp->probe_wait = IKCP_PROBE_LIMIT;
kcp->ts_probe = kcp->current + kcp->probe_wait;
kcp->probe |= IKCP_ASK_SEND;
}
}
} else {
kcp->ts_probe = 0;
kcp->probe_wait = 0;
}
// flush window probing commands
if (kcp->probe & IKCP_ASK_SEND) {
seg.cmd = IKCP_CMD_WASK;
size = (int)(ptr - buffer);
if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) {
ikcp_output(kcp, buffer, size);
ptr = buffer;
}
ptr = ikcp_encode_seg(ptr, &seg);
}
// flush window probing commands
if (kcp->probe & IKCP_ASK_TELL) {
seg.cmd = IKCP_CMD_WINS;
size = (int)(ptr - buffer);
if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) {
ikcp_output(kcp, buffer, size);
ptr = buffer;
}
ptr = ikcp_encode_seg(ptr, &seg);
}
kcp->probe = 0;
// calculate window size
cwnd = _imin_(kcp->snd_wnd, kcp->rmt_wnd);
if (kcp->nocwnd == 0) cwnd = _imin_(kcp->cwnd, cwnd);
// move data from snd_queue to snd_buf
while (_itimediff(kcp->snd_nxt, kcp->snd_una + cwnd) < 0) {
IKCPSEG *newseg;
if (iqueue_is_empty(&kcp->snd_queue)) break;
newseg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node);
iqueue_del(&newseg->node);
iqueue_add_tail(&newseg->node, &kcp->snd_buf);
kcp->nsnd_que--;
kcp->nsnd_buf++;
newseg->conv = kcp->conv;
newseg->cmd = IKCP_CMD_PUSH;
newseg->wnd = seg.wnd;
newseg->ts = current;
newseg->sn = kcp->snd_nxt++;
newseg->una = kcp->rcv_nxt;
newseg->resendts = current;
newseg->rto = kcp->rx_rto;
newseg->fastack = 0;
newseg->xmit = 0;
}
// calculate resent
resent = (kcp->fastresend > 0)? (IUINT32)kcp->fastresend : 0xffffffff;
rtomin = (kcp->nodelay == 0)? (kcp->rx_rto >> 3) : 0;
// flush data segments
for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) {
IKCPSEG *segment = iqueue_entry(p, IKCPSEG, node);
int needsend = 0;
if (segment->xmit == 0) {
needsend = 1;
segment->xmit++;
segment->rto = kcp->rx_rto;
segment->resendts = current + segment->rto + rtomin;
}
else if (_itimediff(current, segment->resendts) >= 0) {
needsend = 1;
segment->xmit++;
kcp->xmit++;
if (kcp->nodelay == 0) {
segment->rto += _imax_(segment->rto, (IUINT32)kcp->rx_rto);
} else {
IINT32 step = (kcp->nodelay < 2)?
((IINT32)(segment->rto)) : kcp->rx_rto;
segment->rto += step / 2;
}
segment->resendts = current + segment->rto;
lost = 1;
}
else if (segment->fastack >= resent) {
if ((int)segment->xmit <= kcp->fastlimit ||
kcp->fastlimit <= 0) {
needsend = 1;
segment->xmit++;
segment->fastack = 0;
segment->resendts = current + segment->rto;
change++;
}
}
if (needsend) {
int need;
segment->ts = current;
segment->wnd = seg.wnd;
segment->una = kcp->rcv_nxt;
size = (int)(ptr - buffer);
need = IKCP_OVERHEAD + segment->len;
if (size + need > (int)kcp->mtu) {
ikcp_output(kcp, buffer, size);
ptr = buffer;
}
ptr = ikcp_encode_seg(ptr, segment);
if (segment->len > 0) {
memcpy(ptr, segment->data, segment->len);
ptr += segment->len;
}
if (segment->xmit >= kcp->dead_link) {
kcp->state = (IUINT32)-1;
}
}
}
// flash remain segments
size = (int)(ptr - buffer);
if (size > 0) {
ikcp_output(kcp, buffer, size);
}
// update ssthresh
if (change) {
IUINT32 inflight = kcp->snd_nxt - kcp->snd_una;
kcp->ssthresh = inflight / 2;
if (kcp->ssthresh < IKCP_THRESH_MIN)
kcp->ssthresh = IKCP_THRESH_MIN;
kcp->cwnd = kcp->ssthresh + resent;
kcp->incr = kcp->cwnd * kcp->mss;
}
if (lost) {
kcp->ssthresh = cwnd / 2;
if (kcp->ssthresh < IKCP_THRESH_MIN)
kcp->ssthresh = IKCP_THRESH_MIN;
kcp->cwnd = 1;
kcp->incr = kcp->mss;
}
if (kcp->cwnd < 1) {
kcp->cwnd = 1;
kcp->incr = kcp->mss;
}
}
//---------------------------------------------------------------------
// update state (call it repeatedly, every 10ms-100ms), or you can ask
// ikcp_check when to call it again (without ikcp_input/_send calling).
// 'current' - current timestamp in millisec.
//---------------------------------------------------------------------
void ikcp_update(ikcpcb *kcp, IUINT32 current)
{
IINT32 slap;
kcp->current = current;
if (kcp->updated == 0) {
kcp->updated = 1;
kcp->ts_flush = kcp->current;
}
slap = _itimediff(kcp->current, kcp->ts_flush);
if (slap >= 10000 || slap < -10000) {
kcp->ts_flush = kcp->current;
slap = 0;
}
if (slap >= 0) {
kcp->ts_flush += kcp->interval;
if (_itimediff(kcp->current, kcp->ts_flush) >= 0) {
kcp->ts_flush = kcp->current + kcp->interval;
}
ikcp_flush(kcp);
}
}
//---------------------------------------------------------------------
// Determine when should you invoke ikcp_update:
// returns when you should invoke ikcp_update in millisec, if there
// is no ikcp_input/_send calling. you can call ikcp_update in that
// time, instead of call update repeatly.
// Important to reduce unnacessary ikcp_update invoking. use it to
// schedule ikcp_update (eg. implementing an epoll-like mechanism,
// or optimize ikcp_update when handling massive kcp connections)
//---------------------------------------------------------------------
IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current)
{
IUINT32 ts_flush = kcp->ts_flush;
IINT32 tm_flush = 0x7fffffff;
IINT32 tm_packet = 0x7fffffff;
IUINT32 minimal = 0;
struct IQUEUEHEAD *p;
if (kcp->updated == 0) {
return current;
}
if (_itimediff(current, ts_flush) >= 10000 ||
_itimediff(current, ts_flush) < -10000) {
ts_flush = current;
}
if (_itimediff(current, ts_flush) >= 0) {
return current;
}
tm_flush = _itimediff(ts_flush, current);
for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) {
const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node);
IINT32 diff = _itimediff(seg->resendts, current);
if (diff <= 0) {
return current;
}
if (diff < tm_packet) tm_packet = diff;
}
minimal = (IUINT32)(tm_packet < tm_flush ? tm_packet : tm_flush);
if (minimal >= kcp->interval) minimal = kcp->interval;
return current + minimal;
}
int ikcp_setmtu(ikcpcb *kcp, int mtu)
{
char *buffer;
if (mtu < 50 || mtu < (int)IKCP_OVERHEAD)
return -1;
buffer = (char*)ikcp_malloc((mtu + IKCP_OVERHEAD) * 3);
if (buffer == NULL)
return -2;
kcp->mtu = mtu;
kcp->mss = kcp->mtu - IKCP_OVERHEAD;
ikcp_free(kcp->buffer);
kcp->buffer = buffer;
return 0;
}
int ikcp_interval(ikcpcb *kcp, int interval)
{
if (interval > 5000) interval = 5000;
else if (interval < 10) interval = 10;
kcp->interval = interval;
return 0;
}
int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc)
{
if (nodelay >= 0) {
kcp->nodelay = nodelay;
if (nodelay) {
kcp->rx_minrto = IKCP_RTO_NDL;
}
else {
kcp->rx_minrto = IKCP_RTO_MIN;
}
}
if (interval >= 0) {
if (interval > 5000) interval = 5000;
else if (interval < 10) interval = 10;
kcp->interval = interval;
}
if (resend >= 0) {
kcp->fastresend = resend;
}
if (nc >= 0) {
kcp->nocwnd = nc;
}
return 0;
}
int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd)
{
if (kcp) {
if (sndwnd > 0) {
kcp->snd_wnd = sndwnd;
}
if (rcvwnd > 0) { // must >= max fragment size
kcp->rcv_wnd = _imax_(rcvwnd, IKCP_WND_RCV);
}
}
return 0;
}
int ikcp_waitsnd(const ikcpcb *kcp)
{
return kcp->nsnd_buf + kcp->nsnd_que;
}
// read conv
IUINT32 ikcp_getconv(const void *ptr)
{
IUINT32 conv;
ikcp_decode32u((const char*)ptr, &conv);
return conv;
}
}
//#ifdef __cplusplus
//}
//#endif
}
#endif
<file_sep>#ifndef BHO_ENDIAN_DETAIL_ORDER_HPP_INCLUDED
#define BHO_ENDIAN_DETAIL_ORDER_HPP_INCLUDED
// Copyright 2019 <NAME>
//
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/core/scoped_enum.hpp>
#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define BHO_ENDIAN_NATIVE_ORDER_INITIALIZER little
#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
# define BHO_ENDIAN_NATIVE_ORDER_INITIALIZER big
#elif defined(__BYTE_ORDER__) && defined(__ORDER_PDP_ENDIAN__) && __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__
# error The Boost.Endian library does not support platforms with PDP endianness.
#elif defined(__LITTLE_ENDIAN__)
# define BHO_ENDIAN_NATIVE_ORDER_INITIALIZER little
#elif defined(__BIG_ENDIAN__)
# define BHO_ENDIAN_NATIVE_ORDER_INITIALIZER big
#elif defined(_MSC_VER) || defined(__i386__) || defined(__x86_64__)
# define BHO_ENDIAN_NATIVE_ORDER_INITIALIZER little
#else
# error The Boost.Endian library could not determine the endianness of this platform.
#endif
namespace bho
{
namespace endian
{
BHO_SCOPED_ENUM_START(order)
{
big,
little,
native = BHO_ENDIAN_NATIVE_ORDER_INITIALIZER
}; BHO_SCOPED_ENUM_END
} // namespace endian
} // namespace bho
#undef BHO_ENDIAN_NATIVE_ORDER_INITIALIZER
#endif // BHO_ENDIAN_DETAIL_ORDER_HPP_INCLUDED
<file_sep># 关于asio2项目example目录中的几个tcp示例的说明
在 [/asio2/example/tcp/](https://github.com/zhllxt/asio2/tree/master/example/tcp) 目录里有以下这几个关于tcp的示例代码:
tcp_client_character,tcp_client_custom,tcp_client_datagram,tcp_client_general
这几个示例是演示怎么做tcp拆包的,下面详细说明一下(服务端相对应的示例是一样的意思,不再描述):
至于为什么tcp数据要做拆包,不了解的可以网络详细搜索一下,不管你是自己手撸网络代码还是使用第三方开源库,都得处理tcp的拆包问题,asio2只是帮你处理了一些步骤,简化了使用过程。
## tcp_client_character
```cpp
// 第3个参数传\n 就是按字符\n进行拆包
//client.start(host, port, '\n');
// 第3个参数传\r\n 就是按字符串\r\n进行拆包
client.start(host, port, "\r\n");
```
这个示例演示的是用**单个字符或字符串**来做tcp拆包的,此时数据边界就是单个字符或字符串;
举例:比如按\n来拆包,
client发送 123\n45678\nABCDEFG\n
假定server一次性接收完上面的所有数据,也就是server一次性收到了 123\n45678\nABCDEFG\n ,那么接收数据的回调函数是怎么触发的呢?是触发1次还是触发3次?答案:3次
```cpp
bind_recv([&](std::string_view data)
{
// 第1次触发时 data=123\n
// 第2次触发时 data=45678\n
// 第3次触发时 data=ABCDEFG\n
// 也就是说不管收到的是什么数据,框架一定会检测\n这个字符,只有检测到\n这个字符了,
// 框架才会把缓冲区中,从缓冲区开头到\n这个位置的,这一段数据在这里通知你。
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
client.async_send(data);
});
```
如果数据安全性要求不高,就用\n或\r\n来做为数据边界就可以了,不管是组包还是拆包,都是很方便的。
当然,示例这里用的\n或\r\n并不是说只能用\n或\r\n,你用任何其它的字符或字符串来做数据边界都是可以的,只是你在发送数据组包的时候要注意,你的数据内容本身里面不能包含了用于做数据边界的字符,否则对方来拆包处理的时候就会有问题。这里用\n或\r\n来做示例是因为\n或\r\n比较通用,我用过一些厂家的产品就是用\r\n来做数据边界的,主要是处理起来很方便。
下面说另一种情况:如果client只发送了 123\n45678\nABCD 也就是后面有一部分数据没有发,那接收数据的回调函数是怎么触发的?答案:触发2次
```cpp
bind_recv([&](std::string_view data)
{
// 第1次触发时 data=123\n
// 第2次触发时 data=45678\n
// 第2次触发完之后,接收缓冲区里现在的数据是ABCD 框架查找的时候找不到\n,所以是
// 不会把ABCD拿来通知你的,如果之后client又发送了EFG\n也就是发送了后面那部分的数
// 据,那么现在接收缓冲区里的数据就是ABCDEFG\n了,此时框架检测到了\n,于是这个
// bind_recv的回调函数就会第3次被触发,此时data=ABCDEFG\n
// 如果是按字符串\r\n拆包,则一定要收到\r\n才会触发回调,收到\r不行,收到\n也不行。
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
client.async_send(data);
});
```
以上描述了一些基本的情况,更多复杂的情况没有描述,总之道理都一样。
后面的“custom,datagram”和这个道理都是类似的,只是数据格式不一样而已。
## tcp_client_custom
这个示例演示的是,自定义协议的拆包。
上面用\n或\r\n来做数据边界是比较简单的方法,通常用户会有一套复杂的自定义协议,比如“数据头+数据类型+数据长度+数据内容+校验”这种,此时对tcp数据做拆包就是个很麻烦的过程。
在asio2框架里是怎么使用的,如下:
#### 首先定义一个类,每当框架接收到数据时,就会调用这个类进行拆包
```cpp
// 这里用一个较简单的自定义协议来举例,没有用上面所说的“数据头+数据类型+数据长度+数据内容+校验”这种
// 因为它太麻烦了,但是原理是一样的,不管多复杂的数据格式,都可以像这样来处理。
// 第1个字节 数据头 : # 这里数据头是#号
// 第2个字节 数据长度 : 就是接下来的内容的长度
// 第3个字节往后 数据内容 : 内容的长度是可变的
class match_role
{
public:
explicit match_role(char c) : c_(c) {}
template <typename Iterator>
std::pair<Iterator, bool> operator()(Iterator begin, Iterator end) const
{
Iterator p = begin;
while (p != end)
{
// how to convert the Iterator to char*
[[maybe_unused]] const char * buf = &(*p);
// eg : How to close illegal clients
if (*p != c_)
return std::pair(begin, true); // head character is not #, return and kill the client
p++;
if (p == end) break;
int length = std::uint8_t(*p); // get content length
p++;
if (p == end) break;
if (end - p >= length)
return std::pair(p + length, true);
break;
}
return std::pair(begin, false);
}
private:
char c_;
};
```
```cpp
// 然后在启动时将刚才定义的类传到start函数里。
server.start(host, port, match_role('#'));
```
关于自定义协议的拆包,就不再过多描述了,这里有一篇更详细的讲解原理的文章:[asio做tcp的自动拆包时,asio的match condition如何使用的详细说明](https://blog.csdn.net/zhllxt/article/details/127670983)
## tcp_client_datagram
大家在使用websocket时,有没有注意到,每次触发你的数据回调时,都是一份完整的数据,你收到的数据不会是半包或一包半这样的情况,使用websocket后,你不需要再做数据拆包的工作了,websocket框架已经帮你做过了,那websocket协议是怎么实现的呢?
实际上websocket是在数据开始位置添加了一个数据头,这个数据头表示接下来的数据内容的长度(具体协议比这要复杂),于是收到数据时就可以根据数据头里的长度来判断出是否接收完整了。
asio2的tcp_datagram也用了相同的原理:每当你发送数据时,asio2这个框架就会自动在你的数据开始的位置插入一个数据头,这个数据头是一个整数,用来表示你的真正的数据内容的长度,同样,在接收时,也会先解析这个数据头,解析出数据内容的长度,解析成功后会在bind_recv的回调函数里通知你,通知里面的数据不包含数据头,只有你的真正的数据内容。
```cpp
void on_recv(asio2::tcp_client& client, std::string_view data)
{
// data这个变量是你的数据内容,不包含asio2框架自动添加的数据头
printf("recv : %.*s\n", (int)data.size(), data.data());
client.async_send(data);
}
```
```cpp
// 像这样在启动时将start函数的第3个参数设置为asio2::use_dgram即表示使用此功能
client.start(host, port, asio2::use_dgram);
```
要注意:使用了asio2框架时,如果server端使用了use_dgram参数,那么client也要使用use_dgram参数,保证server和client要匹配(就是说要保证server和client的数据协议要一致),否则 asio2框架在解析数据时会出问题。
如果你的应用场景简单,服务端客户端程序都是你自己一个人写的,就可以使用这个功能,这样你可以不用关心复杂的协议解析处理了。
这个模式会保证收到的数据一定和对端发过来的数据完全一样。下面举例描述一下:
比如
client.async_send("123");
client.async_send("abc");
那么
server端的recv回调函数一定会触发2次,第1次的数据是123,第2次的数据是abc。
也就是说只要你调用了async_send或send,那么对端就一定会收到你调用async_send或send时的,那个完整的不多不少的数据,你调用了几次send,对方就会收到几次数据。
关于asio2的dgram模式下数据头的规则如下(和websocket的部分规则类似,稍微做了改变):
部分代码在这里:[/asio2/include/asio2/base/detail/condition_wrap.hpp - dgram_match_role](https://github.com/zhllxt/asio2/blob/master/include/asio2/base/detail/condition_wrap.hpp)
websocket协议在这里:[RFC 6455: The WebSocket Protocol](https://www.rfc-editor.org/rfc/rfc6455#section-5.2)
如果数据内容长度小于等于253个字节,则数据头是1个字节,数据头的值等于数据内容的长度,之后是数据内容。
如果数据内容长度大于等于254小于等于65535字节,则数据头是3个字节,第1个字节的值等于254,后2个字节表示内容的长度。
如果数据内容大于65535字节,则数据头是9个字节,第1个字节的值等于255,后8个字节表示内容的长度。
## tcp_client_general
```cpp
// 这个例子中start函数没有第3个参数
client.start(host, port);
```
这个示例的意思是,没有做任何数据拆包的工作,无论收到什么数据,都会触发recv回调函数。比如你一次性发送了数据 123abc\n 并且期望对方也一次性完整接收到123abc\n,但实际情况可能不是这样,有可能bind_recv回调函数会触发多次,比如第1次收到123,第2次收到abc\n 总之只要收到操作系统socket的数据了,就立即通知回调函数,不管数据是否完整,因此在这种情况下收到什么数据的情况都有可能。
所以此时你必须自己做数据拆包的工作。
如果你就想这样用,并且就想自己做拆包的话,那接下来说一下可以怎么做:
##### 首先是一个简单的示例
```cpp
// 首先定义一个buffer用来保存接收的数据
std::string buffer;
// 下面是recv回调函数触发时,对收到的数据进行拆包的过程
bind_recv([&](std::string_view data)
{
// 把收到的数据添加到你的buffer的尾部
// 就像上面的描述一样,这里可能会多次触发,比如
// 第1次触发时 data=123
// 第2次触发时 data=abc\n
buffer += data;
// 第1次触发后,buffer=123 此时buffer.find('\n')肯定找不到
// 第2次触发后,buffer=123abc\n 此时buffer.find('\n')就可以找到了
// 在一个循环中查找\n
// 这里只用\n来做个示意,其它的复杂协议的处理原理是一样的
// 必须循环查找,因为可能一次性收到多包完整的数据
while (true)
{
// 在buffer中查找\n
auto pos = buffer.find('\n');
// 如果找到了,说明缓冲区中已经有完整的数据了
if (pos != std::string::npos)
{
// 取出这包完整的数据
std::string msg = buffer.substr(0, pos + 1);
// 调用你的业务函数,把数据传过去
//do_work(msg);
// 处理完这包数据了,把你的buffer中的这段数据删掉
buffer.erase(0, pos + 1);
// 接下来会继续执行while循环,继续查找\n,如果找到了就会继续处理
}
else
{
// 如果找不到就跳出循环,等待下一次接收数据后再放到buffer中再找\n
break;
}
}
});
```
##### 深入一点的处理
上面的处理存在一个问题就是:再定义一个buffer,还需要把数据再往自己的这个buffer里面拷贝,这无形中增加了一些冗余的内存拷贝操作。
框架内部肯定已经有接收缓冲区了,收到的数据肯定也已经在缓冲区里了,那能不能不再自己去定义一个buffer了呢,直接去框架的缓冲区里面去操作数据呢?答案是可以的。
像这样做即可:
```cpp
// 第3个参数传入asio2::hook_buffer,这样就可以直接操作asio2框架内部的buffer了
client.start(host, port, asio2::hook_buffer);
```
```cpp
// 下面是recv回调函数触发时,对收到的数据进行拆包的过程
bind_recv([&](std::string_view data)
{
// 这次和前面不一样了
// 第1次触发时 data=123
// 第2次触发时 data=123abc\n
// 也就是说前面的没有使用hook_buffer的情况下,每次recv回调触发结束之后,asio2框架
// 就会清空他内部的缓冲区,而使用了hook_buffer以后,每次recv回调触发之后,asio2
// 框架不会清空他内部的缓冲区,而是把新收到的数据接着添加到缓冲区的尾部,此时处理
// 完数据之后,你就需要自己手动清空缓冲区,如果你不手动清空缓冲区的话,那么缓冲区
// 就会越来越大,表现出来的就是data这个string_view的长度会越来越长。
// data 这个变量实际上就是整个缓冲区的全部的数据视图。
// 仍然是在一个循环中查找\n
while (true)
{
// 在data中查找\n
auto pos = data.find('\n');
// 如果找到了,说明缓冲区中已经有完整的数据了
if (pos != std::string::npos)
{
// 取出这包完整的数据
std::string_view msg = data.substr(0, pos + 1);
// 调用你的业务函数,把数据传过去
//do_work(msg);
// 处理完这包数据了,我们要开始清理缓冲区了,否则缓冲区会越来越大
// 这次清理缓冲区的方式和前面的不一样了,因为这次要清理的是asio2
// 框架内部的缓冲区
// consume(pos + 1)的意思是把缓冲区前面的pos + 1个字节的内容清理
// 掉,清理掉之后,缓冲区后半部分的有效数据会移动到缓冲区的开头,
// 这个形为和vector类似,调用consume之后缓冲区中的数据长度就变小了
// 如果是server就是session_ptr->buffer().consume(pos + 1);
client.buffer().consume(pos + 1);
// 由于清理缓冲区之后,缓冲区的内容发生了变化,而data变量还是针对
// 以前的缓冲区的内容,所以要重新给data变量赋值,否则继续下一次
// while循环时在data中查找\n会出问题
// 如果是server就是session_ptr->buffer().data_view();
// 给string_view赋值是没有内存拷贝操作的,不用担心效率问题。
data = client.buffer().data_view();
// 接下来会继续执行while循环,继续查找\n,如果找到了就会继续处理
}
else
{
// 如果找不到就跳出循环,等待下一次接收数据后,asio2框架会把数据再
// 次添加到其内部缓冲区的尾部,然后这里的bind_recv被触发后,再次
// 查找 \n 即可
break;
}
}
});
```
各个功能的具体的代码可以参考项目中的example示例。
### 最后编辑于:2022-11-04
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at g<EMAIL> dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_ROLE_HPP
#define BHO_BEAST_ROLE_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
namespace bho {
namespace beast {
/** The role of local or remote peer.
Whether the endpoint is a client or server affects the
behavior of teardown.
The teardown behavior also depends on the type of the stream
being torn down.
The default implementation of teardown for regular
TCP/IP sockets is as follows:
@li In the client role, a TCP/IP shutdown is sent after
reading all remaining data on the connection.
@li In the server role, a TCP/IP shutdown is sent before
reading all remaining data on the connection.
When the next layer type is a `net::ssl::stream`,
the connection is closed by performing the SSL closing
handshake corresponding to the role type, client or server.
*/
enum class role_type
{
/// The stream is operating as a client.
client,
/// The stream is operating as a server.
server
};
} // beast
} // bho
#endif
<file_sep>// Copyright (c) 2017 Dynatrace
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// See http://www.boost.org for most recent version.
// Compiler setup for IBM z/OS XL C/C++ compiler.
// Oldest compiler version currently supported is 2.1 (V2R1)
#if !defined(__IBMCPP__) || !defined(__COMPILER_VER__) || __COMPILER_VER__ < 0x42010000
# error "Compiler not supported or configured - please reconfigure"
#endif
#if __COMPILER_VER__ > 0x42010000
# if defined(BHO_ASSERT_CONFIG)
# error "Unknown compiler version - please run the configure tests and report the results"
# endif
#endif
#define BHO_COMPILER "IBM z/OS XL C/C++ version " BHO_STRINGIZE(__COMPILER_VER__)
#define BHO_XLCPP_ZOS __COMPILER_VER__
// -------------------------------------
#include <features.h> // For __UU, __C99, __TR1, ...
#if !defined(__IBMCPP_DEFAULTED_AND_DELETED_FUNCTIONS)
# define BHO_NO_CXX11_DELETED_FUNCTIONS
# define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
# define BHO_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS
#endif
// -------------------------------------
#if defined(__UU) || defined(__C99) || defined(__TR1)
# define BHO_HAS_LOG1P
# define BHO_HAS_EXPM1
#endif
#if defined(__C99) || defined(__TR1)
# define BHO_HAS_STDINT_H
#else
# define BHO_NO_FENV_H
#endif
// -------------------------------------
#define BHO_HAS_NRVO
#if !defined(__RTTI_ALL__)
# define BHO_NO_RTTI
#endif
#if !defined(_CPPUNWIND) && !defined(__EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
#endif
#if defined(_LONG_LONG) || defined(__IBMCPP_C99_LONG_LONG) || defined(__LL)
# define BHO_HAS_LONG_LONG
#else
# define BHO_NO_LONG_LONG
#endif
#if defined(_LONG_LONG) || defined(__IBMCPP_C99_LONG_LONG) || defined(__LL) || defined(_LP64)
# define BHO_HAS_MS_INT64
#endif
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_CXX11_SFINAE_EXPR
#if defined(__IBMCPP_VARIADIC_TEMPLATES)
# define BHO_HAS_VARIADIC_TMPL
#else
# define BHO_NO_CXX11_VARIADIC_TEMPLATES
# define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#endif
#if defined(__IBMCPP_STATIC_ASSERT)
# define BHO_HAS_STATIC_ASSERT
#else
# define BHO_NO_CXX11_STATIC_ASSERT
#endif
#if defined(__IBMCPP_RVALUE_REFERENCES)
# define BHO_HAS_RVALUE_REFS
#else
# define BHO_NO_CXX11_RVALUE_REFERENCES
#endif
#if !defined(__IBMCPP_SCOPED_ENUM)
# define BHO_NO_CXX11_SCOPED_ENUMS
#endif
#define BHO_NO_CXX11_FIXED_LENGTH_VARIADIC_TEMPLATE_EXPANSION_PACKS
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#if !defined(__IBMCPP_EXPLICIT_CONVERSION_OPERATORS)
# define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#endif
#if !defined(__IBMCPP_DECLTYPE)
# define BHO_NO_CXX11_DECLTYPE
#else
# define BHO_HAS_DECLTYPE
#endif
#define BHO_NO_CXX11_DECLTYPE_N3276
#if !defined(__IBMCPP_INLINE_NAMESPACE)
# define BHO_NO_CXX11_INLINE_NAMESPACES
#endif
#if !defined(__IBMCPP_AUTO_TYPEDEDUCTION)
# define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
# define BHO_NO_CXX11_AUTO_DECLARATIONS
# define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#endif
#if !defined(__IBM_CHAR32_T__)
# define BHO_NO_CXX11_CHAR32_T
#endif
#if !defined(__IBM_CHAR16_T__)
# define BHO_NO_CXX11_CHAR16_T
#endif
#if !defined(__IBMCPP_CONSTEXPR)
# define BHO_NO_CXX11_CONSTEXPR
#endif
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#define BHO_NO_CXX11_UNICODE_LITERALS
#define BHO_NO_CXX11_RAW_LITERALS
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_LAMBDAS
#define BHO_NO_CXX11_USER_DEFINED_LITERALS
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_FINAL
#define BHO_NO_CXX11_OVERRIDE
#define BHO_NO_CXX11_ALIGNAS
#define BHO_NO_CXX11_UNRESTRICTED_UNION
#define BHO_NO_CXX14_VARIABLE_TEMPLATES
#define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#define BHO_NO_CXX14_AGGREGATE_NSDMI
#define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#define BHO_NO_CXX14_GENERIC_LAMBDAS
#define BHO_NO_CXX14_DIGIT_SEPARATORS
#define BHO_NO_CXX14_DECLTYPE_AUTO
#define BHO_NO_CXX14_CONSTEXPR
#define BHO_NO_CXX14_BINARY_LITERALS
#define BHO_NO_CXX17_STRUCTURED_BINDINGS
#define BHO_NO_CXX17_INLINE_VARIABLES
#define BHO_NO_CXX17_FOLD_EXPRESSIONS
#define BHO_NO_CXX17_IF_CONSTEXPR
// -------------------------------------
#if defined(__IBM_ATTRIBUTES)
# define BHO_FORCEINLINE inline __attribute__ ((__always_inline__))
# define BHO_NOINLINE __attribute__ ((__noinline__))
# define BHO_MAY_ALIAS __attribute__((__may_alias__))
// No BHO_ALIGNMENT - explicit alignment support is broken (V2R1).
#endif
extern "builtin" long __builtin_expect(long, long);
#define BHO_LIKELY(x) __builtin_expect((x) && true, 1)
#define BHO_UNLIKELY(x) __builtin_expect((x) && true, 0)
<file_sep>// (C) Copyright <NAME> 2001 - 2002.
// (C) Copyright <NAME> 2002.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// MPW C++ compilers setup:
# if defined(__SC__)
# define BHO_COMPILER "MPW SCpp version " BHO_STRINGIZE(__SC__)
# elif defined(__MRC__)
# define BHO_COMPILER "MPW MrCpp version " BHO_STRINGIZE(__MRC__)
# else
# error "Using MPW compiler configuration by mistake. Please update."
# endif
//
// MPW 8.90:
//
#if (MPW_CPLUS <= 0x890) || !defined(BHO_STRICT_CONFIG)
# define BHO_NO_CV_SPECIALIZATIONS
# define BHO_NO_DEPENDENT_NESTED_DERIVATIONS
# define BHO_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS
# define BHO_NO_INCLASS_MEMBER_INITIALIZATION
# define BHO_NO_INTRINSIC_WCHAR_T
# define BHO_NO_TEMPLATE_PARTIAL_SPECIALIZATION
# define BHO_NO_USING_TEMPLATE
# define BHO_NO_CWCHAR
# define BHO_NO_LIMITS_COMPILE_TIME_CONSTANTS
# define BHO_NO_STD_ALLOCATOR /* actually a bug with const reference overloading */
#endif
//
// C++0x features
//
// See boost\config\suffix.hpp for BHO_NO_LONG_LONG
//
#define BHO_NO_CXX11_AUTO_DECLARATIONS
#define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#define BHO_NO_CXX11_CHAR16_T
#define BHO_NO_CXX11_CHAR32_T
#define BHO_NO_CXX11_CONSTEXPR
#define BHO_NO_CXX11_DECLTYPE
#define BHO_NO_CXX11_DECLTYPE_N3276
#define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#define BHO_NO_CXX11_DELETED_FUNCTIONS
#define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#define BHO_NO_CXX11_EXTERN_TEMPLATE
#define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define BHO_NO_CXX11_HDR_INITIALIZER_LIST
#define BHO_NO_CXX11_LAMBDAS
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_RAW_LITERALS
#define BHO_NO_CXX11_RVALUE_REFERENCES
#define BHO_NO_CXX11_SCOPED_ENUMS
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_CXX11_SFINAE_EXPR
#define BHO_NO_CXX11_STATIC_ASSERT
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_UNICODE_LITERALS
#define BHO_NO_CXX11_VARIADIC_TEMPLATES
#define BHO_NO_CXX11_VARIADIC_MACROS
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#define BHO_NO_CXX11_USER_DEFINED_LITERALS
#define BHO_NO_CXX11_ALIGNAS
#define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#define BHO_NO_CXX11_INLINE_NAMESPACES
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_FINAL
#define BHO_NO_CXX11_OVERRIDE
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_UNRESTRICTED_UNION
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
//
// versions check:
// we don't support MPW prior to version 8.9:
#if MPW_CPLUS < 0x890
# error "Compiler not supported or configured - please reconfigure"
#endif
//
// last known and checked version is 0x890:
#if (MPW_CPLUS > 0x890)
# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown compiler version - please run the configure tests and report the results"
# endif
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_IAR_H
#define BHO_PREDEF_COMPILER_IAR_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_IAR`
IAR C/{CPP} compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__IAR_SYSTEMS_ICC__+` | {predef_detection}
| `+__VER__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_IAR BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__IAR_SYSTEMS_ICC__)
# define BHO_COMP_IAR_DETECTION BHO_PREDEF_MAKE_10_VVRR(__VER__)
#endif
#ifdef BHO_COMP_IAR_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_IAR_EMULATED BHO_COMP_IAR_DETECTION
# else
# undef BHO_COMP_IAR
# define BHO_COMP_IAR BHO_COMP_IAR_DETECTION
# endif
# define BHO_COMP_IAR_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_IAR_NAME "IAR C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_IAR,BHO_COMP_IAR_NAME)
#ifdef BHO_COMP_IAR_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_IAR_EMULATED,BHO_COMP_IAR_NAME)
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_X86_32_H
#define BHO_PREDEF_ARCHITECTURE_X86_32_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_X86_32`
http://en.wikipedia.org/wiki/X86[Intel x86] architecture:
If available versions [3-6] are specifically detected.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `i386` | {predef_detection}
| `+__i386__+` | {predef_detection}
| `+__i486__+` | {predef_detection}
| `+__i586__+` | {predef_detection}
| `+__i686__+` | {predef_detection}
| `+__i386+` | {predef_detection}
| `+_M_IX86+` | {predef_detection}
| `+_X86_+` | {predef_detection}
| `+__THW_INTEL__+` | {predef_detection}
| `+__I86__+` | {predef_detection}
| `+__INTEL__+` | {predef_detection}
| `+__I86__+` | V.0.0
| `+_M_IX86+` | V.0.0
| `+__i686__+` | 6.0.0
| `+__i586__+` | 5.0.0
| `+__i486__+` | 4.0.0
| `+__i386__+` | 3.0.0
|===
*/ // end::reference[]
#define BHO_ARCH_X86_32 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(i386) || defined(__i386__) || \
defined(__i486__) || defined(__i586__) || \
defined(__i686__) || defined(__i386) || \
defined(_M_IX86) || defined(_X86_) || \
defined(__THW_INTEL__) || defined(__I86__) || \
defined(__INTEL__)
# undef BHO_ARCH_X86_32
# if !defined(BHO_ARCH_X86_32) && defined(__I86__)
# define BHO_ARCH_X86_32 BHO_VERSION_NUMBER(__I86__,0,0)
# endif
# if !defined(BHO_ARCH_X86_32) && defined(_M_IX86)
# define BHO_ARCH_X86_32 BHO_PREDEF_MAKE_10_VV00(_M_IX86)
# endif
# if !defined(BHO_ARCH_X86_32) && defined(__i686__)
# define BHO_ARCH_X86_32 BHO_VERSION_NUMBER(6,0,0)
# endif
# if !defined(BHO_ARCH_X86_32) && defined(__i586__)
# define BHO_ARCH_X86_32 BHO_VERSION_NUMBER(5,0,0)
# endif
# if !defined(BHO_ARCH_X86_32) && defined(__i486__)
# define BHO_ARCH_X86_32 BHO_VERSION_NUMBER(4,0,0)
# endif
# if !defined(BHO_ARCH_X86_32) && defined(__i386__)
# define BHO_ARCH_X86_32 BHO_VERSION_NUMBER(3,0,0)
# endif
# if !defined(BHO_ARCH_X86_32)
# define BHO_ARCH_X86_32 BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_X86_32
# define BHO_ARCH_X86_32_AVAILABLE
#endif
#if BHO_ARCH_X86_32
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_X86_32_NAME "Intel x86-32"
#include <asio2/bho/predef/architecture/x86.h>
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_X86_32,BHO_ARCH_X86_32_NAME)
<file_sep>#ifndef BHO_MP11_DETAIL_MP_IS_LIST_HPP_INCLUDED
#define BHO_MP11_DETAIL_MP_IS_LIST_HPP_INCLUDED
// Copyright 2015-2019 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/mp11/integral.hpp>
namespace bho
{
namespace mp11
{
// mp_is_list<L>
namespace detail
{
template<class L> struct mp_is_list_impl
{
using type = mp_false;
};
template<template<class...> class L, class... T> struct mp_is_list_impl<L<T...>>
{
using type = mp_true;
};
} // namespace detail
template<class L> using mp_is_list = typename detail::mp_is_list_impl<L>::type;
} // namespace mp11
} // namespace bho
#endif // #ifndef BHO_MP11_DETAIL_MP_IS_LIST_HPP_INCLUDED
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_DISCONNECT_COMPONENT_HPP__
#define __ASIO2_DISCONNECT_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class disconnect_cp
{
public:
using self = disconnect_cp<derived_t, args_t>;
public:
/**
* @brief constructor
*/
disconnect_cp() noexcept {}
/**
* @brief destructor
*/
~disconnect_cp() = default;
protected:
template<typename E = defer_event<void, derived_t>>
inline void _do_disconnect(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, E chain = defer_event<void, derived_t>{})
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.dispatch([&derive, ec, this_ptr = std::move(this_ptr), chain = std::move(chain)]() mutable
{
ASIO2_LOG_DEBUG("disconnect_cp::_do_disconnect: {} {}", ec.value(), ec.message());
derive._do_shutdown(ec, std::move(this_ptr), std::move(chain));
});
}
template<typename DeferEvent>
inline void _post_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
ASIO2_LOG_DEBUG("disconnect_cp::_post_disconnect: {} {}", ec.value(), ec.message());
derive._handle_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _handle_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
// we should wait for the async read functions returned.
// the reading flag will be always false of udp session.
if (derive.reading_)
{
derive._make_readend_timer(ec, std::move(this_ptr), std::move(chain));
}
else
{
derive._handle_readend(ec, std::move(this_ptr), std::move(chain));
}
}
template<typename DeferEvent>
inline void _handle_readend(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
// at here the disconnect is completely finished.
derive.disconnecting_ = false;
if constexpr (args_t::is_session)
{
derive._do_stop(ec, std::move(this_ptr), std::move(chain));
}
else
{
detail::ignore_unused(ec, this_ptr, chain);
}
}
protected:
template<typename DeferEvent>
inline void _make_readend_timer(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, ec, this_ptr = std::move(this_ptr), chain = std::move(chain)]() mutable
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(this->readend_timer_ == nullptr);
if (this->readend_timer_)
{
this->readend_timer_->cancel();
}
this->readend_timer_ = std::make_shared<safe_timer>(derive.io().context());
derive._post_readend_timer(ec, std::move(this_ptr), std::move(chain), this->readend_timer_);
}));
}
template<typename DeferEvent>
inline void _post_readend_timer(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain,
std::shared_ptr<safe_timer> timer_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
// a new timer is maked, this is the prev timer, so return directly.
if (timer_ptr.get() != this->readend_timer_.get())
return;
safe_timer* ptimer = timer_ptr.get();
ptimer->timer.expires_after(derive.get_disconnect_timeout());
ptimer->timer.async_wait(
[&derive, ec, this_ptr = std::move(this_ptr), chain = std::move(chain), timer_ptr = std::move(timer_ptr)]
(const error_code& timer_ec) mutable
{
derive._handle_readend_timer(
timer_ec, ec, std::move(this_ptr), std::move(chain), std::move(timer_ptr));
});
}
template<typename DeferEvent>
inline void _handle_readend_timer(
const error_code& timer_ec,
const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain,
std::shared_ptr<safe_timer> timer_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT((!timer_ec) || timer_ec == asio::error::operation_aborted);
// a new timer is maked, this is the prev timer, so return directly.
if (timer_ptr.get() != this->readend_timer_.get())
return;
// member variable timer should't be empty
if (!this->readend_timer_)
{
ASIO2_ASSERT(false);
return;
}
// current timer is canceled by manual
if (timer_ec == asio::error::operation_aborted || timer_ptr->canceled.test_and_set())
{
ASIO2_LOG_DEBUG("disconnect_cp::_handle_readend_timer: canceled");
}
// timeout
else
{
ASIO2_LOG_DEBUG("disconnect_cp::_handle_readend_timer: timeout");
}
timer_ptr->canceled.clear();
this->readend_timer_.reset();
derive._handle_readend(ec, std::move(this_ptr), std::move(chain));
}
inline void _stop_readend_timer(std::shared_ptr<derived_t> this_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = std::move(this_ptr)]() mutable
{
if (this->readend_timer_)
{
this->readend_timer_->cancel();
}
}));
}
public:
/**
* @brief get the disconnect timeout
*/
inline std::chrono::steady_clock::duration get_disconnect_timeout() noexcept
{
return this->disconnect_timeout_;
}
/**
* @brief set the disconnect timeout
*/
template<class Rep, class Period>
inline derived_t& set_disconnect_timeout(std::chrono::duration<Rep, Period> timeout) noexcept
{
if (timeout > std::chrono::duration_cast<
std::chrono::duration<Rep, Period>>((std::chrono::steady_clock::duration::max)()))
this->disconnect_timeout_ = (std::chrono::steady_clock::duration::max)();
else
this->disconnect_timeout_ = timeout;
return static_cast<derived_t&>(*this);
}
protected:
std::chrono::steady_clock::duration disconnect_timeout_ = std::chrono::seconds(30);
///
bool disconnecting_ = false;
std::shared_ptr<safe_timer> readend_timer_;
};
}
#endif // !__ASIO2_DISCONNECT_COMPONENT_HPP__
<file_sep># 基于c++和asio的网络编程框架asio2教程基础篇:3、各个回调函数的触发线程以及多线程总结
- 关于asio的多线程的知识点感觉挺多的,需要对“服务端,客户端,tcp,udp”分别来总结。
- 而且了解各个函数分别在哪个线程中执行的,对于多线程编程以及和做具体业务时变量要不要用锁来保护,非常重要。
- <font color=#ff0000>asio2是“one io_context per cpu”的多线程模式。</font>这个概念主要是asio本身的概念,不了解的可以搜索一下,资料还是挺多的。
## 服务端:
### tcp_server:
- 由于tcp是面向连接的协议,所以服务端大都设计成多线程的,把多个连接(比如1千个连接)平均分布到各个线程中去处理。
- asio2的tcp_server构造函数的默认参数如下:
```cpp
explicit tcp_server_impl_t(
std::size_t init_buffer_size = tcp_frame_size,
std::size_t max_buffer_size = (std::numeric_limits<std::size_t>::max)(),
std::size_t concurrency = std::thread::hardware_concurrency() * 2
)
```
- 参数1表示接收缓冲区的初始大小(即默认给每个连接分配这个大小的buffer来接收数据)
- 参数2表示接收缓冲区的最大大小(当接收的数据越来越多时,asio会自动扩大buffer,默认是可以无限制扩大)
- 参数3表示服务端启动多少个线程,默认值是cpu*2
```cpp
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8028";
// 由于tcp_server默认会启动cpu*2个数量的线程,假定cpu核数为4,那就是8个线程,
// 假定为“线程0,线程1,...到...线程7”
// 这里main函数的线程假定为“线程main”,(新版本asio2没有任何事件会在main线程中触发)
asio2::tcp_server server;
// 针对server对象启动一个定时器
server.start_timer(123, std::chrono::seconds(1), []()
{
// 这个定时器的回调函数固定在“线程0”中触发
});
// 针对这个session_ptr投递一个异步事件
server.post([]()
{
// 对这个server对象的投递的异步事件固定在“线程0”中触发
printf("投递的异步事件被执行了\n");
});
server.bind_init([]()
{
// 固定在“线程0”中触发
}).bind_start([&]()
{
// 固定在“线程0”中触发
}).bind_accept([](std::shared_ptr<asio2::tcp_session>& session_ptr)
{
// 固定在“线程0”中触发
}).bind_connect([&](auto & session_ptr)
{
// 固定在“线程0”中触发
// 连接成功以后,可以给这个连接(即session_ptr)启动一个定时器
session_ptr->start_timer("123", std::chrono::seconds(1), []()
{
// 这个session_ptr的定时器的回调函数和bind_recv的触发线程是同一个线程
// (见下方bind_recv中的说明)
});
// 针对这个session_ptr投递一个异步事件
session_ptr->post([]()
{
// 对这个session_ptr投递的异步事件的回调函数和bind_recv的触发线程是
// 同一个线程(见下方bind_recv中的说明)
printf("投递的异步事件被执行了\n");
});
}).bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
// 平均分布在“线程0,线程1,...到...线程7”中触发
// 假如session A的bind_recv在“线程2”中触发,session B的bind_recv在“线程3”中触发,
// 那么session A的bind_recv将永远只在“线程2”中触发,不会出现一会儿在“线程2”中触发
// 一会儿在“线程3”中触发这种情况,session B同理。
// 对于async_send发送数据函数来说,真正发送数据时所在的线
// 程和bind_recv的触发线程是同一个线程。
// 假定session A的bind_recv的触发线程是“线程2”,那么session A的async_send函数也是在“线程2”
// 中发送的数据的(不管async_send函数在哪里调用,不管在哪个线程调用,最终都是投递到“线程2”中
// 去发送的)。
session_ptr->async_send(data, [](std::size_t bytes_sent)
{
// async_send函数可以设置一个回调函数,当发送数据结束以后(不管发送成功还是发送失败),这个
// 回调函数就会被调用。
// 这个回调函数也是在“线程2”中触发的。
if (asio2::get_last_error())
printf("发送数据失败,失败原因:%s\n", asio2::last_error_msg().c_str());
else
printf("发送数据成功,共发送了%d个字节\n", int(bytes_sent));
});
}).bind_disconnect([&](auto & session_ptr)
{
// 固定在“线程0”中触发
}).bind_stop([&]()
{
// 固定在“线程0”中触发
});
server.start(host, port);
while (std::getchar() != '\n'); // press enter to exit this program
server.stop();
return 0;
}
```
- http,websocket,rpc都是基于tcp协议实现的,所以这些组件的服务端回调函数触发线程和tcp完全一样。
- 但有点不同的是ssl有握手事件,websocket有协商事件,如下:
```cpp
// 对于ssl有:
server.bind_handshake([&](auto & session_ptr)
{
// 固定在“线程0”中触发
})
```
```cpp
// 对于websocket有:
server.bind_upgrade([&](auto & session_ptr)
{
// 固定在“线程0”中触发
})
```
### udp_server:
- asio2的udp_server构造函数的默认参数如下:
```cpp
explicit udp_server_impl_t(
std::size_t init_buffer_size = udp_frame_size,
std::size_t max_buffer_size = (std::numeric_limits<std::size_t>::max)()
)
```
- 这里只有参数1和参数2的缓冲区大小设置,没有启动多少个线程这个参数了,这是因为udp是无连接的,所以服务端通信线程在这里设置为固定的1了。启动多个线程没有意义。
```cpp
#include <asio2/asio2.hpp>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8035";
asio2::udp_server server;
// 因为udp_server只有一个线程,所有的事件,包括recv,timer,post事件等,都是在“线程0”中触发的。
server.bind_init([&]()
{
// 固定在“线程0”中触发
}).bind_start([&]()
{
// 固定在“线程0”中触发
}).bind_connect([](auto & session_ptr)
{
// 固定在“线程0”中触发
}).bind_handshake([](auto & session_ptr)
{
// 固定在“线程0”中触发
// 注意bind_handshake是针对可靠UDP的,即使用KCP时才有handshake事件,普通UDP
// 是没有handshake事件的。但不管有没有用KCP,你调用不调用bind_handshake都
// 可以,无所谓的,大不了不会触发而已。
}).bind_recv([](std::shared_ptr<asio2::udp_session> & session_ptr, std::string_view s)
{
// 固定在“线程0”中触发
session_ptr->async_send(s, []() {});
}).bind_disconnect([](auto & session_ptr)
{
// 固定在“线程0”中触发
}).bind_stop([&]()
{
// 固定在“线程0”中触发
});
server.start(host, port);
while (std::getchar() != '\n');
return 0;
}
```
## 客户端
- asio2的tcp_client构造函数的默认参数如下:
```cpp
explicit tcp_client_impl_t(
std::size_t init_buffer_size = tcp_frame_size,
std::size_t max_buffer_size = (std::numeric_limits<std::size_t>::max)()
)
```
- 同样没有启动多少个线程这个参数了,因为所有客户端,不管是tcp还是udp,都将通信线程设置为固定的1个了。
```cpp
#include <asio2/asio2.hpp>
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8028";
asio2::tcp_client client;
// 因为所有客户端只有一个线程,所有的事件,包括recv,timer,post事件等,都是在“线程0”中触发的。
// 注意:客户端没有start和stop事件了,实际上已经被connect和disconnect
// 事件代替了。
client.start_timer(1, std::chrono::seconds(1), []() {});
client.bind_init([&]()
{
// 固定在“线程0”中触发
}).bind_connect([&]()
{
// 固定在“线程0”中触发
client.async_send("abc", [](std::size_t bytes) {});
}).bind_recv([&](std::string_view sv)
{
// 固定在“线程0”中触发
}).bind_disconnect([&]()
{
// 固定在“线程0”中触发
});
client.start(host, port);
while (std::getchar() != '\n');
return 0;
}
```
## 项目地址:
github : [https://github.com/zhllxt/asio2](https://github.com/zhllxt/asio2)
码云 : [https://gitee.com/zhllxt/asio2](https://gitee.com/zhllxt/asio2)
### 最后编辑于2022-06-23
<file_sep>#include <asio2/udp/udp_cast.hpp>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8022";
asio2::udp_cast udp_cast;
udp_cast.bind_recv([&](asio::ip::udp::endpoint& endpoint, std::string_view data)
{
printf("recv : %s %u %zu %.*s\n",
endpoint.address().to_string().c_str(), endpoint.port(),
data.size(), (int)data.size(), data.data());
udp_cast.async_send(endpoint, data);
}).bind_start([&]()
{
printf("start : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
printf("stop : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_init([&]()
{
//// Join the multicast group.
//udp_cast.socket().set_option(
// asio::ip::multicast::join_group(asio::ip::make_address("172.16.17.32")));
});
udp_cast.start(host, port);
std::string str("<0123456789abcdefghijklmnopqrstowvxyz>");
// send to self
udp_cast.send("127.0.0.1", 8022, str);
asio::ip::udp::endpoint ep(asio::ip::make_address("127.0.0.1"), 8020);
udp_cast.async_send(ep, str);
// this is a multicast address
udp_cast.async_send("172.16.17.32", "8030", str);
// the resolve function is a time-consuming operation
//asio::ip::udp::resolver resolver(udp_cast.io().context());
//asio::ip::udp::resolver::query query("www.baidu.com", "18080");
//asio::ip::udp::endpoint ep2 = *resolver.resolve(query);
//udp_cast.async_send(ep2, std::move(str));
// stop the udp cast after 10 seconds.
udp_cast.start_timer(1, 10000, 1, [&]()
{
// note : the stop is called in the io_context thread is ok.
// of course you can call the udp_cast.stop() function anywhere.
udp_cast.stop();
});
// the udp_cast.wait_stop() will be blocked forever until the udp_cast.stop() is called.
udp_cast.wait_stop();
// Or you can call the wait_for function directly to block for 10 seconds
//udp_cast.wait_for(std::chrono::seconds(10));
return 0;
}
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_LLVM_H
#define BHO_PREDEF_COMPILER_LLVM_H
/* Other compilers that emulate this one need to be detected first. */
#include <asio2/bho/predef/compiler/clang.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_LLVM`
http://en.wikipedia.org/wiki/LLVM[LLVM] compiler.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__llvm__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_COMP_LLVM BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__llvm__)
# define BHO_COMP_LLVM_DETECTION BHO_VERSION_NUMBER_AVAILABLE
#endif
#ifdef BHO_COMP_LLVM_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_LLVM_EMULATED BHO_COMP_LLVM_DETECTION
# else
# undef BHO_COMP_LLVM
# define BHO_COMP_LLVM BHO_COMP_LLVM_DETECTION
# endif
# define BHO_COMP_LLVM_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_LLVM_NAME "LLVM"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_LLVM,BHO_COMP_LLVM_NAME)
#ifdef BHO_COMP_LLVM_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_LLVM_EMULATED,BHO_COMP_LLVM_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_AOP_CONNECT_HPP__
#define __ASIO2_MQTT_AOP_CONNECT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class caller_t, class args_t>
class mqtt_aop_connect
{
friend caller_t;
protected:
template<class Response>
inline void _set_connack_reason_code_with_invalid_id(error_code& ec, Response& rep)
{
using response_type = typename detail::remove_cvref_t<Response>;
ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid);
if constexpr /**/ (std::is_same_v<response_type, mqtt::v3::connack>)
{
rep.reason_code(mqtt::v3::connect_reason_code::identifier_rejected);
}
else if constexpr (std::is_same_v<response_type, mqtt::v4::connack>)
{
rep.reason_code(mqtt::v4::connect_reason_code::identifier_rejected);
}
else if constexpr (std::is_same_v<response_type, mqtt::v5::connack>)
{
rep.reason_code(mqtt::error::client_identifier_not_valid);
}
else
{
static_assert(detail::always_false_v<Response>);
}
}
template<class Response>
inline void _set_connack_reason_code_with_bad_user_name_or_password(error_code& ec, Response& rep)
{
using response_type = typename detail::remove_cvref_t<Response>;
ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password);
if constexpr /**/ (std::is_same_v<response_type, mqtt::v3::connack>)
{
rep.reason_code(mqtt::v3::connect_reason_code::bad_user_name_or_password);
}
else if constexpr (std::is_same_v<response_type, mqtt::v4::connack>)
{
rep.reason_code(mqtt::v4::connect_reason_code::bad_user_name_or_password);
}
else if constexpr (std::is_same_v<response_type, mqtt::v5::connack>)
{
rep.reason_code(mqtt::error::bad_user_name_or_password);
}
else
{
static_assert(detail::always_false_v<Response>);
}
}
template<class Response>
inline void _set_connack_reason_code_with_not_authorized(error_code& ec, Response& rep)
{
using response_type = typename detail::remove_cvref_t<Response>;
ec = mqtt::make_error_code(mqtt::error::not_authorized);
if constexpr /**/ (std::is_same_v<response_type, mqtt::v3::connack>)
{
rep.reason_code(mqtt::v3::connect_reason_code::not_authorized);
}
else if constexpr (std::is_same_v<response_type, mqtt::v4::connack>)
{
rep.reason_code(mqtt::v4::connect_reason_code::not_authorized);
}
else if constexpr (std::is_same_v<response_type, mqtt::v5::connack>)
{
rep.reason_code(mqtt::error::not_authorized);
}
else
{
static_assert(detail::always_false_v<Response>);
}
}
template<class Message, class Response>
inline void _check_connect_client_id(error_code& ec, caller_t* caller, Message& msg, Response& rep)
{
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
std::string_view client_id = msg.client_id();
if constexpr /**/ (std::is_same_v<response_type, mqtt::v3::connack>)
{
// The first UTF-encoded string. The Client Identifier (Client ID) is between 1 and 23
// characters long, and uniquely identifies the client to the server. It must be unique
// across all clients connecting to a single server, and is the key in handling Message
// IDs messages with QoS levels 1 and 2. If the Client ID contains more than 23 characters,
// the server responds to the CONNECT message with a CONNACK return code 2: Identifier Rejected.
if (client_id.size() < static_cast<std::string_view::size_type>(1) ||
client_id.size() > static_cast<std::string_view::size_type>(23))
return _set_connack_reason_code_with_invalid_id(ec, rep);
}
else if constexpr (std::is_same_v<response_type, mqtt::v4::connack>)
{
// If the Client supplies a zero-byte ClientId, the Client MUST also set CleanSession
// to 1[MQTT-3.1.3-7].
// If the Client supplies a zero-byte ClientId with CleanSession set to 0, the Server
// MUST respond to the CONNECT Packet with a CONNACK return code 0x02 (Identifier rejected)
// and then close the Network Connection[MQTT-3.1.3-8].
// If the Server rejects the ClientId it MUST respond to the CONNECT Packet with a CONNACK
// return code 0x02 (Identifier rejected) and then close the Network Connection[MQTT-3.1.3-9].
if (client_id.empty())
{
if (msg.clean_session() == false)
return _set_connack_reason_code_with_invalid_id(ec, rep);
// assign a unique ClientId to that Client.
msg.client_id(std::to_string(reinterpret_cast<std::size_t>(caller)));
}
}
else if constexpr (std::is_same_v<response_type, mqtt::v5::connack>)
{
// and MUST return the Assigned Client Identifier in the CONNACK packet [MQTT-3.1.3-7].
if (client_id.empty())
{
// assign a unique ClientId to that Client.
msg.client_id(std::to_string(reinterpret_cast<std::size_t>(caller)));
rep.properties().add(mqtt::v5::assigned_client_identifier(msg.client_id()));
}
}
else
{
static_assert(detail::always_false_v<Response>);
}
// check whether uniquely identifier
}
// must be server
template<class Message, class Response, bool IsClient = args_t::is_client>
inline std::enable_if_t<!IsClient, void>
_before_connect_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
// if started already and recvd connect message again, disconnect
state_t expected = state_t::started;
if (caller->state_.compare_exchange_strong(expected, state_t::started))
{
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
rep.set_send_flag(false);
return;
}
// mqtt auth
if (caller->security().enabled())
{
std::optional<std::string> username;
if (caller->get_preauthed_username())
{
if (caller->security().login_cert(caller->get_preauthed_username().value()))
{
username = caller->get_preauthed_username();
}
}
else if (msg.has_username() && msg.has_password())
{
username = caller->security().login(msg.username(), msg.password());
}
else
{
username = caller->security().login_anonymous();
}
// If login fails, try the unauthenticated user
if (!username)
{
username = caller->security().login_unauthenticated();
}
if (!username)
{
ASIO2_LOG_TRACE("User failed to login: {}",
(msg.has_username() ? msg.username() : "anonymous user"));
if (msg.has_username() && msg.has_password())
return _set_connack_reason_code_with_bad_user_name_or_password(ec, rep);
return _set_connack_reason_code_with_not_authorized(ec, rep);
}
}
// check client id
if (_check_connect_client_id(ec, caller, msg, rep); ec)
return;
// set keepalive timeout
// If the Keep Alive value is non-zero and the Server does not receive a Control Packet from
// the Client within one and a half times the Keep Alive time period, it MUST disconnect the
// Network Connection to the Client as if the network had failed [MQTT-3.1.2-24].
// A Keep Alive value of zero (0) has the effect of turning off the keep alive mechanism.
// This means that, in this case, the Server is not required to disconnect the Client on the
// grounds of inactivity. Note that a Server is permitted to disconnect a Client that it
// determines to be inactive or non-responsive at any time, regardless of the Keep Alive value
// provided by that Client.
mqtt::two_byte_integer::value_type keepalive = msg.keep_alive();
if (keepalive == 0)
{
caller->set_silence_timeout(std::chrono::milliseconds(detail::tcp_silence_timeout));
}
else
{
caller->set_silence_timeout(std::chrono::milliseconds(keepalive * 1500));
}
// fill the reason code with 0.
rep.reason_code(0);
caller->connect_message_ = msg;
// If a client with the same Client ID is already connected to the server, the "older" client
// must be disconnected by the server before completing the CONNECT flow of the new client.
// If CleanSession is set to 0, the Server MUST resume communications with the Client based on state
// from the current Session (as identified by the Client identifier).
// If there is no Session associated with the Client identifier the Server MUST create a new Session.
// The Client and Server MUST store the Session after the Client and Server are disconnected [MQTT-3.1.2-4].
// After the disconnection of a Session that had CleanSession set to 0, the Server MUST store further
// QoS 1 and QoS 2 messages that match any subscriptions that the client had at the time of disconnection
// as part of the Session state [MQTT-3.1.2-5]. It MAY also store QoS 0 messages that meet the same criteria.
// If CleanSession is set to 1, the Client and Server MUST discard any previous Session and start a new one.
// This Session lasts as long as the Network Connection.State data associated with this Session MUST NOT be
// reused in any subsequent Session[MQTT-3.1.2-6].
// If a CONNECT packet is received with Clean Start is set to 1, the Client and Server MUST discard any
// existing Session and start a new Session [MQTT-3.1.2-4]. Consequently, the Session Present flag in
// CONNACK is always set to 0 if Clean Start is set to 1.
// If a CONNECT packet is received with Clean Start set to 0 and there is a Session associated with the
// Client Identifier, the Server MUST resume communications with the Client based on state from the existing
// Session[MQTT-3.1.2-5].If a CONNECT packet is received with Clean Start set to 0 and there is no Session
// associated with the Client Identifier, the Server MUST create a new Session[MQTT-3.1.2-6].
std::shared_ptr<caller_t> session_ptr = caller->mqtt_sessions().find_mqtt_session(caller->client_id());
// If the Server accepts a connection with Clean Start set to 1, the Server MUST set Session
// Present to 0 in the CONNACK packet in addition to setting a 0x00 (Success) Reason Code in
// the CONNACK packet [MQTT-3.2.2-2].
if (msg.clean_session())
rep.session_present(false);
// If the Server accepts a connection with Clean Start set to 0 and the Server has Session
// State for the ClientID, it MUST set Session Present to 1 in the CONNACK packet, otherwise
// it MUST set Session Present to 0 in the CONNACK packet. In both cases it MUST set a 0x00
// (Success) Reason Code in the CONNACK packet [MQTT-3.2.2-3].
else
rep.session_present(session_ptr != nullptr);
if (session_ptr == nullptr)
{
caller->mqtt_sessions().push_mqtt_session(caller->client_id(), caller_ptr);
session_ptr = caller_ptr;
}
else
{
if (session_ptr->is_started())
{
// send will message
if (!session_ptr->connect_message_.empty())
{
auto f = [caller_ptr, caller](auto& conn) mutable
{
if (!conn.has_will())
return;
// note : why v5 ?
mqtt::v5::publish pub;
pub.qos(conn.will_qos());
pub.retain(conn.will_retain());
pub.topic_name(conn.will_topic());
pub.payload(conn.will_payload());
caller->push_event(
[caller_ptr, caller, pub = std::move(pub)]
(event_queue_guard<caller_t> g) mutable
{
detail::ignore_unused(g);
caller->_multicast_publish(caller_ptr, caller, std::move(pub), std::string{});
});
};
if /**/ (std::holds_alternative<mqtt::v3::connect>(session_ptr->connect_message_.base()))
{
mqtt::v3::connect* p = session_ptr->connect_message_.template get_if<mqtt::v3::connect>();
f(*p);
}
else if (std::holds_alternative<mqtt::v4::connect>(session_ptr->connect_message_.base()))
{
mqtt::v4::connect* p = session_ptr->connect_message_.template get_if<mqtt::v4::connect>();
f(*p);
}
else if (std::holds_alternative<mqtt::v5::connect>(session_ptr->connect_message_.base()))
{
mqtt::v5::connect* p = session_ptr->connect_message_.template get_if<mqtt::v5::connect>();
f(*p);
}
}
// disconnect session
// In previous versions, the mutex is a global variable, when code reached here,
// the mutex status is locked already, so if we call session_ptr->stop()
// directly, the stop maybe blocked forever, beacuse the session1 stop maybe
// called in the session2 thread, and in the handle disconnect funcion of mqtt
// session, the global mutex is required to lock again, so it caused deaklock,
// to solve this problem, we can use session->post([](){session->stop()}).
// but now, we change the mutex from global variable to member variable for each
// mqtt class, so now, it won't caused deaklock, even we only use session->stop,
// but we still use session->post([](){session->stop()}), to enhanced stability.
session_ptr->post([session_ptr]() mutable { session_ptr->stop(); });
//
bool clean_session = false;
if /**/ (std::holds_alternative<mqtt::v3::connect>(session_ptr->connect_message_.base()))
{
clean_session = session_ptr->connect_message_.template get_if<mqtt::v3::connect>()->clean_session();
}
else if (std::holds_alternative<mqtt::v4::connect>(session_ptr->connect_message_.base()))
{
clean_session = session_ptr->connect_message_.template get_if<mqtt::v4::connect>()->clean_session();
}
else if (std::holds_alternative<mqtt::v5::connect>(session_ptr->connect_message_.base()))
{
clean_session = session_ptr->connect_message_.template get_if<mqtt::v5::connect>()->clean_session();
}
if (clean_session)
{
}
else
{
}
if (msg.clean_session())
{
}
else
{
// copy session state from old session to new session
}
}
else
{
}
// replace old session to new session
session_ptr = caller_ptr;
}
}
template<class Message, class Response, bool IsClient = args_t::is_client>
inline std::enable_if_t<IsClient, void>
_before_connect_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
ASIO2_ASSERT(false && "client should't recv the connect message");
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::connect& msg, mqtt::v3::connack& rep)
{
if (_before_connect_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::connect& msg, mqtt::v4::connack& rep)
{
if (_before_connect_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::connect& msg, mqtt::v5::connack& rep)
{
if (_before_connect_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::connect& msg, mqtt::v5::auth& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
//if constexpr (caller_t::is_session())
//{
// // if started already and recvd connect message again, disconnect
// state_t expected = state_t::started;
// if (caller->state_.compare_exchange_strong(expected, state_t::started))
// {
// ec = mqtt::make_error_code(mqtt::error::malformed_packet);
// rep.set_send_flag(false);
// return;
// }
// caller->connect_message_ = msg;
// std::shared_ptr<caller_t> session_ptr = caller->mqtt_sessions().find_mqtt_session(msg.client_id());
// if (session_ptr != nullptr)
// {
// }
//}
//else
//{
// std::ignore = true;
//}
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::connect& msg, mqtt::v3::connack& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
// if already has error, return
if (ec)
return;
// If a client with the same Client ID is already connected to the server, the "older" client
// must be disconnected by the server before completing the CONNECT flow of the new client.
switch(rep.reason_code())
{
case mqtt::v3::connect_reason_code::success : ec = mqtt::make_error_code(mqtt::error::success ); break;
case mqtt::v3::connect_reason_code::unacceptable_protocol_version : ec = mqtt::make_error_code(mqtt::error::unsupported_protocol_version); break;
case mqtt::v3::connect_reason_code::identifier_rejected : ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid ); break;
case mqtt::v3::connect_reason_code::server_unavailable : ec = mqtt::make_error_code(mqtt::error::server_unavailable ); break;
case mqtt::v3::connect_reason_code::bad_user_name_or_password : ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password ); break;
case mqtt::v3::connect_reason_code::not_authorized : ec = mqtt::make_error_code(mqtt::error::not_authorized ); break;
default : ec = mqtt::make_error_code(mqtt::error::malformed_packet ); break;
}
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::connect& msg, mqtt::v4::connack& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
// if already has error, return
if (ec)
return;
switch(rep.reason_code())
{
case mqtt::v4::connect_reason_code::success : ec = mqtt::make_error_code(mqtt::error::success ); break;
case mqtt::v4::connect_reason_code::unacceptable_protocol_version : ec = mqtt::make_error_code(mqtt::error::unsupported_protocol_version); break;
case mqtt::v4::connect_reason_code::identifier_rejected : ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid ); break;
case mqtt::v4::connect_reason_code::server_unavailable : ec = mqtt::make_error_code(mqtt::error::server_unavailable ); break;
case mqtt::v4::connect_reason_code::bad_user_name_or_password : ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password ); break;
case mqtt::v4::connect_reason_code::not_authorized : ec = mqtt::make_error_code(mqtt::error::not_authorized ); break;
default : ec = mqtt::make_error_code(mqtt::error::malformed_packet ); break;
}
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::connect& msg, mqtt::v5::connack& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
// if already has error, return
if (ec)
return;
ec = mqtt::make_error_code(static_cast<mqtt::error>(rep.reason_code()));
if (!ec)
{
if (rep.properties().has<mqtt::v5::topic_alias_maximum>() == false)
rep.properties().add(mqtt::v5::topic_alias_maximum{ caller->topic_alias_maximum() });
}
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::connect& msg, mqtt::v5::auth& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
// if already has error, return
if (ec)
return;
}
};
}
#endif // !__ASIO2_MQTT_AOP_CONNECT_HPP__
<file_sep>/*
Copyright 2019 <NAME>
(<EMAIL>)
Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_CORE_USE_DEFAULT_HPP
#define BHO_CORE_USE_DEFAULT_HPP
namespace bho {
struct use_default { };
} /* boost */
#endif
<file_sep>/*
Copyright (C) 2002 <NAME> (<EMAIL>)
<NAME> (<EMAIL>)
Copyright (C) 2002, 2008, 2013 <NAME>
Copyright (C) 2017 <NAME> (<EMAIL>)
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_CORE_ADDRESSOF_HPP
#define BHO_CORE_ADDRESSOF_HPP
#include <asio2/bho/config.hpp>
#if defined(BHO_MSVC_FULL_VER) && BHO_MSVC_FULL_VER >= 190024215
#define BHO_CORE_HAS_BUILTIN_ADDRESSOF
#elif defined(BHO_GCC) && BHO_GCC >= 70000
#define BHO_CORE_HAS_BUILTIN_ADDRESSOF
#elif defined(__has_builtin)
#if __has_builtin(__builtin_addressof)
#define BHO_CORE_HAS_BUILTIN_ADDRESSOF
#endif
#endif
#if defined(BHO_CORE_HAS_BUILTIN_ADDRESSOF)
#if defined(BHO_NO_CXX11_CONSTEXPR)
#define BHO_CORE_NO_CONSTEXPR_ADDRESSOF
#endif
namespace bho {
template<class T>
BHO_CONSTEXPR inline T*
addressof(T& o) BHO_NOEXCEPT
{
return __builtin_addressof(o);
}
} /* boost */
#else
#include <asio2/bho/config/workaround.hpp>
#include <cstddef>
namespace bho {
namespace detail {
template<class T>
class addrof_ref {
public:
BHO_FORCEINLINE addrof_ref(T& o) BHO_NOEXCEPT
: o_(o) { }
BHO_FORCEINLINE operator T&() const BHO_NOEXCEPT {
return o_;
}
private:
addrof_ref& operator=(const addrof_ref&);
T& o_;
};
template<class T>
struct addrof {
static BHO_FORCEINLINE T* get(T& o, long) BHO_NOEXCEPT {
return reinterpret_cast<T*>(&
const_cast<char&>(reinterpret_cast<const volatile char&>(o)));
}
static BHO_FORCEINLINE T* get(T* p, int) BHO_NOEXCEPT {
return p;
}
};
#if !defined(BHO_NO_CXX11_NULLPTR)
#if !defined(BHO_NO_CXX11_DECLTYPE) && \
(defined(__INTEL_COMPILER) || \
(defined(__clang__) && !defined(_LIBCPP_VERSION)))
typedef decltype(nullptr) addrof_null_t;
#else
typedef std::nullptr_t addrof_null_t;
#endif
template<>
struct addrof<addrof_null_t> {
typedef addrof_null_t type;
static BHO_FORCEINLINE type* get(type& o, int) BHO_NOEXCEPT {
return &o;
}
};
template<>
struct addrof<const addrof_null_t> {
typedef const addrof_null_t type;
static BHO_FORCEINLINE type* get(type& o, int) BHO_NOEXCEPT {
return &o;
}
};
template<>
struct addrof<volatile addrof_null_t> {
typedef volatile addrof_null_t type;
static BHO_FORCEINLINE type* get(type& o, int) BHO_NOEXCEPT {
return &o;
}
};
template<>
struct addrof<const volatile addrof_null_t> {
typedef const volatile addrof_null_t type;
static BHO_FORCEINLINE type* get(type& o, int) BHO_NOEXCEPT {
return &o;
}
};
#endif
} /* detail */
#if defined(BHO_NO_CXX11_SFINAE_EXPR) || \
defined(BHO_NO_CXX11_CONSTEXPR) || \
defined(BHO_NO_CXX11_DECLTYPE)
#define BHO_CORE_NO_CONSTEXPR_ADDRESSOF
template<class T>
BHO_FORCEINLINE T*
addressof(T& o) BHO_NOEXCEPT
{
#if BHO_WORKAROUND(BHO_BORLANDC, BHO_TESTED_AT(0x610)) || \
BHO_WORKAROUND(__SUNPRO_CC, <= 0x5120)
return bho::detail::addrof<T>::get(o, 0);
#else
return bho::detail::addrof<T>::get(bho::detail::addrof_ref<T>(o), 0);
#endif
}
#if BHO_WORKAROUND(__SUNPRO_CC, BHO_TESTED_AT(0x590))
namespace detail {
template<class T>
struct addrof_result {
typedef T* type;
};
} /* detail */
template<class T, std::size_t N>
BHO_FORCEINLINE typename bho::detail::addrof_result<T[N]>::type
addressof(T (&o)[N]) BHO_NOEXCEPT
{
return &o;
}
#endif
#if BHO_WORKAROUND(BHO_BORLANDC, BHO_TESTED_AT(0x564))
template<class T, std::size_t N>
BHO_FORCEINLINE
T (*addressof(T (&o)[N]) BHO_NOEXCEPT)[N]
{
return reinterpret_cast<T(*)[N]>(&o);
}
template<class T, std::size_t N>
BHO_FORCEINLINE
const T (*addressof(const T (&o)[N]) BHO_NOEXCEPT)[N]
{
return reinterpret_cast<const T(*)[N]>(&o);
}
#endif
#else
namespace detail {
template<class T>
T addrof_declval() BHO_NOEXCEPT;
template<class>
struct addrof_void {
typedef void type;
};
template<class T, class E = void>
struct addrof_member_operator {
static constexpr bool value = false;
};
template<class T>
struct addrof_member_operator<T, typename
addrof_void<decltype(addrof_declval<T&>().operator&())>::type> {
static constexpr bool value = true;
};
#if BHO_WORKAROUND(BHO_INTEL, < 1600)
struct addrof_addressable { };
addrof_addressable*
operator&(addrof_addressable&) BHO_NOEXCEPT;
#endif
template<class T, class E = void>
struct addrof_non_member_operator {
static constexpr bool value = false;
};
template<class T>
struct addrof_non_member_operator<T, typename
addrof_void<decltype(operator&(addrof_declval<T&>()))>::type> {
static constexpr bool value = true;
};
template<class T, class E = void>
struct addrof_expression {
static constexpr bool value = false;
};
template<class T>
struct addrof_expression<T,
typename addrof_void<decltype(&addrof_declval<T&>())>::type> {
static constexpr bool value = true;
};
template<class T>
struct addrof_is_constexpr {
static constexpr bool value = addrof_expression<T>::value &&
!addrof_member_operator<T>::value &&
!addrof_non_member_operator<T>::value;
};
template<bool E, class T>
struct addrof_if { };
template<class T>
struct addrof_if<true, T> {
typedef T* type;
};
template<class T>
BHO_FORCEINLINE
typename addrof_if<!addrof_is_constexpr<T>::value, T>::type
addressof(T& o) BHO_NOEXCEPT
{
return addrof<T>::get(addrof_ref<T>(o), 0);
}
template<class T>
constexpr BHO_FORCEINLINE
typename addrof_if<addrof_is_constexpr<T>::value, T>::type
addressof(T& o) BHO_NOEXCEPT
{
return &o;
}
} /* detail */
template<class T>
constexpr BHO_FORCEINLINE T*
addressof(T& o) BHO_NOEXCEPT
{
return bho::detail::addressof(o);
}
#endif
} /* boost */
#endif
#if !defined(BHO_NO_CXX11_RVALUE_REFERENCES) && \
!defined(BHO_NO_CXX11_DELETED_FUNCTIONS)
namespace bho {
template<class T>
const T* addressof(const T&&) = delete;
} /* boost */
#endif
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#if !defined(BHO_PREDEF_COMPILER_H) || defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BHO_PREDEF_COMPILER_H
#define BHO_PREDEF_COMPILER_H
#endif
#include <asio2/bho/predef/compiler/borland.h>
#include <asio2/bho/predef/compiler/clang.h>
#include <asio2/bho/predef/compiler/comeau.h>
#include <asio2/bho/predef/compiler/compaq.h>
#include <asio2/bho/predef/compiler/diab.h>
#include <asio2/bho/predef/compiler/digitalmars.h>
#include <asio2/bho/predef/compiler/dignus.h>
#include <asio2/bho/predef/compiler/edg.h>
#include <asio2/bho/predef/compiler/ekopath.h>
#include <asio2/bho/predef/compiler/gcc_xml.h>
#include <asio2/bho/predef/compiler/gcc.h>
#include <asio2/bho/predef/compiler/greenhills.h>
#include <asio2/bho/predef/compiler/hp_acc.h>
#include <asio2/bho/predef/compiler/iar.h>
#include <asio2/bho/predef/compiler/ibm.h>
#include <asio2/bho/predef/compiler/intel.h>
#include <asio2/bho/predef/compiler/kai.h>
#include <asio2/bho/predef/compiler/llvm.h>
#include <asio2/bho/predef/compiler/metaware.h>
#include <asio2/bho/predef/compiler/metrowerks.h>
#include <asio2/bho/predef/compiler/microtec.h>
#include <asio2/bho/predef/compiler/mpw.h>
#include <asio2/bho/predef/compiler/nvcc.h>
#include <asio2/bho/predef/compiler/palm.h>
#include <asio2/bho/predef/compiler/pgi.h>
#include <asio2/bho/predef/compiler/sgi_mipspro.h>
#include <asio2/bho/predef/compiler/sunpro.h>
#include <asio2/bho/predef/compiler/tendra.h>
#include <asio2/bho/predef/compiler/visualc.h>
#include <asio2/bho/predef/compiler/watcom.h>
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_Z_H
#define BHO_PREDEF_ARCHITECTURE_Z_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_Z`
http://en.wikipedia.org/wiki/Z/Architecture[z/Architecture] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__SYSC_ZARCH__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_Z BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__SYSC_ZARCH__)
# undef BHO_ARCH_Z
# define BHO_ARCH_Z BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_Z
# define BHO_ARCH_Z_AVAILABLE
#endif
#if BHO_ARCH_Z
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_Z_NAME "z/Architecture"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_Z,BHO_ARCH_Z_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_ECS_HPP__
#define __ASIO2_ECS_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <tuple>
#include <asio2/base/detail/match_condition.hpp>
#include <asio2/component/rdc/rdc_option.hpp>
#include <asio2/component/socks/socks5_option.hpp>
namespace asio2::detail
{
struct component_tag {};
struct component_dummy {};
template<class ConditionT, class... Args>
struct component_t : public component_tag
{
static constexpr std::size_t componentc = sizeof...(Args);
using components_type = std::tuple<typename detail::shared_ptr_adapter<Args>::type...>;
using condition_type = condition_t<typename detail::remove_cvref_t<ConditionT>>;
using condition_lowest_type = typename condition_type::type;
template<std::size_t I>
struct components
{
static_assert(I < componentc, "index is out of range, index must less than sizeof Args");
using type = typename std::tuple_element<I, components_type>::type;
using raw_type = typename element_type_adapter<type>::type;
};
component_t(component_t&&) noexcept = default;
component_t(component_t const&) = delete;
component_t& operator=(component_t&&) noexcept = default;
component_t& operator=(component_t const&) = delete;
template<std::size_t... I>
inline component_t clone_impl(std::index_sequence<I...>) noexcept
{
return component_t{ this->condition_.clone(),
(typename components<I>::raw_type(*std::get<I>(this->components_)))... };
}
inline component_t clone()
{
return clone_impl(std::make_index_sequence<componentc>{});
}
template<class LowestT, class... Ts>
explicit component_t(LowestT&& c, Ts&&... ts)
: condition_(std::forward<LowestT>(c))
, components_(detail::to_shared_ptr(std::forward<Ts>(ts))...)
{
}
inline decltype(auto) operator()() noexcept { return condition_(); }
template<typename = void>
static constexpr bool has_rdc() noexcept
{
return (std::is_base_of_v<asio2::rdc::option_base,
typename element_type_adapter<typename detail::remove_cvref_t<Args>>::type> || ...);
}
template<std::size_t I, typename T1, typename... TN>
static constexpr std::size_t rdc_index_helper() noexcept
{
if constexpr (std::is_base_of_v<asio2::rdc::option_base, T1>)
return I;
else
{
if constexpr (sizeof...(TN) == 0)
return std::size_t(0);
else
return rdc_index_helper<I + 1, TN...>();
}
}
template<typename = void>
static constexpr std::size_t rdc_index() noexcept
{
return rdc_index_helper<0,
typename element_type_adapter<typename detail::remove_cvref_t<Args>>::type...>();
}
template<class Tag, std::enable_if_t<std::is_same_v<Tag, std::in_place_t>, int> = 0>
typename components<rdc_index()>::type rdc_option(Tag) noexcept
{
return std::get<rdc_index()>(components_);
}
template<typename = void>
asio2::rdc::option_base* rdc_option_addr() noexcept
{
if constexpr (has_rdc())
{
return this->rdc_option(std::in_place).get();
}
else
{
return nullptr;
}
}
template<typename = void>
static constexpr bool has_socks5() noexcept
{
return (std::is_base_of_v<asio2::socks5::option_base,
typename element_type_adapter<typename detail::remove_cvref_t<Args>>::type> || ...);
}
template<std::size_t I, typename T1, typename... TN>
static constexpr std::size_t socks5_index_helper() noexcept
{
if constexpr (std::is_base_of_v<asio2::socks5::option_base, T1>)
return I;
else
{
if constexpr (sizeof...(TN) == 0)
return std::size_t(0);
else
return socks5_index_helper<I + 1, TN...>();
}
}
template<typename = void>
static constexpr std::size_t socks5_index() noexcept
{
return socks5_index_helper<0,
typename element_type_adapter<typename detail::remove_cvref_t<Args>>::type...>();
}
template<class Tag, std::enable_if_t<std::is_same_v<Tag, std::in_place_t>, int> = 0>
typename components<socks5_index()>::type socks5_option(Tag) noexcept
{
return std::get<socks5_index()>(components_);
}
inline condition_type & get_condition() noexcept { return condition_; }
inline components_type & values () noexcept { return components_; }
protected:
condition_type condition_;
components_type components_;
};
// C++17 class template argument deduction guides
template<class C, class... Ts>
component_t(C, Ts...)->component_t<C, Ts...>;
}
namespace asio2::detail
{
/**
*
*/
class ecs_base
{
public:
virtual ~ecs_base() {}
virtual asio2::rdc::option_base* get_rdc() noexcept { return nullptr; }
};
template<class T>
class ecs_t : public ecs_base
{
public:
using component_type = component_dummy;
using condition_type = condition_t<T>;
using condition_lowest_type = typename condition_type::type;
ecs_t() noexcept = default;
~ecs_t() noexcept = default;
ecs_t(ecs_t&&) noexcept = default;
ecs_t(ecs_t const&) = delete;
ecs_t& operator=(ecs_t&&) noexcept = default;
ecs_t& operator=(ecs_t const&) = delete;
inline ecs_t clone() noexcept { return ecs_t{ this->condition_.clone() }; }
template<class LowestT, std::enable_if_t<!std::is_base_of_v<ecs_t, detail::remove_cvref_t<LowestT>>, int> = 0>
explicit ecs_t(LowestT c) noexcept : condition_(std::move(c)) {}
explicit ecs_t(condition_type c) noexcept : condition_(std::move(c)) {}
inline condition_type& get_condition() noexcept { return condition_; }
inline component_type& get_component() noexcept { return component_; }
protected:
condition_type condition_;
component_type component_;
};
// C++17 class template argument deduction guides
template<class T>
ecs_t(T)->ecs_t<std::remove_reference_t<T>>;
template<>
class ecs_t<void> : public ecs_base
{
public:
using component_type = component_dummy;
using condition_type = condition_t<void>;
using condition_lowest_type = void;
ecs_t() noexcept = default;
~ecs_t() noexcept = default;
ecs_t(ecs_t&&) noexcept = default;
ecs_t(ecs_t const&) noexcept = delete;
ecs_t& operator=(ecs_t&&) noexcept = default;
ecs_t& operator=(ecs_t const&) noexcept = delete;
inline ecs_t clone() noexcept { return ecs_t{}; }
inline condition_type& get_condition() noexcept { return condition_; }
inline component_type& get_component() noexcept { return component_; }
protected:
condition_type condition_;
component_type component_;
};
template<class ConditionT, class... Args>
class ecs_t<component_t<ConditionT, Args...>> : public ecs_base
{
public:
using component_type = component_t<ConditionT, Args...>;
using condition_type = typename component_type::condition_type;
using condition_lowest_type = typename condition_type::type;
ecs_t() noexcept = default;
~ecs_t() noexcept = default;
ecs_t(ecs_t&&) noexcept = default;
ecs_t(ecs_t const&) = delete;
ecs_t& operator=(ecs_t&&) noexcept = default;
ecs_t& operator=(ecs_t const&) = delete;
inline ecs_t clone() noexcept { return ecs_t{ this->component_.clone() }; }
template<class C, std::enable_if_t<!std::is_base_of_v<ecs_t, detail::remove_cvref_t<C>>, int> = 0>
explicit ecs_t(C c) : component_(std::move(c)) {}
inline condition_type& get_condition() noexcept { return component_.get_condition(); }
inline component_type& get_component() noexcept { return component_; }
virtual asio2::rdc::option_base* get_rdc() noexcept override
{
return this->component_.rdc_option_addr();
}
protected:
component_type component_;
};
}
namespace asio2::detail
{
struct ecs_helper
{
template<class T>
static constexpr bool is_component() noexcept
{
using type = detail::remove_cvref_t<T>;
if constexpr (is_template_instance_of_v<std::shared_ptr, type>)
{
return is_component<typename type::element_type>();
}
else
{
if /**/ constexpr (std::is_base_of_v<asio2::rdc::option_base, type>)
return true;
else if constexpr (std::is_base_of_v<asio2::socks5::option_base, type>)
return true;
else
return false;
}
}
template<class... Args>
static constexpr bool args_has_match_condition() noexcept
{
if constexpr (sizeof...(Args) == std::size_t(0))
return false;
else
return (!(ecs_helper::is_component<Args>() && ...));
}
template<class... Args>
static constexpr bool args_has_rdc() noexcept
{
if constexpr (sizeof...(Args) == std::size_t(0))
return false;
else
return (std::is_base_of_v<asio2::rdc::option_base, detail::remove_cvref_t<Args>> || ...);
}
template<class... Args>
static constexpr bool args_has_socks5() noexcept
{
if constexpr (sizeof...(Args) == std::size_t(0))
return false;
else
return (std::is_base_of_v<asio2::socks5::option_base, detail::remove_cvref_t<Args>> || ...);
}
// use "DefaultConditionT c, Args... args", not use "DefaultConditionT&& c, Args&&... args"
// to avoid the "c and args..." variables being references
template<class DefaultConditionT, class... Args>
static constexpr auto make_ecs(DefaultConditionT c, Args... args) noexcept
{
detail::ignore_unused(c);
if constexpr (ecs_helper::args_has_match_condition<Args...>())
{
if constexpr (sizeof...(Args) == std::size_t(1))
return detail::to_shared_ptr(ecs_t{ std::move(args)... });
else
return detail::to_shared_ptr(ecs_t{ component_t{std::move(args)...} });
}
else
{
if constexpr (sizeof...(Args) == std::size_t(0))
return detail::to_shared_ptr(ecs_t{ std::move(c), std::move(args)... });
else
return detail::to_shared_ptr(ecs_t{ component_t{std::move(c), std::move(args)...} });
}
}
template<typename C>
static constexpr bool has_rdc() noexcept
{
if constexpr (std::is_base_of_v<component_tag, detail::remove_cvref_t<C>>)
{
return C::has_rdc();
}
else
{
return false;
}
}
template<typename C>
static constexpr bool has_socks5() noexcept
{
if constexpr (std::is_base_of_v<component_tag, detail::remove_cvref_t<C>>)
{
return C::has_socks5();
}
else
{
return false;
}
}
};
}
#endif // !__ASIO2_ECS_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
// No header guard
#if defined(__clang__)
# pragma clang diagnostic pop
#endif
#if defined(__GNUC__) || defined(__GNUG__)
# pragma GCC diagnostic pop
#endif
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_WS_SEND_OP_HPP__
#define __ASIO2_WS_SEND_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/external/asio.hpp>
#include <asio2/external/beast.hpp>
#include <asio2/base/error.hpp>
#include <asio2/http/request.hpp>
#include <asio2/http/response.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class ws_send_op
{
public:
/**
* @brief constructor
*/
ws_send_op() = default;
/**
* @brief destructor
*/
~ws_send_op() = default;
protected:
template<class Data, class Callback>
inline bool _ws_send(Data& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
derive.ws_stream().async_write(asio::buffer(data), make_allocator(derive.wallocator(),
[&derive, p = derive.selfptr(), callback = std::forward<Callback>(callback)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
callback(ec, bytes_sent);
if (ec)
{
// must stop, otherwise re-sending will cause body confusion
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, std::move(p));
}
}
}));
return true;
}
template<bool isRequest, class Body, class Fields, class Callback>
inline bool _ws_send(http::message<isRequest, Body, Fields>& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::ostringstream oss;
oss << data;
std::unique_ptr<std::string> str = std::make_unique<std::string>(oss.str());
auto buffer = asio::buffer(*str);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
derive.ws_stream().async_write(buffer, make_allocator(derive.wallocator(),
[&derive, p = derive.selfptr(), str = std::move(str), callback = std::forward<Callback>(callback)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
callback(ec, bytes_sent);
if (ec)
{
// must stop, otherwise re-sending will cause body confusion
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, std::move(p));
}
}
}));
return true;
}
template<class Body, class Fields, class Callback>
inline bool _ws_send(detail::http_request_impl_t<Body, Fields>& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive._ws_send(data.base(), std::forward<Callback>(callback));
}
template<class Body, class Fields, class Callback>
inline bool _ws_send(detail::http_response_impl_t<Body, Fields>& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive._ws_send(data.base(), std::forward<Callback>(callback));
}
protected:
};
}
#endif // !__ASIO2_WS_SEND_OP_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_EXECUTE_HPP__
#define __ASIO2_HTTP_EXECUTE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/http/detail/http_util.hpp>
#include <asio2/http/detail/http_make.hpp>
#include <asio2/http/detail/http_traits.hpp>
#include <asio2/component/socks/socks5_client.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t, bool Enable = is_http_execute_download_enabled<args_t>::value()>
struct http_execute_impl_bridge;
template<class derived_t, class args_t>
struct http_execute_impl_bridge<derived_t, args_t, false>
{
};
template<class derived_t, class args_t>
struct http_execute_impl_bridge<derived_t, args_t, true>
{
protected:
template<typename String, typename StrOrInt, class Proxy, class Body, class Fields, class Buffer>
static void _execute_with_socks5(
asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
http::parser<false, Body, typename Fields::allocator_type>& parser,
Buffer& buffer,
String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, Proxy&& proxy)
{
auto sk5 = detail::to_shared_ptr(std::forward<Proxy>(proxy));
std::string_view h{ sk5->host() };
std::string_view p{ sk5->port() };
// Look up the domain name
resolver.async_resolve(h, p, [&, s5 = std::move(sk5)]
(const error_code& ec1, const asio::ip::tcp::resolver::results_type& endpoints) mutable
{
if (ec1) { set_last_error(ec1); return; }
// Make the connection on the IP address we get from a lookup
asio::async_connect(socket, endpoints,
[&, s5 = std::move(s5)](const error_code& ec2, const asio::ip::tcp::endpoint&) mutable
{
if (ec2) { set_last_error(ec2); return; }
detail::socks5_client_connect_op
{
ioc,
detail::to_string(std::forward<String >(host)),
detail::to_string(std::forward<StrOrInt>(port)),
socket,
std::move(s5),
[&](error_code ecs5) mutable
{
if (ecs5) { set_last_error(ecs5); return; }
http::async_write(socket, req, [&](const error_code & ec3, std::size_t) mutable
{
if (ec3) { set_last_error(ec3); return; }
// Then start asynchronous reading
http::async_read(socket, buffer, parser,
[&](const error_code& ec4, std::size_t) mutable
{
// Reading completed, assign the read the result to last error
// If the code does not execute into here, the last error
// is the default value timed_out.
set_last_error(ec4);
});
});
}
};
});
});
}
template<typename String, typename StrOrInt, class Body, class Fields, class Buffer>
static void _execute_trivially(
asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
http::parser<false, Body, typename Fields::allocator_type>& parser,
Buffer& buffer,
String&& host, StrOrInt&& port,
http::request<Body, Fields>& req)
{
detail::ignore_unused(ioc);
// Look up the domain name
resolver.async_resolve(std::forward<String>(host), detail::to_string(std::forward<StrOrInt>(port)),
[&](const error_code& ec1, const asio::ip::tcp::resolver::results_type& endpoints) mutable
{
if (ec1) { set_last_error(ec1); return; }
// Make the connection on the IP address we get from a lookup
asio::async_connect(socket, endpoints,
[&](const error_code& ec2, const asio::ip::tcp::endpoint&) mutable
{
if (ec2) { set_last_error(ec2); return; }
http::async_write(socket, req, [&](const error_code & ec3, std::size_t) mutable
{
if (ec3) { set_last_error(ec3); return; }
// Then start asynchronous reading
http::async_read(socket, buffer, parser,
[&](const error_code& ec4, std::size_t) mutable
{
// Reading completed, assign the read the result to last error
// If the code does not execute into here, the last error
// is the default value timed_out.
set_last_error(ec4);
});
});
});
});
}
template<typename String, typename StrOrInt, class Proxy, class Body, class Fields, class Buffer>
static void _execute_impl(
asio::io_context& ioc, asio::ip::tcp::resolver& resolver, asio::ip::tcp::socket& socket,
http::parser<false, Body, typename Fields::allocator_type>& parser,
Buffer& buffer,
String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, Proxy&& proxy)
{
// if has socks5 proxy
if constexpr (std::is_base_of_v<asio2::socks5::option_base,
typename detail::element_type_adapter<detail::remove_cvref_t<Proxy>>::type>)
{
derived_t::_execute_with_socks5(ioc, resolver, socket, parser, buffer
, std::forward<String>(host), std::forward<StrOrInt>(port)
, req
, std::forward<Proxy>(proxy)
);
}
else
{
detail::ignore_unused(proxy);
derived_t::_execute_trivially(ioc, resolver, socket, parser, buffer
, std::forward<String>(host), std::forward<StrOrInt>(port)
, req
);
}
}
public:
template<typename String, typename StrOrInt, class Rep, class Period, class Proxy,
class Body = http::string_body, class Fields = http::fields, class Buffer = beast::flat_buffer>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
http::parser<false, Body, typename Fields::allocator_type> parser;
// First assign default value timed_out to last error
set_last_error(asio::error::timed_out);
// set default result to unknown
parser.get().result(http::status::unknown);
parser.eager(true);
// The io_context is required for all I/O
asio::io_context ioc;
// These objects perform our I/O
asio::ip::tcp::resolver resolver{ ioc };
asio::ip::tcp::socket socket{ ioc };
// This buffer is used for reading and must be persisted
Buffer buffer;
// do work
derived_t::_execute_impl(ioc, resolver, socket, parser, buffer
, std::forward<String>(host), std::forward<StrOrInt>(port)
, req, std::forward<Proxy>(proxy)
);
// timedout run
ioc.run_for(timeout);
error_code ec_ignore{};
// Gracefully close the socket
socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec_ignore);
socket.cancel(ec_ignore);
socket.close(ec_ignore);
return parser.release();
}
// ----------------------------------------------------------------------------------------
template<typename String, typename StrOrInt, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port,
http::request<Body, Fields>& req, std::chrono::duration<Rep, Period> timeout)
{
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port), req, timeout, std::in_place);
}
template<typename String, typename StrOrInt, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, http::request<Body, Fields>& req)
{
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
req, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
template<class Rep, class Period, class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(
http::web_request& req, std::chrono::duration<Rep, Period> timeout)
{
return derived_t::execute(req.url().host(), req.url().port(), req.base(), timeout, std::in_place);
}
template<class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(http::web_request& req)
{
return derived_t::execute(req, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Rep, class Period, class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(std::string_view url,
std::chrono::duration<Rep, Period> timeout)
{
http::web_request req = http::make_request(url);
if (get_last_error())
{
return http::response<Body, Fields>{ http::status::unknown, 11};
}
return derived_t::execute(
req.host(), req.port(), req.base(), timeout, std::in_place);
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Body = http::string_body, class Fields = http::fields>
static inline http::response<Body, Fields> execute(std::string_view url)
{
return derived_t::execute(url, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Rep, class Period,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port,
std::string_view target, std::chrono::duration<Rep, Period> timeout)
{
http::web_request req = http::make_request(host, port, target);
if (get_last_error())
{
return http::response<Body, Fields>{ http::status::unknown, 11};
}
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
req.base(), timeout, std::in_place);
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, std::string_view target)
{
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
target, std::chrono::milliseconds(http_execute_timeout));
}
// ----------------------------------------------------------------------------------------
template<typename String, typename StrOrInt, class Proxy,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, http::request<Body, Fields>& req, Proxy&& proxy)
{
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
req, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
}
// ----------------------------------------------------------------------------------------
template<class Rep, class Period, class Proxy, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(http::web_request& req, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
return derived_t::execute(req.url().host(), req.url().port(), req.base(), timeout,
std::forward<Proxy>(proxy));
}
template<class Proxy, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(http::web_request& req, Proxy&& proxy)
{
return derived_t::execute(req, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Rep, class Period, class Proxy, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(std::string_view url, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
http::web_request req = http::make_request(url);
if (get_last_error())
{
return http::response<Body, Fields>{ http::status::unknown, 11};
}
return derived_t::execute(req.host(), req.port(), req.base(), timeout, std::forward<Proxy>(proxy));
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<class Proxy, class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(std::string_view url, Proxy&& proxy)
{
return derived_t::execute(url, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
}
// ----------------------------------------------------------------------------------------
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Rep, class Period, class Proxy,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port,
std::string_view target, std::chrono::duration<Rep, Period> timeout, Proxy&& proxy)
{
http::web_request req = http::make_request(host, port, target);
if (get_last_error())
{
return http::response<Body, Fields>{ http::status::unknown, 11};
}
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
req.base(), timeout, std::forward<Proxy>(proxy));
}
/**
* @brief blocking execute the http request until it is returned on success or failure
*/
template<typename String, typename StrOrInt, class Proxy,
class Body = http::string_body, class Fields = http::fields>
typename std::enable_if_t<detail::is_character_string_v<detail::remove_cvref_t<String>>
&& detail::http_proxy_checker_v<Proxy>, http::response<Body, Fields>>
static inline execute(String&& host, StrOrInt&& port, std::string_view target, Proxy&& proxy)
{
return derived_t::execute(
std::forward<String>(host), std::forward<StrOrInt>(port),
target, std::chrono::milliseconds(http_execute_timeout), std::forward<Proxy>(proxy));
}
};
template<class derived_t, class args_t = void>
struct http_execute_impl : public http_execute_impl_bridge<derived_t, args_t> {};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTP_EXECUTE_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_UNIX_H
#define BHO_PREDEF_OS_UNIX_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_UNIX`
http://en.wikipedia.org/wiki/Unix[Unix Environment] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `unix` | {predef_detection}
| `+__unix+` | {predef_detection}
| `+_XOPEN_SOURCE+` | {predef_detection}
| `+_POSIX_SOURCE+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_UNIX BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(unix) || defined(__unix) || \
defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE)
# undef BHO_OS_UNIX
# define BHO_OS_UNIX BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_UNIX
# define BHO_OS_UNIX_AVAILABLE
#endif
#define BHO_OS_UNIX_NAME "Unix Environment"
/* tag::reference[]
= `BHO_OS_SVR4`
http://en.wikipedia.org/wiki/UNIX_System_V[SVR4 Environment] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__sysv__+` | {predef_detection}
| `+__SVR4+` | {predef_detection}
| `+__svr4__+` | {predef_detection}
| `+_SYSTYPE_SVR4+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_SVR4 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__sysv__) || defined(__SVR4) || \
defined(__svr4__) || defined(_SYSTYPE_SVR4)
# undef BHO_OS_SVR4
# define BHO_OS_SVR4 BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_SVR4
# define BHO_OS_SVR4_AVAILABLE
#endif
#define BHO_OS_SVR4_NAME "SVR4 Environment"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_UNIX,BHO_OS_UNIX_NAME)
BHO_PREDEF_DECLARE_TEST(BHO_OS_SVR4,BHO_OS_SVR4_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_DINKUMWARE_H
#define BHO_PREDEF_LIBRARY_STD_DINKUMWARE_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_DINKUMWARE`
http://en.wikipedia.org/wiki/Dinkumware[Dinkumware] Standard {CPP} Library.
If available version number as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+_YVALS+`, `+__IBMCPP__+` | {predef_detection}
| `+_CPPLIB_VER+` | {predef_detection}
| `+_CPPLIB_VER+` | V.R.0
|===
*/ // end::reference[]
#define BHO_LIB_STD_DINKUMWARE BHO_VERSION_NUMBER_NOT_AVAILABLE
#if (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER)
# undef BHO_LIB_STD_DINKUMWARE
# if defined(_CPPLIB_VER)
# define BHO_LIB_STD_DINKUMWARE BHO_PREDEF_MAKE_10_VVRR(_CPPLIB_VER)
# else
# define BHO_LIB_STD_DINKUMWARE BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_LIB_STD_DINKUMWARE
# define BHO_LIB_STD_DINKUMWARE_AVAILABLE
#endif
#define BHO_LIB_STD_DINKUMWARE_NAME "Dinkumware"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_DINKUMWARE,BHO_LIB_STD_DINKUMWARE_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_TCP_CLIENT_HPP__
#define __ASIO2_TCP_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/client.hpp>
#include <asio2/tcp/impl/tcp_keepalive_cp.hpp>
#include <asio2/tcp/impl/tcp_send_op.hpp>
#include <asio2/tcp/impl/tcp_recv_op.hpp>
namespace asio2::detail
{
struct template_args_tcp_client
{
static constexpr bool is_session = false;
static constexpr bool is_client = true;
static constexpr bool is_server = false;
using socket_t = asio::ip::tcp::socket;
using buffer_t = asio::streambuf;
using send_data_t = std::string_view;
using recv_data_t = std::string_view;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class derived_t, class args_t = template_args_tcp_client>
class tcp_client_impl_t
: public client_impl_t <derived_t, args_t>
, public tcp_keepalive_cp <derived_t, args_t>
, public tcp_send_op <derived_t, args_t>
, public tcp_recv_op <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using super = client_impl_t <derived_t, args_t>;
using self = tcp_client_impl_t<derived_t, args_t>;
using args_type = args_t;
using buffer_type = typename args_t::buffer_t;
using send_data_t = typename args_t::send_data_t;
using recv_data_t = typename args_t::recv_data_t;
public:
/**
* @brief constructor
*/
explicit tcp_client_impl_t(
std::size_t init_buf_size = tcp_frame_size,
std::size_t max_buf_size = max_buffer_size,
std::size_t concurrency = 1
)
: super(init_buf_size, max_buf_size, concurrency)
, tcp_keepalive_cp<derived_t, args_t>()
, tcp_send_op <derived_t, args_t>()
, tcp_recv_op <derived_t, args_t>()
{
this->set_connect_timeout(std::chrono::milliseconds(tcp_connect_timeout));
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit tcp_client_impl_t(
std::size_t init_buf_size,
std::size_t max_buf_size,
Scheduler&& scheduler
)
: super(init_buf_size, max_buf_size, std::forward<Scheduler>(scheduler))
, tcp_keepalive_cp<derived_t, args_t>()
, tcp_send_op <derived_t, args_t>()
, tcp_recv_op <derived_t, args_t>()
{
this->set_connect_timeout(std::chrono::milliseconds(tcp_connect_timeout));
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit tcp_client_impl_t(Scheduler&& scheduler)
: tcp_client_impl_t(tcp_frame_size, max_buffer_size, std::forward<Scheduler>(scheduler))
{
}
// -- Support initializer_list causes the code of inherited classes to be not concised
//template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
//explicit tcp_client_impl_t(
// std::size_t init_buf_size,
// std::size_t max_buf_size,
// std::initializer_list<Scheduler> scheduler
//)
// : tcp_client_impl_t(init_buf_size, max_buf_size, std::vector<Scheduler>{std::move(scheduler)})
//{
//}
//template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
//explicit tcp_client_impl_t(std::initializer_list<Scheduler> scheduler)
// : tcp_client_impl_t(tcp_frame_size, max_buffer_size, std::move(scheduler))
//{
//}
/**
* @brief destructor
*/
~tcp_client_impl_t()
{
this->stop();
}
/**
* @brief start the client, blocking connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
* @param args - The delimiter condition.Valid value types include the following:
* char,std::string,std::string_view,
* function:std::pair<iterator, bool> match_condition(iterator begin, iterator end),
* asio::transfer_at_least,asio::transfer_exactly
* more details see asio::read_until
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& port, Args&&... args)
{
return this->derived().template _do_connect<false>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs(asio::transfer_at_least(1), std::forward<Args>(args)...));
}
/**
* @brief start the client, asynchronous connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
* @param args - The delimiter condition.Valid value types include the following:
* char,std::string,std::string_view,
* function:std::pair<iterator, bool> match_condition(iterator begin, iterator end),
* asio::transfer_at_least,asio::transfer_exactly
* more details see asio::read_until
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool async_start(String&& host, StrOrInt&& port, Args&&... args)
{
return this->derived().template _do_connect<true>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs(asio::transfer_at_least(1), std::forward<Args>(args)...));
}
/**
* @brief stop the client
* You can call this function in the communication thread and anywhere to stop the client.
* If this function is called in the communication thread, it will post a asynchronous
* event into the event queue, then return immediately.
* If this function is called not in the communication thread, it will blocking forever
* util the client is stopped completed.
*/
inline void stop()
{
if (this->is_iopool_stopped())
return;
derived_t& derive = this->derived();
derive.io().unregobj(&derive);
// use promise to get the result of stop
std::promise<state_t> promise;
std::future<state_t> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[this, p = std::move(promise)]() mutable
{
p.set_value(this->state().load());
}
};
// if user call stop in the recv callback, use post event to executed a async event.
derive.post_event([&derive, this_ptr = derive.selfptr(), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
// first close the reconnect timer
derive._stop_reconnect_timer();
derive._do_disconnect(asio::error::operation_aborted, derive.selfptr(), defer_event
{
[&derive, this_ptr = std::move(this_ptr), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
derive._do_stop(asio::error::operation_aborted, std::move(this_ptr), defer_event
{
[pg = std::move(pg)](event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
});
}, std::move(g)
});
});
// use this to ensure the client is stopped completed when the stop is called not in
// the io_context thread
while (!derive.running_in_this_thread())
{
std::future_status status = future.wait_for(std::chrono::milliseconds(100));
if (status == std::future_status::ready)
{
ASIO2_ASSERT(future.get() == state_t::stopped);
break;
}
else
{
if (derive.get_thread_id() == std::thread::id{})
break;
if (derive.io().context().stopped())
break;
}
}
this->stop_iopool();
}
public:
/**
* @brief bind recv listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void(std::string_view data)
*/
template<class F, class ...C>
inline derived_t & bind_recv(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::recv,
observer_t<std::string_view>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind connect listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called after the client connection completed, whether successful or unsuccessful
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_connect(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::connect,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind disconnect listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called before the client is ready to disconnect
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_disconnect(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::disconnect,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind init listener,we should set socket options at here
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_init(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::init,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<bool IsAsync, typename String, typename StrOrInt, typename C>
inline bool _do_connect(String&& host, StrOrInt&& port, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = this->derived();
// if log is enabled, init the log first, otherwise when "Too many open files" error occurs,
// the log file will be created failed too.
#if defined(ASIO2_ENABLE_LOG)
asio2::detail::get_logger();
#endif
this->start_iopool();
if (!this->is_iopool_started())
{
set_last_error(asio::error::operation_aborted);
return false;
}
asio::dispatch(derive.io().context(), [&derive, this_ptr = derive.selfptr()]() mutable
{
detail::ignore_unused(this_ptr);
// init the running thread id
derive.io().init_thread_id();
});
// use promise to get the result of async connect
std::promise<error_code> promise;
std::future<error_code> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[promise = std::move(promise)]() mutable
{
promise.set_value(get_last_error());
}
};
// if user call start in the recv callback, use post event to executed a async event.
derive.post_event(
[this, this_ptr = derive.selfptr(), ecs = std::move(ecs),
host = std::forward<String>(host), port = std::forward<StrOrInt>(port), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
derived_t& derive = this->derived();
defer_event chain
{
[pg = std::move(pg)] (event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
};
state_t expected = state_t::stopped;
if (!derive.state_.compare_exchange_strong(expected, state_t::starting))
{
// if the state is not stopped, set the last error to already_started
set_last_error(asio::error::already_started);
return;
}
// must read/write ecs in the io_context thread.
derive.ecs_ = ecs;
clear_last_error();
derive.io().regobj(&derive);
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_reconnect_timer_called_ = false;
this->is_post_reconnect_timer_called_ = false;
this->is_stop_connect_timeout_timer_called_ = false;
this->is_disconnect_called_ = false;
#endif
// convert to string maybe throw some exception.
this->host_ = detail::to_string(std::move(host));
this->port_ = detail::to_string(std::move(port));
super::start();
derive._do_init(ecs);
// ecs init
derive._rdc_init(ecs);
derive._socks5_init(ecs);
derive.template _start_connect<IsAsync>(std::move(this_ptr), std::move(ecs), std::move(chain));
});
if constexpr (IsAsync)
{
set_last_error(asio::error::in_progress);
return true;
}
else
{
if (!derive.io().running_in_this_thread())
{
set_last_error(future.get());
// beacuse here code is running in the user thread, not in the io_context thread,
// so, even if the client is start successed, but if the server disconnect this
// client after connect success, and when code run to here, the client's state
// maybe stopping, so if we return derive.is_started();, the return value maybe
// false, but we did connect to the server is successfully.
return static_cast<bool>(!get_last_error());
}
else
{
set_last_error(asio::error::in_progress);
}
// if the state is stopped , the return value is "is_started()".
// if the state is stopping, the return value is false, the last error is already_started
// if the state is starting, the return value is false, the last error is already_started
// if the state is started , the return value is true , the last error is already_started
return derive.is_started();
}
}
template<typename C>
inline void _do_init(std::shared_ptr<ecs_t<C>>&) noexcept
{
#if defined(ASIO2_ENABLE_LOG)
// Used to test whether the behavior of different compilers is consistent
static_assert(tcp_send_op<derived_t, args_t>::template has_member_dgram<self>::value,
"The behavior of different compilers is not consistent");
#endif
if constexpr (std::is_same_v<typename ecs_t<C>::condition_lowest_type, use_dgram_t>)
this->dgram_ = true;
else
this->dgram_ = false;
}
template<typename C, typename DeferEvent>
inline void _do_start(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
this->derived().update_alive_time();
this->derived().reset_connect_time();
this->derived()._start_recv(std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename DeferEvent>
inline void _handle_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(this->state_ == state_t::stopped);
ASIO2_LOG_DEBUG("tcp_client::_handle_disconnect: {} {}", ec.value(), ec.message());
this->derived()._rdc_stop();
// should we close the socket in handle disconnect function? otherwise when send
// data failed, will cause the _do_disconnect function be called, then cause the
// auto reconnect executed, and then the _post_recv will be return with some error,
// and the _post_recv will cause the auto reconnect executed again.
// can't use push event to close the socket, beacuse when used with websocket,
// the websocket's async_close will be called, and the chain will passed into
// the async_close, but the async_close will cause the chain interrupted, and
// we don't know when the async_close will be completed, if another push event
// was called during async_close executing, then here push event will after
// the another event in the queue.
// call shutdown again, beacuse the do shutdown maybe not called, eg: when
// protocol error is checked in the mqtt or http, then the do disconnect
// maybe called directly.
// the socket maybe closed already in the connect timeout timer.
if (this->socket().is_open())
{
error_code ec_linger{}, ec_ignore{};
asio::socket_base::linger lnger{};
this->socket().lowest_layer().get_option(lnger, ec_linger);
// call socket's close function to notify the _handle_recv function response with
// error > 0 ,then the socket can get notify to exit
// Call shutdown() to indicate that you will not write any more data to the socket.
if (!ec_linger && !(lnger.enabled() == true && lnger.timeout() == 0))
{
this->socket().shutdown(asio::socket_base::shutdown_both, ec_ignore);
}
// if the socket is basic_stream with rate limit, we should call the cancel,
// otherwise the rate timer maybe can't canceled, and cause the io_context
// can't stopped forever, even if the socket is closed already.
this->socket().cancel(ec_ignore);
// Call close,otherwise the _handle_recv will never return
this->socket().close(ec_ignore);
}
super::_handle_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _do_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
// When use call client.stop in the io_context thread, then the iopool is not stopped,
// but this client is stopped, When client.stop is called again in the not io_context
// thread, then this client state is stopped.
ASIO2_ASSERT(this->state_ == state_t::stopped);
this->derived()._post_stop(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _post_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
// All pending sending events will be cancelled after enter the callback below.
this->derived().disp_event([this, ec, this_ptr = std::move(this_ptr), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
set_last_error(ec);
defer_event chain(std::move(e), std::move(g));
// call the base class stop function
super::stop();
// call CRTP polymorphic stop
this->derived()._handle_stop(ec, std::move(this_ptr), std::move(chain));
}, chain.move_guard());
}
template<typename DeferEvent>
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
detail::ignore_unused(ec, this_ptr, chain);
ASIO2_ASSERT(this->state_ == state_t::stopped);
}
template<typename C, typename DeferEvent>
inline void _start_recv(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
// Connect succeeded. post recv request.
asio::dispatch(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
using condition_lowest_type = typename ecs_t<C>::condition_lowest_type;
detail::ignore_unused(chain);
if constexpr (!std::is_same_v<condition_lowest_type, asio2::detail::hook_buffer_t>)
{
this->derived().buffer().consume(this->derived().buffer().size());
}
else
{
std::ignore = true;
}
this->derived()._post_recv(std::move(this_ptr), std::move(ecs));
}));
}
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
return this->derived()._tcp_send(data, std::forward<Callback>(callback));
}
template<class Data>
inline send_data_t _rdc_convert_to_send_data(Data& data) noexcept
{
auto buffer = asio::buffer(data);
return send_data_t{ reinterpret_cast<
std::string_view::const_pointer>(buffer.data()),buffer.size() };
}
template<class Invoker>
inline void _rdc_invoke_with_none(const error_code& ec, Invoker& invoker)
{
if (invoker)
invoker(ec, send_data_t{}, recv_data_t{});
}
template<class Invoker>
inline void _rdc_invoke_with_recv(const error_code& ec, Invoker& invoker, recv_data_t data)
{
if (invoker)
invoker(ec, send_data_t{}, data);
}
template<class Invoker>
inline void _rdc_invoke_with_send(const error_code& ec, Invoker& invoker, send_data_t data)
{
if (invoker)
invoker(ec, data, recv_data_t{});
}
protected:
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._tcp_post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _handle_recv(const error_code & ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._tcp_handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}
inline void _fire_init()
{
// the _fire_init must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(!get_last_error());
this->listener_.notify(event_type::init);
}
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, data);
this->derived()._rdc_handle_recv(this_ptr, ecs, data);
}
template<typename C>
inline void _fire_connect(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
// the _fire_connect must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_disconnect_called_ == false);
#endif
if (!get_last_error())
{
this->derived()._rdc_start(this_ptr, ecs);
}
this->listener_.notify(event_type::connect);
}
inline void _fire_disconnect(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_disconnect must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
this->is_disconnect_called_ = true;
#endif
detail::ignore_unused(this_ptr);
this->listener_.notify(event_type::disconnect);
}
protected:
bool dgram_ = false;
#if defined(_DEBUG) || defined(DEBUG)
bool is_disconnect_called_ = false;
#endif
};
}
namespace asio2
{
using tcp_client_args = detail::template_args_tcp_client;
template<class derived_t, class args_t>
using tcp_client_impl_t = detail::tcp_client_impl_t<derived_t, args_t>;
/**
* @brief tcp client template class
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
template<class derived_t>
class tcp_client_t : public detail::tcp_client_impl_t<derived_t, detail::template_args_tcp_client>
{
public:
using detail::tcp_client_impl_t<derived_t, detail::template_args_tcp_client>::tcp_client_impl_t;
};
/**
* @brief tcp client
* If this object is created as a shared_ptr like std::shared_ptr<asio2::tcp_client> client;
* you must call the client->stop() manual when exit, otherwise maybe cause memory leaks.
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
class tcp_client : public tcp_client_t<tcp_client>
{
public:
using tcp_client_t<tcp_client>::tcp_client_t;
};
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct tcp_rate_client_args : public tcp_client_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
template<class derived_t>
class tcp_rate_client_t : public asio2::tcp_client_impl_t<derived_t, tcp_rate_client_args>
{
public:
using asio2::tcp_client_impl_t<derived_t, tcp_rate_client_args>::tcp_client_impl_t;
};
class tcp_rate_client : public asio2::tcp_rate_client_t<tcp_rate_client>
{
public:
using asio2::tcp_rate_client_t<tcp_rate_client>::tcp_rate_client_t;
};
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_TCP_CLIENT_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_SPARC_H
#define BHO_PREDEF_ARCHITECTURE_SPARC_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_SPARC`
http://en.wikipedia.org/wiki/SPARC[SPARC] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__sparc__+` | {predef_detection}
| `+__sparc+` | {predef_detection}
| `+__sparcv9+` | 9.0.0
| `+__sparc_v9__+` | 9.0.0
| `+__sparcv8+` | 8.0.0
| `+__sparc_v8__+` | 8.0.0
|===
*/ // end::reference[]
#define BHO_ARCH_SPARC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__sparc__) || defined(__sparc)
# undef BHO_ARCH_SPARC
# if !defined(BHO_ARCH_SPARC) && (defined(__sparcv9) || defined(__sparc_v9__))
# define BHO_ARCH_SPARC BHO_VERSION_NUMBER(9,0,0)
# endif
# if !defined(BHO_ARCH_SPARC) && (defined(__sparcv8) || defined(__sparc_v8__))
# define BHO_ARCH_SPARC BHO_VERSION_NUMBER(8,0,0)
# endif
# if !defined(BHO_ARCH_SPARC)
# define BHO_ARCH_SPARC BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_SPARC
# define BHO_ARCH_SPARC_AVAILABLE
#endif
#if BHO_ARCH_SPARC
# if BHO_ARCH_SPARC >= BHO_VERSION_NUMBER(9,0,0)
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
# else
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#define BHO_ARCH_SPARC_NAME "SPARC"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_SPARC,BHO_ARCH_SPARC_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : mqtt_cpp/include/mqtt/broker/session_state.hpp
*/
#ifndef __ASIO2_MQTT_SESSION_STATE_HPP__
#define __ASIO2_MQTT_SESSION_STATE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <algorithm>
#include <set>
#include <optional>
#include <chrono>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/detail/mqtt_inflight_message.hpp>
#include <asio2/mqtt/detail/mqtt_offline_message.hpp>
#include <asio2/mqtt/detail/mqtt_shared_target.hpp>
namespace asio2::mqtt
{
class session_state
{
public:
session_state()
{
}
~session_state()
{
}
void clean()
{
//inflight_messages_.clear();
offline_messages_.clear();
qos2_publish_processed_.clear();
//shared_targets_.erase(*this);
//unsubscribe_all();
}
void exactly_once_start(mqtt::two_byte_integer::value_type packet_id)
{
qos2_publish_processed_.insert(packet_id);
}
bool exactly_once_processing(mqtt::two_byte_integer::value_type packet_id) const
{
return qos2_publish_processed_.find(packet_id) != qos2_publish_processed_.end();
}
void exactly_once_finish(mqtt::two_byte_integer::value_type packet_id)
{
qos2_publish_processed_.erase(packet_id);
}
protected:
//std::shared_ptr<asio::steady_timer> will_expiry_timer_;
//std::optional<MQTT_NS::will> will_value_;
//sub_con_map& subs_map_;
//shared_target& shared_targets_;
//con_sp_t con_;
std::string_view client_id_;
std::optional<std::chrono::steady_clock::duration> will_delay_;
std::optional<std::chrono::steady_clock::duration> session_expiry_interval_;
std::shared_ptr<asio::steady_timer> session_expiry_timer_;
//inflight_messages inflight_messages_;
std::set<mqtt::two_byte_integer::value_type> qos2_publish_processed_;
offline_messages<omnode> offline_messages_;
//std::set<sub_con_map::handle> handles_; // to efficient remove
};
}
#endif // !__ASIO2_MQTT_SESSION_STATE_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_CYGWIN_H
#define BHO_PREDEF_OS_CYGWIN_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_CYGWIN`
http://en.wikipedia.org/wiki/Cygwin[Cygwin] evironment.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__CYGWIN__+` | {predef_detection}
| `CYGWIN_VERSION_API_MAJOR`, `CYGWIN_VERSION_API_MINOR` | V.R.0
|===
*/ // end::reference[]
#define BHO_OS_CYGWIN BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__CYGWIN__) \
)
# include <cygwin/version.h>
# undef BHO_OS_CYGWIN
# define BHO_OS_CYGWIN \
BHO_VERSION_NUMBER(CYGWIN_VERSION_API_MAJOR,\
CYGWIN_VERSION_API_MINOR, 0)
#endif
#if BHO_OS_CYGWIN
# define BHO_OS_CYGWIN_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_CYGWIN_NAME "Cygwin"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_CYGWIN,BHO_OS_CYGWIN_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* boost/uuid
* https://lowrey.me/guid-generation-in-c-11/
* https://github.com/mariusbancila/stduuid
* https://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c
*/
#ifndef __ASIO2_UUID_IMPL_HPP__
#define __ASIO2_UUID_IMPL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstring>
#include <cstdint>
#include <cstddef>
#include <string>
#include <random>
#include <limits>
#include <memory>
#include <array>
#include <algorithm>
#include <iterator>
namespace asio2
{
/**
* UUID Generation in C++11
*/
class uuid
{
protected:
struct random_enginer
{
std::seed_seq sseq_;
std::mt19937 engine_;
std::uniform_int_distribution<std::uint32_t> distribution_;
template<class InputIt>
explicit random_enginer(InputIt begin, InputIt end)
: sseq_(begin, end)
, engine_(sseq_)
{
}
inline std::uint32_t get()
{
return distribution_(engine_);
}
};
public:
uuid()
{
std::random_device rd{};
std::array<std::uint32_t, std::mt19937::state_size> sb{};
std::generate(std::begin(sb), std::end(sb), std::ref(rd));
this->random_enginer_ = std::make_unique<random_enginer>(std::begin(sb), std::end(sb));
}
~uuid() = default;
uuid(const uuid&) = delete;
uuid(uuid&&) noexcept = default;
uuid& operator=(const uuid&) = delete;
uuid& operator=(uuid&&) noexcept = default;
inline uuid& operator()()
{
return generate();
}
inline uuid& next()
{
return generate();
}
inline uuid& generate()
{
for (std::size_t i = 0; i < sizeof(data); i += sizeof(std::uint32_t))
{
*reinterpret_cast<std::uint32_t*>(data + i) = this->random_enginer_->get();
}
// set variant
// must be 0b10xxxxxx
*(data + 8) &= 0xBF;
*(data + 8) |= 0x80;
// set version
// must be 0b0100xxxx
*(data + 6) &= 0x4F; //0b01001111
*(data + 6) |= 0x40; //0b01000000
return (*this);
}
/**
* @brief convert the uuid bytes to std::string
*/
inline std::string str(bool upper = false, bool group = true) noexcept
{
std::string result;
if (group)
{
// 00000000-0000-0000-0000-000000000000
result.reserve(36);
for (std::size_t i = 0; i < sizeof(data); )
{
int n = static_cast<int>(result.size());
if (n == 8 || n == 13 || n == 18 || n == 23)
{
result += '-';
continue;
}
const int hi = ((*(data + i)) >> 4) & 0x0F;
result += to_char(hi, upper);
const int lo = (*(data + i)) & 0x0F;
result += to_char(lo, upper);
++i;
}
}
else
{
// 00000000000000000000000000000000
result.reserve(32);
for (std::size_t i = 0; i < sizeof(data); ++i)
{
const int hi = ((*(data + i)) >> 4) & 0x0F;
result += to_char(hi, upper);
const int lo = (*(data + i)) & 0x0F;
result += to_char(lo, upper);
}
}
return result;
}
// This is equivalent to boost::hash_range(u.begin(), u.end());
inline std::size_t hash() noexcept
{
std::size_t seed = 0;
for (std::size_t i = 0; i < sizeof(data); ++i)
{
seed ^= static_cast<std::size_t>(*(data + i)) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
enum class variant_type
{
ncs, // NCS backward compatibility
rfc, // defined in RFC 4122 document
microsoft, // Microsoft Corporation backward compatibility
future // future definition
};
inline variant_type variant() const noexcept
{
// variant is stored in octet 7
// which is index 8, since indexes count backwards
unsigned char octet7 = data[8]; // octet 7 is array index 8
if ((octet7 & 0x80) == 0x00)
{
// 0b0xxxxxxx
return variant_type::ncs;
}
else if ((octet7 & 0xC0) == 0x80)
{
// 0b10xxxxxx
return variant_type::rfc;
}
else if ((octet7 & 0xE0) == 0xC0)
{
// 0b110xxxxx
return variant_type::microsoft;
}
else
{
//assert( (octet7 & 0xE0) == 0xE0 ) // 0b111xxxx
return variant_type::future;
}
}
enum class version_type
{
unknown = 0, // only possible for nil or invalid uuids
time_based = 1, // The time-based version specified in RFC 4122
dce_security = 2, // DCE Security version, with embedded POSIX UIDs.
name_based_md5 = 3, // The name-based version specified in RFS 4122 with MD5 hashing
random_number_based = 4, // The randomly or pseudo-randomly generated version specified in RFS 4122
name_based_sha1 = 5 // The name-based version specified in RFS 4122 with SHA1 hashing
};
inline version_type version() const noexcept
{
// version is stored in octet 9
// which is index 6, since indexes count backwards
uint8_t octet9 = data[6];
if ((octet9 & 0xF0) == 0x10)
{
return version_type::time_based;
}
else if ((octet9 & 0xF0) == 0x20)
{
return version_type::dce_security;
}
else if ((octet9 & 0xF0) == 0x30)
{
return version_type::name_based_md5;
}
else if ((octet9 & 0xF0) == 0x40)
{
return version_type::random_number_based;
}
else if ((octet9 & 0xF0) == 0x50)
{
return version_type::name_based_sha1;
}
else
{
return version_type::unknown;
}
}
inline std::string short_uuid(int bytes)
{
// use base64 chars as the short uuid chars
static std::string const base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
std::string result;
result.reserve(bytes);
std::uniform_int_distribution<int> d(0, int(base64_chars.size() - 1));
for (int i = 0; i < bytes; ++i)
{
result += base64_chars[d(this->random_enginer_->engine_)];
}
return result;
}
template <typename CharT>
constexpr inline unsigned char hex2char(CharT const ch)
{
if (ch >= static_cast<CharT>('0') && ch <= static_cast<CharT>('9'))
return static_cast<unsigned char>(ch - static_cast<CharT>('0'));
if (ch >= static_cast<CharT>('a') && ch <= static_cast<CharT>('f'))
return static_cast<unsigned char>(10 + ch - static_cast<CharT>('a'));
if (ch >= static_cast<CharT>('A') && ch <= static_cast<CharT>('F'))
return static_cast<unsigned char>(10 + ch - static_cast<CharT>('A'));
return 0;
}
template <typename CharT>
constexpr inline bool is_hex(CharT const ch)
{
return
(ch >= static_cast<CharT>('0') && ch <= static_cast<CharT>('9')) ||
(ch >= static_cast<CharT>('a') && ch <= static_cast<CharT>('f')) ||
(ch >= static_cast<CharT>('A') && ch <= static_cast<CharT>('F'));
}
protected:
inline char to_char(int i, bool upper) noexcept
{
if (i <= 9)
{
return static_cast<char>('0' + i);
}
else
{
return static_cast<char>((upper ? 'A' : 'a') + (i - 10));
}
}
public:
std::uint8_t data[16]{};
protected:
std::unique_ptr<random_enginer> random_enginer_;
};
}
#endif // !__ASIO2_UUID_IMPL_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : mqtt_cpp/include/mqtt/packet_id_manager.hpp
*/
#ifndef __ASIO2_MQTT_ID_MGR_HPP__
#define __ASIO2_MQTT_ID_MGR_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <set>
#include <limits>
#include <atomic>
namespace asio2::mqtt
{
template<typename T>
class idmgr;
template<typename Integer>
class idmgr<std::atomic<Integer>>
{
public:
using id_type = std::remove_cv_t<std::remove_reference_t<Integer>>;
static_assert(std::is_integral_v<id_type>);
idmgr() = default;
~idmgr() = default;
/**
* @brief Get a new unique id
*/
inline id_type get() noexcept
{
id_type r = id_.fetch_add(static_cast<id_type>(1));
while (r == 0)
{
r = id_.fetch_add(static_cast<id_type>(1));
}
return r;
}
/**
* @brief Checks whether contains the given id.
*/
inline bool contains(id_type id) const noexcept
{
return (id_.load() == id);
}
/**
* @brief Release the id.
*/
inline void release(id_type id) noexcept
{
std::ignore = id;
}
/**
* @brief Clear all ids.
*/
inline void clear() noexcept
{
id_.store(0);
}
private:
std::atomic<id_type> id_{ static_cast<id_type>(1) };
};
template<typename Integer>
class idmgr<std::set<Integer>>
{
public:
using id_type = std::remove_cv_t<std::remove_reference_t<Integer>>;
static_assert(std::is_integral_v<id_type>);
idmgr() = default;
~idmgr() = default;
/**
* @brief Get a new unique id, return 0 if failed.
*/
id_type get()
{
if (used_.size() == (std::numeric_limits<id_type>::max)())
return static_cast<id_type>(0);
id_type id;
if (used_.empty())
{
id = static_cast<id_type>(1);
}
else
{
id = *(used_.rbegin());
for (;;)
{
id++;
if (id == static_cast<id_type>(0))
id++;
if (used_.find(id) == used_.end())
break;
}
}
used_.emplace(id);
return id;
}
/**
* @brief Checks whether contains the given id.
*/
bool contains(id_type id)
{
return (used_.find(id) != used_.end());
}
/**
* @brief Release the id.
*/
void release(id_type id)
{
used_.erase(id);
}
/**
* @brief Clear all ids.
*/
void clear()
{
used_.clear();
}
private:
std::set<id_type> used_{};
};
}
#endif // !__ASIO2_MQTT_ID_MGR_HPP__
<file_sep>/*
Copyright <NAME>, 2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_PLAT_WINDOWS_UWP_H
#define BHO_PREDEF_PLAT_WINDOWS_UWP_H
#include <asio2/bho/predef/make.h>
#include <asio2/bho/predef/os/windows.h>
#include <asio2/bho/predef/version_number.h>
/* tag::reference[]
= `BHO_PLAT_WINDOWS_UWP`
http://docs.microsoft.com/windows/uwp/[Universal Windows Platform]
is available if the current development environment is capable of targeting
UWP development.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__MINGW64_VERSION_MAJOR+` from `+_mingw.h+` | `>= 3`
| `VER_PRODUCTBUILD` from `ntverp.h` | `>= 9200`
|===
*/ // end::reference[]
#define BHO_PLAT_WINDOWS_UWP BHO_VERSION_NUMBER_NOT_AVAILABLE
#define BHO_PLAT_WINDOWS_SDK_VERSION BHO_VERSION_NUMBER_NOT_AVAILABLE
#if BHO_OS_WINDOWS
// MinGW (32-bit), WinCE, and wineg++ don't have a ntverp.h header
#if !defined(__MINGW32__) && !defined(_WIN32_WCE) && !defined(__WINE__)
# include <ntverp.h>
# undef BHO_PLAT_WINDOWS_SDK_VERSION
# define BHO_PLAT_WINDOWS_SDK_VERSION BHO_VERSION_NUMBER(0, 0, VER_PRODUCTBUILD)
#endif
// 9200 is Windows SDK 8.0 from ntverp.h which introduced family support
#if ((BHO_PLAT_WINDOWS_SDK_VERSION >= BHO_VERSION_NUMBER(0, 0, 9200)) || \
(defined(__MINGW64__) && __MINGW64_VERSION_MAJOR >= 3))
# undef BHO_PLAT_WINDOWS_UWP
# define BHO_PLAT_WINDOWS_UWP BHO_VERSION_NUMBER_AVAILABLE
#endif
#endif
#if BHO_PLAT_WINDOWS_UWP
# define BHO_PLAT_WINDOWS_UWP_AVAILABLE
# include <asio2/bho/predef/detail/platform_detected.h>
# include <winapifamily.h> // Windows SDK
#endif
#define BHO_PLAT_WINDOWS_UWP_NAME "Universal Windows Platform"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_WINDOWS_UWP, BHO_PLAT_WINDOWS_UWP_NAME)
<file_sep>#include <asio2/asio2.hpp>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/tcp/tcp_client.hpp>
#include <iostream>
class my_tcp_session : public asio2::tcp_session_t<my_tcp_session>
{
public:
//using asio2::tcp_session_t<my_tcp_session>::tcp_session_t;
template<class... Args>
my_tcp_session(Args&&... args) : asio2::tcp_session_t<my_tcp_session>(std::forward<Args>(args)...)
{
uuid = "custom string";
}
// ... user custom properties and functions
std::string uuid;
/**
* @brief Pre process the data before send it.
* You can overload this function in a derived class to implement additional
* processing of the data. eg: encrypt data with a custom encryption algorithm.
*/
template<class T>
inline auto data_filter_before_send(T&& data)
{
std::string_view sv = asio2::to_string_view(asio::buffer(data));
ASIO2_ASSERT(sv == "<0123456789abcdefghijklmnopqrstovwxyz>");
for (const char& c : sv)
{
const_cast<char&>(c) ^= 'X';
}
return std::forward<T>(data);
}
/**
* @brief Pre process the data before recv callback was called.
* You can overload this function in a derived class to implement additional
* processing of the data. eg: decrypt data with a custom encryption algorithm.
*/
inline std::string_view data_filter_before_recv(std::string_view data)
{
for (const char& c : data)
{
const_cast<char&>(c) ^= 'X';
}
ASIO2_ASSERT(data == "<0123456789abcdefghijklmnopqrstovwxyz>");
return data;
}
};
using my_tcp_server1 = asio2::tcp_server_t<my_tcp_session>;
class my_tcp_server2 : public asio2::tcp_server_t<my_tcp_session>
{
public:
using asio2::tcp_server_t<my_tcp_session>::tcp_server_t;
};
class my_tcp_client1 : public asio2::tcp_client_t<my_tcp_client1>
{
public:
// ... user custom properties and functions
std::string uuid;
template<class T>
inline auto data_filter_before_send(T&& data)
{
std::string_view sv = asio2::to_string_view(asio::buffer(data));
ASIO2_ASSERT(sv == "<0123456789abcdefghijklmnopqrstovwxyz>");
for (const char& c : sv)
{
const_cast<char&>(c) ^= 'X';
}
return std::forward<T>(data);
}
inline std::string_view data_filter_before_recv(std::string_view data)
{
for (const char& c : data)
{
const_cast<char&>(c) ^= 'X';
}
ASIO2_ASSERT(data == "<0123456789abcdefghijklmnopqrstovwxyz>");
return data;
}
};
class my_tcp_client2 : public asio2::tcp_client
{
public:
// ... user custom properties and functions
std::string uuid;
};
int main()
{
my_tcp_server1 my_server1;
my_server1.bind_connect([&](std::shared_ptr<my_tcp_session>& session_ptr)
{
session_ptr->uuid = std::to_string(session_ptr->hash_key());
}).bind_recv([&](std::shared_ptr<my_tcp_session>& session_ptr, std::string_view data)
{
asio2::ignore_unused(session_ptr, data);
ASIO2_ASSERT(session_ptr->uuid == std::to_string(session_ptr->hash_key()));
ASIO2_ASSERT(data == "<0123456789abcdefghijklmnopqrstovwxyz>");
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
});
my_server1.start("0.0.0.0", 9981);
// --------------------------------------------------------------------------------
my_tcp_client1 my_client1;
my_client1.bind_connect([&]()
{
if (!asio2::get_last_error())
my_client1.async_send("<0123456789abcdefghijklmnopqrstovwxyz>");
}).bind_recv([&](std::string_view data)
{
//printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
ASIO2_ASSERT(data == "<0123456789abcdefghijklmnopqrstovwxyz>");
my_client1.async_send(data);
});
my_client1.async_start("127.0.0.1", 9981);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_WINDOWS_H
#define BHO_PREDEF_OS_WINDOWS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_WINDOWS`
http://en.wikipedia.org/wiki/Category:Microsoft_Windows[Microsoft Windows] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+_WIN32+` | {predef_detection}
| `+_WIN64+` | {predef_detection}
| `+__WIN32__+` | {predef_detection}
| `+__TOS_WIN__+` | {predef_detection}
| `+__WINDOWS__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_WINDOWS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(_WIN32) || defined(_WIN64) || \
defined(__WIN32__) || defined(__TOS_WIN__) || \
defined(__WINDOWS__) \
)
# undef BHO_OS_WINDOWS
# define BHO_OS_WINDOWS BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_WINDOWS
# define BHO_OS_WINDOWS_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_WINDOWS_NAME "Microsoft Windows"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_WINDOWS,BHO_OS_WINDOWS_NAME)
<file_sep>#include <asio2/udp/udp_server.hpp>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8035";
asio2::udp_server server;
server.bind_recv([](std::shared_ptr<asio2::udp_session> & session_ptr, std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}).bind_connect([](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_start([&]()
{
if (asio2::get_last_error())
printf("start udp server failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("start udp server success : %s %u\n",
server.listen_address().c_str(), server.listen_port());
}).bind_stop([&]()
{
printf("stop udp server : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_init([&]()
{
//// Join the multicast group. you can set this option in the on_init(_fire_init) function.
//server.acceptor().set_option(
// // for ipv6, the host must be a ipv6 address like 0::0
// asio::ip::multicast::join_group(asio::ip::make_address("fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:1234")));
// // for ipv4, the host must be a ipv4 address like 0.0.0.0
// //asio::ip::multicast::join_group(asio::ip::make_address("172.16.58.3")));
});
server.start(host, port);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
Copyright 2017 <NAME>, III
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_PLAT_CLOUDABI_H
#define BHO_PREDEF_PLAT_CLOUDABI_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_PLAT_CLOUDABI`
https://github.com/NuxiNL/cloudabi[CloudABI] platform.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__CloudABI__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_PLAT_CLOUDABI BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__CloudABI__)
# undef BHO_PLAT_CLOUDABI
# define BHO_PLAT_CLOUDABI BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_PLAT_CLOUDABI
# define BHO_PLAT_CLOUDABI_AVAILABLE
# include <asio2/bho/predef/detail/platform_detected.h>
#endif
#define BHO_PLAT_CLOUDABI_NAME "CloudABI"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_CLOUDABI,BHO_PLAT_CLOUDABI_NAME)
<file_sep>/*
Copyright <NAME>, 2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_PLAT_WINDOWS_SERVER_H
#define BHO_PREDEF_PLAT_WINDOWS_SERVER_H
#include <asio2/bho/predef/make.h>
#include <asio2/bho/predef/os/windows.h>
#include <asio2/bho/predef/platform/windows_uwp.h>
#include <asio2/bho/predef/version_number.h>
/* tag::reference[]
= `BHO_PLAT_WINDOWS_SERVER`
https://docs.microsoft.com/en-us/windows/uwp/get-started/universal-application-platform-guide[UWP]
for Windows Server development.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `WINAPI_FAMILY == WINAPI_FAMILY_SERVER` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_PLAT_WINDOWS_SERVER BHO_VERSION_NUMBER_NOT_AVAILABLE
#if BHO_OS_WINDOWS && \
defined(WINAPI_FAMILY_SERVER) && WINAPI_FAMILY == WINAPI_FAMILY_SERVER
# undef BHO_PLAT_WINDOWS_SERVER
# define BHO_PLAT_WINDOWS_SERVER BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_PLAT_WINDOWS_SERVER
# define BHO_PLAT_WINDOWS_SERVER_AVAILABLE
# include <asio2/bho/predef/detail/platform_detected.h>
#endif
#define BHO_PLAT_WINDOWS_SERVER_NAME "Windows Server"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_WINDOWS_SERVER,BHO_PLAT_WINDOWS_SERVER_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : mqtt_cpp/include/mqtt/broker/inflight_message.hpp
*/
#ifndef __ASIO2_MQTT_INFLIGHT_MESSAGE_HPP__
#define __ASIO2_MQTT_INFLIGHT_MESSAGE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <algorithm>
#include <variant>
#include <asio2/base/iopool.hpp>
#include <asio2/mqtt/message.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
namespace asio2::mqtt
{
//class inflight_messages
//{
//public:
// void insert(
// store_message_variant msg,
// any life_keeper,
// std::shared_ptr<asio::steady_timer> tim_message_expiry
// )
// {
// messages_.emplace_back(
// std::move(msg),
// std::move(life_keeper),
// std::move(tim_message_expiry)
// );
// }
// void send_all_messages(endpoint_t& ep)
// {
// for (auto const& ifm : messages_)
// {
// ifm.send(ep);
// }
// }
// void clear()
// {
// messages_.clear();
// }
// template <typename Tag>
// decltype(auto) get()
// {
// return messages_.get<Tag>();
// }
// template <typename Tag>
// decltype(auto) get() const
// {
// return messages_.get<Tag>();
// }
//protected:
// using mi_inflight_message = mi::multi_index_container<
// imnode,
// mi::indexed_by<
// mi::sequenced<
// mi::tag<tag_seq>
// >,
// mi::ordered_unique<
// mi::tag<tag_pid>,
// BOOST_MULTI_INDEX_CONST_MEM_FUN(imnode, packet_id_t, packet_id)
// >,
// mi::ordered_non_unique<
// mi::tag<tag_tim>,
// BOOST_MULTI_INDEX_MEMBER(imnode, std::shared_ptr<asio::steady_timer>, message_expiry_timer_)
// >
// >
// >;
// mi_inflight_message messages_;
//};
//struct imnode
//{
// template<class Message>
// imnode(Message&& msg,
// any life_keeper,
// std::shared_ptr<asio::steady_timer> tim_message_expiry
// )
// : message(std::forward<Message>(msg))
// , life_keeper_{ std::move(life_keeper) }
// , message_expiry_timer_{ std::move(tim_message_expiry) }
// {}
// packet_id_t packet_id() const
// {
// return std::visit(make_lambda_visitor(
// [](auto const& m) {
// return m.packet_id();
// }
// ),
// msg_
// );
// }
// void send(endpoint_t& ep) const
// {
// optional<store_message_variant> msg_opt;
// if (message_expiry_timer_) {
// MQTT_NS::visit(
// make_lambda_visitor(
// [&](v5::basic_publish_message<sizeof(packet_id_t)> const& m) {
// auto updated_msg = m;
// auto d =
// std::chrono::duration_cast<std::chrono::seconds>(
// message_expiry_timer_->expiry() - std::chrono::steady_clock::now()
// ).count();
// if (d < 0) d = 0;
// updated_msg.update_prop(
// v5::property::message_expiry_interval(
// static_cast<uint32_t>(d)
// )
// );
// msg_opt.emplace(std::move(updated_msg));
// },
// [](auto const&) {
// }
// ),
// msg_
// );
// }
// // packet_id_exhausted never happen because inflight message has already
// // allocated packet_id at the previous connection.
// // In send_store_message(), packet_id is registered.
// ep.send_store_message(msg_opt ? msg_opt.value() : msg_, life_keeper_);
// }
//protected:
// mqtt::message message;
// //any life_keeper_;
// std::shared_ptr<asio::steady_timer> message_expiry_timer_;
//};
}
#endif // !__ASIO2_MQTT_INFLIGHT_MESSAGE_HPP__
<file_sep>#include <asio2/tcp/tcp_client.hpp>
int main(int argc, char* argv[])
{
asio2::iopool iopool;
iopool.start();
int client_count = 10000;
if (argc > 1)
client_count = std::stoi(argv[1]);
for (int i = 0; i < client_count; i++)
{
std::shared_ptr<asio2::tcp_client> client = std::make_shared<asio2::tcp_client>(iopool.get(i));
client->bind_connect([pclt = client.get()]()
{
std::string strmsg(1024, 'A');
if (!asio2::get_last_error())
pclt->async_send(std::move(strmsg));
}).bind_recv([pclt = client.get()](std::string_view data)
{
pclt->async_send(asio::buffer(data)); // no allocate memory
//pclt->async_send(data); // allocate memory
});
client->async_start("127.0.0.1", "18081");
}
while (std::getchar() != '\n');
iopool.stop();
return 0;
}
<file_sep># asio做tcp的自动拆包时,asio的match condition如何使用的详细说明
首先说点基础概念:因为tcp是流式的,所以如果你自己定制有协议(一般如数据头,命令,数据长度,数据内容,校验),
在tcp下发送你自己的协议的数据包时,就必须要考虑tcp的封包和拆包的问题了。
目前asio使用的人也比较多了吧,我觉得asio对tcp的封包和拆包的支持和设计做的很不错,如果你用asio去做一次对
tcp的拆包,会发现真的是相当方便的。
我在asio的基础上包装了一个网络框架asio2(见[https://github.com/zhllxt/asio2](https://github.com/zhllxt/asio2)或[https://gitee.com/zhllxt/asio2](https://gitee.com/zhllxt/asio2)),里面包含了对TCP数据拆包功能的完整支持(当然内部还是用的asio本身来实现的),按指定的单个字符,按字符串,按用户自定义协议 对数据自动进行拆包,最近发现有些人问起asio的这个自动拆包match condition如何使用的问题,而网上也搜不到match condition的详细使用说明或资料,于是这里写一下,给大家提供点思路。详细代码和说明如下:
```cpp
// 假定协议格式为:数据头、数据长度、数据内容
// 类型如下:
// int head; // 数据头 假定数据头的值固定为0x01020304
// int length; // 数据长度
// ... // 数据内容 数据内容的长度是可变的
// 接下来示意用asio的match condition如何来进行解析
using iterator = asio::buffers_iterator<asio::streambuf::const_buffers_type>;
std::pair<iterator, bool> match_role(iterator begin, iterator end)
{
// 当asio内部接收到数据后,将数据存储在它的缓冲区中,然后就会调用你的match_role函数,
// 参数begin表示数据的起始位置,也就是数据的开头
// 参数end表示数据的结尾向后偏移一个字节,类似字符串char*的结尾会向后偏移一个字节,那个\0
// 注意end虽然是数据的尾部,但它只是所接收到的数据的尾部,并不一定是你的整包数据的尾部
// 这里我来举个例子仔细说明:
// 1、假定你构造好了一包完整的数据,如下:
// 0x01 02 03 04 00 00 00 01 41
// <----头-----> <--长度---> <-数据-> 41是字符A
// 2、发送该包数据
// 3、对端开始接收数据
// 我们拿极端情况举例:假定对端第1次只收到1个字节0x01,asio内部会把这1个字节放到它的缓冲区中,
// 缓冲区内此时有1个字节:0x01 此时begin就是0x01这个数据的指针地址,end是0x01这个位置向后偏移
// 一个字节;对端第2次又只收到1个字节0x02,asio内部会把字节0x02接着放到缓冲区中,缓冲区中此
// 时有2个字节:0x01 02 此时begin还是0x01这个数据的指针地址,而end是0x02这个位置向后偏移一个
// 字节。依次类推...,记住begin永远是数据的开始位置
// 那么这个iterator是个什么东西呢?简单理解,你可以把它当成一个char*来用就行了,有++自增,有*取值
// 接下来开始实例怎么解析:
iterator i = begin; // 首先把begin保存到一个临时变量i中,你可以简单理解为char * i = begin;
// 用end减去begin就是当前缓冲区中的数据长度,我们先看这个长度够不够最小的长度,最小的长度就是head
// 类型的长度4个字节 加上 length类型的长度4个字节,共8个字节,如果当前缓冲区中的数据不够8个字节,
// 就还得接收下一次的数据
if (end - begin < 4 + 4)
{
// 返回值的含义:首先必须返回一个pair类型
// pair的第一个参数要填一个iterator,可以理解为填一个char*即可,表示满足你要求的那一包数据的结尾位置
// pair的第二个参数表示当前缓冲区的数据是否满足你的要求,如果满足就是true,不满足就是false
// 如果pair的第二个参数你填了false,就意味着告诉asio当前缓冲区中的数据还不够,你再给我接着接收,
// 当下一次又接收到数据时,asio又会“再次调用”这里的match_role函数,而这个“再次调用”的第一个参
// 数begin就是此时你在pair的第一个参数中填写的这个地址值。
// 如果pair的第二个参数你填了true,意味着当前缓冲区的数据已经满足要求了,会发生下面的事情:
// 当这个pair返回到asio的内部之后,asio内部会做两个操作:1、把从“begin到pair的第一个参数”这一段
// 数据通过回调函数发给你,2、你在你的回调函数里处理这些数据过后,asio就会把这段数据清理掉了,然后下
// 一次再进到这里的match_role函数时,参数begin就是刚才你通过pair第一个参数所给的那个数据的位置了,
// 这里由于长度不足,所以我们把pair的第一个参数填为begin,表示下一次解析时还从begin这个位置开始解析,
// 第二个参数填为false,表示当前缓冲区中的数据不满足要求,需要接着接收
return std::pair(begin, false);
}
// 最小长度够了,接着判断数据头head是不是0x01020304
// i.operator->() 表示取出i里面数据的指针,也就是将i变为了const char *类型
// 取出char*指针再强转为int*指针,再取*号,就转换成一个整数了,注意asio2已经处理过大小端的问题了,你不用考虑
// 强制转换时的大小端问题
int head = *(reinterpret_cast<const int*>(i.operator->()));
if (head != 0x01020304)
{
// 如果head不等于0x01020304则说明数据非法,说明客户端可能根本不是你自己的客户端,如果是你自己的客户
// 端,而且按照协议发的数据,那么是不可能出现这种情况的,所以此时最好直接断开这个连接,怎么断开呢?
// 往后面看有关于这个问题的说明。
return std::pair(begin, true);
}
// 最小长度和数据头都对了,开始判断数据内容的长度
i += 4; // i向后偏移4个字节,到length这个位置处
int length = *(reinterpret_cast<const int*>(i.operator->()));// 求出这包数据的内容的长度
// end - begin等于总长度,再减去8表示真正的数据的内容的长度
// 如果内容长度小于求出的长度,则还需要接着接收,所以这里还是返回pair(begin, false)
if (end - begin - 8 < length)
return std::pair(begin, false);
// 现在最小长度和数据头和内容长度都对了,
i += 4; // i再向后偏移4个字节,到真正的数据内容这个位置处
// 返回值中的i + length也就是这一包数据的结尾处了,true表示数据满足要求了,这样asio就会把从begin到i + length
// 这个指针位置处的数据全部返回给你,当下一次asio再次调用这里的match_role时,传入的begin就是i + length向后偏移
// 一个字节的位置了,相当于把下一包数据的开始位置传给你了
return std::pair(i + length, true);
}
// 下面是我asio2原demo中的示例,这里用了while循环,其实用不用while循环没有任何差别,或者说用while循环完全没有任何
// 意义,因为看代码就知道这个while循环只可能执行一次,那我为什么还写了个while呢,这好像是参考哪里的示例不记得了,
// 没怎么管就直接搬上来了,这段示例代码我选择也放上来而没有删除,主要给大家多个参考吧。
// 还有要注意这下面的解析所用的协议和我上面举例用的协议是不同的,上面协议中的包头和长度都是int类型的,而下面不是的。
// 当然大家可能会有这种经验:如果一次性接收了多包完整的数据,一般解析数据时是要用while循环解析的,否则会出问题,
// 但asio如果一次性接收到多包完整的数据的话,这里是不需要用while循环来解析的,因为每返回一次pair(i + length, true)
// 之后,asio内部后面的代码中会接着再调用这里的match_role函数,于是又再次开始解析,相当于asio帮你做了那个while循环
//while (i != end)
//{
// if (*i != '#')
// return std::pair(begin, true); // head character is not #, return and kill the client
// i++;
// if (i == end) break;
// int length = std::uint8_t(*i); // get content length
// i++;
// if (i == end) break;
// if (end - i >= length)
// return std::pair(i + length, true);
// break;
//}
//return std::pair(begin, false);
```
**还有一个比较常见的问题是:使用了match condition后,如果发现接收的数据非法,怎么关闭连接呢?**
```cpp
class match_role
{
public:
explicit match_role(char c) : c_(c) {}
template <typename Iterator>
std::pair<Iterator, bool> operator()(Iterator begin, Iterator end) const
{
Iterator i = begin;
while (i != end)
{
// 发现数据不正确后,如何关闭非法连接?
// 方法1:直接调用连接的关闭函数即可,但是这有个前提,这个match condition必须是一个类,
// 而不能是一个全局函数(asio的match condition可以是一个类,也可以是一个函数),而且要
// 在这个类中添加一个init函数来保存连接指针,具体请看下面的init函数说明。
if (*i != c_)
{
session_ptr_->stop();
break;
}
// 方法2:直接返回std::pair(begin, true);然后在bind_recv的回调函数里判断,
// 如果接收到的数据长度是0就关闭连接。
// 返回值pair的第二个参数true表示数据解析成功,而pair的第一个参数给的是begin表示数据的长度是0。
// 于是bind_recv的回调函数就会被触发,在bind_recv回调函数中判断一下数据长度,如果长度是0就表
// 示数据非法,直接关闭连接即可。(具体代码请参考示例程序tcp_server_custom.cpp):
if (*i != c_)
return std::pair(begin, true);
i++;
if (i == end) break;
int length = std::uint8_t(*i); // get content length
i++;
if (i == end) break;
if (end - i >= length)
return std::pair(i + length, true);
break;
}
return std::pair(begin, false);
}
// 当连接刚刚创建完成之后,框架会自动调用这个init函数,你可以在这个函数里把这个连接
// 对应的session_ptr保存起来,留着后面使用
void init(std::shared_ptr<asio2::tcp_session>& session_ptr)
{
session_ptr_ = session_ptr;
}
private:
char c_;
// 这里直接用智能指针不会导致循环引用
std::shared_ptr<asio2::tcp_session> session_ptr_;
};
server.bind_recv([&](auto & session_ptr, std::string_view s)
{
// 在这里判断数据长度是不是0,如果是0就表示数据非法,直接关闭连接
if (s.size() == 0)
{
printf("close illegal client : %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port());
// 关闭连接
session_ptr->stop();
return;
}
printf("recv : %u %.*s\n", (unsigned)s.size(), (int)s.size(), s.data());
});
```
关键词:tcp 自动 封包 拆包 asio match condition role asio2
### 最后编辑于:2022-11-04
<file_sep>// Copyright (C) <NAME> 2003
// Copyright (C) <NAME> 2003
//
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Digital Mars C++ compiler setup:
#define BHO_COMPILER __DMC_VERSION_STRING__
#define BHO_HAS_LONG_LONG
#define BHO_HAS_PRAGMA_ONCE
#if !defined(BHO_STRICT_CONFIG)
#define BHO_NO_MEMBER_TEMPLATE_FRIENDS
#define BHO_NO_OPERATORS_IN_NAMESPACE
#define BHO_NO_UNREACHABLE_RETURN_DETECTION
#define BHO_NO_SFINAE
#define BHO_NO_USING_TEMPLATE
#define BHO_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL
#endif
//
// has macros:
#define BHO_HAS_DIRENT_H
#define BHO_HAS_STDINT_H
#define BHO_HAS_WINTHREADS
#if (__DMC__ >= 0x847)
#define BHO_HAS_EXPM1
#define BHO_HAS_LOG1P
#endif
//
// Is this really the best way to detect whether the std lib is in namespace std?
//
#ifdef __cplusplus
#include <cstddef>
#endif
#if !defined(__STL_IMPORT_VENDOR_CSTD) && !defined(_STLP_IMPORT_VENDOR_CSTD)
# define BHO_NO_STDC_NAMESPACE
#endif
// check for exception handling support:
#if !defined(_CPPUNWIND) && !defined(BHO_NO_EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
#endif
//
// C++0x features
//
#define BHO_NO_CXX11_AUTO_DECLARATIONS
#define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#define BHO_NO_CXX11_CHAR16_T
#define BHO_NO_CXX11_CHAR32_T
#define BHO_NO_CXX11_CONSTEXPR
#define BHO_NO_CXX11_DECLTYPE
#define BHO_NO_CXX11_DECLTYPE_N3276
#define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#define BHO_NO_CXX11_DELETED_FUNCTIONS
#define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#define BHO_NO_CXX11_EXTERN_TEMPLATE
#define BHO_NO_CXX11_HDR_INITIALIZER_LIST
#define BHO_NO_CXX11_LAMBDAS
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_RAW_LITERALS
#define BHO_NO_CXX11_RVALUE_REFERENCES
#define BHO_NO_CXX11_SCOPED_ENUMS
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_CXX11_SFINAE_EXPR
#define BHO_NO_CXX11_STATIC_ASSERT
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_UNICODE_LITERALS
#define BHO_NO_CXX11_VARIADIC_TEMPLATES
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#define BHO_NO_CXX11_USER_DEFINED_LITERALS
#define BHO_NO_CXX11_ALIGNAS
#define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#define BHO_NO_CXX11_INLINE_NAMESPACES
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_FINAL
#define BHO_NO_CXX11_OVERRIDE
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_UNRESTRICTED_UNION
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
#if (__DMC__ <= 0x840)
#error "Compiler not supported or configured - please reconfigure"
#endif
//
// last known and checked version is ...:
#if (__DMC__ > 0x848)
# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown compiler version - please run the configure tests and report the results"
# endif
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* KCP MTU , UDP PACKET MAX LENGTH 576
*/
#ifndef __ASIO2_KCP_UTIL_HPP__
#define __ASIO2_KCP_UTIL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <memory>
#include <future>
#include <utility>
#include <string>
#include <string_view>
#include <chrono>
#include <asio2/external/predef.h>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/udp/detail/ikcp.h>
namespace asio2::detail::kcp
{
// struct psdhdr
// {
// unsigned long saddr;
// unsigned long daddr;
// char mbz;
// char ptcl;
// unsigned short tcpl;
// };
//
// struct tcphdr
// {
// std::uint16_t th_sport; /* source port */
// std::uint16_t th_dport; /* destination port */
// std::uint32_t th_seq; /* sequence number */
// std::uint32_t th_ack; /* acknowledgement number */
//#if IWORDS_BIG_ENDIAN
// std::uint16_t th_off : 4; /* data offset */
// std::uint16_t th_x2 : 6; /* (unused) */
//#else
// std::uint16_t th_x2 : 6; /* (unused) */
// std::uint16_t th_off : 4; /* data offset */
//#endif
// std::uint16_t thf_urg : 1; /* flags : Urgent Pointer Field Significant */
// std::uint16_t thf_ack : 1; /* flags : Acknowledgement field significant */
// std::uint16_t thf_psh : 1; /* flags : Push Function */
// std::uint16_t thf_rst : 1; /* flags : Reset the connection */
// std::uint16_t thf_syn : 1; /* flags : Synchronize sequence numbers */
// std::uint16_t thf_fin : 1; /* flags : No more data from sender */
// std::uint16_t th_win; /* window */
// std::uint16_t th_sum; /* checksum */
// std::uint16_t th_urp; /* urgent pointer */
// std::uint32_t th_option : 24; /* option */
// std::uint32_t th_padding : 8; /* padding */
// };
struct kcphdr
{
std::uint32_t th_seq{};
std::uint32_t th_ack{};
union
{
std::uint8_t byte{};
#if ASIO2_ENDIAN_BIG_BYTE
struct
{
std::uint8_t urg : 1;
std::uint8_t ack : 1;
std::uint8_t psh : 1;
std::uint8_t rst : 1;
std::uint8_t syn : 1;
std::uint8_t fin : 1;
std::uint8_t padding : 2;
} bits;
#else
struct
{
std::uint8_t padding : 2;
std::uint8_t fin : 1;
std::uint8_t syn : 1;
std::uint8_t rst : 1;
std::uint8_t psh : 1;
std::uint8_t ack : 1;
std::uint8_t urg : 1;
} bits;
#endif
} th_flag {};
std::uint8_t th_padding{};
std::uint16_t th_sum {};
static constexpr std::size_t required_size() noexcept
{
return (0
+ sizeof(std::uint32_t) // std::uint32_t th_seq;
+ sizeof(std::uint32_t) // std::uint32_t th_ack;
+ sizeof(std::uint8_t ) // std::uint8_t th_flag;
+ sizeof(std::uint8_t ) // std::uint8_t th_padding;
+ sizeof(std::uint16_t) // std::uint16_t th_sum;
);
}
};
struct kcp_deleter
{
inline void operator()(ikcpcb* p) const noexcept { kcp::ikcp_release(p); };
};
namespace
{
std::string to_string(kcphdr& hdr)
{
std::string s/*{ kcphdr::required_size(), '\0' }*/;
s.resize(kcphdr::required_size());
std::string::pointer p = s.data();
detail::write(p, hdr.th_seq );
detail::write(p, hdr.th_ack );
detail::write(p, hdr.th_flag.byte);
detail::write(p, hdr.th_padding );
detail::write(p, hdr.th_sum );
return s;
}
kcphdr to_kcphdr(std::string_view s) noexcept
{
kcphdr hdr{};
std::string_view::pointer p = const_cast<std::string_view::pointer>(s.data());
if (s.size() >= kcphdr::required_size())
{
hdr.th_seq = detail::read<std::uint32_t>(p);
hdr.th_ack = detail::read<std::uint32_t>(p);
hdr.th_flag.byte = detail::read<std::uint8_t >(p);
hdr.th_padding = detail::read<std::uint8_t >(p);
hdr.th_sum = detail::read<std::uint16_t>(p);
}
return hdr;
}
unsigned short checksum(unsigned short * addr, int size) noexcept
{
long sum = 0;
while (size > 1)
{
sum += *(unsigned short*)addr++;
size -= 2;
}
if (size > 0)
{
std::uint8_t left_over[2] = { 0 };
left_over[0] = static_cast<std::uint8_t>(*addr);
sum += *(unsigned short*)left_over;
}
while (sum >> 16)
sum = (sum & 0xffff) + (sum >> 16);
return static_cast<unsigned short>(~sum);
}
inline bool is_kcphdr_syn(std::string_view s) noexcept
{
if (s.size() != kcphdr::required_size())
return false;
kcphdr hdr = to_kcphdr(s);
if (!(
!hdr.th_flag.bits.urg && !hdr.th_flag.bits.ack && !hdr.th_flag.bits.psh &&
!hdr.th_flag.bits.rst && hdr.th_flag.bits.syn && !hdr.th_flag.bits.fin))
return false;
return (hdr.th_sum == checksum((unsigned short *)(s.data()),
static_cast<int>(kcphdr::required_size() - sizeof(kcphdr::th_sum))));
}
inline bool is_kcphdr_synack(std::string_view s, std::uint32_t seq, bool ignore_seq = false) noexcept
{
if (s.size() != kcphdr::required_size())
return false;
kcphdr hdr = to_kcphdr(s);
if (!(
!hdr.th_flag.bits.urg && hdr.th_flag.bits.ack && !hdr.th_flag.bits.psh &&
!hdr.th_flag.bits.rst && hdr.th_flag.bits.syn && !hdr.th_flag.bits.fin))
return false;
if (!ignore_seq && hdr.th_ack != seq + 1)
return false;
return (hdr.th_sum == checksum((unsigned short *)(s.data()),
static_cast<int>(kcphdr::required_size() - sizeof(kcphdr::th_sum))));
}
inline bool is_kcphdr_ack(std::string_view s, std::uint32_t seq, bool ignore_seq = false) noexcept
{
if (s.size() != kcphdr::required_size())
return false;
kcphdr hdr = to_kcphdr(s);
if (!(
!hdr.th_flag.bits.urg && hdr.th_flag.bits.ack && !hdr.th_flag.bits.psh &&
!hdr.th_flag.bits.rst && !hdr.th_flag.bits.syn && !hdr.th_flag.bits.fin))
return false;
if (!ignore_seq && hdr.th_ack != seq + 1)
return false;
return (hdr.th_sum == checksum((unsigned short *)(s.data()),
static_cast<int>(kcphdr::required_size() - sizeof(kcphdr::th_sum))));
}
inline bool is_kcphdr_fin(std::string_view s) noexcept
{
if (s.size() != kcphdr::required_size())
return false;
kcphdr hdr = to_kcphdr(s);
if (!(
!hdr.th_flag.bits.urg && !hdr.th_flag.bits.ack && !hdr.th_flag.bits.psh &&
!hdr.th_flag.bits.rst && !hdr.th_flag.bits.syn && hdr.th_flag.bits.fin))
return false;
return (hdr.th_sum == checksum((unsigned short *)(s.data()),
static_cast<int>(kcphdr::required_size() - sizeof(kcphdr::th_sum))));
}
inline kcphdr make_kcphdr_syn(std::uint32_t conv, std::uint32_t seq)
{
kcphdr hdr{};
hdr.th_seq = seq;
hdr.th_ack = conv;
hdr.th_flag.bits.syn = 1;
std::string s = kcp::to_string(hdr);
hdr.th_sum = checksum(reinterpret_cast<unsigned short *>(s.data()),
static_cast<int>(kcphdr::required_size() - sizeof(kcphdr::th_sum)));
return hdr;
}
inline kcphdr make_kcphdr_synack(std::uint32_t conv, std::uint32_t ack)
{
kcphdr hdr{};
hdr.th_seq = conv;
hdr.th_ack = ack + 1;
hdr.th_flag.bits.ack = 1;
hdr.th_flag.bits.syn = 1;
std::string s = kcp::to_string(hdr);
hdr.th_sum = checksum(reinterpret_cast<unsigned short *>(s.data()),
static_cast<int>(kcphdr::required_size() - sizeof(kcphdr::th_sum)));
return hdr;
}
inline kcphdr make_kcphdr_ack(std::uint32_t ack)
{
kcphdr hdr{};
hdr.th_ack = ack + 1;
hdr.th_flag.bits.ack = 1;
std::string s = kcp::to_string(hdr);
hdr.th_sum = checksum(reinterpret_cast<unsigned short *>(s.data()),
static_cast<int>(kcphdr::required_size() - sizeof(kcphdr::th_sum)));
return hdr;
}
inline kcphdr make_kcphdr_fin(std::uint32_t seq)
{
kcphdr hdr{};
hdr.th_seq = seq;
hdr.th_flag.bits.fin = 1;
std::string s = kcp::to_string(hdr);
hdr.th_sum = checksum(reinterpret_cast<unsigned short *>(s.data()),
static_cast<int>(kcphdr::required_size() - sizeof(kcphdr::th_sum)));
return hdr;
}
[[maybe_unused]] void ikcp_reset(ikcpcb* kcp)
{
//#### ikcp_release without free
assert(kcp);
if (kcp) {
IKCPSEG* seg;
while (!iqueue_is_empty(&kcp->snd_buf)) {
seg = iqueue_entry(kcp->snd_buf.next, IKCPSEG, node);
iqueue_del(&seg->node);
ikcp_segment_delete(kcp, seg);
}
while (!iqueue_is_empty(&kcp->rcv_buf)) {
seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node);
iqueue_del(&seg->node);
ikcp_segment_delete(kcp, seg);
}
while (!iqueue_is_empty(&kcp->snd_queue)) {
seg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node);
iqueue_del(&seg->node);
ikcp_segment_delete(kcp, seg);
}
while (!iqueue_is_empty(&kcp->rcv_queue)) {
seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node);
iqueue_del(&seg->node);
ikcp_segment_delete(kcp, seg);
}
//if (kcp->buffer) {
// ikcp_free(kcp->buffer);
//}
if (kcp->acklist) {
ikcp_free(kcp->acklist);
}
kcp->nrcv_buf = 0;
kcp->nsnd_buf = 0;
kcp->nrcv_que = 0;
kcp->nsnd_que = 0;
kcp->ackcount = 0;
//kcp->buffer = NULL;
kcp->acklist = NULL;
//ikcp_free(kcp);
}
//#### ikcp_create without malloc
if (kcp) {
//ikcpcb* kcp = (ikcpcb*)ikcp_malloc(sizeof(struct IKCPCB));
//if (kcp == NULL) return NULL;
//kcp->conv = conv;
//kcp->user = user;
kcp->snd_una = 0;
kcp->snd_nxt = 0;
kcp->rcv_nxt = 0;
kcp->ts_recent = 0;
kcp->ts_lastack = 0;
kcp->ts_probe = 0;
kcp->probe_wait = 0;
//kcp->snd_wnd = IKCP_WND_SND; // ikcp_wndsize
//kcp->rcv_wnd = IKCP_WND_RCV; // ikcp_wndsize
kcp->rmt_wnd = IKCP_WND_RCV;
kcp->cwnd = 0;
kcp->incr = 0;
kcp->probe = 0;
//kcp->mtu = IKCP_MTU_DEF; // ikcp_setmtu
//kcp->mss = kcp->mtu - IKCP_OVERHEAD; // ikcp_setmtu
kcp->stream = 0;
//kcp->buffer = (char*)ikcp_malloc((kcp->mtu + IKCP_OVERHEAD) * 3);
//if (kcp->buffer == NULL) {
// ikcp_free(kcp);
// return NULL;
//}
iqueue_init(&kcp->snd_queue);
iqueue_init(&kcp->rcv_queue);
iqueue_init(&kcp->snd_buf);
iqueue_init(&kcp->rcv_buf);
kcp->nrcv_buf = 0;
kcp->nsnd_buf = 0;
kcp->nrcv_que = 0;
kcp->nsnd_que = 0;
kcp->state = 0;
kcp->acklist = NULL;
kcp->ackblock = 0;
kcp->ackcount = 0;
kcp->rx_srtt = 0;
kcp->rx_rttval = 0;
kcp->rx_rto = IKCP_RTO_DEF;
//kcp->rx_minrto = IKCP_RTO_MIN; // ikcp_nodelay
kcp->current = 0;
//kcp->interval = IKCP_INTERVAL; // ikcp_nodelay
kcp->ts_flush = IKCP_INTERVAL;
//kcp->nodelay = 0; // ikcp_nodelay
kcp->updated = 0;
//kcp->logmask = 0;
kcp->ssthresh = IKCP_THRESH_INIT;
//kcp->fastresend = 0; // ikcp_nodelay
//kcp->fastlimit = IKCP_FASTACK_LIMIT;
//kcp->nocwnd = 0; // ikcp_nodelay
kcp->xmit = 0;
//kcp->dead_link = IKCP_DEADLINK;
//kcp->output = NULL;
//kcp->writelog = NULL;
}
}
}
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_KCP_UTIL_HPP__
<file_sep>#ifndef ASIO2_ENABLE_SSL
#define ASIO2_ENABLE_SSL
#endif
#include <asio2/websocket/wss_server.hpp>
#include <iostream>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8007";
asio2::wss_server server;
// use verify_fail_if_no_peer_cert, the client must specified a cert
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
server.set_cert_file(
"../../cert/ca.crt",
"../../cert/server.crt",
"../../cert/server.key",
"123456");
if (asio2::get_last_error())
std::cout << "load cert files failed: " << asio2::last_error_msg() << std::endl;
server.set_dh_file("../../cert/dh1024.pem");
if (asio2::get_last_error())
std::cout << "load dh files failed: " << asio2::last_error_msg() << std::endl;
server.bind_accept([](std::shared_ptr<asio2::wss_session>& session_ptr)
{
// accept callback maybe has error like "Too many open files", etc...
if (!asio2::get_last_error())
{
// how to set custom websocket response data :
// the decorator is just a callback function, when the upgrade response is send,
// this callback will be called.
session_ptr->ws_stream().set_option(
websocket::stream_base::decorator([session_ptr](websocket::response_type& rep)
{
// @see /asio2/example/ssl/websocket/client/ssl_websocket_client.cpp
const websocket::request_type& req = session_ptr->get_upgrade_request();
auto it = req.find(http::field::authorization);
if (it != req.end())
rep.set(http::field::authentication_results, "200 OK");
else
rep.set(http::field::authentication_results, "401 unauthorized");
}));
}
else
{
printf("error occurred when calling the accept function : %d %s\n",
asio2::get_last_error_val(), asio2::get_last_error_msg().data());
}
}).bind_recv([](std::shared_ptr<asio2::wss_session> & session_ptr, std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}).bind_connect([](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([](auto & session_ptr)
{
asio2::ignore_unused(session_ptr);
printf("client leave : %s\n", asio2::last_error_msg().c_str());
}).bind_handshake([](auto & session_ptr)
{
printf("client handshake : %s %u %d %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_upgrade([](auto & session_ptr)
{
printf("client upgrade : %s %u %d %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
// how to get the upgrade request request data :
// @see /asio2/example/ssl/websocket/client/ssl_websocket_client.cpp
const websocket::request_type& req = session_ptr->get_upgrade_request();
beast::string_view auth = req.at(http::field::authorization);
std::cout << auth << std::endl;
ASIO2_ASSERT(auth == "<PASSWORD>");
}).bind_start([&]()
{
if (asio2::get_last_error())
printf("start websocket ssl server failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("start websocket ssl server success : %s %u\n",
server.listen_address().c_str(), server.listen_port());
}).bind_stop([&]()
{
printf("stop websocket ssl server : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.start(host, port);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_UTIL_HPP__
#define __ASIO2_HTTP_UTIL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cctype>
#include <sstream>
#include <memory>
#include <asio2/external/asio.hpp>
#include <asio2/external/beast.hpp>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/http/detail/http_parser.h>
#include <asio2/http/detail/mime_types.hpp>
#include <asio2/http/multipart.hpp>
#include <asio2/util/string.hpp>
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::http
#else
namespace boost::beast::http
#endif
{
namespace
{
// Percent-encoding : https://en.wikipedia.org/wiki/Percent-encoding
// ---- RFC 3986 section 2.2 Reserved Characters (January 2005)
// !#$&'()*+,/:;=?@[]
//
// ---- RFC 3986 section 2.3 Unreserved Characters (January 2005)
// ABCDEFGHIJKLMNOPQRSTUVWXYZ
// abcdefghijklmnopqrstuvwxyz
// 0123456789-_.~
//
//
// http://www.baidu.com/query?key=x!#$&'()*+,/:;=?@[ ]-_.~%^{}\"|<>`\\y
//
// C# System.Web.HttpUtility.UrlEncode
// http%3a%2f%2fwww.baidu.com%2fquery%3fkey%3dx!%23%24%26%27()*%2b%2c%2f%3a%3b%3d%3f%40%5b+%5d-_.%7e%25%5e%7b%7d%22%7c%3c%3e%60%5cy
//
// java.net.URLEncoder.encode
// http%3A%2F%2Fwww.baidu.com%2Fquery%3Fkey%3Dx%21%23%24%26%27%28%29*%2B%2C%2F%3A%3B%3D%3F%40%5B+%5D-_.%7E%25%5E%7B%7D%5C%22%7C%3C%3E%60%5C%5Cy
//
// postman
//
//
// asp
// http://127.0.0.1/index.asp?id=x!#$&name='()*+,/:;=?@[ ]-_.~%^{}\"|<>`\\y
// http://127.0.0.1/index.asp?id=x%21%23%24&name=%27%28%29*%2B%2C%2F%3A%3B=?%40%5B%20%5D-_.%7E%25%5E%7B%7D%22%7C%3C%3E%60%5Cy
// the character &=? can't be encoded, otherwise the result of queryString is wrong.
// <%
// id=request.queryString("id")
// response.write "id=" & id
// response.write "</br>"
// name=request.queryString("name")
// response.write "name=" & name
// %>
//
//
// http%+y%2f%2fwww.baidu.com%2fquery%3fkey%3dx!%23%24%26%27()*%2b%2c%2f%3a%3b%3d%3f%40%5b+%5d-_.%7e%25%5e%7b%7d%22%7c%3c%3e%60%+5
//
// C# System.Web.HttpUtility.UrlDecode
// http% y//www.baidu.com/query?key=x!#$&'()*+,/:;=?@[ ]-_.~%^{}"|<>`% 5
//
static constexpr char unreserved_char[] = {
//0 1 2 3 4 5 6 7 8 9 A B C D E F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, // 2
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, // 3
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 5
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, // 7
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F
};
template<
class CharT = char,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
std::basic_string<CharT, Traits, Allocator> url_decode(std::string_view url)
{
using size_type = typename std::string_view::size_type;
using value_type = typename std::string_view::value_type;
using rvalue_type = typename std::basic_string<CharT, Traits, Allocator>::value_type;
std::basic_string<CharT, Traits, Allocator> r;
r.reserve(url.size());
if (url.empty())
return r;
for (size_type i = 0; i < url.size(); ++i)
{
value_type c = url[i];
if (c == '%')
{
if (i + 3 <= url.size())
{
value_type h = url[i + 1];
value_type l = url[i + 2];
bool f1 = false, f2 = false;
if /**/ (h >= '0' && h <= '9') { f1 = true; h = value_type(h - '0' ); }
else if (h >= 'a' && h <= 'f') { f1 = true; h = value_type(h - 'a' + 10); }
else if (h >= 'A' && h <= 'F') { f1 = true; h = value_type(h - 'A' + 10); }
if /**/ (l >= '0' && l <= '9') { f2 = true; l = value_type(l - '0' ); }
else if (l >= 'a' && l <= 'f') { f2 = true; l = value_type(l - 'a' + 10); }
else if (l >= 'A' && l <= 'F') { f2 = true; l = value_type(l - 'A' + 10); }
if (f1 && f2)
{
r += static_cast<rvalue_type>(h * 16 + l);
i += 2;
}
else
{
r += static_cast<rvalue_type>(c);
}
}
else
{
r += static_cast<rvalue_type>(c);
}
}
else if (c == '+')
{
r += static_cast<rvalue_type>(' ');
}
else
{
r += static_cast<rvalue_type>(c);
}
}
return r;
}
template<
class CharT = char,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
std::basic_string<CharT, Traits, Allocator> url_encode(std::string_view url, std::size_t offset = 0)
{
using size_type [[maybe_unused]] = typename std::string_view::size_type;
using value_type [[maybe_unused]] = typename std::string_view::value_type;
using rvalue_type [[maybe_unused]] = typename std::basic_string<CharT, Traits, Allocator>::value_type;
std::basic_string<CharT, Traits, Allocator> r;
r.reserve(url.size() * 2);
if (url.empty())
return r;
size_type i = 0;
if (offset == 0)
{
http::parses::http_parser_url u;
if (0 == http::parses::http_parser_parse_url(url.data(), url.size(), 0, std::addressof(u)))
{
if /**/ (u.field_set & (1 << (int)http::parses::url_fields::UF_PATH))
{
i = u.field_data[(int)http::parses::url_fields::UF_PATH].off + 1;
}
else if (u.field_set & (1 << (int)http::parses::url_fields::UF_PORT))
{
i = u.field_data[(int)http::parses::url_fields::UF_PORT].off +
u.field_data[(int)http::parses::url_fields::UF_PORT].len;
}
else if (u.field_set & (1 << (int)http::parses::url_fields::UF_HOST))
{
i = u.field_data[(int)http::parses::url_fields::UF_HOST].off +
u.field_data[(int)http::parses::url_fields::UF_HOST].len;
}
if constexpr (std::is_same_v<CharT, char>)
{
r += std::string_view{ url.data(), i };
}
else
{
for (size_type n = 0; n < i; ++n)
{
r += static_cast<rvalue_type>(url[n]);
}
}
}
}
else
{
r += url.substr(0, offset);
i = offset;
}
for (; i < url.size(); ++i)
{
unsigned char c = static_cast<unsigned char>(url[i]);
if (/*std::isalnum(c) || */unreserved_char[c])
{
r += static_cast<rvalue_type>(c);
}
else
{
r += static_cast<rvalue_type>('%');
rvalue_type h = rvalue_type(c >> 4);
r += h > rvalue_type(9) ? rvalue_type(h + 55) : rvalue_type(h + 48);
rvalue_type l = rvalue_type(c % 16);
r += l > rvalue_type(9) ? rvalue_type(l + 55) : rvalue_type(l + 48);
}
}
return r;
}
template<typename = void>
bool has_unencode_char(std::string_view url, std::size_t offset = 0) noexcept
{
using size_type = typename std::string_view::size_type;
using value_type = typename std::string_view::value_type;
if (url.empty())
return false;
size_type i = 0;
if (offset == 0)
{
http::parses::http_parser_url u;
if (0 == http::parses::http_parser_parse_url(url.data(), url.size(), 0, std::addressof(u)))
{
if /**/ (u.field_set & (1 << (int)http::parses::url_fields::UF_PATH))
{
i = u.field_data[(int)http::parses::url_fields::UF_PATH].off + 1;
}
else if (u.field_set & (1 << (int)http::parses::url_fields::UF_PORT))
{
i = u.field_data[(int)http::parses::url_fields::UF_PORT].off +
u.field_data[(int)http::parses::url_fields::UF_PORT].len;
}
else if (u.field_set & (1 << (int)http::parses::url_fields::UF_HOST))
{
i = u.field_data[(int)http::parses::url_fields::UF_HOST].off +
u.field_data[(int)http::parses::url_fields::UF_HOST].len;
}
}
}
else
{
i = offset;
}
for (; i < url.size(); ++i)
{
unsigned char c = static_cast<unsigned char>(url[i]);
if (c == static_cast<unsigned char>('%'))
{
if (i + 3 <= url.size())
{
value_type h = url[i + 1];
value_type l = url[i + 2];
if /**/ (h >= '0' && h <= '9') {}
else if (h >= 'a' && h <= 'f') {}
else if (h >= 'A' && h <= 'F') {}
else { return true; }
if /**/ (l >= '0' && l <= '9') {}
else if (l >= 'a' && l <= 'f') {}
else if (l >= 'A' && l <= 'F') {}
else { return true; }
i += 2;
}
else
{
return true;
}
}
else if (!unreserved_char[c])
{
return true;
}
}
return false;
}
template<typename = void>
bool has_undecode_char(std::string_view url, std::size_t offset = 0) noexcept
{
using size_type = typename std::string_view::size_type;
using value_type = typename std::string_view::value_type;
if (url.empty())
return false;
for (size_type i = offset; i < url.size(); ++i)
{
value_type c = url[i];
if (c == '%')
{
if (i + 3 <= url.size())
{
value_type h = url[i + 1];
value_type l = url[i + 2];
bool f1 = false, f2 = false;
if /**/ (h >= '0' && h <= '9') { f1 = true; }
else if (h >= 'a' && h <= 'f') { f1 = true; }
else if (h >= 'A' && h <= 'F') { f1 = true; }
if /**/ (l >= '0' && l <= '9') { f2 = true; }
else if (l >= 'a' && l <= 'f') { f2 = true; }
else if (l >= 'A' && l <= 'F') { f2 = true; }
if (f1 && f2)
{
return true;
}
}
}
else if (c == '+')
{
return true;
}
}
return false;
}
template<typename = void>
std::string_view url_to_host(std::string_view url)
{
if (url.empty())
return std::string_view{};
http::parses::http_parser_url u;
if (0 != http::parses::http_parser_parse_url(url.data(), url.size(), 0, std::addressof(u)))
return std::string_view{};
if (!(u.field_set & (1 << (int)http::parses::url_fields::UF_HOST)))
return std::string_view{};
return std::string_view{ &url[
u.field_data[(int)http::parses::url_fields::UF_HOST].off],
u.field_data[(int)http::parses::url_fields::UF_HOST].len };
}
template<typename = void>
std::string_view url_to_port(std::string_view url)
{
if (url.empty())
return std::string_view{};
http::parses::http_parser_url u;
if (0 != http::parses::http_parser_parse_url(url.data(), url.size(), 0, std::addressof(u)))
return std::string_view{};
if (u.field_set & (1 << (int)http::parses::url_fields::UF_PORT))
return std::string_view{ &url[
u.field_data[(int)http::parses::url_fields::UF_PORT].off],
u.field_data[(int)http::parses::url_fields::UF_PORT].len };
if (u.field_set & (1 << (int)http::parses::url_fields::UF_SCHEMA))
{
std::string_view schema(&url[
u.field_data[(int)http::parses::url_fields::UF_SCHEMA].off],
u.field_data[(int)http::parses::url_fields::UF_SCHEMA].len);
if (asio2::iequals(schema, "http"))
return std::string_view{ "80" };
if (asio2::iequals(schema, "https"))
return std::string_view{ "443" };
}
return std::string_view{ "80" };
}
template<typename = void>
std::string_view url_to_path(std::string_view url)
{
if (url.empty())
return std::string_view{};
http::parses::http_parser_url u;
if (0 != http::parses::http_parser_parse_url(url.data(), url.size(), 0, std::addressof(u)))
return std::string_view{};
if (!(u.field_set & (1 << (int)http::parses::url_fields::UF_PATH)))
return std::string_view{ "/" };
return std::string_view{ &url[
u.field_data[(int)http::parses::url_fields::UF_PATH].off],
u.field_data[(int)http::parses::url_fields::UF_PATH].len };
}
template<typename = void>
std::string_view url_to_query(std::string_view url)
{
if (url.empty())
return std::string_view{};
http::parses::http_parser_url u;
if (0 != http::parses::http_parser_parse_url(url.data(), url.size(), 0, std::addressof(u)))
return std::string_view{};
if (!(u.field_set & (1 << (int)http::parses::url_fields::UF_QUERY)))
return std::string_view{};
return std::string_view{ &url[
u.field_data[(int)http::parses::url_fields::UF_QUERY].off],
u.field_data[(int)http::parses::url_fields::UF_QUERY].len };
}
template<typename = void>
inline bool url_match(std::string_view pattern, std::string_view url)
{
if (pattern == "*" || pattern == "/*")
return true;
if (url.empty())
return false;
std::vector<std::string_view> fragments = asio2::split(pattern, "*");
std::size_t index = 0;
while (!url.empty())
{
if (index == fragments.size())
return (pattern.back() == '*');
std::string_view fragment = fragments[index++];
if (fragment.empty())
continue;
while (fragment.size() > static_cast<std::string_view::size_type>(1) && fragment.back() == '/')
{
fragment.remove_suffix(1);
}
std::size_t pos = url.find(fragment);
if (pos == std::string_view::npos)
return false;
url = url.substr(pos + fragment.size());
}
return true;
}
template<class StringT = std::string_view>
inline std::string make_error_page(http::status result, StringT&& desc = std::string_view{})
{
std::string_view reason = http::obsolete_reason(result);
std::string_view descrb = asio2::detail::to_string_view(desc);
std::string content;
if (descrb.empty())
content.reserve(reason.size() * 2 + 67);
else
content.reserve(reason.size() * 2 + 67 + descrb.size() + 21);
content += "<html><head><title>";
content += reason;
content += "</title></head><body><h1>";
content += std::to_string(asio2::detail::to_underlying(result));
content += " ";
content += reason;
content += "</h1>";
if (!descrb.empty())
{
content += "<p>Description : ";
content += descrb;
content += "</p>";
}
content += "</body></html>";
return content;
}
template<class StringT = std::string_view>
inline std::string error_page(http::status result, StringT&& desc = std::string_view{})
{
return make_error_page(result, std::forward<StringT>(desc));
}
/**
* @brief Returns `true` if the HTTP message's Content-Type is "multipart/form-data";
*/
template<class HttpMessage>
inline bool has_multipart(const HttpMessage& msg) noexcept
{
return (asio2::ifind(msg[http::field::content_type], "multipart/form-data") != std::string_view::npos);
}
/**
* @brief Get the "multipart/form-data" body content.
*/
template<class HttpMessage, class String = std::string>
inline basic_multipart_fields<String> get_multipart(const HttpMessage& msg)
{
return multipart_parser_execute(msg);
}
/**
* @brief Get the "multipart/form-data" body content. same as get_multipart
*/
template<class HttpMessage, class String = std::string>
inline basic_multipart_fields<String> multipart(const HttpMessage& msg)
{
return get_multipart(msg);
}
}
// /boost_1_80_0/libs/beast/example/doc/http_examples.hpp
template<bool isRequest, class SyncReadStream, class DynamicBuffer, class HeaderCallback, class BodyCallback>
void read_large_body(SyncReadStream& stream, DynamicBuffer& buffer, HeaderCallback&& cbh, BodyCallback&& cbb)
{
error_code& ec = asio2::get_last_error();
// Declare the parser with an empty body since
// we plan on capturing the chunks ourselves.
http::parser<isRequest, http::string_body> hp;
// First read the complete header
http::read_header(stream, buffer, hp, ec);
if (ec)
return;
cbh(hp.get());
// should we check the http reponse status?
// should we handle the http range? 301 302 ?
//if (hp.get().result() != http::status::ok)
//{
// ec = http::error::bad_status;
// return;
//}
// if the http response has no body, returned with error.
if (hp.is_done())
{
ec = http::error::end_of_stream;
return;
}
http::parser<isRequest, http::buffer_body> p(std::move(hp));
if (p.get().chunked())
{
// This container will hold the extensions for each chunk
http::chunk_extensions ce;
// This string will hold the body of each chunk
//std::string chunk;
// Declare our chunk header callback This is invoked
// after each chunk header and also after the last chunk.
auto header_cb = [&](
std::uint64_t size, // Size of the chunk, or zero for the last chunk
std::string_view extensions, // The raw chunk-extensions string. Already validated.
error_code& ev) // We can set this to indicate an error
{
// Parse the chunk extensions so we can access them easily
ce.parse(extensions, ev);
if (ev)
return;
// See if the chunk is too big
if (size > (std::numeric_limits<std::size_t>::max)())
{
ev = http::error::body_limit;
return;
}
// Make sure we have enough storage, and
// reset the container for the upcoming chunk
//chunk.reserve(static_cast<std::size_t>(size));
//chunk.clear();
};
// Set the callback. The function requires a non-const reference so we
// use a local variable, since temporaries can only bind to const refs.
p.on_chunk_header(header_cb);
// Declare the chunk body callback. This is called one or
// more times for each piece of a chunk body.
auto body_cb = [&](
std::uint64_t remain, // The number of bytes left in this chunk
std::string_view body, // A buffer holding chunk body data
error_code& ev) // We can set this to indicate an error
{
// If this is the last piece of the chunk body,
// set the error so that the call to `read` returns
// and we can process the chunk.
if (remain == body.size())
ev = http::error::end_of_chunk;
// Append this piece to our container
//chunk.append(body.data(), body.size());
cbb(body);
// The return value informs the parser of how much of the body we
// consumed. We will indicate that we consumed everything passed in.
return body.size();
};
p.on_chunk_body(body_cb);
while (!p.is_done())
{
// Read as much as we can. When we reach the end of the chunk, the chunk
// body callback will make the read return with the end_of_chunk error.
http::read(stream, buffer, p, ec);
if (!ec)
continue;
else if (ec != http::error::end_of_chunk)
return;
else
ec = {};
}
}
else
{
std::array<char, 512> buf;
while (!p.is_done())
{
p.get().body().data = buf.data();
p.get().body().size = buf.size();
std::size_t bytes_read = http::read(stream, buffer, p, ec);
if (ec == http::error::need_buffer)
ec = {};
if (ec)
return;
ASIO2_ASSERT(bytes_read == buf.size() - p.get().body().size);
cbb(std::string_view(buf.data(), bytes_read));
}
}
}
template<bool isRequest, class Body, class Fields>
inline void try_prepare_payload(http::message<isRequest, Body, Fields>& msg)
{
try
{
msg.prepare_payload();
}
catch (const std::exception&)
{
asio2::set_last_error(asio::error::invalid_argument);
}
}
template<typename, typename = void>
struct is_http_message : std::false_type {};
template<typename T>
struct is_http_message<T, std::void_t<typename T::header_type, typename T::body_type,
typename std::enable_if_t<std::is_same_v<T, http::message<
T::header_type::is_request::value,
typename T::body_type,
typename T::header_type::fields_type>>>>> : std::true_type {};
template<class T>
inline constexpr bool is_http_message_v = is_http_message<T>::value;
}
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::websocket
#else
namespace boost::beast::websocket
#endif
{
enum class frame : std::uint8_t
{
///
unknown,
/// A message frame was received
message,
/// A ping frame was received
ping,
/// A pong frame was received
pong,
/// http is upgrade to websocket
open,
/// A close frame was received
close
};
}
#endif // !__ASIO2_HTTP_UTIL_HPP__
<file_sep>/*
Copyright <NAME> 2012-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_BSD_DRAGONFLY_H
#define BHO_PREDEF_OS_BSD_DRAGONFLY_H
#include <asio2/bho/predef/os/bsd.h>
/* tag::reference[]
= `BHO_OS_BSD_DRAGONFLY`
http://en.wikipedia.org/wiki/DragonFly_BSD[DragonFly BSD] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__DragonFly__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_BSD_DRAGONFLY BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__DragonFly__) \
)
# ifndef BHO_OS_BSD_AVAILABLE
# undef BHO_OS_BSD
# define BHO_OS_BSD BHO_VERSION_NUMBER_AVAILABLE
# define BHO_OS_BSD_AVAILABLE
# endif
# undef BHO_OS_BSD_DRAGONFLY
# if defined(__DragonFly__)
# define BHO_OS_DRAGONFLY_BSD BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_OS_BSD_DRAGONFLY
# define BHO_OS_BSD_DRAGONFLY_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_BSD_DRAGONFLY_NAME "DragonFly BSD"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_BSD_DRAGONFLY,BHO_OS_BSD_DRAGONFLY_NAME)
<file_sep>/*
Copyright <NAME> 2015-2019
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_PLAT_ANDROID_H
#define BHO_PREDEF_PLAT_ANDROID_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_PLAT_ANDROID`
http://en.wikipedia.org/wiki/Android_%28operating_system%29[Android] platform.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__ANDROID__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_PLAT_ANDROID BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__ANDROID__)
# undef BHO_PLAT_ANDROID
# define BHO_PLAT_ANDROID BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_PLAT_ANDROID
# define BHO_PLAT_ANDROID_AVAILABLE
# include <asio2/bho/predef/detail/platform_detected.h>
#endif
#define BHO_PLAT_ANDROID_NAME "Android"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_ANDROID,BHO_PLAT_ANDROID_NAME)
<file_sep>/*
Copyright <NAME> 2015
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_HARDWARE_SIMD_X86_AMD_VERSIONS_H
#define BHO_PREDEF_HARDWARE_SIMD_X86_AMD_VERSIONS_H
#include <asio2/bho/predef/version_number.h>
/* tag::reference[]
= `BHO_HW_SIMD_X86_AMD_*_VERSION`
Those defines represent x86 (AMD specific) SIMD extensions versions.
NOTE: You *MUST* compare them with the predef `BHO_HW_SIMD_X86_AMD`.
*/ // end::reference[]
// ---------------------------------
/* tag::reference[]
= `BHO_HW_SIMD_X86_AMD_SSE4A_VERSION`
https://en.wikipedia.org/wiki/SSE4##SSE4A[SSE4A] x86 extension (AMD specific).
Version number is: *4.0.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_AMD_SSE4A_VERSION BHO_VERSION_NUMBER(4, 0, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_AMD_FMA4_VERSION`
https://en.wikipedia.org/wiki/FMA_instruction_set#FMA4_instruction_set[FMA4] x86 extension (AMD specific).
Version number is: *5.1.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_AMD_FMA4_VERSION BHO_VERSION_NUMBER(5, 1, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_AMD_XOP_VERSION`
https://en.wikipedia.org/wiki/XOP_instruction_set[XOP] x86 extension (AMD specific).
Version number is: *5.1.1*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_AMD_XOP_VERSION BHO_VERSION_NUMBER(5, 1, 1)
/* tag::reference[]
*/ // end::reference[]
#endif
<file_sep>#include <asio2/icmp/ping.hpp>
#include <iostream>
int main()
{
// under linux maybe failed always:
// https://github.com/chriskohlhoff/asio/issues/781
std::cout << asio2::ping::execute("www.baidu.com").milliseconds() << std::endl;;
// execute with error, print the error message.
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
asio2::ping ping;
ping.set_timeout(std::chrono::seconds(4));
ping.set_interval(std::chrono::seconds(1));
ping.bind_recv([](asio2::icmp_rep& rep)
{
if (rep.is_timeout())
std::cout << "request timed out" << std::endl;
else
std::cout << rep.total_length() - rep.header_length()
<< " bytes from " << rep.source_address()
<< ": icmp_seq=" << rep.sequence_number()
<< ", ttl=" << rep.time_to_live()
<< ", time=" << rep.milliseconds() << "ms"
<< std::endl;
}).bind_start([]()
{
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
});
ping.start("stackoverflow.com");
while (std::getchar() != '\n');
ping.stop();
printf("loss rate : %.0lf%% average time : %ldms\n", ping.plp(),
long(std::chrono::duration_cast<std::chrono::milliseconds>(ping.avg_lag()).count()));
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refenced from : https://github.com/progschj/ThreadPool
* see c++ 17 version : https://github.com/jhasse/ThreadPool
*
*
* note :
*
* 1 : when declare an global thread_pool object in dll,when enter the
* constructor to create std::thread,it will blocking forever.
* 2 : when declare an global thread_pool object in dll and when dll is
* released,the code will run into thread_pool destructor,then call
* notify_all in the destructor, but the notify_all calling will
* blocking forever.
*
* one resolve method is add a start and stop function,and move the
* notify_all into the stop inner,and tell user call the start and
* stop function manual.
*
* but in order to keep the interface simple,we don't add stop function,
* you can use "new" "delete" way to avoid above problems,you can delete
* thread_pool pointer object before exit.
*
* std::thread cause deadlock in DLLMain :
* The constructor for the std::thread cannot return until the new thread
* starts executing the thread procedure. When a new thread is created,
* before the thread procedure is invoked, the entry point of each loaded
* DLL is invoked for DLL_THREAD_ATTACH. To do this, the new thread must
* acquire the loader lock. Unfortunately, your existing thread already
* holds the loader lock.
*
*/
#ifndef __ASIO2_THREAD_POOL_HPP__
#define __ASIO2_THREAD_POOL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdlib>
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
namespace asio2
{
/**
* thread pool interface, this pool is multi thread safed.
*/
class thread_pool
{
public:
/**
* @brief constructor
*/
explicit thread_pool(std::size_t thread_count = std::thread::hardware_concurrency())
{
if (thread_count < 1)
thread_count = 1;
this->indexed_tasks_ = std::vector<std::queue<std::packaged_task<void()>>>{ thread_count };
this->workers_.reserve(thread_count);
for (std::size_t i = 0; i < thread_count; ++i)
{
// emplace_back can use the parameters to construct the std::thread object automictly
// use lambda function as the thread proc function,lambda can has no parameters list
this->workers_.emplace_back([this, i]() mutable
{
std::queue<std::packaged_task<void()>>& indexed_tasks = this->indexed_tasks_[i];
for (;;)
{
std::packaged_task<void()> task;
{
std::unique_lock<std::mutex> lock(this->mtx_);
this->cv_.wait(lock, [this, &indexed_tasks]
{ return (this->stop_ || !this->tasks_.empty() || !indexed_tasks.empty()); });
if (this->stop_ && this->tasks_.empty() && indexed_tasks.empty())
return;
if (indexed_tasks.empty())
{
task = std::move(this->tasks_.front());
this->tasks_.pop();
}
else
{
task = std::move(indexed_tasks.front());
indexed_tasks.pop();
}
}
task();
}
});
}
}
/**
* @brief destructor
*/
~thread_pool()
{
{
std::unique_lock<std::mutex> lock(this->mtx_);
this->stop_ = true;
}
this->cv_.notify_all();
for (auto & worker : this->workers_)
{
if (worker.joinable())
worker.join();
}
}
/**
* @brief post a function object into the thread pool, then return immediately,
* the function object will never be executed inside this function. Instead, it will
* be executed asynchronously in the thread pool.
* @param fun - global function,static function,lambda,member function,std::function.
* @return std::future<fun_return_type>
*/
template<class Fun, class... Args>
auto post(Fun&& fun, Args&&... args) -> std::future<std::invoke_result_t<Fun, Args...>>
{
using return_type = std::invoke_result_t<Fun, Args...>;
std::packaged_task<return_type()> task(
std::bind(std::forward<Fun>(fun), std::forward<Args>(args)...));
std::future<return_type> future = task.get_future();
{
std::unique_lock<std::mutex> lock(this->mtx_);
// don't allow post after stopping the pool
if (this->stop_)
throw std::runtime_error("post a task into thread pool but the pool is stopped");
this->tasks_.emplace(std::move(task));
}
this->cv_.notify_one();
return future;
}
/**
* @brief post a function object into the thread pool with specified thread index,
* then return immediately, the function object will never be executed inside this
* function. Instead, it will be executed asynchronously in the thread pool.
* @param thread_index - which thread to execute the function.
* @param fun - global function,static function,lambda,member function,std::function.
* @return std::future<fun_return_type>
*/
template<class IntegerT, class Fun, class... Args,
std::enable_if_t<std::is_integral_v<std::remove_cv_t<std::remove_reference_t<IntegerT>>>, int> = 0>
auto post(IntegerT thread_index, Fun&& fun, Args&&... args) -> std::future<std::invoke_result_t<Fun, Args...>>
{
using return_type = std::invoke_result_t<Fun, Args...>;
std::packaged_task<return_type()> task(
std::bind(std::forward<Fun>(fun), std::forward<Args>(args)...));
std::future<return_type> future = task.get_future();
{
std::unique_lock<std::mutex> lock(this->mtx_);
// don't allow post after stopping the pool
if (this->stop_)
throw std::runtime_error("post a task into thread pool but the pool is stopped");
this->indexed_tasks_[thread_index % this->indexed_tasks_.size()].emplace(std::move(task));
}
this->cv_.notify_one();
return future;
}
/**
* @brief get thread count of the thread pool, same as get_pool_size()
*/
inline std::size_t pool_size() noexcept
{
return this->get_pool_size();
}
/**
* @brief get thread count of the thread pool
*/
inline std::size_t get_pool_size() noexcept
{
// is std container.size() thread safety ?
// @see: the size() function in file: /asio2/base/session_mgr.hpp
std::unique_lock<std::mutex> lock(this->mtx_);
return this->workers_.size();
}
/**
* @brief get remain task size, same as get_task_size()
*/
inline std::size_t task_size() noexcept
{
return this->get_task_size();
}
/**
* @brief get remain task size
*/
inline std::size_t get_task_size() noexcept
{
std::unique_lock<std::mutex> lock(this->mtx_);
std::size_t count = this->tasks_.size();
for (std::queue<std::packaged_task<void()>>& queue : this->indexed_tasks_)
{
count += queue.size();
}
return count;
}
/**
* @brief Determine whether current code is running in the pool's threads.
*/
inline bool running_in_threads() noexcept
{
std::unique_lock<std::mutex> lock(this->mtx_);
std::thread::id curr_tid = std::this_thread::get_id();
for (auto & thread : this->workers_)
{
if (curr_tid == thread.get_id())
return true;
}
return false;
}
/**
* @brief Determine whether current code is running in the thread by index
*/
inline bool running_in_thread(std::size_t index) noexcept
{
std::unique_lock<std::mutex> lock(this->mtx_);
if (!(index < this->workers_.size()))
return false;
return (std::this_thread::get_id() == this->workers_[index].get_id());
}
/**
* @brief Get the thread id of the specified thread index.
*/
inline std::thread::id get_thread_id(std::size_t index) noexcept
{
std::unique_lock<std::mutex> lock(this->mtx_);
return this->workers_[index % this->workers_.size()].get_id();
}
private:
/// no copy construct function
thread_pool(const thread_pool&) = delete;
/// no operator equal function
thread_pool& operator=(const thread_pool&) = delete;
protected:
// need to keep track of threads so we can join them
std::vector<std::thread> workers_;
// the task queue
std::queue<std::packaged_task<void()>> tasks_;
// the task queue with thread index can be specified
std::vector<std::queue<std::packaged_task<void()>>> indexed_tasks_;
// synchronization
std::mutex mtx_;
std::condition_variable cv_;
// flag indicate the pool is stoped
bool stop_ = false;
};
}
#endif // !__ASIO2_THREAD_POOL_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RPC_INVOKER_HPP__
#define __ASIO2_RPC_INVOKER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <queue>
#include <any>
#include <future>
#include <tuple>
#include <unordered_map>
#include <type_traits>
#include <optional>
#include <asio2/base/iopool.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
#include <asio2/rpc/detail/rpc_serialization.hpp>
#include <asio2/rpc/detail/rpc_protocol.hpp>
#include <asio2/util/string.hpp>
namespace asio2::detail
{
// forward declare
template<class, class> class rpc_invoker_t;
}
namespace asio2::rpc
{
template<class T>
class response_defer
{
template<class, class> friend class asio2::detail::rpc_invoker_t;
public:
response_defer() = default;
~response_defer()
{
ASIO2_ASSERT(f_);
if (f_) { f_(); }
}
template<class V>
inline void set_value(V&& v) { v_ = std::forward<V>(v); }
protected:
template<class F>
inline void _bind (F&& f) { f_ = std::forward<F>(f); }
protected:
std::optional<T> v_{};
std::function<void()> f_{};
};
template<class T>
class future
{
template<class, class> friend class asio2::detail::rpc_invoker_t;
public:
future() = delete;
future(std::shared_ptr<response_defer<T>> defer) noexcept : defer_(std::move(defer))
{
}
~future() = default;
future(future&&) noexcept = default;
future(future const&) noexcept = default;
future& operator=(future&&) noexcept = default;
future& operator=(future const&) noexcept = default;
protected:
std::shared_ptr<response_defer<T>> defer_{};
};
template<class T>
class promise
{
template<class, class> friend class asio2::detail::rpc_invoker_t;
public:
promise() = default;
~promise() = default;
promise(promise&&) noexcept = default;
promise(promise const&) noexcept = default;
promise& operator=(promise&&) noexcept = default;
promise& operator=(promise const&) noexcept = default;
inline future<T> get_future() noexcept { return future<T>{ defer_ }; }
template<class V>
inline void set_value(V&& v) { defer_->set_value(std::forward<V>(v)); }
protected:
std::shared_ptr<response_defer<T>> defer_ = std::make_shared<response_defer<T>>();
};
//---------------------------------------------------------------------------------------------
// specialize for void
//---------------------------------------------------------------------------------------------
template<>
class response_defer<void>
{
template<class, class> friend class asio2::detail::rpc_invoker_t;
public:
response_defer() = default;
~response_defer()
{
ASIO2_ASSERT(f_);
if (f_) { f_(); }
}
template<typename = void>
inline void set_value() { v_ = '0'; }
protected:
template<class F>
inline void _bind (F&& f) { f_ = std::forward<F>(f); }
protected:
std::optional<char> v_{};
std::function<void()> f_{};
};
template<>
class future<void>
{
template<class, class> friend class asio2::detail::rpc_invoker_t;
public:
future() = delete;
future(std::shared_ptr<response_defer<void>> defer) noexcept : defer_(std::move(defer))
{
}
~future() = default;
future(future&&) noexcept = default;
future(future const&) noexcept = default;
future& operator=(future&&) noexcept = default;
future& operator=(future const&) noexcept = default;
protected:
std::shared_ptr<response_defer<void>> defer_{};
};
template<>
class promise<void>
{
template<class, class> friend class asio2::detail::rpc_invoker_t;
public:
promise() = default;
~promise() = default;
promise(promise&&) noexcept = default;
promise(promise const&) noexcept = default;
promise& operator=(promise&&) noexcept = default;
promise& operator=(promise const&) noexcept = default;
inline future<void> get_future() noexcept { return future<void>{ defer_ }; }
template<typename = void>
inline void set_value() { defer_->set_value(); }
protected:
std::shared_ptr<response_defer<void>> defer_ = std::make_shared<response_defer<void>>();
};
}
namespace asio2::detail
{
template<class T>
struct rpc_result_t
{
using type = typename std::remove_cv_t<std::remove_reference_t<T>>;
};
template<>
struct rpc_result_t<void>
{
using type = std::int8_t;
};
template<class caller_t, class args_t>
class rpc_invoker_t
{
protected:
struct dummy {};
public:
using self = rpc_invoker_t<caller_t, args_t>;
using fntype = std::function<
bool(std::shared_ptr<caller_t>&, caller_t*, rpc_serializer&, rpc_deserializer&)>;
/**
* @brief constructor
*/
rpc_invoker_t() = default;
/**
* @brief destructor
*/
~rpc_invoker_t() = default;
rpc_invoker_t(rpc_invoker_t&& o) noexcept : rpc_invokers_(std::move(o.rpc_invokers_))
{
}
rpc_invoker_t(rpc_invoker_t const& o) : rpc_invokers_(o.rpc_invokers_)
{
}
rpc_invoker_t& operator=(rpc_invoker_t&& o) noexcept
{
this->rpc_invokers_ = std::move(o.rpc_invokers_);
}
rpc_invoker_t& operator=(rpc_invoker_t const& o)
{
this->rpc_invokers_ = o.rpc_invokers_;
}
/**
* @brief bind a rpc function
* @param name - Function name in string format.
* @param fun - Function object.
* @param obj - A pointer or reference to a class object, this parameter can be none.
* if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
*/
template<class F, class ...C>
inline self& bind(std::string name, F&& fun, C&&... obj)
{
asio2::trim_both(name);
ASIO2_ASSERT(!name.empty());
if (name.empty())
return (*this);
#if defined(_DEBUG) || defined(DEBUG)
{
#if defined(ASIO2_ENABLE_RPC_INVOKER_THREAD_SAFE)
asio2::shared_locker guard(this->rpc_invoker_mutex_);
#endif
ASIO2_ASSERT(this->rpc_invokers_.find(name) == this->rpc_invokers_.end());
}
#endif
this->_bind(std::move(name), std::forward<F>(fun), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief unbind a rpc function
*/
inline self& unbind(std::string const& name)
{
#if defined(ASIO2_ENABLE_RPC_INVOKER_THREAD_SAFE)
asio2::unique_locker guard(this->rpc_invoker_mutex_);
#endif
this->rpc_invokers_.erase(name);
return (*this);
}
/**
* @brief find binded rpc function by name
*/
inline std::shared_ptr<fntype> find(std::string const& name)
{
#if defined(ASIO2_ENABLE_RPC_INVOKER_THREAD_SAFE)
asio2::shared_locker guard(this->rpc_invoker_mutex_);
#endif
if (auto iter = this->rpc_invokers_.find(name); iter != this->rpc_invokers_.end())
return iter->second;
return nullptr;
}
protected:
inline self& _invoker() noexcept { return (*this); }
template<class F>
inline void _bind(std::string name, F f)
{
#if defined(ASIO2_ENABLE_RPC_INVOKER_THREAD_SAFE)
asio2::unique_locker guard(this->rpc_invoker_mutex_);
#endif
this->rpc_invokers_[std::move(name)] = std::make_shared<fntype>(std::bind(&self::template _proxy<F, dummy>,
this, std::move(f), nullptr,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
}
template<class F, class C>
inline void _bind(std::string name, F f, C& c)
{
#if defined(ASIO2_ENABLE_RPC_INVOKER_THREAD_SAFE)
asio2::unique_locker guard(this->rpc_invoker_mutex_);
#endif
this->rpc_invokers_[std::move(name)] = std::make_shared<fntype>(std::bind(&self::template _proxy<F, C>,
this, std::move(f), std::addressof(c),
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
}
template<class F, class C>
inline void _bind(std::string name, F f, C* c)
{
#if defined(ASIO2_ENABLE_RPC_INVOKER_THREAD_SAFE)
asio2::unique_locker guard(this->rpc_invoker_mutex_);
#endif
this->rpc_invokers_[std::move(name)] = std::make_shared<fntype>(std::bind(&self::template _proxy<F, C>,
this, std::move(f), c,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
}
template<class F, class C>
inline bool _proxy(F& f, C* c, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
rpc_serializer& sr, rpc_deserializer& dr)
{
using fun_traits_type = function_traits<F>;
return _argc_proxy<fun_traits_type::argc>(f, c, caller_ptr, caller, sr, dr);
}
template<std::size_t Argc, class F, class C>
typename std::enable_if_t<Argc == 0, bool>
inline _argc_proxy(F& f, C* c, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
rpc_serializer& sr, rpc_deserializer& dr)
{
using fun_traits_type = function_traits<F>;
using fun_args_tuple = typename fun_traits_type::pod_tuple_type;
using fun_ret_type = typename fun_traits_type::return_type;
fun_args_tuple tp;
detail::for_each_tuple(tp, [&dr](auto& elem) mutable
{
dr >> elem;
});
return _invoke<fun_ret_type>(f, c, caller_ptr, caller, sr, dr, std::move(tp));
}
template<std::size_t Argc, class F, class C>
typename std::enable_if_t<Argc != 0, bool>
inline _argc_proxy(F& f, C* c, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
rpc_serializer& sr, rpc_deserializer& dr)
{
detail::ignore_unused(caller);
using fun_traits_type = function_traits<F>;
using fun_args_tuple = typename fun_traits_type::pod_tuple_type;
using fun_ret_type = typename fun_traits_type::return_type;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
if constexpr /**/ (std::is_same_v<arg0_type, std::shared_ptr<caller_t>>)
{
auto tp = _body_args_tuple((fun_args_tuple*)0);
detail::for_each_tuple(tp, [&dr](auto& elem) mutable
{
dr >> elem;
});
auto tp_new = std::tuple_cat(std::tuple<std::shared_ptr<caller_t>&>(caller_ptr), tp);
return _invoke<fun_ret_type>(f, c, caller_ptr, caller, sr, dr, std::move(tp_new));
}
else if constexpr (std::is_same_v<arg0_type, caller_t>)
{
auto tp = _body_args_tuple((fun_args_tuple*)0);
detail::for_each_tuple(tp, [&dr](auto& elem) mutable
{
dr >> elem;
});
auto tp_new = std::tuple_cat(std::tuple<caller_t&>(*caller), tp);
return _invoke<fun_ret_type>(f, c, caller_ptr, caller, sr, dr, std::move(tp_new));
}
else
{
fun_args_tuple tp;
detail::for_each_tuple(tp, [&dr](auto& elem) mutable
{
dr >> elem;
});
return _invoke<fun_ret_type>(f, c, caller_ptr, caller, sr, dr, std::move(tp));
}
}
template<typename... Args>
inline decltype(auto) _body_args_tuple(std::tuple<Args...>* tp)
{
return (_body_args_tuple_impl(std::make_index_sequence<sizeof...(Args) - 1>{}, tp));
}
template<std::size_t... I, typename... Args>
inline decltype(auto) _body_args_tuple_impl(std::index_sequence<I...>, std::tuple<Args...>*) noexcept
{
return (std::tuple<typename std::tuple_element<I + 1, std::tuple<Args...>>::type...>{});
}
template<typename R, typename F, typename C>
inline bool _invoke_with_future(F& f, C* c, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
rpc_serializer& sr, rpc_deserializer& dr, typename rpc_result_t<R>::type r)
{
detail::ignore_unused(f, c, caller_ptr, caller, sr, dr);
error_code ec = rpc::make_error_code(rpc::error::success);
if (dr.buffer().in_avail() != 0)
{
ec = rpc::make_error_code(rpc::error::invalid_argument);
}
auto* defer = r.defer_.get();
r.defer_->_bind([caller_ptr, caller, &sr, ec, head = caller->header_, defer]() mutable
{
if (head.id() == static_cast<rpc_header::id_type>(0))
return;
// the "header_, async_send" should not appear in this "invoker" module, But I thought
// for a long time and couldn't find of a good method to solve this problem.
// the operator for "sr" must be in the io_context thread.
asio::dispatch(caller->io().context(), make_allocator(caller->wallocator(),
[caller_ptr = std::move(caller_ptr), caller, &sr, ec, head = std::move(head),
v = std::move(defer->v_)]
() mutable
{
if (!caller->is_started())
return;
head.type(rpc_type_rep);
if (v.has_value() == false && (!ec))
{
ec = rpc::make_error_code(rpc::error::no_data);
}
sr.reset();
sr << head;
sr << ec;
try
{
if constexpr (!std::is_same_v<rpc::future<void>, R>)
{
if (!ec)
{
sr << std::move(v.value()); // maybe throw some exception
}
}
else
{
std::ignore = v;
}
caller->async_send(sr.str());
return; // not exception, return
}
catch (cereal::exception const&)
{
if (!ec) ec = rpc::make_error_code(rpc::error::invalid_argument);
}
catch (std::exception const&)
{
if (!ec) ec = rpc::make_error_code(rpc::error::unspecified_error);
}
// the error_code must not be 0.
ASIO2_ASSERT(ec);
// code run to here, it means that there has some exception.
sr.reset();
sr << head;
sr << ec;
caller->async_send(sr.str());
}));
});
return true;
}
// async - return true, sync - return false
template<typename R, typename F, typename C, typename... Args>
inline bool _invoke(F& f, C* c, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller,
rpc_serializer& sr, rpc_deserializer& dr, std::tuple<Args...>&& tp)
{
detail::ignore_unused(caller_ptr, caller, sr, dr);
if (caller_ptr)
{
detail::get_current_object<std::shared_ptr<caller_t>>() = caller_ptr;
}
else
{
detail::get_current_object<caller_t*>() = caller;
}
typename rpc_result_t<R>::type r = _invoke_impl<R>(f, c,
std::make_index_sequence<sizeof...(Args)>{}, std::move(tp));
if constexpr (detail::is_template_instance_of_v<rpc::future, R>)
{
return _invoke_with_future<R>(f, c, caller_ptr, caller, sr, dr, std::move(r));
}
else if constexpr (!std::is_same_v<R, void>)
{
sr << rpc::make_error_code(rpc::error::success);
sr << r;
return false;
}
else
{
sr << rpc::make_error_code(rpc::error::success);
std::ignore = r;
return false;
}
}
template<typename R, typename F, typename C, std::size_t... I, typename... Args>
typename std::enable_if_t<!std::is_same_v<R, void>, typename rpc_result_t<R>::type>
inline _invoke_impl(F& f, C* c, std::index_sequence<I...>, std::tuple<Args...>&& tp)
{
detail::ignore_unused(c);
if constexpr (std::is_same_v<detail::remove_cvref_t<C>, dummy>)
return f(std::get<I>(std::move(tp))...);
else
return (c->*f)(std::get<I>(std::move(tp))...);
}
template<typename R, typename F, typename C, std::size_t... I, typename... Args>
typename std::enable_if_t<std::is_same_v<R, void>, typename rpc_result_t<R>::type>
inline _invoke_impl(F& f, C* c, std::index_sequence<I...>, std::tuple<Args...>&& tp)
{
detail::ignore_unused(c);
if constexpr (std::is_same_v<detail::remove_cvref_t<C>, dummy>)
f(std::get<I>(std::move(tp))...);
else
(c->*f)(std::get<I>(std::move(tp))...);
return 1;
}
protected:
#if defined(ASIO2_ENABLE_RPC_INVOKER_THREAD_SAFE)
mutable asio2::shared_mutexer rpc_invoker_mutex_;
#endif
std::unordered_map<std::string, std::shared_ptr<fntype>> rpc_invokers_
#if defined(ASIO2_ENABLE_RPC_INVOKER_THREAD_SAFE)
ASIO2_GUARDED_BY(rpc_invoker_mutex_)
#endif
;
};
}
#endif // !__ASIO2_RPC_INVOKER_HPP__
<file_sep>#ifndef ASIO2_ENABLE_SSL
#define ASIO2_ENABLE_SSL
#endif
#include <iostream>
#include <asio2/http/https_server.hpp>
struct aop_log
{
bool before(http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(rep);
printf("aop_log before %s\n", req.method_string().data());
return true;
}
bool after(std::shared_ptr<asio2::https_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
ASIO2_ASSERT(asio2::get_current_caller<std::shared_ptr<asio2::https_session>>().get() == session_ptr.get());
asio2::ignore_unused(session_ptr, req, rep);
printf("aop_log after\n");
return true;
}
};
struct aop_check
{
bool before(std::shared_ptr<asio2::https_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
ASIO2_ASSERT(asio2::get_current_caller<std::shared_ptr<asio2::https_session>>().get() == session_ptr.get());
asio2::ignore_unused(session_ptr, req, rep);
printf("aop_check before\n");
return true;
}
bool after(http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
printf("aop_check after\n");
return true;
}
};
int main()
{
// try open https://localhost:8443 in your browser
std::string_view host = "0.0.0.0";
std::string_view port = "8443";
asio2::https_server server;
server.support_websocket(true);
// set the root directory, here is: /asio2/example/wwwroot
std::filesystem::path root = std::filesystem::current_path().parent_path().parent_path().append("wwwroot");
server.set_root_directory(std::move(root));
server.set_cert_file(
"../../cert/ca.crt",
"../../cert/server.crt",
"../../cert/server.key",
"123456");
if (asio2::get_last_error())
std::cout << "load cert files failed: " << asio2::last_error_msg() << std::endl;
server.set_dh_file("../../cert/dh1024.pem");
if (asio2::get_last_error())
std::cout << "load dh files failed: " << asio2::last_error_msg() << std::endl;
server.bind_accept([](std::shared_ptr<asio2::https_session> & session_ptr)
{
// accept callback maybe has error like "Too many open files", etc...
if (!asio2::get_last_error())
{
// how to close the invalid client:
if (session_ptr->remote_address().find("192.168.10.") != std::string::npos)
session_ptr->stop();
}
else
{
printf("error occurred when calling the accept function : %d %s\n",
asio2::get_last_error_val(), asio2::get_last_error_msg().data());
}
}).bind_start([&]()
{
printf("start https server : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
printf("stop https server : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.bind<http::verb::get, http::verb::post>("/", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
rep.fill_file("index.html");
}, aop_log{});
// If no method is specified, GET and POST are both enabled by default.
server.bind("*", [](http::web_request& req, http::web_response& rep)
{
rep.fill_file(req.target());
}, aop_check{});
// the /ws is the websocket upgraged target
server.bind("/ws", websocket::listener<asio2::https_session>{}.
on("message", [](std::shared_ptr<asio2::https_session>& session_ptr, std::string_view data)
{
printf("ws msg : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}).on("open", [](std::shared_ptr<asio2::https_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
printf("ws open\n");
}).on("close", [](std::shared_ptr<asio2::https_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
printf("ws close\n");
}).on("ping", [](std::shared_ptr<asio2::https_session>& session_ptr, std::string_view data)
{
asio2::ignore_unused(session_ptr);
printf("ws ping %d\n", int(data.size()));
}).on("pong", [](std::shared_ptr<asio2::https_session>& session_ptr, std::string_view data)
{
asio2::ignore_unused(session_ptr);
printf("ws pong %d\n", int(data.size()));
}));
server.bind_not_found([](/*std::shared_ptr<asio2::http_session>& session_ptr, */
http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req);
rep.fill_page(http::status::not_found);
});
server.start(host, port);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_ALPHA_H
#define BHO_PREDEF_ARCHITECTURE_ALPHA_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_ALPHA`
http://en.wikipedia.org/wiki/DEC_Alpha[DEC Alpha] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__alpha__+` | {predef_detection}
| `+__alpha+` | {predef_detection}
| `+_M_ALPHA+` | {predef_detection}
| `+__alpha_ev4__+` | 4.0.0
| `+__alpha_ev5__+` | 5.0.0
| `+__alpha_ev6__+` | 6.0.0
|===
*/ // end::reference[]
#define BHO_ARCH_ALPHA BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__alpha__) || defined(__alpha) || \
defined(_M_ALPHA)
# undef BHO_ARCH_ALPHA
# if !defined(BHO_ARCH_ALPHA) && defined(__alpha_ev4__)
# define BHO_ARCH_ALPHA BHO_VERSION_NUMBER(4,0,0)
# endif
# if !defined(BHO_ARCH_ALPHA) && defined(__alpha_ev5__)
# define BHO_ARCH_ALPHA BHO_VERSION_NUMBER(5,0,0)
# endif
# if !defined(BHO_ARCH_ALPHA) && defined(__alpha_ev6__)
# define BHO_ARCH_ALPHA BHO_VERSION_NUMBER(6,0,0)
# endif
# if !defined(BHO_ARCH_ALPHA)
# define BHO_ARCH_ALPHA BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_ALPHA
# define BHO_ARCH_ALPHA_AVAILABLE
#endif
#if BHO_ARCH_ALPHA
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_ALPHA_NAME "DEC Alpha"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_ALPHA,BHO_ARCH_ALPHA_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_KCP_STREAM_CP_HPP__
#define __ASIO2_KCP_STREAM_CP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/session_mgr.hpp>
#include <asio2/base/detail/object.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/udp/detail/kcp_util.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_UDP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_CLIENT;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SESSION;
/*
* because udp is connectionless, in order to simplify the code logic, KCP shakes
* hands only twice (compared with TCP handshakes three times)
* 1 : client send syn to server
* 2 : server send synack to client
*/
template<class derived_t, class args_t>
class kcp_stream_cp
{
friend derived_t; // C++11
ASIO2_CLASS_FRIEND_DECLARE_UDP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_CLIENT;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SESSION;
public:
/**
* @brief constructor
*/
kcp_stream_cp(derived_t& d, io_t& io)
: derive(d), kcp_timer_(io.context())
{
}
/**
* @brief destructor
*/
~kcp_stream_cp() noexcept
{
if (this->kcp_)
{
kcp::ikcp_release(this->kcp_);
this->kcp_ = nullptr;
}
}
protected:
void _kcp_start(std::shared_ptr<derived_t> this_ptr, std::uint32_t conv)
{
// used to restore configs
kcp::ikcpcb* old = this->kcp_;
struct old_kcp_destructor
{
old_kcp_destructor(kcp::ikcpcb* p) : p_(p) {}
~old_kcp_destructor()
{
if (p_)
kcp::ikcp_release(p_);
}
kcp::ikcpcb* p_ = nullptr;
} old_kcp_destructor_guard(old);
ASIO2_ASSERT(conv != 0);
this->kcp_ = kcp::ikcp_create(conv, (void*)this);
this->kcp_->output = &kcp_stream_cp<derived_t, args_t>::_kcp_output;
if (old)
{
// ikcp_setmtu
kcp::ikcp_setmtu(this->kcp_, old->mtu);
// ikcp_wndsize
kcp::ikcp_wndsize(this->kcp_, old->snd_wnd, old->rcv_wnd);
// ikcp_nodelay
kcp::ikcp_nodelay(this->kcp_, old->nodelay, old->interval, old->fastresend, old->nocwnd);
}
else
{
kcp::ikcp_nodelay(this->kcp_, 1, 10, 2, 1);
kcp::ikcp_wndsize(this->kcp_, 128, 512);
}
// if call kcp_timer_.cancel first, then call _post_kcp_timer second immediately,
// use asio::post to avoid start timer failed.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = std::move(this_ptr)]() mutable
{
this->_post_kcp_timer(std::move(this_ptr));
}));
}
void _kcp_stop()
{
error_code ec_ignore{};
// if is kcp mode, send FIN handshake before close
if (this->send_fin_)
this->_kcp_send_hdr(kcp::make_kcphdr_fin(0), ec_ignore);
detail::cancel_timer(this->kcp_timer_);
}
inline void _kcp_reset()
{
kcp::ikcp_reset(this->kcp_);
}
protected:
inline std::size_t _kcp_send_hdr(kcp::kcphdr hdr, error_code& ec)
{
std::string msg = kcp::to_string(hdr);
std::size_t sent_bytes = 0;
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
if constexpr (args_t::is_session)
sent_bytes = derive.stream().send_to(asio::buffer(msg), derive.remote_endpoint_, 0, ec);
else
sent_bytes = derive.stream().send(asio::buffer(msg), 0, ec);
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
return sent_bytes;
}
inline std::size_t _kcp_send_syn(std::uint32_t seq, error_code& ec)
{
kcp::kcphdr syn = kcp::make_kcphdr_syn(derive.kcp_conv_, seq);
return this->_kcp_send_hdr(syn, ec);
}
inline std::size_t _kcp_send_synack(kcp::kcphdr syn, error_code& ec)
{
// the syn.th_ack is the kcp conv
kcp::kcphdr synack = kcp::make_kcphdr_synack(syn.th_ack, syn.th_seq);
return this->_kcp_send_hdr(synack, ec);
}
template<class Data, class Callback>
inline bool _kcp_send(Data& data, Callback&& callback)
{
#if defined(ASIO2_ENABLE_LOG)
static_assert(decltype(tallocator_)::storage_size == 168);
#endif
auto buffer = asio::buffer(data);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
int ret = kcp::ikcp_send(this->kcp_, (const char *)buffer.data(), (int)buffer.size());
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
switch (ret)
{
case 0: set_last_error(error_code{} ); break;
case -1: set_last_error(asio::error::invalid_argument ); break;
case -2: set_last_error(asio::error::no_memory ); break;
default: set_last_error(asio::error::operation_not_supported); break;
}
if (ret == 0)
{
kcp::ikcp_flush(this->kcp_);
}
callback(get_last_error(), ret < 0 ? 0 : buffer.size());
return (ret == 0);
}
void _post_kcp_timer(std::shared_ptr<derived_t> this_ptr)
{
std::uint32_t clock1 = static_cast<std::uint32_t>(std::chrono::duration_cast<
std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count());
std::uint32_t clock2 = kcp::ikcp_check(this->kcp_, clock1);
this->kcp_timer_.expires_after(std::chrono::milliseconds(clock2 - clock1));
this->kcp_timer_.async_wait(make_allocator(this->tallocator_,
[this, this_ptr = std::move(this_ptr)](const error_code & ec) mutable
{
this->_handle_kcp_timer(ec, std::move(this_ptr));
}));
}
void _handle_kcp_timer(const error_code & ec, std::shared_ptr<derived_t> this_ptr)
{
if (ec == asio::error::operation_aborted) return;
std::uint32_t clock = static_cast<std::uint32_t>(std::chrono::duration_cast<
std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count());
kcp::ikcp_update(this->kcp_, clock);
if (this->kcp_->state == (kcp::IUINT32)-1)
{
if (derive.state() == state_t::started)
{
derive._do_disconnect(asio::error::network_reset, std::move(this_ptr));
}
return;
}
if (derive.is_started())
this->_post_kcp_timer(std::move(this_ptr));
}
template<typename C>
void _kcp_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
auto& buffer = derive.buffer();
int len = kcp::ikcp_input(this->kcp_, (const char *)data.data(), (long)data.size());
buffer.consume(buffer.size());
if (len != 0)
{
set_last_error(asio::error::message_size);
if (derive.state() == state_t::started)
{
derive._do_disconnect(asio::error::message_size, this_ptr);
}
return;
}
for (;;)
{
len = kcp::ikcp_recv(this->kcp_, (char *)buffer.prepare(
buffer.pre_size()).data(), (int)buffer.pre_size());
if /**/ (len >= 0)
{
buffer.commit(len);
derive._fire_recv(this_ptr, ecs, std::string_view(static_cast
<std::string_view::const_pointer>(buffer.data().data()), len));
buffer.consume(len);
}
else if (len == -3)
{
buffer.pre_size((std::min)(buffer.pre_size() * 2, buffer.max_size()));
}
else
{
break;
}
}
kcp::ikcp_flush(this->kcp_);
}
template<typename C>
inline void _kcp_handle_recv(
error_code ec, std::string_view data,
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
// the kcp message header length is 24
// the kcphdr length is 12
if /**/ (data.size() > kcp::kcphdr::required_size())
{
this->_kcp_recv(this_ptr, ecs, data);
}
else if (data.size() == kcp::kcphdr::required_size())
{
// Check whether the packet is SYN handshake
// It is possible that the client did not receive the synack package, then the client
// will resend the syn package, so we just need to reply to the syncack package directly.
// If the client is disconnect without send a "fin" or the server has't recvd the
// "fin", and then the client connect again a later, at this time, the client
// is in the session map already, and we need check whether the first message is fin
if /**/ (kcp::is_kcphdr_syn(data))
{
ASIO2_ASSERT(this->kcp_);
if (this->kcp_)
{
kcp::kcphdr syn = kcp::to_kcphdr(data);
std::uint32_t conv = syn.th_ack;
if (conv == 0)
{
conv = this->kcp_->conv;
syn.th_ack = conv;
}
// If the client is forced disconnect after sent some messages, and the server
// has recvd the messages already, we must recreated the kcp object, otherwise
// the client and server will can't handle the next messages correctly.
#if 0
// set send_fin_ = false to make the _kcp_stop don't sent the fin frame.
this->send_fin_ = false;
this->_kcp_stop();
this->_kcp_start(this_ptr, conv);
#else
this->_kcp_reset();
#endif
this->send_fin_ = true;
// every time we recv kcp syn, we sent synack to the client
this->_kcp_send_synack(syn, ec);
if (ec)
{
derive._do_disconnect(ec, this_ptr);
}
}
else
{
derive._do_disconnect(asio::error::operation_aborted, this_ptr);
}
}
else if (kcp::is_kcphdr_synack(data, 0, true))
{
ASIO2_ASSERT(this->kcp_);
}
else if (kcp::is_kcphdr_ack(data, 0, true))
{
ASIO2_ASSERT(this->kcp_);
}
else if (kcp::is_kcphdr_fin(data))
{
ASIO2_ASSERT(this->kcp_);
this->send_fin_ = false;
derive._do_disconnect(asio::error::connection_reset, this_ptr);
}
else
{
ASIO2_ASSERT(false);
}
}
else
{
ASIO2_ASSERT(false);
}
}
template<typename C, typename DeferEvent>
void _session_post_handshake(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
error_code ec;
std::string& data = *(derive.first_data_);
// step 3 : server recvd syn from client (the first data is the syn)
kcp::kcphdr syn = kcp::to_kcphdr(data);
std::uint32_t conv = syn.th_ack;
if (conv == 0)
{
conv = derive.kcp_conv_;
syn.th_ack = conv;
}
// step 4 : server send synack to client
this->_kcp_send_synack(syn, ec);
if (ec)
{
derive._do_disconnect(ec, std::move(this_ptr), std::move(chain));
return;
}
this->_kcp_start(this_ptr, conv);
this->_handle_handshake(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename C, typename DeferEvent>
void _client_post_handshake(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
error_code ec;
// step 1 : client send syn to server
std::uint32_t seq = static_cast<std::uint32_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count());
this->_kcp_send_syn(seq, ec);
if (ec)
{
derive._do_disconnect(ec, std::move(this_ptr), defer_event(chain.move_guard()));
return;
}
// use a loop timer to execute "client send syn to server" until the server
// has recvd the syn packet and this client recvd reply.
std::shared_ptr<detail::safe_timer> timer =
mktimer(derive.io().context(), std::chrono::milliseconds(500),
[this, this_ptr, seq](error_code ec) mutable
{
if (ec == asio::error::operation_aborted)
return false;
this->_kcp_send_syn(seq, ec);
if (ec)
{
set_last_error(ec);
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, std::move(this_ptr));
}
return false;
}
// return true : let the timer continue execute.
// return false : kill the timer.
return true;
});
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_recv_counter_.load() == 0);
derive.post_recv_counter_++;
#endif
// step 2 : client wait for recv synack util connect timeout or recvd some data
derive.socket().async_receive(derive.buffer().prepare(derive.buffer().pre_size()),
make_allocator(derive.rallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain),
seq, timer = std::move(timer)]
(const error_code & ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
ASIO2_ASSERT(derive.io().running_in_this_thread());
timer->cancel();
if (ec)
{
// if connect_timeout_timer_ is empty, it means that the connect timeout timer is
// timeout and the callback has called already, so reset the error to timed_out.
// note : when the async_resolve is failed, the socket is invalid to.
this->_handle_handshake(
derive.connect_timeout_timer_ ? ec : asio::error::timed_out,
std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
derive.buffer().commit(bytes_recvd);
std::string_view data = std::string_view(static_cast<std::string_view::const_pointer>
(derive.buffer().data().data()), bytes_recvd);
// Check whether the data is the correct handshake information
if (kcp::is_kcphdr_synack(data, seq))
{
kcp::kcphdr hdr = kcp::to_kcphdr(data);
std::uint32_t conv = hdr.th_seq;
if (derive.kcp_conv_ != 0)
{
ASIO2_ASSERT(derive.kcp_conv_ == conv);
}
this->_kcp_start(this_ptr, conv);
this->_handle_handshake(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
else
{
this->_handle_handshake(asio::error::address_family_not_supported,
std::move(this_ptr), std::move(ecs), std::move(chain));
}
derive.buffer().consume(bytes_recvd);
}));
}
template<typename C, typename DeferEvent>
void _post_handshake(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
if constexpr (args_t::is_session)
{
this->_session_post_handshake(std::move(this_ptr), std::move(ecs), std::move(chain));
}
else
{
this->_client_post_handshake(std::move(this_ptr), std::move(ecs), std::move(chain));
}
}
template<typename C, typename DeferEvent>
void _handle_handshake(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs,
DeferEvent chain)
{
set_last_error(ec);
if constexpr (args_t::is_session)
{
derive._fire_handshake(this_ptr);
if (ec)
{
derive._do_disconnect(ec, std::move(this_ptr), std::move(chain));
return;
}
derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
else
{
derive._fire_handshake(this_ptr);
derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
}
static int _kcp_output(const char *buf, int len, kcp::ikcpcb *kcp, void *user)
{
std::ignore = kcp;
kcp_stream_cp * zhis = ((kcp_stream_cp*)user);
derived_t & derive = zhis->derive;
error_code ec;
if constexpr (args_t::is_session)
derive.stream().send_to(asio::buffer(buf, len),
derive.remote_endpoint_, 0, ec);
else
derive.stream().send(asio::buffer(buf, len), 0, ec);
return 0;
}
protected:
derived_t & derive;
kcp::ikcpcb * kcp_ = nullptr;
bool send_fin_ = true;
asio::steady_timer kcp_timer_;
handler_memory<std::true_type, allocator_fixed_size_op<168>> tallocator_;
};
}
#endif // !__ASIO2_KCP_STREAM_CP_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_UDP_SEND_OP_HPP__
#define __ASIO2_UDP_SEND_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/error.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class udp_send_op
{
public:
/**
* @brief constructor
*/
udp_send_op() noexcept {}
/**
* @brief destructor
*/
~udp_send_op() = default;
protected:
template<class Data, class Callback>
inline bool _udp_send(Data& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
derive.stream().async_send(asio::buffer(data),
make_allocator(derive.wallocator(),
[
#if defined(_DEBUG) || defined(DEBUG)
&derive,
#endif
p = derive.selfptr(), callback = std::forward<Callback>(callback)
]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
callback(ec, bytes_sent);
}));
return true;
}
template<class Endpoint, class Data, class Callback>
inline bool _udp_send_to(Endpoint& endpoint, Data& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
// issue: when on the server, all udp session are used a same socket, so
// multiple sessions maybe use the same socket to send data concurrently
// at the same time. But the test can't detect this problem. On windows
// platform, the WSASendTo always success and return 0.
derive.stream().async_send_to(asio::buffer(data), endpoint,
make_allocator(derive.wallocator(),
[
#if defined(_DEBUG) || defined(DEBUG)
&derive,
#endif
p = derive.selfptr(), callback = std::forward<Callback>(callback)
]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
callback(ec, bytes_sent);
}));
return true;
}
protected:
};
}
#endif // !__ASIO2_UDP_SEND_OP_HPP__
<file_sep>#include "unit_test.hpp"
#include <asio2/util/thread_pool.hpp>
#include <set>
std::atomic<int> c1 = 0;
void test1()
{
c1++;
}
void test2(int i)
{
c1 += i;
}
struct member_test
{
void test1()
{
c1++;
}
void test2(int i)
{
c1 += i;
}
};
void thread_pool_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
{
c1 = 0;
{
asio2::thread_pool thpool(2);
thpool.post([&]()
{
c1++;
ASIO2_CHECK(thpool.pool_size() == 2);
ASIO2_CHECK(thpool.task_size() == 0);
ASIO2_CHECK(thpool.running_in_threads());
});
}
ASIO2_CHECK_VALUE(c1.load(), c1 == 1);
}
{
c1 = 0;
{
asio2::thread_pool thpool;
thpool.post([&]()
{
c1++;
ASIO2_CHECK(thpool.pool_size() == std::thread::hardware_concurrency());
ASIO2_CHECK(thpool.running_in_threads());
});
thpool.post([&]() mutable
{
c1++;
ASIO2_CHECK(thpool.pool_size() == std::thread::hardware_concurrency());
ASIO2_CHECK(thpool.running_in_threads());
});
thpool.post(test1);
thpool.post(std::bind(test1));
thpool.post(test2, 1);
thpool.post(test2, 2);
thpool.post(std::bind(test2, 1));
thpool.post(std::bind(test2, 2));
member_test membertest;
thpool.post(&member_test::test1, membertest);
thpool.post(&member_test::test2, membertest, 1);
thpool.post(&member_test::test2, membertest, 2);
thpool.post(std::bind(&member_test::test1, membertest));
thpool.post(std::bind(&member_test::test2, membertest, 1));
thpool.post(std::bind(&member_test::test2, membertest, 2));
}
ASIO2_CHECK_VALUE(c1.load(), c1 == 18);
}
{
asio2::thread_pool thpool;
thpool.post(0, [&thpool]()
{
ASIO2_CHECK(std::this_thread::get_id() == thpool.get_thread_id(0));
});
for (std::size_t i = 0; i < thpool.get_pool_size(); ++i)
{
thpool.post(i, [&thpool, i]()
{
ASIO2_CHECK(std::this_thread::get_id() == thpool.get_thread_id(i));
});
}
for (int i = 0; i < test_loop_times / 10; ++i)
{
int thread_index = std::rand();
thpool.post([]()
{
std::this_thread::yield();
});
thpool.post(thread_index, [&thpool, thread_index]()
{
ASIO2_CHECK(std::this_thread::get_id() == thpool.get_thread_id(thread_index % thpool.get_pool_size()));
});
}
}
{
asio2::thread_pool thpool;
std::mutex mtx;
std::set<std::thread::id> thread_ids_set;
std::vector<std::future<void>> futures;
for (std::size_t i = 0; i < thpool.get_pool_size(); ++i)
{
auto future = thpool.post(i, [&thread_ids_set, &mtx]()
{
std::lock_guard g(mtx);
thread_ids_set.emplace(std::this_thread::get_id());
std::this_thread::sleep_for(std::chrono::milliseconds(1));
});
futures.emplace_back(std::move(future));
}
for (auto& f : futures)
{
f.wait();
}
ASIO2_CHECK(thread_ids_set.size() == thpool.get_pool_size());
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"thread_pool",
ASIO2_TEST_CASE(thread_pool_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SOCKS5_CORE_HPP__
#define __ASIO2_SOCKS5_CORE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <string>
#include <string_view>
#include <type_traits>
#include <asio2/base/error.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/util.hpp>
namespace asio2::socks5
{
///-----------------------------------------------------------------------------------------------
/// SOCKS Protocol Version 5:
/// https://www.ietf.org/rfc/rfc1928.txt
/// Username/Password Authentication for SOCKS V5 :
/// https://www.ietf.org/rfc/rfc1929.txt
/// GSSAPI : Generic Security Services Application Program Interface
/// https://en.wikipedia.org/wiki/Generic_Security_Services_Application_Program_Interface
///-----------------------------------------------------------------------------------------------
/// The type of error category used by the library
using error_category = asio::error_category;
/// The type of error condition used by the library
using error_condition = asio::error_condition;
enum class error
{
success = 0,
/// unsupported version.
unsupported_version,
/// unsupported method.
unsupported_method,
/// no acceptable methods.
no_acceptable_methods,
/// username required.
username_required,
/// unsupported authentication version.
unsupported_authentication_version,
/// authentication failed.
authentication_failed,
/// general failure.
general_failure,
/// no identd running.
no_identd,
/// no identd running.
identd_error,
/// general socks server failure
general_socks_server_failure,
/// connection not allowed by ruleset
connection_not_allowed_by_ruleset,
/// network unreachable
network_unreachable,
/// host unreachable
host_unreachable,
/// connection refused
connection_refused,
/// ttl expired
ttl_expired,
/// command not supported
command_not_supported,
/// address type not supported
address_type_not_supported,
/// to x'ff' unassigned
unassigned,
};
enum class condition
{
success = 0,
/// unsupported version.
unsupported_version,
/// unsupported method.
unsupported_method,
/// no acceptable methods.
no_acceptable_methods,
/// username required.
username_required,
/// unsupported authentication version.
unsupported_authentication_version,
/// authentication failed.
authentication_failed,
/// general failure.
general_failure,
/// no identd running.
no_identd,
/// no identd running.
identd_error,
/// general socks server failure
general_socks_server_failure,
/// connection not allowed by ruleset
connection_not_allowed_by_ruleset,
/// network unreachable
network_unreachable,
/// host unreachable
host_unreachable,
/// connection refused
connection_refused,
/// ttl expired
ttl_expired,
/// command not supported
command_not_supported,
/// address type not supported
address_type_not_supported,
/// to x'ff' unassigned
unassigned,
};
class socks5_error_category : public error_category
{
public:
const char* name() const noexcept override
{
return "asio2.socks5";
}
inline std::string message(int ev) const override
{
switch (static_cast<error>(ev))
{
case error::success:
return "Success";
case error::unsupported_version:
return "unsupported version";
case error::unsupported_method:
return "unsupported method";
case error::no_acceptable_methods:
return "no acceptable methods";
case error::username_required:
return "username required";
case error::unsupported_authentication_version:
return "unsupported authentication version";
case error::authentication_failed:
return "authentication failed";
case error::general_failure:
return "general failure";
case error::no_identd:
return "no identd running";
case error::identd_error:
return "no identd running";
case error::general_socks_server_failure:
return "general socks server failure";
case error::connection_not_allowed_by_ruleset:
return "connection not allowed by ruleset";
case error::network_unreachable:
return "network unreachable";
case error::host_unreachable:
return "host unreachable";
case error::connection_refused:
return "connection refused";
case error::ttl_expired:
return "ttl expired";
case error::command_not_supported:
return "command not supported";
case error::address_type_not_supported:
return "address type not supported";
case error::unassigned:
return "to x'ff' unassigned";
default:
return "Unknown PROXY error";
}
}
inline error_condition default_error_condition(int ev) const noexcept override
{
return error_condition{ ev, *this };
}
};
inline const socks5_error_category& socks5_category() noexcept
{
static socks5_error_category const cat{};
return cat;
}
inline error_code make_error_code(error e) noexcept
{
return error_code{ static_cast<std::underlying_type<error>::type>(e), socks5_category() };
}
inline error_condition make_error_condition(condition c) noexcept
{
return error_condition{ static_cast<std::underlying_type<condition>::type>(c), socks5_category() };
}
}
namespace std
{
template<>
struct is_error_code_enum<::asio2::socks5::error>
{
static bool const value = true;
};
template<>
struct is_error_condition_enum<::asio2::socks5::condition>
{
static bool const value = true;
};
}
namespace asio2::socks5
{
enum class method : std::uint8_t
{
anonymous = 0x00, // X'00' NO AUTHENTICATION REQUIRED
gssapi = 0x01, // X'01' GSSAPI
password = 0x02, // X'02' USERNAME/PASSWORD
//iana = 0x03, // X'03' to X'7F' IANA ASSIGNED
//reserved = 0x80, // X'80' to X'FE' RESERVED FOR PRIVATE METHODS
noacceptable = 0xFF, // X'FF' NO ACCEPTABLE METHODS
};
enum class command : std::uint8_t
{
connect = 0x01, // CONNECT X'01'
bind = 0x02, // BIND X'02'
udp_associate = 0x03, // UDP ASSOCIATE X'03'
};
}
#endif // !__ASIO2_SOCKS5_CORE_HPP__
<file_sep>#include <asio2/tcp/tcp_client.hpp>
void on_recv(asio2::tcp_client& client, std::string_view data)
{
printf("recv : %.*s\n", (int)data.size(), data.data());
// No matter what data we send, the server recved data must
// to be exactly the same as what we sent here
std::string str;
str += '#';
int len = 10 + (std::rand() % 100);
for (int i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
client.async_send(std::move(str));
}
void on_connect(asio2::tcp_client& client)
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n",
client.local_address().c_str(), client.local_port());
std::string str = "abc0123456789xyz";
// Beacuse the server specify the "max recv buffer size" to 1024, so if we
// send a too long packet, then this client will be disconnect .
//str.resize(1500);
client.async_send(std::move(str));
}
void on_disconnect()
{
printf("disconnect : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8027";
asio2::tcp_client client;
// bind global function
client
.bind_recv (std::bind(on_recv , std::ref(client), std::placeholders::_1)) // use std::bind
.bind_connect(std::bind(on_connect, std::ref(client)))
.bind_disconnect(on_disconnect);
client.start(host, port, asio2::use_dgram);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
Copyright <NAME> 2011-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LANGUAGE_STDCPP_H
#define BHO_PREDEF_LANGUAGE_STDCPP_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LANG_STDCPP`
http://en.wikipedia.org/wiki/C%2B%2B[Standard {CPP}] language.
If available, the year of the standard is detected as YYYY.MM.1 from the Epoch date.
Because of the way the {CPP} standardization process works the
defined version year will not be the commonly known year of the standard.
Specifically the defined versions are:
.Detected Version Number vs. {CPP} Standard Year
[options="header"]
|===
| Detected Version Number | Standard Year | {CPP} Standard
| 27.11.1 | 1998 | ISO/IEC 14882:1998
| 41.3.1 | 2011 | ISO/IEC 14882:2011
| 44.2.1 | 2014 | ISO/IEC 14882:2014
| 47.3.1 | 2017 | ISO/IEC 14882:2017
|===
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__cplusplus+` | {predef_detection}
| `+__cplusplus+` | YYYY.MM.1
|===
*/ // end::reference[]
#define BHO_LANG_STDCPP BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__cplusplus)
# undef BHO_LANG_STDCPP
# if (__cplusplus > 100)
# define BHO_LANG_STDCPP BHO_PREDEF_MAKE_YYYYMM(__cplusplus)
# else
# define BHO_LANG_STDCPP BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_LANG_STDCPP
# define BHO_LANG_STDCPP_AVAILABLE
#endif
#define BHO_LANG_STDCPP_NAME "Standard C++"
/* tag::reference[]
= `BHO_LANG_STDCPPCLI`
http://en.wikipedia.org/wiki/C%2B%2B/CLI[Standard {CPP}/CLI] language.
If available, the year of the standard is detected as YYYY.MM.1 from the Epoch date.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__cplusplus_cli+` | {predef_detection}
| `+__cplusplus_cli+` | YYYY.MM.1
|===
*/ // end::reference[]
#define BHO_LANG_STDCPPCLI BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__cplusplus_cli)
# undef BHO_LANG_STDCPPCLI
# if (__cplusplus_cli > 100)
# define BHO_LANG_STDCPPCLI BHO_PREDEF_MAKE_YYYYMM(__cplusplus_cli)
# else
# define BHO_LANG_STDCPPCLI BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_LANG_STDCPPCLI
# define BHO_LANG_STDCPPCLI_AVAILABLE
#endif
#define BHO_LANG_STDCPPCLI_NAME "Standard C++/CLI"
/* tag::reference[]
= `BHO_LANG_STDECPP`
http://en.wikipedia.org/wiki/Embedded_C%2B%2B[Standard Embedded {CPP}] language.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__embedded_cplusplus+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_LANG_STDECPP BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__embedded_cplusplus)
# undef BHO_LANG_STDECPP
# define BHO_LANG_STDECPP BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_LANG_STDECPP
# define BHO_LANG_STDECPP_AVAILABLE
#endif
#define BHO_LANG_STDECPP_NAME "Standard Embedded C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LANG_STDCPP,BHO_LANG_STDCPP_NAME)
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LANG_STDCPPCLI,BHO_LANG_STDCPPCLI_NAME)
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LANG_STDECPP,BHO_LANG_STDECPP_NAME)
<file_sep>#ifndef BHO_CORE_REF_HPP
#define BHO_CORE_REF_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <asio2/bho/config.hpp>
#include <asio2/bho/config/workaround.hpp>
#include <asio2/bho/core/addressof.hpp>
#include <asio2/bho/core/enable_if.hpp>
//
// ref.hpp - ref/cref, useful helper functions
//
// Copyright (C) 1999, 2000 <NAME> (<EMAIL>)
// Copyright (C) 2001, 2002 <NAME>
// Copyright (C) 2002 <NAME>
//
// Copyright (C) 2014 <NAME>
// (<EMAIL>)
//
// Copyright (C) 2014 <NAME>
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/core/doc/html/core/ref.html for documentation.
//
/**
@file
*/
/**
bho namespace.
*/
namespace bho
{
#if defined( BHO_MSVC ) && BHO_WORKAROUND( BHO_MSVC, == 1600 )
struct ref_workaround_tag {};
#endif
namespace detail
{
template< class Y, class T > struct ref_convertible
{
typedef char (&yes) [1];
typedef char (&no) [2];
static yes f( T* );
static no f( ... );
enum _vt { value = sizeof( (f)( static_cast<Y*>(0) ) ) == sizeof(yes) };
};
struct ref_empty
{
};
} // namespace detail
// reference_wrapper
/**
@brief Contains a reference to an object of type `T`.
`reference_wrapper` is primarily used to "feed" references to
function templates (algorithms) that take their parameter by
value. It provides an implicit conversion to `T&`, which
usually allows the function templates to work on references
unmodified.
*/
template<class T> class reference_wrapper
{
public:
/**
Type `T`.
*/
typedef T type;
/**
Constructs a `reference_wrapper` object that stores a
reference to `t`.
@remark Does not throw.
*/
BHO_FORCEINLINE explicit reference_wrapper(T& t): t_(bho::addressof(t)) {}
#if defined( BHO_MSVC ) && BHO_WORKAROUND( BHO_MSVC, == 1600 )
BHO_FORCEINLINE explicit reference_wrapper( T & t, ref_workaround_tag ): t_( bho::addressof( t ) ) {}
#endif
#if !defined(BHO_NO_CXX11_RVALUE_REFERENCES)
/**
@remark Construction from a temporary object is disabled.
*/
BHO_DELETED_FUNCTION(reference_wrapper(T&& t))
public:
#endif
template<class Y> friend class reference_wrapper;
/**
Constructs a `reference_wrapper` object that stores the
reference stored in the compatible `reference_wrapper` `r`.
@remark Only enabled when `Y*` is convertible to `T*`.
@remark Does not throw.
*/
template<class Y> reference_wrapper( reference_wrapper<Y> r,
typename enable_if_c<bho::detail::ref_convertible<Y, T>::value,
bho::detail::ref_empty>::type = bho::detail::ref_empty() ): t_( r.t_ )
{
}
/**
@return The stored reference.
@remark Does not throw.
*/
BHO_FORCEINLINE operator T& () const { return *t_; }
/**
@return The stored reference.
@remark Does not throw.
*/
BHO_FORCEINLINE T& get() const { return *t_; }
/**
@return A pointer to the object referenced by the stored
reference.
@remark Does not throw.
*/
BHO_FORCEINLINE T* get_pointer() const { return t_; }
private:
T* t_;
};
// ref
/**
@cond
*/
#if defined( BHO_BORLANDC ) && BHO_WORKAROUND( BHO_BORLANDC, BHO_TESTED_AT(0x581) )
# define BHO_REF_CONST
#else
# define BHO_REF_CONST const
#endif
/**
@endcond
*/
/**
@return `reference_wrapper<T>(t)`
@remark Does not throw.
*/
template<class T> BHO_FORCEINLINE reference_wrapper<T> BHO_REF_CONST ref( T & t )
{
#if defined( BHO_MSVC ) && BHO_WORKAROUND( BHO_MSVC, == 1600 )
return reference_wrapper<T>( t, ref_workaround_tag() );
#else
return reference_wrapper<T>( t );
#endif
}
// cref
/**
@return `reference_wrapper<T const>(t)`
@remark Does not throw.
*/
template<class T> BHO_FORCEINLINE reference_wrapper<T const> BHO_REF_CONST cref( T const & t )
{
return reference_wrapper<T const>(t);
}
#undef BHO_REF_CONST
#if !defined(BHO_NO_CXX11_RVALUE_REFERENCES)
/**
@cond
*/
#if defined(BHO_NO_CXX11_DELETED_FUNCTIONS)
# define BHO_REF_DELETE
#else
# define BHO_REF_DELETE = delete
#endif
/**
@endcond
*/
/**
@remark Construction from a temporary object is disabled.
*/
template<class T> void ref(T const&&) BHO_REF_DELETE;
/**
@remark Construction from a temporary object is disabled.
*/
template<class T> void cref(T const&&) BHO_REF_DELETE;
#undef BHO_REF_DELETE
#endif
// is_reference_wrapper
/**
@brief Determine if a type `T` is an instantiation of
`reference_wrapper`.
The value static constant will be true if the type `T` is a
specialization of `reference_wrapper`.
*/
template<typename T> struct is_reference_wrapper
{
BHO_STATIC_CONSTANT( bool, value = false );
};
/**
@cond
*/
template<typename T> struct is_reference_wrapper< reference_wrapper<T> >
{
BHO_STATIC_CONSTANT( bool, value = true );
};
#if !defined(BHO_NO_CV_SPECIALIZATIONS)
template<typename T> struct is_reference_wrapper< reference_wrapper<T> const >
{
BHO_STATIC_CONSTANT( bool, value = true );
};
template<typename T> struct is_reference_wrapper< reference_wrapper<T> volatile >
{
BHO_STATIC_CONSTANT( bool, value = true );
};
template<typename T> struct is_reference_wrapper< reference_wrapper<T> const volatile >
{
BHO_STATIC_CONSTANT( bool, value = true );
};
#endif // !defined(BHO_NO_CV_SPECIALIZATIONS)
/**
@endcond
*/
// unwrap_reference
/**
@brief Find the type in a `reference_wrapper`.
The `typedef` type is `T::type` if `T` is a
`reference_wrapper`, `T` otherwise.
*/
template<typename T> struct unwrap_reference
{
typedef T type;
};
/**
@cond
*/
template<typename T> struct unwrap_reference< reference_wrapper<T> >
{
typedef T type;
};
#if !defined(BHO_NO_CV_SPECIALIZATIONS)
template<typename T> struct unwrap_reference< reference_wrapper<T> const >
{
typedef T type;
};
template<typename T> struct unwrap_reference< reference_wrapper<T> volatile >
{
typedef T type;
};
template<typename T> struct unwrap_reference< reference_wrapper<T> const volatile >
{
typedef T type;
};
#endif // !defined(BHO_NO_CV_SPECIALIZATIONS)
/**
@endcond
*/
// unwrap_ref
/**
@return `unwrap_reference<T>::type&(t)`
@remark Does not throw.
*/
template<class T> BHO_FORCEINLINE typename unwrap_reference<T>::type& unwrap_ref( T & t )
{
return t;
}
// get_pointer
/**
@cond
*/
template<class T> BHO_FORCEINLINE T* get_pointer( reference_wrapper<T> const & r )
{
return r.get_pointer();
}
/**
@endcond
*/
} // namespace bho
#endif // #ifndef BHO_CORE_REF_HPP
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_RPCS_SESSION_HPP__
#define __ASIO2_RPCS_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if __has_include(<cereal/cereal.hpp>)
#include <asio2/rpc/rpc_session.hpp>
namespace asio2
{
namespace detail
{
template<asio2::net_protocol np> struct template_args_rpcs_session;
template<>
struct template_args_rpcs_session<asio2::net_protocol::tcps> : public template_args_tcp_session
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::tcps;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
template<>
struct template_args_rpcs_session<asio2::net_protocol::wss> : public template_args_wss_session
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::wss;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
}
using rpcs_session_args_tcp = detail::template_args_rpcs_session<asio2::net_protocol::tcps>;
using rpcs_session_args_ws = detail::template_args_rpcs_session<asio2::net_protocol::wss >;
template<class derived_t, asio2::net_protocol np> class rpcs_session_t;
template<class derived_t>
class rpcs_session_t<derived_t, asio2::net_protocol::tcps> : public detail::rpc_session_impl_t<derived_t,
detail::tcps_session_impl_t<derived_t, detail::template_args_rpcs_session<asio2::net_protocol::tcps>>>
{
public:
using detail::rpc_session_impl_t<derived_t, detail::tcps_session_impl_t<
derived_t, detail::template_args_rpcs_session<asio2::net_protocol::tcps>>>::rpc_session_impl_t;
};
template<class derived_t>
class rpcs_session_t<derived_t, asio2::net_protocol::wss> : public detail::rpc_session_impl_t<derived_t,
detail::wss_session_impl_t<derived_t, detail::template_args_rpcs_session<asio2::net_protocol::wss>>>
{
public:
using detail::rpc_session_impl_t<derived_t, detail::wss_session_impl_t<
derived_t, detail::template_args_rpcs_session<asio2::net_protocol::wss>>>::rpc_session_impl_t;
};
template<asio2::net_protocol np>
class rpcs_session_use : public rpcs_session_t<rpcs_session_use<np>, np>
{
public:
using rpcs_session_t<rpcs_session_use<np>, np>::rpcs_session_t;
};
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpcs_session = rpcs_session_use<asio2::net_protocol::tcps>;
#else
/// Using websocket as the underlying communication support
using rpcs_session = rpcs_session_use<asio2::net_protocol::wss>;
#endif
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct rpcs_rate_session_args_tcp : public rpcs_session_args_tcp
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
struct rpcs_rate_session_args_ws : public rpcs_session_args_ws
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
using stream_t = websocket::stream<asio::ssl::stream<socket_t&>&>;
};
template<class derived_t, asio2::net_protocol np> class rpcs_rate_session_t;
template<class derived_t>
class rpcs_rate_session_t<derived_t, asio2::net_protocol::tcps> : public detail::rpc_session_impl_t<derived_t,
detail::tcps_session_impl_t<derived_t, rpcs_rate_session_args_tcp>>
{
public:
using detail::rpc_session_impl_t<derived_t,
detail::tcps_session_impl_t<derived_t, rpcs_rate_session_args_tcp>>::rpc_session_impl_t;
};
template<class derived_t>
class rpcs_rate_session_t<derived_t, asio2::net_protocol::wss> : public detail::rpc_session_impl_t<derived_t,
detail::wss_session_impl_t<derived_t, rpcs_rate_session_args_ws>>
{
public:
using detail::rpc_session_impl_t<derived_t,
detail::wss_session_impl_t<derived_t, rpcs_rate_session_args_ws>>::rpc_session_impl_t;
};
template<asio2::net_protocol np>
class rpcs_rate_session_use : public rpcs_rate_session_t<rpcs_rate_session_use<np>, np>
{
public:
using rpcs_rate_session_t<rpcs_rate_session_use<np>, np>::rpcs_rate_session_t;
};
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpcs_rate_session = rpcs_rate_session_use<asio2::net_protocol::tcps>;
#else
/// Using websocket as the underlying communication support
using rpcs_rate_session = rpcs_rate_session_use<asio2::net_protocol::wss>;
#endif
}
#endif
#endif
#endif // !__ASIO2_RPCS_SESSION_HPP__
#endif
<file_sep>// Copyright (c) 2016-2021 <NAME>
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BHO_PFR_DETAIL_CORE_HPP
#define BHO_PFR_DETAIL_CORE_HPP
#pragma once
#include <asio2/bho/pfr/detail/config.hpp>
// Each core provides `bho::pfr::detail::tie_as_tuple` and
// `bho::pfr::detail::for_each_field_dispatcher` functions.
//
// The whole PFR library is build on top of those two functions.
#if BHO_PFR_USE_CPP17
# include <asio2/bho/pfr/detail/core17.hpp>
#elif BHO_PFR_USE_LOOPHOLE
# include <asio2/bho/pfr/detail/core14_loophole.hpp>
#else
# include <asio2/bho/pfr/detail/core14_classic.hpp>
#endif
#endif // BHO_PFR_DETAIL_CORE_HPP
<file_sep>// (C) Copyright <NAME> 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE auto_link.hpp
* VERSION see <asio2/bho/version.hpp>
* DESCRIPTION: Automatic library inclusion for Borland/Microsoft compilers.
*/
/*************************************************************************
USAGE:
~~~~~~
Before including this header you must define one or more of define the following macros:
BHO_LIB_NAME: Required: A string containing the basename of the library,
for example boost_regex.
BHO_LIB_TOOLSET: Optional: the base name of the toolset.
BHO_DYN_LINK: Optional: when set link to dll rather than static library.
BHO_LIB_DIAGNOSTIC: Optional: when set the header will print out the name
of the library selected (useful for debugging).
BHO_AUTO_LINK_NOMANGLE: Specifies that we should link to BHO_LIB_NAME.lib,
rather than a mangled-name version.
BHO_AUTO_LINK_TAGGED: Specifies that we link to libraries built with the --layout=tagged option.
This is essentially the same as the default name-mangled version, but without
the compiler name and version, or the Boost version. Just the build options.
BHO_AUTO_LINK_SYSTEM: Specifies that we link to libraries built with the --layout=system option.
This is essentially the same as the non-name-mangled version, but with
the prefix to differentiate static and dll builds
These macros will be undef'ed at the end of the header, further this header
has no include guards - so be sure to include it only once from your library!
Algorithm:
~~~~~~~~~~
Libraries for Borland and Microsoft compilers are automatically
selected here, the name of the lib is selected according to the following
formula:
BHO_LIB_PREFIX
+ BHO_LIB_NAME
+ "_"
+ BHO_LIB_TOOLSET
+ BHO_LIB_THREAD_OPT
+ BHO_LIB_RT_OPT
+ BHO_LIB_ARCH_AND_MODEL_OPT
"-"
+ BHO_LIB_VERSION
+ BHO_LIB_SUFFIX
These are defined as:
BHO_LIB_PREFIX: "lib" for static libraries otherwise "".
BHO_LIB_NAME: The base name of the lib ( for example boost_regex).
BHO_LIB_TOOLSET: The compiler toolset name (vc6, vc7, bcb5 etc).
BHO_LIB_THREAD_OPT: "-mt" for multithread builds, otherwise nothing.
BHO_LIB_RT_OPT: A suffix that indicates the runtime library used,
contains one or more of the following letters after
a hyphen:
s static runtime (dynamic if not present).
g debug/diagnostic runtime (release if not present).
y Python debug/diagnostic runtime (release if not present).
d debug build (release if not present).
p STLport build.
n STLport build without its IOStreams.
BHO_LIB_ARCH_AND_MODEL_OPT: The architecture and address model
(-x32 or -x64 for x86/32 and x86/64 respectively)
BHO_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y.
BHO_LIB_SUFFIX: Static/import libraries extension (".lib", ".a") for the compiler.
***************************************************************************/
#ifdef __cplusplus
# ifndef BHO_CONFIG_HPP
# include <asio2/bho/config.hpp>
# endif
#elif defined(_MSC_VER) && !defined(__MWERKS__) && !defined(__EDG_VERSION__)
//
// C language compatability (no, honestly)
//
# define BHO_MSVC _MSC_VER
# define BHO_STRINGIZE(X) BHO_DO_STRINGIZE(X)
# define BHO_DO_STRINGIZE(X) #X
#endif
//
// Only include what follows for known and supported compilers:
//
#if defined(BHO_MSVC) \
|| defined(BHO_EMBTC_WINDOWS) \
|| defined(BHO_BORLANDC) \
|| (defined(__MWERKS__) && defined(_WIN32) && (__MWERKS__ >= 0x3000)) \
|| (defined(__ICL) && defined(_MSC_EXTENSIONS) && (_MSC_VER >= 1200)) \
|| (defined(BHO_CLANG) && defined(BHO_WINDOWS) && defined(_MSC_VER) && (__clang_major__ >= 4))
#ifndef BHO_VERSION_HPP
# include <asio2/bho/version.hpp>
#endif
#ifndef BHO_LIB_NAME
# error "Macro BHO_LIB_NAME not set (internal error)"
#endif
//
// error check:
//
#if defined(__MSVC_RUNTIME_CHECKS) && !defined(_DEBUG)
# pragma message("Using the /RTC option without specifying a debug runtime will lead to linker errors")
# pragma message("Hint: go to the code generation options and switch to one of the debugging runtimes")
# error "Incompatible build options"
#endif
//
// select toolset if not defined already:
//
#ifndef BHO_LIB_TOOLSET
# if defined(BHO_MSVC) && (BHO_MSVC < 1200)
// Note: no compilers before 1200 are supported
# elif defined(BHO_MSVC) && (BHO_MSVC < 1300)
# ifdef UNDER_CE
// eVC4:
# define BHO_LIB_TOOLSET "evc4"
# else
// vc6:
# define BHO_LIB_TOOLSET "vc6"
# endif
# elif defined(BHO_MSVC) && (BHO_MSVC < 1310)
// vc7:
# define BHO_LIB_TOOLSET "vc7"
# elif defined(BHO_MSVC) && (BHO_MSVC < 1400)
// vc71:
# define BHO_LIB_TOOLSET "vc71"
# elif defined(BHO_MSVC) && (BHO_MSVC < 1500)
// vc80:
# define BHO_LIB_TOOLSET "vc80"
# elif defined(BHO_MSVC) && (BHO_MSVC < 1600)
// vc90:
# define BHO_LIB_TOOLSET "vc90"
# elif defined(BHO_MSVC) && (BHO_MSVC < 1700)
// vc10:
# define BHO_LIB_TOOLSET "vc100"
# elif defined(BHO_MSVC) && (BHO_MSVC < 1800)
// vc11:
# define BHO_LIB_TOOLSET "vc110"
# elif defined(BHO_MSVC) && (BHO_MSVC < 1900)
// vc12:
# define BHO_LIB_TOOLSET "vc120"
# elif defined(BHO_MSVC) && (BHO_MSVC < 1910)
// vc14:
# define BHO_LIB_TOOLSET "vc140"
# elif defined(BHO_MSVC) && (BHO_MSVC < 1920)
// vc14.1:
# define BHO_LIB_TOOLSET "vc141"
# elif defined(BHO_MSVC) && (BHO_MSVC < 1930)
// vc14.2:
# define BHO_LIB_TOOLSET "vc142"
# elif defined(BHO_MSVC)
// vc14.3:
# define BHO_LIB_TOOLSET "vc143"
# elif defined(BHO_EMBTC_WINDOWS)
// Embarcadero Clang based compilers:
# define BHO_LIB_TOOLSET "embtc"
# elif defined(BHO_BORLANDC)
// CBuilder 6:
# define BHO_LIB_TOOLSET "bcb"
# elif defined(__ICL)
// Intel C++, no version number:
# define BHO_LIB_TOOLSET "iw"
# elif defined(__MWERKS__) && (__MWERKS__ <= 0x31FF )
// Metrowerks CodeWarrior 8.x
# define BHO_LIB_TOOLSET "cw8"
# elif defined(__MWERKS__) && (__MWERKS__ <= 0x32FF )
// Metrowerks CodeWarrior 9.x
# define BHO_LIB_TOOLSET "cw9"
# elif defined(BHO_CLANG) && defined(BHO_WINDOWS) && defined(_MSC_VER) && (__clang_major__ >= 4)
// Clang on Windows
# define BHO_LIB_TOOLSET "clangw" BHO_STRINGIZE(__clang_major__)
# endif
#endif // BHO_LIB_TOOLSET
//
// select thread opt:
//
#if defined(_MT) || defined(__MT__)
# define BHO_LIB_THREAD_OPT "-mt"
#else
# define BHO_LIB_THREAD_OPT
#endif
#if defined(_MSC_VER) || defined(__MWERKS__)
# ifdef _DLL
# if (defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) && (defined(_STLP_OWN_IOSTREAMS) || defined(__STL_OWN_IOSTREAMS))
# if defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG))\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-gydp"
# elif defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG))
# define BHO_LIB_RT_OPT "-gdp"
# elif defined(_DEBUG)\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-gydp"
# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1")
# error "Build options aren't compatible with pre-built libraries"
# elif defined(_DEBUG)
# define BHO_LIB_RT_OPT "-gdp"
# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1")
# error "Build options aren't compatible with pre-built libraries"
# else
# define BHO_LIB_RT_OPT "-p"
# endif
# elif defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)
# if defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG))\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-gydpn"
# elif defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG))
# define BHO_LIB_RT_OPT "-gdpn"
# elif defined(_DEBUG)\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-gydpn"
# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1")
# error "Build options aren't compatible with pre-built libraries"
# elif defined(_DEBUG)
# define BHO_LIB_RT_OPT "-gdpn"
# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1")
# error "Build options aren't compatible with pre-built libraries"
# else
# define BHO_LIB_RT_OPT "-pn"
# endif
# else
# if defined(_DEBUG) && defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-gyd"
# elif defined(_DEBUG)
# define BHO_LIB_RT_OPT "-gd"
# else
# define BHO_LIB_RT_OPT
# endif
# endif
# else
# if (defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) && (defined(_STLP_OWN_IOSTREAMS) || defined(__STL_OWN_IOSTREAMS))
# if defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG))\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-sgydp"
# elif defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG))
# define BHO_LIB_RT_OPT "-sgdp"
# elif defined(_DEBUG)\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-sgydp"
# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1")
# error "Build options aren't compatible with pre-built libraries"
# elif defined(_DEBUG)
# define BHO_LIB_RT_OPT "-sgdp"
# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1")
# error "Build options aren't compatible with pre-built libraries"
# else
# define BHO_LIB_RT_OPT "-sp"
# endif
# elif defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)
# if defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG))\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-sgydpn"
# elif defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG))
# define BHO_LIB_RT_OPT "-sgdpn"
# elif defined(_DEBUG)\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-sgydpn"
# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1")
# error "Build options aren't compatible with pre-built libraries"
# elif defined(_DEBUG)
# define BHO_LIB_RT_OPT "-sgdpn"
# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1")
# error "Build options aren't compatible with pre-built libraries"
# else
# define BHO_LIB_RT_OPT "-spn"
# endif
# else
# if defined(_DEBUG)\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-sgyd"
# elif defined(_DEBUG)
# define BHO_LIB_RT_OPT "-sgd"
# else
# define BHO_LIB_RT_OPT "-s"
# endif
# endif
# endif
#elif defined(BHO_EMBTC_WINDOWS)
# ifdef _RTLDLL
# if defined(_DEBUG)
# define BHO_LIB_RT_OPT "-d"
# else
# define BHO_LIB_RT_OPT
# endif
# else
# if defined(_DEBUG)
# define BHO_LIB_RT_OPT "-sd"
# else
# define BHO_LIB_RT_OPT "-s"
# endif
# endif
#elif defined(BHO_BORLANDC)
//
// figure out whether we want the debug builds or not:
//
#if BHO_BORLANDC > 0x561
#pragma defineonoption BHO_BORLAND_DEBUG -v
#endif
//
// sanity check:
//
#if defined(__STL_DEBUG) || defined(_STLP_DEBUG)
#error "Pre-built versions of the Boost libraries are not provided in STLport-debug form"
#endif
# ifdef _RTLDLL
# if defined(BHO_BORLAND_DEBUG)\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-yd"
# elif defined(BHO_BORLAND_DEBUG)
# define BHO_LIB_RT_OPT "-d"
# elif defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-y"
# else
# define BHO_LIB_RT_OPT
# endif
# else
# if defined(BHO_BORLAND_DEBUG)\
&& defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-syd"
# elif defined(BHO_BORLAND_DEBUG)
# define BHO_LIB_RT_OPT "-sd"
# elif defined(BHO_DEBUG_PYTHON) && defined(BHO_LINKING_PYTHON)
# define BHO_LIB_RT_OPT "-sy"
# else
# define BHO_LIB_RT_OPT "-s"
# endif
# endif
#endif
//
// BHO_LIB_ARCH_AND_MODEL_OPT
//
#if defined( _M_IX86 )
# define BHO_LIB_ARCH_AND_MODEL_OPT "-x32"
#elif defined( _M_X64 )
# define BHO_LIB_ARCH_AND_MODEL_OPT "-x64"
#elif defined( _M_ARM )
# define BHO_LIB_ARCH_AND_MODEL_OPT "-a32"
#elif defined( _M_ARM64 )
# define BHO_LIB_ARCH_AND_MODEL_OPT "-a64"
#endif
//
// select linkage opt:
//
#if (defined(_DLL) || defined(_RTLDLL)) && defined(BHO_DYN_LINK)
# define BHO_LIB_PREFIX
#elif defined(BHO_DYN_LINK)
# error "Mixing a dll boost library with a static runtime is a really bad idea..."
#else
# define BHO_LIB_PREFIX "lib"
#endif
//
// now include the lib:
//
#if defined(BHO_LIB_NAME) \
&& defined(BHO_LIB_PREFIX) \
&& defined(BHO_LIB_TOOLSET) \
&& defined(BHO_LIB_THREAD_OPT) \
&& defined(BHO_LIB_RT_OPT) \
&& defined(BHO_LIB_ARCH_AND_MODEL_OPT) \
&& defined(BHO_LIB_VERSION)
#if defined(BHO_EMBTC_WIN64)
# define BHO_LIB_SUFFIX ".a"
#else
# define BHO_LIB_SUFFIX ".lib"
#endif
#ifdef BHO_AUTO_LINK_NOMANGLE
# pragma comment(lib, BHO_STRINGIZE(BHO_LIB_NAME) BHO_LIB_SUFFIX)
# ifdef BHO_LIB_DIAGNOSTIC
# pragma message ("Linking to lib file: " BHO_STRINGIZE(BHO_LIB_NAME) BHO_LIB_SUFFIX)
# endif
#elif defined(BHO_AUTO_LINK_TAGGED)
# pragma comment(lib, BHO_LIB_PREFIX BHO_STRINGIZE(BHO_LIB_NAME) BHO_LIB_THREAD_OPT BHO_LIB_RT_OPT BHO_LIB_ARCH_AND_MODEL_OPT BHO_LIB_SUFFIX)
# ifdef BHO_LIB_DIAGNOSTIC
# pragma message ("Linking to lib file: " BHO_LIB_PREFIX BHO_STRINGIZE(BHO_LIB_NAME) BHO_LIB_THREAD_OPT BHO_LIB_RT_OPT BHO_LIB_ARCH_AND_MODEL_OPT BHO_LIB_SUFFIX)
# endif
#elif defined(BHO_AUTO_LINK_SYSTEM)
# pragma comment(lib, BHO_LIB_PREFIX BHO_STRINGIZE(BHO_LIB_NAME) BHO_LIB_SUFFIX)
# ifdef BHO_LIB_DIAGNOSTIC
# pragma message ("Linking to lib file: " BHO_LIB_PREFIX BHO_STRINGIZE(BHO_LIB_NAME) BHO_LIB_SUFFIX)
# endif
#elif defined(BHO_LIB_BUILDID)
# pragma comment(lib, BHO_LIB_PREFIX BHO_STRINGIZE(BHO_LIB_NAME) "-" BHO_LIB_TOOLSET BHO_LIB_THREAD_OPT BHO_LIB_RT_OPT BHO_LIB_ARCH_AND_MODEL_OPT "-" BHO_LIB_VERSION "-" BHO_STRINGIZE(BHO_LIB_BUILDID) BHO_LIB_SUFFIX)
# ifdef BHO_LIB_DIAGNOSTIC
# pragma message ("Linking to lib file: " BHO_LIB_PREFIX BHO_STRINGIZE(BHO_LIB_NAME) "-" BHO_LIB_TOOLSET BHO_LIB_THREAD_OPT BHO_LIB_RT_OPT BHO_LIB_ARCH_AND_MODEL_OPT "-" BHO_LIB_VERSION "-" BHO_STRINGIZE(BHO_LIB_BUILDID) BHO_LIB_SUFFIX)
# endif
#else
# pragma comment(lib, BHO_LIB_PREFIX BHO_STRINGIZE(BHO_LIB_NAME) "-" BHO_LIB_TOOLSET BHO_LIB_THREAD_OPT BHO_LIB_RT_OPT BHO_LIB_ARCH_AND_MODEL_OPT "-" BHO_LIB_VERSION BHO_LIB_SUFFIX)
# ifdef BHO_LIB_DIAGNOSTIC
# pragma message ("Linking to lib file: " BHO_LIB_PREFIX BHO_STRINGIZE(BHO_LIB_NAME) "-" BHO_LIB_TOOLSET BHO_LIB_THREAD_OPT BHO_LIB_RT_OPT BHO_LIB_ARCH_AND_MODEL_OPT "-" BHO_LIB_VERSION BHO_LIB_SUFFIX)
# endif
#endif
#else
# error "some required macros where not defined (internal logic error)."
#endif
#endif // _MSC_VER || __BORLANDC__
//
// finally undef any macros we may have set:
//
#ifdef BHO_LIB_PREFIX
# undef BHO_LIB_PREFIX
#endif
#if defined(BHO_LIB_NAME)
# undef BHO_LIB_NAME
#endif
// Don't undef this one: it can be set by the user and should be the
// same for all libraries:
//#if defined(BHO_LIB_TOOLSET)
//# undef BHO_LIB_TOOLSET
//#endif
#if defined(BHO_LIB_THREAD_OPT)
# undef BHO_LIB_THREAD_OPT
#endif
#if defined(BHO_LIB_RT_OPT)
# undef BHO_LIB_RT_OPT
#endif
#if defined(BHO_LIB_ARCH_AND_MODEL_OPT)
# undef BHO_LIB_ARCH_AND_MODEL_OPT
#endif
#if defined(BHO_LIB_LINK_OPT)
# undef BHO_LIB_LINK_OPT
#endif
#if defined(BHO_LIB_DEBUG_OPT)
# undef BHO_LIB_DEBUG_OPT
#endif
#if defined(BHO_DYN_LINK)
# undef BHO_DYN_LINK
#endif
#if defined(BHO_LIB_SUFFIX)
# undef BHO_LIB_SUFFIX
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_OPTIONS_HPP__
#define __ASIO2_MQTT_OPTIONS_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
class mqtt_options
{
public:
using self = mqtt_options;
/**
* @brief constructor
*/
mqtt_options()
{
_receive_maximum = static_cast<decltype(_receive_maximum )>(65535); // broker.hivemq.com is 10
_topic_alias_maximum = static_cast<decltype(_topic_alias_maximum)>(65535); // broker.hivemq.com is 5
_maximum_qos = static_cast<decltype(_maximum_qos )>(mqtt::qos_type::exactly_once);
_retain_available = static_cast<decltype(_retain_available )>(1);
}
/**
* @brief destructor
*/
~mqtt_options() = default;
/**
* set the mqtt options
*/
inline self& set_options(const mqtt_options& options)
{
this->_mqtt_options_copy_from(options);
return (*this);
}
// The Client uses this value to limit the number of QoS 1 and QoS 2 publications that it is willing to
// process concurrently. There is no mechanism to limit the QoS 0 publications that the Server might try to send.
// The value of Receive Maximum applies only to the current Network Connection.
// If the Receive Maximum value is absent then its value defaults to 65,535.
template<class Integer>
inline self& receive_maximum(Integer v)
{
static_assert(std::is_integral_v<detail::remove_cvref_t<Integer>>);
_receive_maximum = static_cast<decltype(_receive_maximum)>(v);
return (*this);
}
inline auto receive_maximum() { return _receive_maximum; }
// This value indicates the highest value that the Client will accept as a Topic Alias sent by the Server.
// The Client uses this value to limit the number of Topic Aliases that it is willing to hold on this Connection.
// The Server MUST NOT send a Topic Alias in a PUBLISH packet to the Client greater than Topic Alias Maximum [MQTT-3.1.2-26].
// A value of 0 indicates that the Client does not accept any Topic Aliases on this connection.
// If Topic Alias Maximum is absent or zero, the Server MUST NOT send any Topic Aliases to the Client [MQTT-3.1.2-27].
template<class Integer>
inline self& topic_alias_maximum(Integer v)
{
static_assert(std::is_integral_v<detail::remove_cvref_t<Integer>>);
_topic_alias_maximum = static_cast<decltype(_topic_alias_maximum)>(v);
return (*this);
}
inline auto topic_alias_maximum() { return _topic_alias_maximum; }
// Followed by a Byte with a value of either 0 or 1.
// It is a Protocol Error to include Maximum QoS more than once, or to have a value other than 0 or 1.
// If the Maximum QoS is absent, the Client uses a Maximum QoS of 2.
template<class Integer>
inline self& maximum_qos(Integer v)
{
static_assert(std::is_integral_v<detail::remove_cvref_t<Integer>>);
ASIO2_ASSERT(v >= 0 && v <= 2);
_maximum_qos = static_cast<decltype(_maximum_qos)>(v);
return (*this);
}
inline auto maximum_qos() { return _maximum_qos; }
// If present, this byte declares whether the Server supports retained messages.
// A value of 0 means that retained messages are not supported.
// A value of 1 means retained messages are supported.
// If not present, then retained messages are supported.
// It is a Protocol Error to include Retain Available more than once or to use a value other than 0 or 1.
inline self& retain_available(bool v)
{
_retain_available = static_cast<decltype(_retain_available)>(v);
return (*this);
}
inline bool retain_available() { return (_retain_available == static_cast<decltype(_retain_available)>(1)); }
protected:
template<class MqttOptions>
inline void _mqtt_options_copy_from(const MqttOptions& o)
{
//this->payload_format_indicator ( o._payload_format_indicator );
//this->message_expiry_interval ( o._message_expiry_interval );
//this->content_type ( o._content_type );
//this->response_topic ( o._response_topic );
//this->correlation_data ( o._correlation_data );
//this->subscription_identifier ( o._subscription_identifier );
//this->session_expiry_interval ( o._session_expiry_interval );
//this->assigned_client_identifier ( o._assigned_client_identifier );
//this->server_keep_alive ( o._server_keep_alive );
//this->authentication_method ( o._authentication_method );
//this->authentication_data ( o._authentication_data );
//this->request_problem_information ( o._request_problem_information );
//this->will_delay_interval ( o._will_delay_interval );
//this->request_response_information ( o._request_response_information );
//this->response_information ( o._response_information );
//this->server_reference ( o._server_reference );
//this->reason_string ( o._reason_string );
this->receive_maximum ( o._receive_maximum );//
this->topic_alias_maximum ( o._topic_alias_maximum );//
//this->topic_alias ( o._topic_alias );
this->maximum_qos ( o._maximum_qos );//
this->retain_available ( o._retain_available );//
//this->user_property ( o._user_property );
//this->maximum_packet_size ( o._maximum_packet_size );
//this->wildcard_subscription_available ( o._wildcard_subscription_available );
//this->subscription_identifier_available ( o._subscription_identifier_available );
//this->shared_subscription_available ( o._shared_subscription_available );
}
protected:
decltype(std::declval<mqtt::v5::payload_format_indicator >().value()) _payload_format_indicator {};
decltype(std::declval<mqtt::v5::message_expiry_interval >().value()) _message_expiry_interval {};
decltype(std::declval<mqtt::v5::content_type >().value()) _content_type {};
decltype(std::declval<mqtt::v5::response_topic >().value()) _response_topic {};
decltype(std::declval<mqtt::v5::correlation_data >().value()) _correlation_data {};
decltype(std::declval<mqtt::v5::subscription_identifier >().value()) _subscription_identifier {};
decltype(std::declval<mqtt::v5::session_expiry_interval >().value()) _session_expiry_interval {};
decltype(std::declval<mqtt::v5::assigned_client_identifier >().value()) _assigned_client_identifier {};
decltype(std::declval<mqtt::v5::server_keep_alive >().value()) _server_keep_alive {};
decltype(std::declval<mqtt::v5::authentication_method >().value()) _authentication_method {};
decltype(std::declval<mqtt::v5::authentication_data >().value()) _authentication_data {};
decltype(std::declval<mqtt::v5::request_problem_information >().value()) _request_problem_information {};
decltype(std::declval<mqtt::v5::will_delay_interval >().value()) _will_delay_interval {};
decltype(std::declval<mqtt::v5::request_response_information >().value()) _request_response_information {};
decltype(std::declval<mqtt::v5::response_information >().value()) _response_information {};
decltype(std::declval<mqtt::v5::server_reference >().value()) _server_reference {};
decltype(std::declval<mqtt::v5::reason_string >().value()) _reason_string {};
decltype(std::declval<mqtt::v5::receive_maximum >().value()) _receive_maximum {};
decltype(std::declval<mqtt::v5::topic_alias_maximum >().value()) _topic_alias_maximum {};
decltype(std::declval<mqtt::v5::topic_alias >().value()) _topic_alias {};
decltype(std::declval<mqtt::v5::maximum_qos >().value()) _maximum_qos {};
decltype(std::declval<mqtt::v5::retain_available >().value()) _retain_available {};
decltype(std::declval<mqtt::v5::user_property >().value()) _user_property {};
decltype(std::declval<mqtt::v5::maximum_packet_size >().value()) _maximum_packet_size {};
decltype(std::declval<mqtt::v5::wildcard_subscription_available >().value()) _wildcard_subscription_available {};
decltype(std::declval<mqtt::v5::subscription_identifier_available >().value()) _subscription_identifier_available {};
decltype(std::declval<mqtt::v5::shared_subscription_available >().value()) _shared_subscription_available {};
};
}
namespace asio2::mqtt
{
using options = asio2::detail::mqtt_options;
}
namespace asio2
{
using mqtt_options = asio2::detail::mqtt_options;
}
#endif // !__ASIO2_MQTT_OPTIONS_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RPC_SESSION_HPP__
#define __ASIO2_RPC_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if __has_include(<cereal/cereal.hpp>)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/config.hpp>
#include <asio2/udp/udp_session.hpp>
#include <asio2/tcp/tcp_session.hpp>
#include <asio2/tcp/tcps_session.hpp>
#include <asio2/http/ws_session.hpp>
#include <asio2/http/wss_session.hpp>
#include <asio2/rpc/detail/rpc_serialization.hpp>
#include <asio2/rpc/detail/rpc_protocol.hpp>
#include <asio2/rpc/detail/rpc_invoker.hpp>
#include <asio2/rpc/impl/rpc_recv_op.hpp>
#include <asio2/rpc/impl/rpc_call_cp.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SESSION;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class derived_t, class executor_t>
class rpc_session_impl_t
: public executor_t
, public rpc_call_cp<derived_t, typename executor_t::args_type>
, public rpc_recv_op<derived_t, typename executor_t::args_type>
, protected id_maker<typename rpc_header::id_type>
{
friend executor_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
public:
using super = executor_t;
using self = rpc_session_impl_t<derived_t, executor_t>;
using executor_type = executor_t;
using args_type = typename executor_t::args_type;
static constexpr asio2::net_protocol net_protocol = args_type::net_protocol;
protected:
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
template<class ...Args>
explicit rpc_session_impl_t(
rpc_invoker_t<derived_t, typename executor_t::args_type>& invoker,
Args&&... args
)
: super(std::forward<Args>(args)...)
, rpc_call_cp<derived_t, typename executor_t::args_type>(this->io_, this->serializer_, this->deserializer_)
, rpc_recv_op<derived_t, typename executor_t::args_type>()
, id_maker<typename rpc_header::id_type>()
, invoker_(invoker)
{
}
/**
* @brief destructor
*/
~rpc_session_impl_t()
{
}
protected:
inline rpc_invoker_t<derived_t, typename executor_t::args_type>& _invoker() noexcept
{
return (this->invoker_);
}
template<typename C, typename Socket>
inline void _ws_start(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, Socket& socket)
{
super::_ws_start(this_ptr, ecs, socket);
this->derived().ws_stream().binary(true);
}
template<typename DeferEvent>
inline void _handle_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
while (!this->reqs_.empty())
{
auto& fn = this->reqs_.begin()->second;
fn(rpc::make_error_code(rpc::error::operation_aborted), std::string_view{});
}
super::_handle_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, this_ptr, data);
this->derived()._rpc_handle_recv(this_ptr, ecs, data);
}
protected:
rpc_serializer serializer_;
rpc_deserializer deserializer_;
rpc_header header_;
rpc_invoker_t<derived_t, typename executor_t::args_type> & invoker_;
};
}
namespace asio2
{
namespace detail
{
template<asio2::net_protocol np> struct template_args_rpc_session;
template<>
struct template_args_rpc_session<asio2::net_protocol::udp> : public template_args_udp_session
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::udp;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
template<>
struct template_args_rpc_session<asio2::net_protocol::tcp> : public template_args_tcp_session
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::tcp;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
template<>
struct template_args_rpc_session<asio2::net_protocol::ws> : public template_args_ws_session
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::ws;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
}
using rpc_session_args_udp = detail::template_args_rpc_session<asio2::net_protocol::udp>;
using rpc_session_args_tcp = detail::template_args_rpc_session<asio2::net_protocol::tcp>;
using rpc_session_args_ws = detail::template_args_rpc_session<asio2::net_protocol::ws >;
template<class derived_t, class executor_t>
using rpc_session_impl_t = detail::rpc_session_impl_t<derived_t, executor_t>;
template<class derived_t, asio2::net_protocol np> class rpc_session_t;
template<class derived_t>
class rpc_session_t<derived_t, asio2::net_protocol::udp> : public detail::rpc_session_impl_t<derived_t,
detail::udp_session_impl_t<derived_t, detail::template_args_rpc_session<asio2::net_protocol::udp>>>
{
public:
using detail::rpc_session_impl_t<derived_t, detail::udp_session_impl_t<
derived_t, detail::template_args_rpc_session<asio2::net_protocol::udp>>>::rpc_session_impl_t;
};
template<class derived_t>
class rpc_session_t<derived_t, asio2::net_protocol::tcp> : public detail::rpc_session_impl_t<derived_t,
detail::tcp_session_impl_t<derived_t, detail::template_args_rpc_session<asio2::net_protocol::tcp>>>
{
public:
using detail::rpc_session_impl_t<derived_t, detail::tcp_session_impl_t<
derived_t, detail::template_args_rpc_session<asio2::net_protocol::tcp>>>::rpc_session_impl_t;
};
template<class derived_t>
class rpc_session_t<derived_t, asio2::net_protocol::ws> : public detail::rpc_session_impl_t<derived_t,
detail::ws_session_impl_t<derived_t, detail::template_args_rpc_session<asio2::net_protocol::ws>>>
{
public:
using detail::rpc_session_impl_t<derived_t, detail::ws_session_impl_t<
derived_t, detail::template_args_rpc_session<asio2::net_protocol::ws>>>::rpc_session_impl_t;
};
template<asio2::net_protocol np>
class rpc_session_use : public rpc_session_t<rpc_session_use<np>, np>
{
public:
using rpc_session_t<rpc_session_use<np>, np>::rpc_session_t;
};
using rpc_kcp_session = rpc_session_use<asio2::net_protocol::udp>;
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpc_session = rpc_session_use<asio2::net_protocol::tcp>;
#else
/// Using websocket as the underlying communication support
using rpc_session = rpc_session_use<asio2::net_protocol::ws>;
#endif
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct rpc_rate_session_args_tcp : public rpc_session_args_tcp
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
struct rpc_rate_session_args_ws : public rpc_session_args_ws
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
using stream_t = websocket::stream<socket_t&>;
};
template<class derived_t, asio2::net_protocol np> class rpc_rate_session_t;
template<class derived_t>
class rpc_rate_session_t<derived_t, asio2::net_protocol::tcp> : public detail::rpc_session_impl_t<derived_t,
detail::tcp_session_impl_t<derived_t, rpc_rate_session_args_tcp>>
{
public:
using detail::rpc_session_impl_t<derived_t,
detail::tcp_session_impl_t<derived_t, rpc_rate_session_args_tcp>>::rpc_session_impl_t;
};
template<class derived_t>
class rpc_rate_session_t<derived_t, asio2::net_protocol::ws> : public detail::rpc_session_impl_t<derived_t,
detail::ws_session_impl_t<derived_t, rpc_rate_session_args_ws>>
{
public:
using detail::rpc_session_impl_t<derived_t,
detail::ws_session_impl_t<derived_t, rpc_rate_session_args_ws>>::rpc_session_impl_t;
};
template<asio2::net_protocol np>
class rpc_rate_session_use : public rpc_rate_session_t<rpc_rate_session_use<np>, np>
{
public:
using rpc_rate_session_t<rpc_rate_session_use<np>, np>::rpc_rate_session_t;
};
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpc_rate_session = rpc_rate_session_use<asio2::net_protocol::tcp>;
#else
/// Using websocket as the underlying communication support
using rpc_rate_session = rpc_rate_session_use<asio2::net_protocol::ws>;
#endif
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif
#endif // !__ASIO2_RPC_SESSION_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* https://www.zhihu.com/question/25016042
* Windows API : send
* The successful completion of a send function does not indicate that the data
* was successfully delivered and received to the recipient. This function only
* indicates the data was successfully sent.
*
*/
#ifndef __ASIO2_SEND_COMPONENT_HPP__
#define __ASIO2_SEND_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <functional>
#include <string>
#include <future>
#include <tuple>
#include <utility>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/base/impl/data_persistence_cp.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
template<class derived_t, class args_t>
class send_cp : public data_persistence_cp<derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
public:
/**
* @brief constructor
*/
send_cp() noexcept {}
/**
* @brief destructor
*/
~send_cp() = default;
public:
/**
* @brief Asynchronous send data, support multiple data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
*/
template<class DataT>
inline void async_send(DataT&& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
// use this guard to fix the issue of below "# issue x:"
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
// # issue x:
// 1. user call "async_send" function in some worker thread (not io_context thread)
// 2. code run to here, "here" means between "if (!derive.is_started())" and
// "derive.push_event("
// 3. the operating system switched from this thread to other thread
// 4. user call "client.stop", and the client is stopped successed
// 5. the operating system switched from other thread to this thread
// 6. code run to below, it means code run to "derive.push_event("
// 7. beacuse the iopool is stopped alreadly, so the "derive.push_event(" and
// "derive._do_send(..." will can't be executed.
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(),
data = derive._data_persistence(std::forward<DataT>(data))]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
return;
}
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
return;
}
clear_last_error();
derive._do_send(data, [g = std::move(g)](const error_code&, std::size_t) mutable {});
});
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType * : async_send("abc");
*/
template<class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<detail::is_char_v<CharT>, void> async_send(CharT * s) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.async_send(s, s ? Traits::length(s) : 0);
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType (&data)[N] : double m[10]; async_send(m,5);
*/
template<class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>>, void>
async_send(CharT* s, SizeT count) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
if (!s)
{
set_last_error(asio::error::invalid_argument);
return;
}
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), data = derive._data_persistence(s, count)]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
return;
}
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
return;
}
clear_last_error();
derive._do_send(data, [g = std::move(g)](const error_code&, std::size_t) mutable {});
});
}
/**
* @brief Asynchronous send data, support multiple data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
* the pair.first save the send result error_code,the pair.second save the sent_bytes.
* note : Do not call this function in any listener callback function like this:
* auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
* the future.get() will never return.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
*/
template<class DataT>
inline std::future<std::pair<error_code, std::size_t>> async_send(DataT&& data, asio::use_future_t<>)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
// why use copyable_wrapper? beacuse std::promise is moveable-only, but
// std::function need copy-constructible.
// 20220211 :
// Due to the event_queue_cp uses a custom detail::function that supports moveable-only instead
// of std::function, so copyable_wrapper is no longer required.
// https://en.cppreference.com/w/cpp/utility/functional/function/function
// The program is ill-formed if the target type is not copy-constructible or
// initialization of the target is ill-formed.
std::promise<std::pair<error_code, std::size_t>> promise;
std::future<std::pair<error_code, std::size_t>> future = promise.get_future();
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), promise = std::move(promise),
data = derive._data_persistence(std::forward<DataT>(data))]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
promise.set_value(std::pair<error_code, std::size_t>(asio::error::not_connected, 0));
return;
}
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
promise.set_value(std::pair<error_code, std::size_t>(asio::error::operation_aborted, 0));
return;
}
clear_last_error();
derive._do_send(data, [&promise, g = std::move(g)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
promise.set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
});
});
return future;
}
/**
* @brief Asynchronous send data
* the pair.first save the send result error_code,the pair.second save the sent_bytes.
* note : Do not call this function in any listener callback function like this:
* auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
* the future.get() will never return.
* PodType * : async_send("abc");
*/
template<class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<detail::is_char_v<CharT>, std::future<std::pair<error_code, std::size_t>>>
async_send(CharT * s, asio::use_future_t<> flag)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.async_send(s, s ? Traits::length(s) : 0, std::move(flag));
}
/**
* @brief Asynchronous send data
* the pair.first save the send result error_code,the pair.second save the sent_bytes.
* note : Do not call this function in any listener callback function like this:
* auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock,
* the future.get() will never return.
* PodType (&data)[N] : double m[10]; async_send(m,5);
*/
template<class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>>,
std::future<std::pair<error_code, std::size_t>>>
async_send(CharT * s, SizeT count, asio::use_future_t<>)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
std::promise<std::pair<error_code, std::size_t>> promise;
std::future<std::pair<error_code, std::size_t>> future = promise.get_future();
if (!s)
{
set_last_error(asio::error::invalid_argument);
promise.set_value(std::pair<error_code, std::size_t>(asio::error::invalid_argument, 0));
return future;
}
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), promise = std::move(promise),
data = derive._data_persistence(s, count)]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
promise.set_value(std::pair<error_code, std::size_t>(asio::error::not_connected, 0));
return;
}
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
promise.set_value(std::pair<error_code, std::size_t>(asio::error::operation_aborted, 0));
return;
}
clear_last_error();
derive._do_send(data, [&promise, g = std::move(g)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
promise.set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
});
});
return future;
}
/**
* @brief Asynchronous send data, support multiple data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
* Callback signature : void() or void(std::size_t bytes_sent)
*/
template<class DataT, class Callback>
inline typename std::enable_if_t<is_callable_v<Callback>, void> async_send(DataT&& data, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), fn = std::forward<Callback>(fn),
data = derive._data_persistence(std::forward<DataT>(data))]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
derive._send_cp_invoke_callback(asio::error::not_connected, std::forward<Callback>(fn));
return;
}
if (id != derive.life_id())
{
derive._send_cp_invoke_callback(asio::error::operation_aborted, std::forward<Callback>(fn));
return;
}
clear_last_error();
derive._do_send(data, [&fn, g = std::move(g)]
(const error_code&, std::size_t bytes_sent) mutable
{
ASIO2_ASSERT(!g.is_empty());
callback_helper::call(fn, bytes_sent);
});
});
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType * : async_send("abc");
* Callback signature : void() or void(std::size_t bytes_sent)
*/
template<class Callback, class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<is_callable_v<Callback> && detail::is_char_v<CharT>, void>
async_send(CharT * s, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.async_send(s, s ? Traits::length(s) : 0, std::forward<Callback>(fn));
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType (&data)[N] : double m[10]; async_send(m,5);
* Callback signature : void() or void(std::size_t bytes_sent)
*/
template<class Callback, class CharT, class SizeT>
inline typename std::enable_if_t<is_callable_v<Callback> &&
std::is_integral_v<detail::remove_cvref_t<SizeT>>, void>
async_send(CharT * s, SizeT count, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
if (!s)
{
derive._send_cp_invoke_callback(asio::error::invalid_argument, std::forward<Callback>(fn));
return;
}
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), fn = std::forward<Callback>(fn),
data = derive._data_persistence(s, count)]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
derive._send_cp_invoke_callback(asio::error::not_connected, std::forward<Callback>(fn));
return;
}
if (id != derive.life_id())
{
derive._send_cp_invoke_callback(asio::error::operation_aborted, std::forward<Callback>(fn));
return;
}
clear_last_error();
derive._do_send(data, [&fn, g = std::move(g)]
(const error_code&, std::size_t bytes_sent) mutable
{
callback_helper::call(fn, bytes_sent);
});
});
}
public:
/**
* @brief Synchronous send data, support multiple data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* @return Number of bytes written from the data. If an error occurred,
* this will be less than the sum of the data size.
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* Note : If this function is called in communication thread, it will degenerates into async_send
* and the return value is 0, you can use asio2::get_last_error() to check whether the
* send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
* means success, otherwise failed.
* use like this : std::string m; send(std::move(m)); can reducing memory allocation.
* PodType * : send("abc");
* PodType (&data)[N] : double m[10]; send(m);
* std::array<PodType, N> : std::array<int,10> m; send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; send(m);
*/
template<class DataT>
inline std::size_t send(DataT&& data)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::future<std::pair<error_code, std::size_t>> future = derive.async_send(
std::forward<DataT>(data), asio::use_future);
// Whether we run on the io_context thread
if (derive.io().running_in_this_thread())
{
std::future_status status = future.wait_for(std::chrono::nanoseconds(0));
// async_send failed :
// beacuse current thread is the io_context thread, so the data must be sent in the future,
// so if the "status" is ready, it means that the data must have failed to be sent.
if (status == std::future_status::ready)
{
set_last_error(future.get().first);
return std::size_t(0);
}
// async_send in_progress.
else
{
set_last_error(asio::error::in_progress);
return std::size_t(0);
}
}
std::pair<error_code, std::size_t> pair = future.get();
set_last_error(pair.first);
return pair.second;
}
/**
* @brief Synchronous send data
* @return Number of bytes written from the data. If an error occurred,
* this will be less than the sum of the data size.
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* Note : If this function is called in communication thread, it will degenerates into async_send
* and the return value is 0, you can use asio2::get_last_error() to check whether the
* send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
* means success, otherwise failed.
* PodType * : send("abc");
*/
template<class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<detail::is_char_v<CharT>, std::size_t> send(CharT * s)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.send(s, s ? Traits::length(s) : 0);
}
/**
* @brief Synchronous send data
* @return Number of bytes written from the data. If an error occurred,
* this will be less than the sum of the data size.
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* Note : If this function is called in communication thread, it will degenerates into async_send
* and the return value is 0, you can use asio2::get_last_error() to check whether the
* send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
* means success, otherwise failed.
* PodType (&data)[N] : double m[10]; send(m,5);
*/
template<class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>>, std::size_t>
send(CharT* s, SizeT count)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.send(derive._data_persistence(s, count));
}
protected:
template<class Callback>
inline void _send_cp_invoke_callback(error_code ec, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
set_last_error(ec);
// we should ensure that the callback must be called in the io_context thread.
derive.post([ec, fn = std::forward<Callback>(fn)]() mutable
{
set_last_error(ec);
callback_helper::call(fn, 0);
});
}
};
}
#endif // !__ASIO2_SEND_COMPONENT_HPP__
<file_sep>/*
Copyright <NAME> 2012-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_BSD_OPEN_H
#define BHO_PREDEF_OS_BSD_OPEN_H
#include <asio2/bho/predef/os/bsd.h>
/* tag::reference[]
= `BHO_OS_BSD_OPEN`
http://en.wikipedia.org/wiki/Openbsd[OpenBSD] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__OpenBSD__+` | {predef_detection}
| `OpenBSD2_0` | 2.0.0
| `OpenBSD2_1` | 2.1.0
| `OpenBSD2_2` | 2.2.0
| `OpenBSD2_3` | 2.3.0
| `OpenBSD2_4` | 2.4.0
| `OpenBSD2_5` | 2.5.0
| `OpenBSD2_6` | 2.6.0
| `OpenBSD2_7` | 2.7.0
| `OpenBSD2_8` | 2.8.0
| `OpenBSD2_9` | 2.9.0
| `OpenBSD3_0` | 3.0.0
| `OpenBSD3_1` | 3.1.0
| `OpenBSD3_2` | 3.2.0
| `OpenBSD3_3` | 3.3.0
| `OpenBSD3_4` | 3.4.0
| `OpenBSD3_5` | 3.5.0
| `OpenBSD3_6` | 3.6.0
| `OpenBSD3_7` | 3.7.0
| `OpenBSD3_8` | 3.8.0
| `OpenBSD3_9` | 3.9.0
| `OpenBSD4_0` | 4.0.0
| `OpenBSD4_1` | 4.1.0
| `OpenBSD4_2` | 4.2.0
| `OpenBSD4_3` | 4.3.0
| `OpenBSD4_4` | 4.4.0
| `OpenBSD4_5` | 4.5.0
| `OpenBSD4_6` | 4.6.0
| `OpenBSD4_7` | 4.7.0
| `OpenBSD4_8` | 4.8.0
| `OpenBSD4_9` | 4.9.0
| `OpenBSD5_0` | 5.0.0
| `OpenBSD5_1` | 5.1.0
| `OpenBSD5_2` | 5.2.0
| `OpenBSD5_3` | 5.3.0
| `OpenBSD5_4` | 5.4.0
| `OpenBSD5_5` | 5.5.0
| `OpenBSD5_6` | 5.6.0
| `OpenBSD5_7` | 5.7.0
| `OpenBSD5_8` | 5.8.0
| `OpenBSD5_9` | 5.9.0
| `OpenBSD6_0` | 6.0.0
| `OpenBSD6_1` | 6.1.0
| `OpenBSD6_2` | 6.2.0
| `OpenBSD6_3` | 6.3.0
| `OpenBSD6_4` | 6.4.0
| `OpenBSD6_5` | 6.5.0
| `OpenBSD6_6` | 6.6.0
| `OpenBSD6_7` | 6.7.0
| `OpenBSD6_8` | 6.8.0
| `OpenBSD6_9` | 6.9.0
|===
*/ // end::reference[]
#define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__OpenBSD__) \
)
# ifndef BHO_OS_BSD_AVAILABLE
# undef BHO_OS_BSD
# define BHO_OS_BSD BHO_VERSION_NUMBER_AVAILABLE
# define BHO_OS_BSD_AVAILABLE
# endif
# undef BHO_OS_BSD_OPEN
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_0)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,0,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_1)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,1,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_2)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,2,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_3)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,3,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_4)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,4,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_5)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,5,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_6)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,6,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_7)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,7,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_8)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,8,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD2_9)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(2,9,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_0)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,0,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_1)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,1,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_2)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,2,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_3)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,3,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_4)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,4,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_5)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,5,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_6)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,6,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_7)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,7,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_8)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,8,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD3_9)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(3,9,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_0)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,0,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_1)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,1,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_2)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,2,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_3)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,3,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_4)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,4,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_5)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,5,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_6)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,6,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_7)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,7,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_8)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,8,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD4_9)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(4,9,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_0)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,0,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_1)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,1,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_2)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,2,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_3)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,3,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_4)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,4,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_5)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,5,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_6)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,6,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_7)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,7,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_8)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,8,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD5_9)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(5,9,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_0)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,0,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_1)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,1,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_2)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,2,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_3)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,3,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_4)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,4,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_5)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,5,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_6)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,6,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_7)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,7,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_8)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,8,0)
# endif
# if !defined(BHO_OS_BSD_OPEN) && defined(OpenBSD6_9)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER(6,9,0)
# endif
# if !defined(BHO_OS_BSD_OPEN)
# define BHO_OS_BSD_OPEN BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_OS_BSD_OPEN
# define BHO_OS_BSD_OPEN_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_BSD_OPEN_NAME "OpenBSD"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_BSD_OPEN,BHO_OS_BSD_OPEN_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_TCP_SESSION_HPP__
#define __ASIO2_TCP_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/session.hpp>
#include <asio2/tcp/impl/tcp_keepalive_cp.hpp>
#include <asio2/tcp/impl/tcp_send_op.hpp>
#include <asio2/tcp/impl/tcp_recv_op.hpp>
namespace asio2::detail
{
struct template_args_tcp_session
{
static constexpr bool is_session = true;
static constexpr bool is_client = false;
static constexpr bool is_server = false;
using socket_t = asio::ip::tcp::socket;
using buffer_t = asio::streambuf;
using send_data_t = std::string_view;
using recv_data_t = std::string_view;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class derived_t, class args_t = template_args_tcp_session>
class tcp_session_impl_t
: public session_impl_t <derived_t, args_t>
, public tcp_keepalive_cp <derived_t, args_t>
, public tcp_send_op <derived_t, args_t>
, public tcp_recv_op <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
public:
using super = session_impl_t <derived_t, args_t>;
using self = tcp_session_impl_t<derived_t, args_t>;
using args_type = args_t;
using key_type = std::size_t;
using buffer_type = typename args_t::buffer_t;
using send_data_t = typename args_t::send_data_t;
using recv_data_t = typename args_t::recv_data_t;
public:
/**
* @brief constructor
*/
explicit tcp_session_impl_t(
session_mgr_t<derived_t> & sessions,
listener_t & listener,
io_t & rwio,
std::size_t init_buf_size,
std::size_t max_buf_size
)
: super(sessions, listener, rwio, init_buf_size, max_buf_size, rwio.context())
, tcp_keepalive_cp<derived_t, args_t>()
, tcp_send_op <derived_t, args_t>()
, tcp_recv_op <derived_t, args_t>()
, rallocator_()
, wallocator_()
{
this->set_silence_timeout(std::chrono::milliseconds(tcp_silence_timeout));
this->set_connect_timeout(std::chrono::milliseconds(tcp_connect_timeout));
}
/**
* @brief destructor
*/
~tcp_session_impl_t()
{
}
protected:
/**
* @brief start the session for prepare to recv/send msg
*/
template<typename C>
inline void start(std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = this->derived();
error_code ec = get_last_error();
#if defined(ASIO2_ENABLE_LOG)
// Used to test whether the behavior of different compilers is consistent
static_assert(tcp_send_op<derived_t, args_t>::template has_member_dgram<self>::value,
"The behavior of different compilers is not consistent");
#endif
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
ASIO2_ASSERT(this->io().get_thread_id() != std::thread::id{});
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_silence_timer_called_ = false;
this->is_stop_connect_timeout_timer_called_ = false;
this->is_disconnect_called_ = false;
#endif
std::shared_ptr<derived_t> this_ptr = derive.selfptr();
try
{
this->remote_endpoint_copy_ = this->socket_.lowest_layer().remote_endpoint();
}
catch (const system_error&)
{
}
state_t expected = state_t::stopped;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
derive._do_disconnect(asio::error::already_started, std::move(this_ptr));
return;
}
// must read/write ecs in the io_context thread.
derive.ecs_ = ecs;
// init function maybe change the last error.
derive._do_init(this_ptr, ecs);
// if the accept function has error, reset the last error to it.
if (ec)
{
set_last_error(ec);
}
// now, the fire accept maybe has error, so the user should check it.
derive._fire_accept(this_ptr);
// if the accept has error, disconnect this session.
if (ec)
{
derive._do_disconnect(ec, std::move(this_ptr));
return;
}
// user maybe called the session stop in the accept callbak, so we need check it.
expected = state_t::starting;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
derive._do_disconnect(asio::error::operation_aborted, std::move(this_ptr));
return;
}
// user maybe closed the socket in the accept callbak, so we need check it.
if (!derive.socket().is_open())
{
derive._do_disconnect(asio::error::operation_aborted, std::move(this_ptr));
return;
}
// First call the base class start function
super::start();
// if the ecs has remote data call mode,do some thing.
derive._rdc_init(ecs);
// use push event to avoid this problem in ssl session:
// 1. _post_handshake not completed, this means the handshake callback hasn't been called.
// 2. call session stop, then the ssl async shutdown will be called.
// 3. then "ASIO2_ASSERT(derive.post_send_counter_.load() == 0);" will be failed.
derive.push_event(
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(event_queue_guard<derived_t> g) mutable
{
derive.sessions().dispatch(
[&derive, this_ptr, ecs = std::move(ecs), g = std::move(g)]
() mutable
{
derive._handle_connect(
error_code{}, std::move(this_ptr), std::move(ecs), defer_event(std::move(g)));
});
});
}
public:
/**
* @brief stop session
* You can call this function in the communication thread and anywhere to stop the session.
* If this function is called in the communication thread, it will post a asynchronous
* event into the event queue, then return immediately.
* If this function is called not in the communication thread, it will blocking forever
* util the session is stopped completed.
* note : this function must be noblocking if it is called in the communication thread,
* otherwise if it's blocking, maybe cause circle lock.
* If the session stop is called in the server's bind connect callback, then the session
* will can't be added into the session manager, and the session's bind disconnect event
* can't be called also.
*/
inline void stop()
{
derived_t& derive = this->derived();
state_t expected = state_t::stopped;
if (this->state_.compare_exchange_strong(expected, state_t::stopped))
return;
expected = state_t::stopping;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
return;
// if user call session stop in the bind accept callback, we close the connection with RST.
// after test, if close the connection with RST, no timewait will be generated.
if (derive.sessions().io().running_in_this_thread())
{
if (this->state_ == state_t::starting)
{
// How to close the socket with RST instead of FIN/ACK/FIN/ACK ?
// set the linger with 1,0
derive.set_linger(true, 0);
// close the socket directly.
error_code ec_ignore;
derive.socket().close(ec_ignore);
}
}
// use promise to get the result of stop
std::promise<state_t> promise;
std::future<state_t> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[this, p = std::move(promise)]() mutable
{
p.set_value(this->state().load());
}
};
derive.post_event([&derive, this_ptr = derive.selfptr(), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
derive._do_disconnect(asio::error::operation_aborted, derive.selfptr(), defer_event
{
[&derive, this_ptr = std::move(this_ptr), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(derive, pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
});
});
// use this to ensure the client is stopped completed when the stop is called not in the io_context thread
while (!derive.running_in_this_thread() && !derive.sessions().io().running_in_this_thread())
{
std::future_status status = future.wait_for(std::chrono::milliseconds(100));
if (status == std::future_status::ready)
{
ASIO2_ASSERT(future.get() == state_t::stopped);
break;
}
else
{
if (derive.get_thread_id() == std::thread::id{})
break;
if (derive.sessions().io().get_thread_id() == std::thread::id{})
break;
if (derive.io().context().stopped())
break;
}
}
}
/**
* @brief get this object hash key,used for session map
*/
inline key_type hash_key() const noexcept
{
return reinterpret_cast<key_type>(this);
}
protected:
template<class T, class R, class... Args>
struct condition_has_member_init : std::false_type {};
template<class T, class... Args>
struct condition_has_member_init<T, decltype(std::declval<std::decay_t<T>>().
init((std::declval<Args>())...)), Args...> : std::true_type {};
template<typename C>
inline void _do_init(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs) noexcept
{
detail::ignore_unused(this_ptr, ecs);
// reset the variable to default status
this->derived().reset_connect_time();
this->derived().update_alive_time();
if constexpr (std::is_same_v<typename ecs_t<C>::condition_lowest_type, use_dgram_t>)
{
this->dgram_ = true;
}
else
{
this->dgram_ = false;
}
using condition_lowest_type = typename detail::remove_cvref_t<typename ecs_t<C>::condition_lowest_type>;
if constexpr (std::is_class_v<condition_lowest_type>)
{
if constexpr (condition_has_member_init<condition_lowest_type, void, std::shared_ptr<derived_t>&>::value)
{
ecs->get_condition().lowest().init(this_ptr);
}
else
{
}
}
else
{
}
// set keeplive options
this->derived().set_keep_alive_options();
}
template<typename C, typename DeferEvent>
inline void _do_start(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = this->derived();
// Beacuse we ensured that the session::_do_disconnect must be called in the session's
// io_context thread, so if the session::stop is called in the server's bind_connect
// callback, the session's disconnect event maybe still be called, However, in this case,
// we do not want the disconnect event to be called, so at here, we need use post_event
// to ensure the join session is must be executed after the disconnect event, otherwise,
// the join session maybe executed before the disconnect event(the bind_disconnect callback).
// if the join session is executed before the disconnect event, the bind_disconnect will
// be called.
derive.post_event(
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
defer_event chain(std::move(e), std::move(g));
if (!derive.is_started())
{
derive._do_disconnect(asio::error::operation_aborted, std::move(this_ptr), std::move(chain));
return;
}
derive._join_session(std::move(this_ptr), std::move(ecs), std::move(chain));
});
}
template<typename DeferEvent>
inline void _handle_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(this->state_ == state_t::stopped);
ASIO2_LOG_DEBUG("tcp_session::_handle_disconnect: {} {}", ec.value(), ec.message());
set_last_error(ec);
this->derived()._rdc_stop();
// call shutdown again, beacuse the do shutdown maybe not called, eg: when
// protocol error is checked in the mqtt or http, then the do disconnect
// maybe called directly.
// the socket maybe closed already somewhere else.
if (this->socket().is_open())
{
error_code ec_linger{}, ec_ignore{};
asio::socket_base::linger lnger{};
this->socket().lowest_layer().get_option(lnger, ec_linger);
// call socket's close function to notify the _handle_recv function response with
// error > 0 ,then the socket can get notify to exit
// Call shutdown() to indicate that you will not write any more data to the socket.
if (!ec_linger && !(lnger.enabled() == true && lnger.timeout() == 0))
{
this->socket().shutdown(asio::socket_base::shutdown_both, ec_ignore);
}
// if the socket is basic_stream with rate limit, we should call the cancel,
// otherwise the rate timer maybe can't canceled, and cause the io_context
// can't stopped forever, even if the socket is closed already.
this->socket().cancel(ec_ignore);
// Call close,otherwise the _handle_recv will never return
this->socket().close(ec_ignore);
}
super::_handle_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _do_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
this->derived()._post_stop(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _post_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
// call the base class stop function
super::stop();
// call CRTP polymorphic stop
this->derived()._handle_stop(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
detail::ignore_unused(ec, this_ptr, chain);
ASIO2_ASSERT(this->state_ == state_t::stopped);
}
template<typename C, typename DeferEvent>
inline void _join_session(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
this->sessions_.emplace(this_ptr,
[this, this_ptr, ecs = std::move(ecs), chain = std::move(chain)](bool inserted) mutable
{
if (inserted)
this->derived()._start_recv(std::move(this_ptr), std::move(ecs), std::move(chain));
else
this->derived()._do_disconnect(
asio::error::address_in_use, std::move(this_ptr), std::move(chain));
});
}
template<typename C, typename DeferEvent>
inline void _start_recv(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
// to avlid the user call stop in another thread,then it may be socket.async_read_some
// and socket.close be called at the same time
asio::dispatch(this->io().context(), make_allocator(this->wallocator_,
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
using condition_lowest_type = typename ecs_t<C>::condition_lowest_type;
detail::ignore_unused(chain);
if constexpr (!std::is_same_v<condition_lowest_type, asio2::detail::hook_buffer_t>)
{
this->derived().buffer().consume(this->derived().buffer().size());
}
else
{
std::ignore = true;
}
// start the timer of check silence timeout
this->derived()._post_silence_timer(this->silence_timeout_, this_ptr);
this->derived()._post_recv(std::move(this_ptr), std::move(ecs));
}));
}
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
return this->derived()._tcp_send(data, std::forward<Callback>(callback));
}
template<class Data>
inline send_data_t _rdc_convert_to_send_data(Data& data) noexcept
{
auto buffer = asio::buffer(data);
return send_data_t{ reinterpret_cast<
std::string_view::const_pointer>(buffer.data()),buffer.size() };
}
template<class Invoker>
inline void _rdc_invoke_with_none(const error_code& ec, Invoker& invoker)
{
if (invoker)
invoker(ec, send_data_t{}, recv_data_t{});
}
template<class Invoker>
inline void _rdc_invoke_with_recv(const error_code& ec, Invoker& invoker, recv_data_t data)
{
if (invoker)
invoker(ec, send_data_t{}, data);
}
template<class Invoker>
inline void _rdc_invoke_with_send(const error_code& ec, Invoker& invoker, send_data_t data)
{
if (invoker)
invoker(ec, data, recv_data_t{});
}
protected:
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._tcp_post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._tcp_handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, this_ptr, data);
this->derived()._rdc_handle_recv(this_ptr, ecs, data);
}
inline void _fire_accept(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_accept must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
this->listener_.notify(event_type::accept, this_ptr);
}
template<typename C>
inline void _fire_connect(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
// the _fire_connect must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_disconnect_called_ == false);
#endif
this->derived()._rdc_start(this_ptr, ecs);
this->listener_.notify(event_type::connect, this_ptr);
}
inline void _fire_disconnect(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_disconnect must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
this->is_disconnect_called_ = true;
#endif
this->listener_.notify(event_type::disconnect, this_ptr);
}
protected:
/**
* @brief get the recv/read allocator object refrence
*/
inline auto & rallocator() noexcept { return this->rallocator_; }
/**
* @brief get the send/write allocator object refrence
*/
inline auto & wallocator() noexcept { return this->wallocator_; }
protected:
/// The memory to use for handler-based custom memory allocation. used fo recv/read.
handler_memory<std::true_type , assizer<args_t>> rallocator_;
/// The memory to use for handler-based custom memory allocation. used fo send/write.
handler_memory<std::false_type, assizer<args_t>> wallocator_;
/// Does it have the same datagram mechanism as udp?
bool dgram_ = false;
#if defined(_DEBUG) || defined(DEBUG)
bool is_disconnect_called_ = false;
#endif
};
}
namespace asio2
{
using tcp_session_args = detail::template_args_tcp_session;
template<class derived_t, class args_t>
using tcp_session_impl_t = detail::tcp_session_impl_t<derived_t, args_t>;
/**
* @brief tcp session
*/
template<class derived_t>
class tcp_session_t : public detail::tcp_session_impl_t<derived_t, detail::template_args_tcp_session>
{
public:
using detail::tcp_session_impl_t<derived_t, detail::template_args_tcp_session>::tcp_session_impl_t;
};
/**
* @brief tcp session
*/
class tcp_session : public tcp_session_t<tcp_session>
{
public:
using tcp_session_t<tcp_session>::tcp_session_t;
};
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct tcp_rate_session_args : public tcp_session_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
template<class derived_t>
class tcp_rate_session_t : public asio2::tcp_session_impl_t<derived_t, tcp_rate_session_args>
{
public:
using asio2::tcp_session_impl_t<derived_t, tcp_rate_session_args>::tcp_session_impl_t;
};
class tcp_rate_session : public asio2::tcp_rate_session_t<tcp_rate_session>
{
public:
using asio2::tcp_rate_session_t<tcp_rate_session>::tcp_rate_session_t;
};
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_TCP_SESSION_HPP__
<file_sep>#include <asio2/udp/udp_client.hpp>
int main()
{
asio2::udp_client client(1500, 1500);
client.bind_connect([&]()
{
std::string strmsg(1024, 'A');
if (!asio2::get_last_error())
client.async_send(std::move(strmsg));
}).bind_recv([&](std::string_view data)
{
client.async_send(asio::buffer(data)); // no allocate memory
//client.async_send(data); // allocate memory
});
client.start("127.0.0.1", "8116", asio2::use_kcp);
while (std::getchar() != '\n');
return 0;
}
<file_sep>// (C) Copyright <NAME> 2001.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// BeOS specific config options:
#define BHO_PLATFORM "BeOS"
#define BHO_NO_CWCHAR
#define BHO_NO_CWCTYPE
#define BHO_HAS_UNISTD_H
#define BHO_HAS_BETHREADS
#ifndef BHO_DISABLE_THREADS
# define BHO_HAS_THREADS
#endif
// boilerplate code:
#include <asio2/bho/config/detail/posix_features.hpp>
<file_sep>/*
Copyright <NAME> 2014
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_IOS_H
#define BHO_PREDEF_OS_IOS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_IOS`
http://en.wikipedia.org/wiki/iOS[iOS] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__APPLE__+` | {predef_detection}
| `+__MACH__+` | {predef_detection}
| `+__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__+` | {predef_detection}
| `+__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__+` | +__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__+*1000
|===
*/ // end::reference[]
#define BHO_OS_IOS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__APPLE__) && defined(__MACH__) && \
defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) \
)
# undef BHO_OS_IOS
# define BHO_OS_IOS (__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__*1000)
#endif
#if BHO_OS_IOS
# define BHO_OS_IOS_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_IOS_NAME "iOS"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_IOS,BHO_OS_IOS_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#if !defined(BHO_PREDEF_H) || defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BHO_PREDEF_H
#define BHO_PREDEF_H
#endif
#include <asio2/bho/predef/language.h>
#include <asio2/bho/predef/architecture.h>
#include <asio2/bho/predef/compiler.h>
#include <asio2/bho/predef/library.h>
#include <asio2/bho/predef/os.h>
#include <asio2/bho/predef/other.h>
#include <asio2/bho/predef/platform.h>
#include <asio2/bho/predef/hardware.h>
#include <asio2/bho/predef/version.h>
#endif
<file_sep>#ifndef BHO_CONFIG_PRAGMA_MESSAGE_HPP_INCLUDED
#define BHO_CONFIG_PRAGMA_MESSAGE_HPP_INCLUDED
// Copyright 2017 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// BHO_PRAGMA_MESSAGE("message")
//
// Expands to the equivalent of #pragma message("message")
//
// Note that this header is C compatible.
#include <asio2/bho/config/helper_macros.hpp>
#if defined(BHO_DISABLE_PRAGMA_MESSAGE)
# define BHO_PRAGMA_MESSAGE(x)
#elif defined(__INTEL_COMPILER)
# define BHO_PRAGMA_MESSAGE(x) __pragma(message(__FILE__ "(" BHO_STRINGIZE(__LINE__) "): note: " x))
#elif defined(__GNUC__)
# define BHO_PRAGMA_MESSAGE(x) _Pragma(BHO_STRINGIZE(message(x)))
#elif defined(_MSC_VER)
# define BHO_PRAGMA_MESSAGE(x) __pragma(message(__FILE__ "(" BHO_STRINGIZE(__LINE__) "): note: " x))
#else
# define BHO_PRAGMA_MESSAGE(x)
#endif
#endif // BHO_CONFIG_PRAGMA_MESSAGE_HPP_INCLUDED
<file_sep>#ifndef BHO_MP11_HPP_INCLUDED
#define BHO_MP11_HPP_INCLUDED
// Copyright 2015 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/mp11/list.hpp>
#include <asio2/bho/mp11/algorithm.hpp>
#include <asio2/bho/mp11/integral.hpp>
#include <asio2/bho/mp11/utility.hpp>
#include <asio2/bho/mp11/function.hpp>
#include <asio2/bho/mp11/map.hpp>
#include <asio2/bho/mp11/set.hpp>
#include <asio2/bho/mp11/bind.hpp>
#include <asio2/bho/mp11/integer_sequence.hpp>
#include <asio2/bho/mp11/tuple.hpp>
#endif // #ifndef BHO_MP11_HPP_INCLUDED
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_SEND_OP_HPP__
#define __ASIO2_HTTP_SEND_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/external/asio.hpp>
#include <asio2/external/beast.hpp>
#include <asio2/base/error.hpp>
#include <asio2/http/detail/http_util.hpp>
#include <asio2/http/request.hpp>
#include <asio2/http/response.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class http_send_op
{
public:
using body_type = typename args_t::body_t;
using buffer_type = typename args_t::buffer_t;
/**
* @brief constructor
*/
http_send_op() noexcept {}
/**
* @brief destructor
*/
~http_send_op() = default;
protected:
template<bool isRequest, class Body, class Fields>
inline void _check_http_message(http::message<isRequest, Body, Fields>& msg)
{
// https://datatracker.ietf.org/doc/html/rfc2616#section-14.13
// If an http message header don't has neither "Content-Length" nor "Transfer-Encoding"(chunk)
// Then the receiver may not be able to parse the http message normally.
if (!msg.chunked())
{
if (msg.find(http::field::content_length) == msg.end())
{
http::try_prepare_payload(msg);
}
}
}
protected:
template<class Data, class Callback>
inline bool _http_send(Data& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive._tcp_send(data, std::forward<Callback>(callback));
}
template<bool isRequest, class Body, class Fields, class Callback>
inline bool _http_send(http::message<isRequest, Body, Fields>& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive._check_http_message(data);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
http::async_write(derive.stream(), data, make_allocator(derive.wallocator(),
[&derive, p = derive.selfptr(), callback = std::forward<Callback>(callback)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
callback(ec, bytes_sent);
if (ec)
{
// must stop, otherwise re-sending will cause body confusion
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, std::move(p));
}
}
}));
return true;
}
template<class Body, class Fields, class Callback>
inline bool _http_send(detail::http_request_impl_t<Body, Fields>& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive._check_http_message(data.base());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
http::async_write(derive.stream(), data.base(), make_allocator(derive.wallocator(),
[&derive, p = derive.selfptr(), callback = std::forward<Callback>(callback)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
callback(ec, bytes_sent);
if (ec)
{
// must stop, otherwise re-sending will cause body confusion
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, std::move(p));
}
}
}));
return true;
}
template<class Body, class Fields, class Callback>
inline bool _http_send(detail::http_response_impl_t<Body, Fields>& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive._check_http_message(data.base());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
http::async_write(derive.stream(), data.base(), make_allocator(derive.wallocator(),
[&derive, p = derive.selfptr(), callback = std::forward<Callback>(callback)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
callback(ec, bytes_sent);
if (ec)
{
// must stop, otherwise re-sending will cause body confusion
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, std::move(p));
}
}
}));
return true;
}
protected:
};
}
#endif // !__ASIO2_HTTP_SEND_OP_HPP__
<file_sep>// (C) Copyright <NAME> 2010.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BHO_CONFIG_PLATFORM_VMS_HPP
#define BHO_CONFIG_PLATFORM_VMS_HPP
#define BHO_PLATFORM "OpenVMS"
#undef BHO_HAS_STDINT_H
#define BHO_HAS_UNISTD_H
#define BHO_HAS_NL_TYPES_H
#define BHO_HAS_GETTIMEOFDAY
#define BHO_HAS_DIRENT_H
#define BHO_HAS_PTHREADS
#define BHO_HAS_NANOSLEEP
#define BHO_HAS_CLOCK_GETTIME
#define BHO_HAS_PTHREAD_MUTEXATTR_SETTYPE
#define BHO_HAS_LOG1P
#define BHO_HAS_EXPM1
#define BHO_HAS_THREADS
#undef BHO_HAS_SCHED_YIELD
#endif
<file_sep>openssl的编译方法可以直接看下载的openssl包中的INSTALL文件,不管是想编译成静态库动态库等等都可以通过该文件的说明自己去编译适合自己所用的.
## Windows下编译openssl步骤
安装ActivePerl http://www.activestate.com/activeperl/downloads/
如果安装目录是C:\Perl64\ 将perl的bin路径放到电脑的环境变量PATH
安装nasm https://www.nasm.us/
如果安装目录是C:\Program Files\NASM 将C:\Program Files\NASM路径放到电脑的环境变量PATH
1.到https://github.com/openssl/openssl下载openssl源码,比如下载的源码包为openssl-OpenSSL_1_1_1h.zip,解压缩
2.打开 适用于 VS 2017 的 x64 本机工具命令提示(如果要编译32位的则打开VS 2017的开发人员命令提示符即可),进入到解压缩的openssl文件夹中
3.perl Configure VC-WIN64A no-shared
4.nmake
5.nmake test
6.nmake install
7.以上编译步骤实际参考自下载的源码包中的openssl/INSTALL文件
附:32位编译方法和上面步骤相同,只不过某些编译参数不同而已,如perl Configure VC-WIN32 no-shared
## Linux下编译openssl步骤
看INSTALL文件即可,很简单,只需要注意编译静态库时加上no-shared选项,如./config no-shared
./Configure no-shared
make
make test
make install
以上编译步骤实际参考自下载的源码包中的openssl/INSTALL文件中的Building OpenSSL段落和Installing OpenSSL段落
## Arm下的openssl交叉编译步骤
1.下载arm gcc编译器
打开https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-a/downloads
页面上显示有GNU-A和GNU-RM
下载GNU-A这个页面里面的arm gcc编译器:gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf.tar.xz
如果下载的其它的编译器包,在编译时可能会提示无法识别的指令"-pthread",这里你到这个包里面搜索一下,看有没有pthread的静态库,如果没有,那这个包可能就不能用
另:名字中带有none-linux的包似乎是只能编译操作系统内核不能编译application 所以优先找那些不带none-linux的下载
2.解压gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf.tar.xz包到某个文件夹,如/usr/local/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf
3.vim /etc/profile (将把交叉编译工具链的路径添加到系统环境变量PATH中去)
4.在profile中最后一行添加 export PATH=$PATH:/usr/local/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/bin
5.重启系统
6.arm-linux-gnueabihf-gcc -v 查看版本,如果显示正常说明arm gcc编译器安装成功
7.下载并解压openssl-OpenSSL_1_1_1h.zip包
8.进入到解压后的目录中,执行命令
./config no-asm no-shared --api=0.9.8 --prefix=/opt/openssl --openssldir=/usr/local/ssl CROSS_COMPILE=arm-linux-gnueabihf- CC=gcc
命令中的--api=0.9.8表示编译后老版本中已废弃的API仍然可以使用,如果不加这个选项,可能在使用这些库时会提示报错
如果提示无法识别的指令"-m64",那就编辑目录下的Makefile文件,找到所有-m64选项然后直接删掉即可
源码头文件添加(在包含openssl头文件之前)#define OPENSSL_API_COMPAT 0x00908000L
9.make
10.make install
11.编译其它代码的指令和标准linux下的gcc编译指令一样,如
// 编译
arm-linux-gnueabihf-g++ -c -x c++ main.cpp -I /usr/local/include -I /opt/openssl/include -g2 -gdwarf-2 -o main.o -Wall -Wswitch -W"no-deprecated-declarations" -W"empty-body" -Wconversion -W"return-type" -Wparentheses -W"no-format" -Wuninitialized -W"unreachable-code" -W"unused-function" -W"unused-value" -W"unused-variable" -O3 -fno-strict-aliasing -fno-omit-frame-pointer -fthreadsafe-statics -fexceptions -frtti -std=c++17
// 链接
arm-linux-gnueabihf-g++ -o main.out -Wl,--no-undefined -Wl,-L/opt/openssl/lib -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -pthread -lrt -ldl -Wl,-rpath=. main.o -lstdc++fs -l:libssl.a -l:libcrypto.a
附:经过测试,用此编译器编译的可执行文件在树莓派4下可以正常运行,可用关键字"树莓派交叉编译"来查询相关结果
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SERIAL_PORT_HPP__
#define __ASIO2_SERIAL_PORT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <queue>
#include <any>
#include <future>
#include <tuple>
#include <asio2/base/iopool.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/object.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/base/detail/ecs.hpp>
#include <asio2/base/impl/thread_id_cp.hpp>
#include <asio2/base/impl/alive_time_cp.hpp>
#include <asio2/base/impl/user_data_cp.hpp>
#include <asio2/base/impl/socket_cp.hpp>
#include <asio2/base/impl/user_timer_cp.hpp>
#include <asio2/base/impl/post_cp.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
#include <asio2/base/impl/condition_event_cp.hpp>
#include <asio2/base/impl/send_cp.hpp>
#include <asio2/tcp/impl/tcp_send_op.hpp>
#include <asio2/tcp/impl/tcp_recv_op.hpp>
#include <asio2/component/rdc/rdc_call_cp.hpp>
namespace asio2::detail
{
struct template_args_serial_port
{
using socket_t = asio::serial_port;
using buffer_t = asio::streambuf;
using send_data_t = std::string_view;
using recv_data_t = std::string_view;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
/**
* The serial_port class provides a wrapper over serial port functionality.
*/
template<class derived_t, class args_t = template_args_serial_port>
class serial_port_impl_t
: public object_t <derived_t >
, public iopool_cp <derived_t, args_t>
, public thread_id_cp <derived_t, args_t>
, public event_queue_cp <derived_t, args_t>
, public user_data_cp <derived_t, args_t>
, public alive_time_cp <derived_t, args_t>
, public user_timer_cp <derived_t, args_t>
, public send_cp <derived_t, args_t>
, public tcp_send_op <derived_t, args_t>
, public tcp_recv_op <derived_t, args_t>
, public post_cp <derived_t, args_t>
, public condition_event_cp<derived_t, args_t>
, public rdc_call_cp <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
public:
using super = object_t <derived_t >;
using self = serial_port_impl_t<derived_t, args_t>;
using iopoolcp = iopool_cp <derived_t, args_t>;
using args_type = args_t;
using socket_type = typename args_t::socket_t;
using buffer_type = typename args_t::buffer_t;
using send_data_t = typename args_t::send_data_t;
using recv_data_t = typename args_t::recv_data_t;
/**
* @brief constructor
*/
explicit serial_port_impl_t(
std::size_t init_buf_size = 1024,
std::size_t max_buf_size = max_buffer_size,
std::size_t concurrency = 1
)
: super()
, iopool_cp <derived_t, args_t>(concurrency)
, event_queue_cp <derived_t, args_t>()
, user_data_cp <derived_t, args_t>()
, alive_time_cp <derived_t, args_t>()
, user_timer_cp <derived_t, args_t>()
, send_cp <derived_t, args_t>()
, tcp_send_op <derived_t, args_t>()
, tcp_recv_op <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp<derived_t, args_t>()
, rdc_call_cp <derived_t, args_t>()
, socket_ (iopoolcp::_get_io(0).context())
, rallocator_()
, wallocator_()
, listener_ ()
, io_ (iopoolcp::_get_io(0))
, buffer_ (init_buf_size, max_buf_size)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit serial_port_impl_t(
std::size_t init_buf_size,
std::size_t max_buf_size,
Scheduler&& scheduler
)
: super()
, iopool_cp <derived_t, args_t>(std::forward<Scheduler>(scheduler))
, event_queue_cp <derived_t, args_t>()
, user_data_cp <derived_t, args_t>()
, alive_time_cp <derived_t, args_t>()
, user_timer_cp <derived_t, args_t>()
, send_cp <derived_t, args_t>()
, tcp_send_op <derived_t, args_t>()
, tcp_recv_op <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp<derived_t, args_t>()
, rdc_call_cp <derived_t, args_t>()
, socket_ (iopoolcp::_get_io(0).context())
, rallocator_()
, wallocator_()
, listener_ ()
, io_ (iopoolcp::_get_io(0))
, buffer_ (init_buf_size, max_buf_size)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit serial_port_impl_t(Scheduler&& scheduler)
: serial_port_impl_t(1024, max_buffer_size, std::forward<Scheduler>(scheduler))
{
}
/**
* @brief destructor
*/
~serial_port_impl_t()
{
this->stop();
}
/**
* @brief start
* @param device - The platform-specific device name for this serial, example "/dev/ttyS0" or "COM1"
* @param baud_rate - Communication speed, example 9600 or 115200
* @param condition - The delimiter condition.Valid value types include the following:
* char,std::string,std::string_view,
* function:std::pair<iterator, bool> match_condition(iterator begin, iterator end),
* asio::transfer_at_least,asio::transfer_exactly
* more details see asio::read_until
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& device, StrOrInt&& baud_rate, Args&&... args)
{
return this->derived()._do_start(
std::forward<String>(device), std::forward<StrOrInt>(baud_rate),
ecs_helper::make_ecs(asio::transfer_at_least(1), std::forward<Args>(args)...));
}
/**
* @brief stop
* You can call this function in the communication thread and anywhere to stop the serial port.
* If this function is called in the communication thread, it will post a asynchronous
* event into the event queue, then return immediately.
* If this function is called not in the communication thread, it will blocking forever
* util the serial port is stopped completed.
*/
inline void stop()
{
if (this->is_iopool_stopped())
return;
derived_t& derive = this->derived();
derive.io().unregobj(&derive);
// use promise to get the result of stop
std::promise<state_t> promise;
std::future<state_t> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[this, p = std::move(promise)]() mutable
{
p.set_value(this->state().load());
}
};
derive.post_event([&derive, this_ptr = derive.selfptr(), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
derive._do_disconnect(asio::error::operation_aborted, std::move(this_ptr), defer_event
{
[pg = std::move(pg)](event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
});
});
while (!derive.running_in_this_thread())
{
std::future_status status = future.wait_for(std::chrono::milliseconds(100));
if (status == std::future_status::ready)
{
ASIO2_ASSERT(future.get() == state_t::stopped);
break;
}
else
{
if (derive.get_thread_id() == std::thread::id{})
break;
if (derive.io().context().stopped())
break;
}
}
this->stop_iopool();
}
/**
* @brief check whether the client is started
*/
inline bool is_started()
{
return (this->state_ == state_t::started && this->socket().is_open());
}
/**
* @brief check whether the client is stopped
*/
inline bool is_stopped()
{
return (this->state_ == state_t::stopped && !this->socket().is_open());
}
public:
/**
* @brief bind recv listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* void on_recv(std::string_view data){...}
* or a lumbda function like this :
* [&](std::string_view data){...}
*/
template<class F, class ...C>
inline derived_t & bind_recv(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::recv,
observer_t<std::string_view>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind init listener,we should set socket options at here
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* void on_init(){...}
* or a lumbda function like this :
* [&](){...}
*/
template<class F, class ...C>
inline derived_t & bind_init(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::init,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind start listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called after the server starts up, whether successful or unsuccessful
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_start(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::start,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind stop listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called before the server is ready to stop
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_stop(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::stop,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
public:
/**
* @brief get the socket object refrence
*/
inline socket_type & socket() noexcept { return this->socket_; }
/**
* @brief get the socket object refrence
*/
inline const socket_type & socket() const noexcept { return this->socket_; }
/**
* @brief get the stream object refrence
*/
inline socket_type & stream() noexcept { return this->socket_; }
/**
* @brief get the stream object refrence
*/
inline const socket_type & stream() const noexcept { return this->socket_; }
/**
* This function is used to set an option on the serial port.
*
* @param option - The option value to be set on the serial port.
* @li
* asio::serial_port::baud_rate
* asio::serial_port::flow_control
* asio::serial_port::parity
* asio::serial_port::stop_bits
* asio::serial_port::character_size
*/
template <typename SettableSerialPortOption>
derived_t& set_option(const SettableSerialPortOption& option) noexcept
{
this->socket().set_option(option, get_last_error());
return (this->derived());
}
/**
* This function is used to get the current value of an option on the serial
* port.
*
* @param option - The option value to be obtained from the serial port.
* @li
* asio::serial_port::baud_rate
* asio::serial_port::flow_control
* asio::serial_port::parity
* asio::serial_port::stop_bits
* asio::serial_port::character_size
*/
template <typename GettableSerialPortOption>
GettableSerialPortOption get_option() const
{
GettableSerialPortOption option{};
this->socket().get_option(option, get_last_error());
return option;
}
/**
* This function is used to get the current value of an option on the serial
* port.
*
* @param option - The option value to be obtained from the serial port.
* @li
* asio::serial_port_base::baud_rate
* asio::serial_port_base::flow_control
* asio::serial_port_base::parity
* asio::serial_port_base::stop_bits
* asio::serial_port_base::character_size
*/
template <typename GettableSerialPortOption>
derived_t& get_option(GettableSerialPortOption& option)
{
this->socket().get_option(option, get_last_error());
return (this->derived());
}
protected:
template<typename String, typename StrOrInt, typename C>
bool _do_start(String&& device, StrOrInt&& baud_rate, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = this->derived();
// if log is enabled, init the log first, otherwise when "Too many open files" error occurs,
// the log file will be created failed too.
#if defined(ASIO2_ENABLE_LOG)
asio2::detail::get_logger();
#endif
this->start_iopool();
if (!this->is_iopool_started())
{
set_last_error(asio::error::operation_aborted);
return false;
}
asio::dispatch(derive.io().context(), [&derive, this_ptr = derive.selfptr()]() mutable
{
detail::ignore_unused(this_ptr);
// init the running thread id
derive.io().init_thread_id();
});
// use promise to get the result of async connect
std::promise<error_code> promise;
std::future<error_code> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[promise = std::move(promise)]() mutable
{
promise.set_value(get_last_error());
}
};
derive.post_event(
[this, this_ptr = derive.selfptr(), ecs = std::move(ecs), pg = std::move(pg),
device = std::forward<String>(device), baud_rate = std::forward<StrOrInt>(baud_rate)]
(event_queue_guard<derived_t> g) mutable
{
derived_t& derive = this->derived();
defer_event chain
{
[pg = std::move(pg)](event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
};
state_t expected = state_t::stopped;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
// if the state is not stopped, set the last error to already_started
set_last_error(asio::error::already_started);
return;
}
// must read/write ecs in the io_context thread.
derive.ecs_ = ecs;
derive.io().regobj(&derive);
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_called_ = false;
#endif
// convert to string maybe throw some exception.
std::string d = detail::to_string(std::move(device));
unsigned int b = detail::to_numeric<unsigned int>(std::move(baud_rate));
expected = state_t::starting;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
ASIO2_ASSERT(false);
derive._handle_start(asio::error::operation_aborted,
std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
error_code ec, ec_ignore;
this->socket().cancel(ec_ignore);
this->socket().close(ec_ignore);
this->socket().open(d, ec);
if (ec)
{
derive._handle_start(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
this->socket().set_option(asio::serial_port::baud_rate(b), ec_ignore);
// if the ecs has remote data call mode,do some thing.
derive._rdc_init(ecs);
clear_last_error();
derive._fire_init();
// You can set other serial port parameters in on_init(bind_init) callback function like this:
// sp.set_option(asio::serial_port::flow_control(serial_port::flow_control::type(flow_control)));
// sp.set_option(asio::serial_port::parity(serial_port::parity::type(parity)));
// sp.set_option(asio::serial_port::stop_bits(serial_port::stop_bits::type(stop_bits)));
// sp.set_option(asio::serial_port::character_size(character_size));
derive._handle_start(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
});
if (!derive.io().running_in_this_thread())
{
set_last_error(future.get());
return static_cast<bool>(!get_last_error());
}
else
{
set_last_error(asio::error::in_progress);
}
// if the state is stopped , the return value is "is_started()".
// if the state is stopping, the return value is false, the last error is already_started
// if the state is starting, the return value is false, the last error is already_started
// if the state is started , the return value is true , the last error is already_started
return derive.is_started();
}
template<typename C, typename DeferEvent>
void _handle_start(
error_code ec, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
// Whether the startup succeeds or fails, always call fire_start notification
state_t expected = state_t::starting;
if (!ec)
if (!this->state_.compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
set_last_error(ec);
this->derived()._fire_start(this_ptr, ecs);
expected = state_t::started;
if (!ec)
if (!this->state_.compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
if (ec)
{
this->derived()._do_disconnect(ec, std::move(this_ptr), std::move(chain));
return;
}
this->derived()._start_recv(std::move(this_ptr), std::move(ecs));
}
template<typename E = defer_event<void, derived_t>>
inline void _do_disconnect(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, E chain = defer_event<void, derived_t>{})
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
state_t expected = state_t::started;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
{
return this->derived()._post_disconnect(ec, std::move(this_ptr), expected, std::move(chain));
}
expected = state_t::starting;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
{
return this->derived()._post_disconnect(ec, std::move(this_ptr), expected, std::move(chain));
}
}
template<typename DeferEvent>
inline void _post_disconnect(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state, DeferEvent chain)
{
// All pending sending events will be cancelled after enter the callback below.
this->derived().disp_event(
[this, ec, old_state, this_ptr = std::move(this_ptr), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(g);
this->derived()._handle_disconnect(
ec, std::move(this_ptr), old_state, defer_event(std::move(e), std::move(g)));
}, chain.move_guard());
}
template<typename DeferEvent>
inline void _handle_disconnect(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state, DeferEvent chain)
{
set_last_error(ec);
this->derived()._rdc_stop();
this->derived()._do_stop(ec, std::move(this_ptr), old_state, std::move(chain));
}
inline void _stop_readend_timer(std::shared_ptr<derived_t> this_ptr)
{
detail::ignore_unused(this_ptr);
}
template<typename DeferEvent>
inline void _do_stop(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state, DeferEvent chain)
{
this->derived()._post_stop(ec, std::move(this_ptr), old_state, std::move(chain));
}
template<typename DeferEvent>
inline void _post_stop(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state, DeferEvent chain)
{
// All pending sending events will be cancelled after enter the callback below.
this->derived().disp_event(
[this, ec, old_state, this_ptr = std::move(this_ptr), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(g, old_state);
set_last_error(ec);
defer_event chain(std::move(e), std::move(g));
state_t expected = state_t::stopping;
if (this->state_.compare_exchange_strong(expected, state_t::stopped))
{
this->derived()._fire_stop(this_ptr);
// call CRTP polymorphic stop
this->derived()._handle_stop(ec, std::move(this_ptr), std::move(chain));
}
else
{
ASIO2_ASSERT(false);
}
}, chain.move_guard());
}
template<typename DeferEvent>
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
detail::ignore_unused(ec, this_ptr, chain);
ASIO2_ASSERT(this->state_ == state_t::stopped);
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
// close user custom timers
this->_dispatch_stop_all_timers();
// close all posted timed tasks
this->_dispatch_stop_all_timed_events();
// close all async_events
this->notify_all_condition_events();
error_code ec_ignore{};
this->socket().cancel(ec_ignore);
// Call close,otherwise the _handle_recv will never return
this->socket().close(ec_ignore);
// clear recv buffer
this->buffer().consume(this->buffer().size());
// destroy user data, maybe the user data is self shared_ptr,
// if don't destroy it, will cause loop refrence.
this->user_data_.reset();
// destroy the ecs
this->ecs_.reset();
//
this->reset_life_id();
}
template<typename C>
inline void _start_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
// Connect succeeded. post recv request.
asio::dispatch(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]() mutable
{
using condition_lowest_type = typename ecs_t<C>::condition_lowest_type;
if constexpr (!std::is_same_v<condition_lowest_type, asio2::detail::hook_buffer_t>)
{
this->derived().buffer().consume(this->derived().buffer().size());
}
else
{
std::ignore = true;
}
this->derived()._post_recv(std::move(this_ptr), std::move(ecs));
}));
}
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
return this->derived()._tcp_send(data, std::forward<Callback>(callback));
}
template<class Data>
inline send_data_t _rdc_convert_to_send_data(Data& data) noexcept
{
auto buffer = asio::buffer(data);
return send_data_t{ reinterpret_cast<
std::string_view::const_pointer>(buffer.data()),buffer.size() };
}
template<class Invoker>
inline void _rdc_invoke_with_none(const error_code& ec, Invoker& invoker)
{
if (invoker)
invoker(ec, send_data_t{}, recv_data_t{});
}
template<class Invoker>
inline void _rdc_invoke_with_recv(const error_code& ec, Invoker& invoker, recv_data_t data)
{
if (invoker)
invoker(ec, send_data_t{}, data);
}
template<class Invoker>
inline void _rdc_invoke_with_send(const error_code& ec, Invoker& invoker, send_data_t data)
{
if (invoker)
invoker(ec, data, recv_data_t{});
}
protected:
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._tcp_post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._tcp_handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}
inline void _fire_init()
{
// the _fire_init must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(!get_last_error());
this->listener_.notify(event_type::init);
}
template<typename C>
inline void _fire_start(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
// the _fire_start must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_stop_called_ == false);
#endif
if (!get_last_error())
{
this->derived()._rdc_start(this_ptr, ecs);
}
this->listener_.notify(event_type::start);
}
inline void _fire_stop(std::shared_ptr<derived_t>&)
{
// the _fire_stop must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_called_ = true;
#endif
this->listener_.notify(event_type::stop);
}
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, data);
this->derived()._rdc_handle_recv(this_ptr, ecs, data);
}
public:
/**
* @brief set the default remote call timeout for rpc/rdc
*/
template<class Rep, class Period>
inline derived_t & set_default_timeout(std::chrono::duration<Rep, Period> duration) noexcept
{
this->rc_timeout_ = duration;
return (this->derived());
}
/**
* @brief get the default remote call timeout for rpc/rdc
*/
inline std::chrono::steady_clock::duration get_default_timeout() noexcept
{
return this->rc_timeout_;
}
/**
* @brief get the buffer object refrence
*/
inline buffer_wrap<buffer_type> & buffer() noexcept { return this->buffer_; }
/**
* @brief get the io object refrence
*/
inline io_t & io() noexcept { return this->io_; }
protected:
/**
* @brief get the recv/read allocator object refrence
*/
inline auto & rallocator() noexcept { return this->rallocator_; }
/**
* @brief get the send/write allocator object refrence
*/
inline auto & wallocator() noexcept { return this->wallocator_; }
inline listener_t & listener() noexcept { return this->listener_; }
inline std::atomic<state_t> & state () noexcept { return this->state_; }
inline const char* life_id () noexcept { return this->life_id_.get(); }
inline void reset_life_id () noexcept { this->life_id_ = std::make_unique<char>(); }
protected:
/// socket
socket_type socket_;
/// The memory to use for handler-based custom memory allocation. used fo recv/read.
handler_memory<std::true_type , assizer<args_t>> rallocator_;
/// The memory to use for handler-based custom memory allocation. used fo send/write.
handler_memory<std::false_type, assizer<args_t>> wallocator_;
/// listener
listener_t listener_;
/// The io_context wrapper used to handle the accept event.
io_t & io_;
/// buffer
buffer_wrap<buffer_type> buffer_;
/// state
std::atomic<state_t> state_ = state_t::stopped;
/// Remote call (rpc/rdc) response timeout.
std::chrono::steady_clock::duration rc_timeout_ = std::chrono::milliseconds(http_execute_timeout);
/// the pointer of ecs_t
std::shared_ptr<ecs_base> ecs_;
/// Whether the async_read... is called.
bool reading_ = false;
/// @see client life id
std::unique_ptr<char> life_id_ = std::make_unique<char>();
#if defined(_DEBUG) || defined(DEBUG)
bool is_stop_called_ = false;
std::atomic<int> post_send_counter_ = 0;
std::atomic<int> post_recv_counter_ = 0;
#endif
};
}
namespace asio2
{
using serial_port_args = detail::template_args_serial_port;
template<class derived_t, class args_t>
using serial_port_impl_t = detail::serial_port_impl_t<derived_t, args_t>;
template<class derived_t>
class serial_port_t : public detail::serial_port_impl_t<derived_t, detail::template_args_serial_port>
{
public:
using detail::serial_port_impl_t<derived_t, detail::template_args_serial_port>::serial_port_impl_t;
};
/**
* The serial_port class provides a wrapper over serial port functionality.
* You can use the following commands to query the serial device under Linux:
* cat /proc/tty/driver/serial
* If this object is created as a shared_ptr like std::shared_ptr<asio2::serial_port> sp;
* you must call the sp->stop() manual when exit, otherwise maybe cause memory leaks.
*/
class serial_port : public serial_port_t<serial_port>
{
public:
using serial_port_t<serial_port>::serial_port_t;
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_SERIAL_PORT_HPP__
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL> dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_WEBSOCKET_HPP
#define BHO_BEAST_WEBSOCKET_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/beast/websocket/error.hpp>
#include <asio2/bho/beast/websocket/option.hpp>
#include <asio2/bho/beast/websocket/rfc6455.hpp>
#include <asio2/bho/beast/websocket/stream.hpp>
#include <asio2/bho/beast/websocket/stream_base.hpp>
#include <asio2/bho/beast/websocket/stream_fwd.hpp>
#include <asio2/bho/beast/websocket/teardown.hpp>
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_SESSION_HPP__
#define __ASIO2_MQTT_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_session.hpp>
#include <asio2/mqtt/impl/mqtt_recv_connect_op.hpp>
#include <asio2/mqtt/impl/mqtt_send_op.hpp>
#include <asio2/mqtt/detail/mqtt_handler.hpp>
#include <asio2/mqtt/detail/mqtt_invoker.hpp>
#include <asio2/mqtt/detail/mqtt_topic_alias.hpp>
#include <asio2/mqtt/detail/mqtt_session_state.hpp>
#include <asio2/mqtt/detail/mqtt_broker_state.hpp>
#include <asio2/mqtt/idmgr.hpp>
#include <asio2/mqtt/options.hpp>
namespace asio2::detail
{
struct template_args_mqtt_session : public template_args_tcp_session
{
static constexpr bool rdc_call_cp_enabled = false;
template<class caller_t>
struct subnode
{
explicit subnode(
std::weak_ptr<caller_t> c,
mqtt::subscription s,
mqtt::v5::properties_set p = mqtt::v5::properties_set{}
)
: caller(std::move(c))
, sub (std::move(s))
, props (std::move(p))
{
}
inline std::string_view share_name () { return sub.share_name (); }
inline std::string_view topic_filter() { return sub.topic_filter(); }
//
std::weak_ptr<caller_t> caller;
// subscription info
mqtt::subscription sub;
// subscription properties
mqtt::v5::properties_set props;
};
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class derived_t, class args_t = template_args_mqtt_session>
class mqtt_session_impl_t
: public tcp_session_impl_t<derived_t, args_t>
, public mqtt_options
, public mqtt_handler_t <derived_t, args_t>
, public mqtt_topic_alias_t<derived_t, args_t>
, public mqtt_send_op <derived_t, args_t>
, public mqtt::session_state
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
template <class> friend class mqtt::shared_target;
public:
using super = tcp_session_impl_t <derived_t, args_t>;
using self = mqtt_session_impl_t<derived_t, args_t>;
using args_type = args_t;
using key_type = std::size_t;
using subnode_type = typename args_type::template subnode<derived_t>;
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
explicit mqtt_session_impl_t(
mqtt::broker_state<derived_t, args_t>& broker_state,
session_mgr_t <derived_t>& sessions,
listener_t & listener,
io_t & rwio,
std::size_t init_buf_size,
std::size_t max_buf_size
)
: super(sessions, listener, rwio, init_buf_size, max_buf_size)
, mqtt_options ()
, mqtt_handler_t <derived_t, args_t>()
, mqtt_topic_alias_t<derived_t, args_t>()
, mqtt_send_op <derived_t, args_t>()
, broker_state_(broker_state)
{
this->set_silence_timeout(std::chrono::milliseconds(mqtt_silence_timeout));
}
/**
* @brief destructor
*/
~mqtt_session_impl_t()
{
}
public:
/**
* @brief get this object hash key,used for session map
*/
inline key_type hash_key() const
{
return reinterpret_cast<key_type>(this);
}
/**
* @brief get the mqtt version number
*/
inline mqtt::version version()
{
return this->get_version();
}
/**
* @brief get the mqtt version number
*/
inline mqtt::version get_version()
{
return this->version_;
}
/**
* @brief get the mqtt client id
*/
inline std::string_view client_id()
{
return this->get_client_id();
}
/**
* @brief get the mqtt client id
*/
inline std::string_view get_client_id()
{
std::string_view id{};
if (!this->connect_message_.empty())
{
if /**/ (std::holds_alternative<mqtt::v3::connect>(connect_message_.base()))
{
id = this->connect_message_.template get_if<mqtt::v3::connect>()->client_id();
}
else if (std::holds_alternative<mqtt::v4::connect>(connect_message_.base()))
{
id = this->connect_message_.template get_if<mqtt::v4::connect>()->client_id();
}
else if (std::holds_alternative<mqtt::v5::connect>(connect_message_.base()))
{
id = this->connect_message_.template get_if<mqtt::v5::connect>()->client_id();
}
}
return id;
}
inline void remove_subscribed_topic(std::string_view topic_filter)
{
this->subs_map().erase(topic_filter, this->client_id());
}
inline void remove_all_subscribed_topic()
{
this->subs_map().erase(this->client_id());
}
protected:
template<typename E = defer_event<void, derived_t>>
inline void _do_disconnect(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, E chain = defer_event<void, derived_t>{})
{
state_t expected = state_t::started;
if (this->derived().state_.compare_exchange_strong(expected, state_t::started))
{
mqtt::version ver = this->derived().version();
if /**/ (ver == mqtt::version::v3)
{
mqtt::v3::disconnect disconnect;
this->derived().async_send(std::move(disconnect));
}
else if (ver == mqtt::version::v4)
{
mqtt::v4::disconnect disconnect;
this->derived().async_send(std::move(disconnect));
}
else if (ver == mqtt::version::v5)
{
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901208
mqtt::v5::disconnect disconnect;
if (ec.value() != 4)
disconnect.reason_code(static_cast<std::uint8_t>(ec.value()));
this->derived().async_send(std::move(disconnect));
}
else
{
ASIO2_ASSERT(false);
}
}
super::_do_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
detail::ignore_unused(ec);
ASIO2_ASSERT(!ec);
ASIO2_ASSERT(this->derived().sessions().io().running_in_this_thread());
asio::dispatch(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
derived_t& derive = this->derived();
ASIO2_ASSERT(derive.io().running_in_this_thread());
// wait for the connect message which send by the client.
mqtt_recv_connect_op
{
derive.io().context(),
derive.stream(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
(error_code ec, std::unique_ptr<asio::streambuf> stream) mutable
{
this->derived()._handle_mqtt_connect_message(ec,
std::move(this_ptr),std::move(ecs), std::move(stream), std::move(chain));
}
};
}));
}
template<typename C, typename DeferEvent>
inline void _handle_mqtt_connect_message(
error_code ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs,
std::unique_ptr<asio::streambuf> stream, DeferEvent chain)
{
do
{
if (ec)
break;
std::string_view data{ reinterpret_cast<std::string_view::const_pointer>(
static_cast<const char*>(stream->data().data())), stream->size() };
mqtt::control_packet_type type = mqtt::message_type_from_data(data);
// If the server does not receive a CONNECT message within a reasonable amount of time
// after the TCP/IP connection is established, the server should close the connection.
if (type != mqtt::control_packet_type::connect)
{
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
break;
}
// parse the connect message to get the mqtt version
mqtt::version ver = mqtt::version_from_connect_data(data);
if (ver != mqtt::version::v3 && ver != mqtt::version::v4 && ver != mqtt::version::v5)
{
ec = mqtt::make_error_code(mqtt::error::unsupported_protocol_version);
break;
}
this->version_ = ver;
// If the client sends an invalid CONNECT message, the server should close the connection.
// This includes CONNECT messages that provide invalid Protocol Name or Protocol Version Numbers.
// If the server can parse enough of the CONNECT message to determine that an invalid protocol
// has been requested, it may try to send a CONNACK containing the "Connection Refused:
// unacceptable protocol version" code before dropping the connection.
this->invoker()._call_mqtt_handler(type, ec, this_ptr, static_cast<derived_t*>(this), data);
} while (false);
this->derived().sessions().dispatch(
[this, ec, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
super::_handle_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
});
}
template<typename DeferEvent>
inline void _handle_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
std::string_view clientid = this->client_id();
this->subs_map().erase(clientid);
this->mqtt_sessions().erase_mqtt_session(clientid, static_cast<derived_t*>(this));
super::_handle_disconnect(ec, std::move(this_ptr), std::move(chain));
}
protected:
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
return this->derived()._mqtt_send(data, std::forward<Callback>(callback));
}
protected:
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, this_ptr, data);
this->derived()._rdc_handle_recv(this_ptr, ecs, data);
mqtt::control_packet_type type = mqtt::message_type_from_data(data);
if (type > mqtt::control_packet_type::auth)
{
ASIO2_ASSERT(false);
this->derived()._do_disconnect(mqtt::make_error_code(mqtt::error::malformed_packet), this_ptr);
return;
}
error_code ec;
this->invoker()._call_mqtt_handler(type, ec, this_ptr, static_cast<derived_t*>(this), data);
if (ec)
{
this->derived()._do_disconnect(ec, this_ptr);
}
}
inline auto& invoker () noexcept { return this->broker_state_.invoker_ ; }
inline auto& mqtt_sessions () noexcept { return this->broker_state_.mqtt_sessions_ ; }
inline auto& subs_map () noexcept { return this->broker_state_.subs_map_ ; }
inline auto& shared_targets () noexcept { return this->broker_state_.shared_targets_ ; }
inline auto& retained_messages() noexcept { return this->broker_state_.retained_messages_; }
inline auto& security () noexcept { return this->broker_state_.security_ ; }
inline void set_preauthed_username(std::optional<std::string> username)
{
preauthed_username_ = std::move(username);
}
inline std::optional<std::string> get_preauthed_username() const
{
return preauthed_username_;
}
protected:
///
mqtt::broker_state<derived_t, args_t> & broker_state_;
/// packet id manager
mqtt::idmgr<std::atomic<mqtt::two_byte_integer::value_type>> idmgr_;
/// user to find session for shared targets
std::chrono::nanoseconds::rep shared_target_key_;
mqtt::message connect_message_{};
std::optional<std::string> preauthed_username_;
mqtt::version version_ = static_cast<mqtt::version>(0);
};
}
namespace asio2
{
using mqtt_session_args = detail::template_args_mqtt_session;
template<class derived_t, class args_t>
using mqtt_session_impl_t = detail::mqtt_session_impl_t<derived_t, args_t>;
template<class derived_t>
class mqtt_session_t : public detail::mqtt_session_impl_t<derived_t, detail::template_args_mqtt_session>
{
public:
using detail::mqtt_session_impl_t<derived_t, detail::template_args_mqtt_session>::mqtt_session_impl_t;
};
class mqtt_session : public mqtt_session_t<mqtt_session>
{
public:
using mqtt_session_t<mqtt_session>::mqtt_session_t;
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_MQTT_SESSION_HPP__
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL> dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef __ASIO2_HTTP_FLEX_BODY_HPP__
#define __ASIO2_HTTP_FLEX_BODY_HPP__
#include <asio2/external/beast.hpp>
#include <asio2/external/assert.hpp>
#include <asio2/http/detail/http_util.hpp>
#ifdef ASIO2_HEADER_ONLY
namespace bho {
#else
namespace boost {
#endif
namespace beast {
namespace http {
/** A message body represented by a file on the filesystem.
Messages with this type have bodies represented by a
file on the file system. When parsing a message using
this body type, the data is stored in the file pointed
to by the path, which must be writable. When serializing,
the implementation will read the file and present those
octets as the body content. This may be used to serve
content from a directory as part of a web service.
@tparam File The implementation to use for accessing files.
This type must meet the requirements of <em>File</em>.
*/
template<class TextBody, class FileBody>
struct basic_flex_body
{
// Algorithm for storing buffers when parsing.
class reader;
// Algorithm for retrieving buffers when serializing.
class writer;
// The type of the @ref message::body member.
class value_type;
/** Returns the size of the body
@param body The file body to use
*/
static inline
std::uint64_t
size(value_type const& body) noexcept;
};
/** The type of the @ref message::body member.
Messages declared using `basic_flex_body` will have this type for
the body member. This rich class interface allow the file to be
opened with the file handle maintained directly in the object,
which is attached to the message.
*/
template<class TextBody, class FileBody>
class basic_flex_body<TextBody, FileBody>::value_type
{
public:
using text_t = typename TextBody::value_type;
using file_t = typename FileBody::value_type;
private:
// This body container holds a handle to the file
// when it is open, and also caches the size when set.
friend class reader;
friend class writer;
friend struct basic_flex_body;
text_t text_;
file_t file_;
public:
/** Destructor.
If the file is open, it is closed first.
*/
~value_type() = default;
/// Constructor
value_type() = default;
/// Constructor
value_type(value_type const&) = default;
/// Assignment
value_type& operator=(value_type const&) = default;
/// Constructor
value_type(value_type&& other) = default;
/// Move assignment
value_type& operator=(value_type&& other) = default;
inline text_t& text() noexcept
{
return text_;
}
inline text_t& text() const noexcept
{
return const_cast<text_t&>(text_);
}
/// Return the file
inline file_t& file() noexcept
{
return file_;
}
/// Return the file
inline file_t& file() const noexcept
{
return const_cast<file_t&>(file_);
}
/// Returns the size of the text or file
inline std::uint64_t size() const noexcept
{
return (is_file() ? file_.size() : text_.size());
}
inline bool is_text() const noexcept { return !is_file(); }
inline bool is_file() const noexcept { return file_.is_open(); }
/// Convert the file body to text body.
inline bool to_text()
{
if (this->is_text())
return true;
if (this->size() > std::uint64_t(text_.max_size()))
return false;
error_code ec;
auto& f = file_.file();
f.seek(0, ec);
if (ec)
return false;
text_.resize(std::size_t(this->size()));
auto const nread = f.read(text_.data(), text_.size(), ec);
if (ec || nread != text_.size())
{
text_.clear();
return false;
}
file_ = file_t{};
return true;
}
};
// This is called from message::payload_size
template<class TextBody, class FileBody>
std::uint64_t
basic_flex_body<TextBody, FileBody>::
size(value_type const& body) noexcept
{
// Forward the call to the body
return body.size();
}
/** Algorithm for retrieving buffers when serializing.
Objects of this type are created during serialization
to extract the buffers representing the body.
*/
template<class TextBody, class FileBody>
class basic_flex_body<TextBody, FileBody>::writer
{
public:
using text_writer = typename TextBody::writer;
using file_writer = typename FileBody::writer;
private:
value_type const& body_; // The body we are reading from
text_writer text_writer_;
file_writer file_writer_;
public:
// The type of buffer sequence returned by `get`.
//
using const_buffers_type =
::asio::const_buffer;
// Constructor.
//
// `h` holds the headers of the message we are
// serializing, while `b` holds the body.
//
// Note that the message is passed by non-const reference.
// This is intentional, because reading from the file
// changes its "current position" which counts makes the
// operation logically not-const (although it is bitwise
// const).
//
// The BodyWriter concept allows the writer to choose
// whether to take the message by const reference or
// non-const reference. Depending on the choice, a
// serializer constructed using that body type will
// require the same const or non-const reference to
// construct.
//
// Readers which accept const messages usually allow
// the same body to be serialized by multiple threads
// concurrently, while readers accepting non-const
// messages may only be serialized by one thread at
// a time.
//
template<bool isRequest, class Fields>
writer(header<isRequest, Fields> const& h, value_type const& b);
// Initializer
//
// This is called before the body is serialized and
// gives the writer a chance to do something that might
// need to return an error code.
//
inline void
init(error_code& ec);
// This function is called zero or more times to
// retrieve buffers. A return value of `std::nullopt`
// means there are no more buffers. Otherwise,
// the contained pair will have the next buffer
// to serialize, and a `bool` indicating whether
// or not there may be additional buffers.
#ifdef ASIO2_HEADER_ONLY
inline std::optional<std::pair<const_buffers_type, bool>>
#else
inline boost::optional<std::pair<const_buffers_type, bool>>
#endif
get(error_code& ec);
};
// Here we just stash a reference to the path for later.
// Rather than dealing with messy constructor exceptions,
// we save the things that might fail for the call to `init`.
//
template<class TextBody, class FileBody>
template<bool isRequest, class Fields>
basic_flex_body<TextBody, FileBody>::
writer::
writer(header<isRequest, Fields> const& h, value_type const& b)
: body_(b)
, text_writer_(const_cast<header<isRequest, Fields>&>(h), const_cast<value_type&>(b).text())
, file_writer_(const_cast<header<isRequest, Fields>&>(h), const_cast<value_type&>(b).file())
{
}
// Initializer
template<class TextBody, class FileBody>
void
basic_flex_body<TextBody, FileBody>::
writer::
init(error_code& ec)
{
// The error_code specification requires that we
// either set the error to some value, or set it
// to indicate no error.
//
// We don't do anything fancy so set "no error"
if (body_.is_file())
file_writer_.init(ec);
else
text_writer_.init(ec);
}
// This function is called repeatedly by the serializer to
// retrieve the buffers representing the body. Our strategy
// is to read into our buffer and return it until we have
// read through the whole file.
//
template<class TextBody, class FileBody>
auto
basic_flex_body<TextBody, FileBody>::
writer::
get(error_code& ec) ->
#ifdef ASIO2_HEADER_ONLY
std::optional<std::pair<const_buffers_type, bool>>
#else
boost::optional<std::pair<const_buffers_type, bool>>
#endif
{
if (body_.is_file())
return file_writer_.get(ec);
else
return text_writer_.get(ec);
}
/** Algorithm for storing buffers when parsing.
Objects of this type are created during parsing
to store incoming buffers representing the body.
*/
template<class TextBody, class FileBody>
class basic_flex_body<TextBody, FileBody>::reader
{
public:
using text_reader = typename TextBody::reader;
using file_reader = typename FileBody::reader;
private:
value_type& body_; // The body we are reading from
text_reader text_reader_;
file_reader file_reader_;
public:
// Constructor.
//
// This is called after the header is parsed and
// indicates that a non-zero sized body may be present.
// `h` holds the received message headers.
// `b` is an instance of `basic_flex_body`.
//
template<bool isRequest, class Fields>
explicit
reader(header<isRequest, Fields>&h, value_type& b);
// Initializer
//
// This is called before the body is parsed and
// gives the reader a chance to do something that might
// need to return an error code. It informs us of
// the payload size (`content_length`) which we can
// optionally use for optimization.
//
inline void
#ifdef ASIO2_HEADER_ONLY
init(std::optional<std::uint64_t> const&, error_code& ec);
#else
init(boost::optional<std::uint64_t> const&, error_code& ec);
#endif
// This function is called one or more times to store
// buffer sequences corresponding to the incoming body.
//
template<class ConstBufferSequence>
inline std::size_t
put(ConstBufferSequence const& buffers,
error_code& ec);
// This function is called when writing is complete.
// It is an opportunity to perform any final actions
// which might fail, in order to return an error code.
// Operations that might fail should not be attempted in
// destructors, since an exception thrown from there
// would terminate the program.
//
inline void
finish(error_code& ec);
};
// We don't do much in the reader constructor since the
// file is already open.
//
template<class TextBody, class FileBody>
template<bool isRequest, class Fields>
basic_flex_body<TextBody, FileBody>::
reader::
reader(header<isRequest, Fields>& h, value_type& body)
: body_(body), text_reader_(h, body.text()), file_reader_(h, body.file())
{
}
template<class TextBody, class FileBody>
void
basic_flex_body<TextBody, FileBody>::
reader::
init(
#ifdef ASIO2_HEADER_ONLY
std::optional<std::uint64_t> const& content_length,
#else
boost::optional<std::uint64_t> const& content_length,
#endif
error_code& ec)
{
if (body_.is_file())
file_reader_.init(content_length, ec);
else
text_reader_.init(content_length, ec);
}
// This will get called one or more times with body buffers
//
template<class TextBody, class FileBody>
template<class ConstBufferSequence>
std::size_t
basic_flex_body<TextBody, FileBody>::
reader::
put(ConstBufferSequence const& buffers, error_code& ec)
{
if (body_.is_file())
return file_reader_.put(buffers, ec);
else
return text_reader_.put(buffers, ec);
}
// Called after writing is done when there's no error.
template<class TextBody, class FileBody>
void
basic_flex_body<TextBody, FileBody>::
reader::
finish(error_code& ec)
{
// This has to be cleared before returning, to
// indicate no error. The specification requires it.
if (body_.is_file())
file_reader_.finish(ec);
else
text_reader_.finish(ec);
}
template<class TextBody, class FileBody>
std::ostream&
operator<<(std::ostream& os,
typename basic_flex_body<TextBody, FileBody>::value_type const& body)
{
if (body.is_text())
{
os << body.text();
}
else
{
ASIO2_ASSERT(false);
}
return os;
}
using flex_body = basic_flex_body<http::string_body, http::file_body>;
template<typename = void>
std::ostream&
operator<<(std::ostream& os,
typename flex_body::value_type const& body)
{
if (body.is_text())
{
os << body.text();
}
else
{
ASIO2_ASSERT(false);
}
return os;
}
} // http
} // beast
} // bho
#endif
<file_sep># rpc性能测试
测试办法:本机127.0.0.1,和rest_rpc进行对比.测试rpc的qps,只测了单连接.
字符串大小为128时:asio2比rest_rpc性能约高14%.字符串越来越大时(测试了16K和64K),两者性能基本相同.
```cpp
测试rpc的远程函数为:std::string echo(std::string a)
参数std::string为128长度的字符:std::string str(128, 'A');
rpc测试的硬件参数:内存8G,cpu(i5 4590)4核3.30GHZ.
rest_rpc和asio2测试所用的asio均为1.12.2版本.
rest_rpc在这里:https://github.com/qicosmos/rest_rpc
测试的时间为2020-01-18 直接下载的rest_rpc的master版本,
rest_rpc的版本为:https://github.com/qicosmos/rest_rpc/tree/e91d5f783888b148d58afd6eb45722507f95b803
asio2的版本为:https://github.com/zhllxt/asio2/tree/9f10555cfdd58026614907e5737f70a6608aa34c
这里只做了单连接的本地测试,测试的具体代码工程在这里: /asio2/test/bench/rpc/
```
## asio2的测试代码:
##### server:
```cpp
#include <asio2/asio2.hpp>
decltype(std::chrono::steady_clock::now()) t1 = std::chrono::steady_clock::now();
decltype(std::chrono::steady_clock::now()) t2 = std::chrono::steady_clock::now();
std::size_t qps = 0;
bool first = true;
std::string echo(std::string a)
{
if (first)
{
first = false;
t1 = std::chrono::steady_clock::now();
t2 = std::chrono::steady_clock::now();
}
qps++;
decltype(std::chrono::steady_clock::now()) t3 = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::seconds>(t3 - t2).count();
if (ms > 1)
{
t2 = t3;
ms = std::chrono::duration_cast<std::chrono::seconds>(t3 - t1).count();
double speed = (double)qps / (double)ms;
printf("%.1lf\n", speed);
}
return a;
}
int main(int argc, char *argv[])
{
asio2::rpc_server server;
server.bind("echo", echo);
server.start("0.0.0.0", "8080", asio2::use_dgram);
while (std::getchar() != '\n');
return 0;
};
```
##### client:
```cpp
#include <asio2/asio2.hpp>
std::string str(128, 'A');
std::function<void()> sender;
int main(int argc, char *argv[])
{
asio2::rpc_client client;
sender = [&]()
{
client.async_call([](asio::error_code ec, std::string v)
{
if (!ec)
sender();
}, "echo", str);
};
client.bind_connect([&](asio::error_code ec)
{
sender();
});
client.start("127.0.0.1", "8080", asio2::use_dgram);
while (std::getchar() != '\n');
return 0;
};
```
## rest_rpc的测试代码:
##### server:
```cpp
#include <rpc_server.h>
using namespace rest_rpc;
using namespace rpc_service;
#include <fstream>
decltype(std::chrono::steady_clock::now()) t1 = std::chrono::steady_clock::now();
decltype(std::chrono::steady_clock::now()) t2 = std::chrono::steady_clock::now();
std::size_t qps = 0;
bool first = true;
std::string echo(rpc_conn conn, std::string a) {
if (first)
{
first = false;
t1 = std::chrono::steady_clock::now();
t2 = std::chrono::steady_clock::now();
}
qps++;
decltype(std::chrono::steady_clock::now()) t3 = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::seconds>(t3 - t2).count();
if (ms > 1)
{
t2 = t3;
ms = std::chrono::duration_cast<std::chrono::seconds>(t3 - t1).count();
double speed = (double)qps / (double)ms;
printf("%.1lf\n", speed);
}
return a;
}
int main() {
rpc_server server(8080, std::thread::hardware_concurrency());
server.register_handler("echo", echo);
server.run();
return 0;
}
```
##### client:
```cpp
#include <iostream>
#include <rpc_client.hpp>
#include <chrono>
#include <fstream>
#include "codec.h"
#include <string>
using namespace rest_rpc;
using namespace rest_rpc::rpc_service;
std::string str(128, 'A');
void test_performance1() {
rpc_client client("127.0.0.1", 8080);
bool r = client.connect();
if (!r) {
std::cout << "connect timeout" << std::endl;
return;
}
for (;;) {
auto future = client.async_call<FUTURE>("echo", str);
auto status = future.wait_for(std::chrono::seconds(2));
if (status == std::future_status::deferred) {
std::cout << "deferred\n";
}
else if (status == std::future_status::timeout) {
std::cout << "timeout\n";
}
else if (status == std::future_status::ready) {
}
}
}
int main() {
test_performance1();
return 0;
}
```
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_SYS390_H
#define BHO_PREDEF_ARCHITECTURE_SYS390_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_SYS390`
http://en.wikipedia.org/wiki/System/390[System/390] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__s390__+` | {predef_detection}
| `+__s390x__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_SYS390 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__s390__) || defined(__s390x__)
# undef BHO_ARCH_SYS390
# define BHO_ARCH_SYS390 BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_SYS390
# define BHO_ARCH_SYS390_AVAILABLE
#endif
#if BHO_ARCH_SYS390
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_SYS390_NAME "System/390"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_SYS390,BHO_ARCH_SYS390_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : https://github.com/qicosmos/rest_rpc/blob/master/include/meta_util.hpp
*/
#ifndef __ASIO2_FUNCTION_TRAITS_HPP__
#define __ASIO2_FUNCTION_TRAITS_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <functional>
#include <type_traits>
namespace asio2::detail
{
template<typename, typename = void>
struct lambda_dummy_t { };
template<typename Ret, typename... Args>
struct lambda_dummy_t<Ret(Args...)>
{
template<typename R = Ret>
inline R operator()(const Args&...)
{
if /**/ constexpr (std::is_same_v<void, std::remove_cv_t<std::remove_reference_t<R>>>)
{
return;
}
else if constexpr (std::is_reference_v<std::remove_cv_t<R>>)
{
static typename std::remove_reference_t<R> s;
return s;
}
else
{
return R{};
}
}
};
/*
* 1. function type ==> Ret(Args...)
* 2. function pointer ==> Ret(*)(Args...)
* 3. function reference ==> Ret(&)(Args...)
* 4. pointer to non-static member function ==> Ret(T::*)(Args...)
* 5. function object and functor ==> &T::operator()
* 6. function with generic operator call ==> template <typeanme ... Args> &T::operator()
*/
template<typename, typename = void>
struct function_traits { static constexpr bool is_callable = false; };
template<typename Ret, typename... Args>
struct function_traits<Ret(Args...)>
{
public:
static constexpr std::size_t argc = sizeof...(Args);
static constexpr bool is_callable = true;
typedef Ret function_type(Args...);
typedef Ret return_type;
using stl_function_type = std::function<function_type>;
using stl_lambda_type = lambda_dummy_t<function_type>;
typedef Ret(*pointer)(Args...);
using class_type = void;
template<std::size_t I>
struct args
{
static_assert(I < argc, "index is out of range, index must less than sizeof Args");
using type = typename std::tuple_element<I, std::tuple<Args...>>::type;
};
typedef std::tuple<Args...> tuple_type;
typedef std::tuple<std::remove_cv_t<std::remove_reference_t<Args>>...> pod_tuple_type;
};
template<typename Class, typename Ret, typename... Args>
struct function_traits<Class, Ret(Args...)>
{
public:
static constexpr std::size_t argc = sizeof...(Args);
static constexpr bool is_callable = true;
typedef Ret function_type(Args...);
typedef Ret return_type;
using stl_function_type = std::function<function_type>;
using stl_lambda_type = lambda_dummy_t<function_type>;
typedef Ret(*pointer)(Args...);
using class_type = Class;
template<std::size_t I>
struct args
{
static_assert(I < argc, "index is out of range, index must less than sizeof Args");
using type = typename std::tuple_element<I, std::tuple<Args...>>::type;
};
typedef std::tuple<Args...> tuple_type;
typedef std::tuple<std::remove_cv_t<std::remove_reference_t<Args>>...> pod_tuple_type;
};
// regular function pointer
template<typename Ret, typename... Args>
struct function_traits<Ret(*)(Args...)> : function_traits<Ret(Args...)> {};
// non-static member function pointer
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...)> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) volatile> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const volatile> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) &> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const &> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) volatile &> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const volatile &> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) && > : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const &&> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) volatile &&> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const volatile &&> : function_traits<Class, Ret(Args...)> {};
// non-static member function pointer -- noexcept versions for (C++17 and later)
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) volatile noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const volatile noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) & noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const & noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) volatile & noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const volatile& noexcept>
: function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) && noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const && noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) volatile && noexcept> : function_traits<Class, Ret(Args...)> {};
template <typename Ret, typename Class, typename... Args>
struct function_traits<Ret(Class::*)(Args...) const volatile&& noexcept>
: function_traits<Class, Ret(Args...)> {};
// functor lambda
template<typename Callable>
struct function_traits<Callable, std::void_t<decltype(&Callable::operator()), char>>
: function_traits<decltype(&Callable::operator())> {};
// std::function
template <typename Ret, typename... Args>
struct function_traits<std::function<Ret(Args...)>> : function_traits<Ret(Args...)> {};
template <typename F>
typename function_traits<F>::stl_function_type to_function(F&& lambda)
{
return static_cast<typename function_traits<F>::stl_function_type>(std::forward<F>(lambda));
}
template <typename F>
typename function_traits<F>::pointer to_function_pointer(const F& lambda) noexcept
{
return static_cast<typename function_traits<F>::pointer>(lambda);
}
template< class F >
inline constexpr bool is_callable_v = function_traits<std::decay_t<F>>::is_callable;
template<typename F, typename Void, typename... Args>
struct is_template_callable : std::false_type {};
template<typename F, typename... Args>
struct is_template_callable<F, std::void_t<decltype(std::declval<std::decay_t<F>&>()
((std::declval<Args>())...)), char>, Args...> : std::true_type {};
template<typename F, typename... Args>
inline constexpr bool is_template_callable_v = is_template_callable<F, void, Args...>::value;
}
#endif // !__ASIO2_FUNCTION_TRAITS_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_KAI_H
#define BHO_PREDEF_COMPILER_KAI_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_KCC`
Kai {CPP} compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__KCC+` | {predef_detection}
| `+__KCC_VERSION+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_KCC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__KCC)
# define BHO_COMP_KCC_DETECTION BHO_PREDEF_MAKE_0X_VRPP(__KCC_VERSION)
#endif
#ifdef BHO_COMP_KCC_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_KCC_EMULATED BHO_COMP_KCC_DETECTION
# else
# undef BHO_COMP_KCC
# define BHO_COMP_KCC BHO_COMP_KCC_DETECTION
# endif
# define BHO_COMP_KCC_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_KCC_NAME "Kai C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_KCC,BHO_COMP_KCC_NAME)
#ifdef BHO_COMP_KCC_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_KCC_EMULATED,BHO_COMP_KCC_NAME)
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_STLPORT_H
#define BHO_PREDEF_LIBRARY_STD_STLPORT_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_STLPORT`
http://sourceforge.net/projects/stlport/[STLport Standard {CPP}] library.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__SGI_STL_PORT+` | {predef_detection}
| `+_STLPORT_VERSION+` | {predef_detection}
| `+_STLPORT_MAJOR+`, `+_STLPORT_MINOR+`, `+_STLPORT_PATCHLEVEL+` | V.R.P
| `+_STLPORT_VERSION+` | V.R.P
| `+__SGI_STL_PORT+` | V.R.P
|===
*/ // end::reference[]
#define BHO_LIB_STD_STLPORT BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)
# undef BHO_LIB_STD_STLPORT
# if !defined(BHO_LIB_STD_STLPORT) && defined(_STLPORT_MAJOR)
# define BHO_LIB_STD_STLPORT \
BHO_VERSION_NUMBER(_STLPORT_MAJOR,_STLPORT_MINOR,_STLPORT_PATCHLEVEL)
# endif
# if !defined(BHO_LIB_STD_STLPORT) && defined(_STLPORT_VERSION)
# define BHO_LIB_STD_STLPORT BHO_PREDEF_MAKE_0X_VRP(_STLPORT_VERSION)
# endif
# if !defined(BHO_LIB_STD_STLPORT)
# define BHO_LIB_STD_STLPORT BHO_PREDEF_MAKE_0X_VRP(__SGI_STL_PORT)
# endif
#endif
#if BHO_LIB_STD_STLPORT
# define BHO_LIB_STD_STLPORT_AVAILABLE
#endif
#define BHO_LIB_STD_STLPORT_NAME "STLport"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_STLPORT,BHO_LIB_STD_STLPORT_NAME)
<file_sep>#ifndef ASIO2_USE_SSL
#define ASIO2_USE_SSL
#endif
#include "unit_test.hpp"
#include <iostream>
#include <asio2/asio2.hpp>
struct aop_log
{
bool before(http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
return true;
}
bool after(std::shared_ptr<asio2::https_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(session_ptr, req, rep);
return true;
}
};
struct aop_check
{
bool before(std::shared_ptr<asio2::https_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(session_ptr, req, rep);
return true;
}
bool after(http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
return true;
}
};
void https_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
{
asio::error_code ec;
auto rep = asio2::https_client::execute("https://www.baidu.com");
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
}
{
std::shared_ptr<asio2::socks5::option<asio2::socks5::method::anonymous>>
sock5_option = std::make_shared<asio2::socks5::option<asio2::socks5::method::anonymous>>(
"127.0.0.1", 10808);
asio::error_code ec;
auto rep = asio2::https_client::execute("https://www.baidu.com", sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream || ec == asio::ssl::error::stream_truncated);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
}
{
asio2::socks5::option<asio2::socks5::method::anonymous>
sock5_option{ "127.0.0.1", 10808 };
asio::error_code ec;
auto rep = asio2::https_client::execute("https://www.baidu.com", sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream || ec == asio::ssl::error::stream_truncated);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
}
// test https download
{
asio2::socks5::option<asio2::socks5::method::anonymous>
sock5_option{ "127.0.0.1",10808 };
std::string url = "https://www.baidu.com/img/flexible/logo/pc/result.png";
std::string pth = "result.png";
asio2::https_client::download(url, [](auto&) {}, [](std::string_view) {});
asio2::https_client::download(asio::ssl::context{ asio::ssl::context::sslv23 }, url, [](auto&) {}, [](std::string_view) {});
asio2::https_client::download(url, [](std::string_view) {});
asio2::https_client::download(asio::ssl::context{ asio::ssl::context::sslv23 }, url, [](std::string_view) {});
asio2::https_client::download(url, pth);
asio2::https_client::download(asio::ssl::context{ asio::ssl::context::sslv23 }, url, pth);
auto req = http::make_request(url);
asio2::https_client::download(asio::ssl::context{ asio::ssl::context::sslv23 }, req.host(), req.port(), req, [](auto&) {}, [](std::string_view) {}, nullptr);
asio2::https_client::download(asio::ssl::context{ asio::ssl::context::sslv23 }, req.host(), req.port(), req, [](auto&) {}, [](std::string_view) {}, sock5_option);
}
{
asio2::https_server server;
server.support_websocket(true);
// set the root directory, here is: /asio2/example/wwwroot
std::filesystem::path root = std::filesystem::current_path()
.parent_path().parent_path().parent_path()
.append("example").append("wwwroot");
server.set_root_directory(std::move(root));
server.set_cert_file(
"../../../example/cert/ca.crt",
"../../../example/cert/server.crt",
"../../../example/cert/server.key",
"123456");
server.set_dh_file("../../../example/cert/dh1024.pem");
server.bind_accept([](std::shared_ptr<asio2::https_session> & session_ptr)
{
if (!asio2::get_last_error())
{
if (session_ptr->remote_address().find("192.168.10.") != std::string::npos)
session_ptr->stop();
}
}).bind_start([&]()
{
}).bind_stop([&]()
{
});
server.bind<http::verb::get, http::verb::post>("/", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
rep.fill_file("index.html");
}, aop_log{});
// If no method is specified, GET and POST are both enabled by default.
server.bind("*", [](http::web_request& req, http::web_response& rep)
{
rep.fill_file(req.target());
}, aop_check{});
bool wss_open_flag = false, wss_close_flag = false;
server.bind("/ws", websocket::listener<asio2::https_session>{}.
on("message", [](std::shared_ptr<asio2::https_session>& session_ptr, std::string_view data)
{
session_ptr->async_send(data);
}).on("open", [&](std::shared_ptr<asio2::https_session>& session_ptr)
{
wss_open_flag = true;
asio2::ignore_unused(session_ptr);
}).on("close", [&](std::shared_ptr<asio2::https_session>& session_ptr)
{
wss_close_flag = true;
asio2::ignore_unused(session_ptr);
}).on("ping", [](std::shared_ptr<asio2::https_session>& session_ptr, std::string_view data)
{
asio2::ignore_unused(session_ptr, data);
}).on("pong", [](std::shared_ptr<asio2::https_session>& session_ptr, std::string_view data)
{
asio2::ignore_unused(session_ptr, data);
}));
server.bind_not_found([](/*std::shared_ptr<asio2::http_session>& session_ptr, */
http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req);
rep.fill_page(http::status::not_found);
});
bool https_server_ret = server.start("127.0.0.1", 8443);
ASIO2_CHECK(https_server_ret);
asio::ssl::context ctx{ asio::ssl::context::sslv23 };
http::request_t<http::string_body> req1;
asio2::https_client::execute(ctx, "127.0.0.1", 8443, req1, std::chrono::seconds(5));
asio2::https_client::execute(ctx, "127.0.0.1", 8443, req1);
asio2::https_client::execute("127.0.0.1", 8443, req1, std::chrono::seconds(5));
asio2::https_client::execute("127.0.0.1", 8443, req1);
asio2::https_client https_client;
//https_client.set_verify_mode(asio::ssl::verify_peer);
https_client.set_cert_file(
"../../../example/cert/ca.crt",
"../../../example/cert/client.crt",
"../../../example/cert/client.key",
"123456");
https_client.set_connect_timeout(std::chrono::seconds(10));
https_client.bind_recv([&](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
}).bind_connect([&]()
{
// send a request
https_client.async_send("GET / HTTP/1.1\r\n\r\n");
}).bind_disconnect([]()
{
}).bind_handshake([&]()
{
});
bool https_client_ret = https_client.start("127.0.0.1", 8443);
ASIO2_CHECK_VALUE(asio2::last_error_msg(), https_client_ret);
asio2::wss_client wss_client;
wss_client.set_connect_timeout(std::chrono::seconds(10));
wss_client.set_verify_mode(asio::ssl::verify_peer);
wss_client.set_cert_file(
"../../../example/cert/ca.crt",
"../../../example/cert/client.crt",
"../../../example/cert/client.key",
"123456");
wss_client.bind_init([&]()
{
// how to set custom websocket request data :
wss_client.ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::request_type& req)
{
req.set(http::field::authorization, " ssl-websocket-coro");
}));
}).bind_recv([&](std::string_view data)
{
wss_client.async_send(data);
}).bind_connect([&]()
{
// a new thread.....
std::thread([&]()
{
wss_client.post([&]()
{
ASIO2_CHECK(wss_client.io().running_in_this_thread());
std::string str(std::size_t(100 + (std::rand() % 300)), char(std::rand() % 255));
wss_client.async_send(std::move(str));
});
}).join();
}).bind_upgrade([&]()
{
wss_client.async_send("abc", []()
{
ASIO2_CHECK(!asio2::get_last_error());
});
}).bind_disconnect([]()
{
});
bool wss_client_ret = wss_client.start("127.0.0.1", 8443, "/ws");
ASIO2_CHECK(wss_client_ret);
ASIO2_CHECK(wss_open_flag);
std::this_thread::sleep_for(std::chrono::milliseconds(50 + std::rand() % 50));
wss_client.stop();
server.stop();
//ASIO2_CHECK(wss_close_flag);
}
// https client with socks5 option
{
asio2::socks5::option<asio2::socks5::method::anonymous>
sock5_option{ "127.0.0.1", 10808 };
//asio2::socks5::option<asio2::socks5::method::anonymous, asio2::socks5::method::password>
// sock5_option{ "s5.doudouip.cn",1088,"zjww-1","aaa123" };
asio2::https_client https_client;
int counter = 0;
https_client.bind_recv([&](http::web_request& req, http::web_response& rep)
{
counter++;
ASIO2_CHECK(rep.result() == http::status::ok);
// Remove all fields
req.clear();
req.set(http::field::user_agent, "Chrome");
req.set(http::field::content_type, "text/html");
req.method(http::verb::get);
req.keep_alive(true);
req.target("/");
req.body() = "Hello World.";
req.prepare_payload();
https_client.async_send(std::move(req));
}).bind_connect([&]()
{
// connect success, send a request.
if (!asio2::get_last_error())
{
const char * msg = "GET / HTTP/1.1\r\n\r\n";
https_client.async_send(msg);
}
});
bool http_client_ret = https_client.start("www.baidu.com", 443, std::move(sock5_option));
ASIO2_CHECK(http_client_ret);
while (http_client_ret && counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
std::this_thread::sleep_for(std::chrono::milliseconds(10 + std::rand() % 10));
}
// https client with socks5 option shared_ptr
{
std::shared_ptr<asio2::socks5::option<asio2::socks5::method::anonymous>>
sock5_option = std::make_shared<asio2::socks5::option<asio2::socks5::method::anonymous>>(
"127.0.0.1", 10808);
//asio2::socks5::option<asio2::socks5::method::anonymous, asio2::socks5::method::password>
// sock5_option{ "s5.doudouip.cn",1088,"zjww-1","aaa123" };
asio2::https_client https_client;
int counter = 0;
https_client.bind_recv([&](http::web_request& req, http::web_response& rep)
{
counter++;
ASIO2_CHECK(rep.result() == http::status::ok);
// Remove all fields
req.clear();
req.set(http::field::user_agent, "Chrome");
req.set(http::field::content_type, "text/html");
req.method(http::verb::get);
req.keep_alive(true);
req.target("/");
req.prepare_payload();
https_client.async_send(std::move(req));
}).bind_connect([&, sock5_option]()
{
// connect success, send a request.
if (!asio2::get_last_error())
{
const char * msg = "GET / HTTP/1.1\r\n\r\n";
https_client.async_send(msg);
}
else
{
sock5_option->set_port(std::stoi(sock5_option->get_port()) + 1);
}
});
bool http_client_ret = https_client.start("www.baidu.com", 443, std::move(sock5_option));
ASIO2_CHECK(http_client_ret);
while (http_client_ret && counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
std::this_thread::sleep_for(std::chrono::milliseconds(10 + std::rand() % 10));
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"https",
ASIO2_TEST_CASE(https_test)
)
<file_sep>/*
Copyright <NAME> 2015
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_HARDWARE_SIMD_PPC_VERSIONS_H
#define BHO_PREDEF_HARDWARE_SIMD_PPC_VERSIONS_H
#include <asio2/bho/predef/version_number.h>
/* tag::reference[]
= `BHO_HW_SIMD_PPC_*_VERSION`
Those defines represent Power PC SIMD extensions versions.
NOTE: You *MUST* compare them with the predef `BHO_HW_SIMD_PPC`.
*/ // end::reference[]
// ---------------------------------
/* tag::reference[]
= `BHO_HW_SIMD_PPC_VMX_VERSION`
The https://en.wikipedia.org/wiki/AltiVec#VMX128[VMX] powerpc extension
version number.
Version number is: *1.0.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_PPC_VMX_VERSION BHO_VERSION_NUMBER(1, 0, 0)
/* tag::reference[]
= `BHO_HW_SIMD_PPC_VSX_VERSION`
The https://en.wikipedia.org/wiki/AltiVec#VSX[VSX] powerpc extension version
number.
Version number is: *1.1.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_PPC_VSX_VERSION BHO_VERSION_NUMBER(1, 1, 0)
/* tag::reference[]
= `BHO_HW_SIMD_PPC_QPX_VERSION`
The QPX powerpc extension version number.
Version number is: *2.0.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_PPC_QPX_VERSION BHO_VERSION_NUMBER(2, 0, 0)
/* tag::reference[]
*/ // end::reference[]
#endif
<file_sep>// Boost config.hpp configuration header file ------------------------------//
// boostinspect:ndprecated_macros -- tell the inspect tool to ignore this file
// Copyright (c) 2001-2003 <NAME>
// Copyright (c) 2001 <NAME>
// Copyright (c) 2001 <NAME>
// Copyright (c) 2002 <NAME>
// Copyright (c) 2002 <NAME>
// Copyright (c) 2002-2003 <NAME>
// Copyright (c) 2003 <NAME>
// Copyright (c) 2003 <NAME>
// Copyright (c) 2010 <NAME>, <NAME>
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/ for most recent version.
// Boost config.hpp policy and rationale documentation has been moved to
// http://www.boost.org/libs/config/
//
// This file is intended to be stable, and relatively unchanging.
// It should contain boilerplate code only - no compiler specific
// code unless it is unavoidable - no changes unless unavoidable.
#ifndef BHO_CONFIG_SUFFIX_HPP
#define BHO_CONFIG_SUFFIX_HPP
#if defined(__GNUC__) && (__GNUC__ >= 4)
//
// Some GCC-4.x versions issue warnings even when __extension__ is used,
// so use this as a workaround:
//
#pragma GCC system_header
#endif
//
// ensure that visibility macros are always defined, thus simplifying use
//
#ifndef BHO_SYMBOL_EXPORT
# define BHO_SYMBOL_EXPORT
#endif
#ifndef BHO_SYMBOL_IMPORT
# define BHO_SYMBOL_IMPORT
#endif
#ifndef BHO_SYMBOL_VISIBLE
# define BHO_SYMBOL_VISIBLE
#endif
//
// look for long long by looking for the appropriate macros in <limits.h>.
// Note that we use limits.h rather than climits for maximal portability,
// remember that since these just declare a bunch of macros, there should be
// no namespace issues from this.
//
#if !defined(BHO_HAS_LONG_LONG) && !defined(BHO_NO_LONG_LONG) \
&& !defined(BHO_MSVC) && !defined(BHO_BORLANDC)
# include <limits.h>
# if (defined(ULLONG_MAX) || defined(ULONG_LONG_MAX) || defined(ULONGLONG_MAX))
# define BHO_HAS_LONG_LONG
# else
# define BHO_NO_LONG_LONG
# endif
#endif
// GCC 3.x will clean up all of those nasty macro definitions that
// BHO_NO_CTYPE_FUNCTIONS is intended to help work around, so undefine
// it under GCC 3.x.
#if defined(__GNUC__) && (__GNUC__ >= 3) && defined(BHO_NO_CTYPE_FUNCTIONS)
# undef BHO_NO_CTYPE_FUNCTIONS
#endif
//
// Assume any extensions are in namespace std:: unless stated otherwise:
//
# ifndef BHO_STD_EXTENSION_NAMESPACE
# define BHO_STD_EXTENSION_NAMESPACE std
# endif
//
// If cv-qualified specializations are not allowed, then neither are cv-void ones:
//
# if defined(BHO_NO_CV_SPECIALIZATIONS) \
&& !defined(BHO_NO_CV_VOID_SPECIALIZATIONS)
# define BHO_NO_CV_VOID_SPECIALIZATIONS
# endif
//
// If there is no numeric_limits template, then it can't have any compile time
// constants either!
//
# if defined(BHO_NO_LIMITS) \
&& !defined(BHO_NO_LIMITS_COMPILE_TIME_CONSTANTS)
# define BHO_NO_LIMITS_COMPILE_TIME_CONSTANTS
# define BHO_NO_MS_INT64_NUMERIC_LIMITS
# define BHO_NO_LONG_LONG_NUMERIC_LIMITS
# endif
//
// if there is no long long then there is no specialisation
// for numeric_limits<long long> either:
//
#if !defined(BHO_HAS_LONG_LONG) && !defined(BHO_NO_LONG_LONG_NUMERIC_LIMITS)
# define BHO_NO_LONG_LONG_NUMERIC_LIMITS
#endif
//
// if there is no __int64 then there is no specialisation
// for numeric_limits<__int64> either:
//
#if !defined(BHO_HAS_MS_INT64) && !defined(BHO_NO_MS_INT64_NUMERIC_LIMITS)
# define BHO_NO_MS_INT64_NUMERIC_LIMITS
#endif
//
// if member templates are supported then so is the
// VC6 subset of member templates:
//
# if !defined(BHO_NO_MEMBER_TEMPLATES) \
&& !defined(BHO_MSVC6_MEMBER_TEMPLATES)
# define BHO_MSVC6_MEMBER_TEMPLATES
# endif
//
// Without partial specialization, can't test for partial specialisation bugs:
//
# if defined(BHO_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
&& !defined(BHO_BCB_PARTIAL_SPECIALIZATION_BUG)
# define BHO_BCB_PARTIAL_SPECIALIZATION_BUG
# endif
//
// Without partial specialization, we can't have array-type partial specialisations:
//
# if defined(BHO_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
&& !defined(BHO_NO_ARRAY_TYPE_SPECIALIZATIONS)
# define BHO_NO_ARRAY_TYPE_SPECIALIZATIONS
# endif
//
// Without partial specialization, std::iterator_traits can't work:
//
# if defined(BHO_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
&& !defined(BHO_NO_STD_ITERATOR_TRAITS)
# define BHO_NO_STD_ITERATOR_TRAITS
# endif
//
// Without partial specialization, partial
// specialization with default args won't work either:
//
# if defined(BHO_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
&& !defined(BHO_NO_PARTIAL_SPECIALIZATION_IMPLICIT_DEFAULT_ARGS)
# define BHO_NO_PARTIAL_SPECIALIZATION_IMPLICIT_DEFAULT_ARGS
# endif
//
// Without member template support, we can't have template constructors
// in the standard library either:
//
# if defined(BHO_NO_MEMBER_TEMPLATES) \
&& !defined(BHO_MSVC6_MEMBER_TEMPLATES) \
&& !defined(BHO_NO_TEMPLATED_ITERATOR_CONSTRUCTORS)
# define BHO_NO_TEMPLATED_ITERATOR_CONSTRUCTORS
# endif
//
// Without member template support, we can't have a conforming
// std::allocator template either:
//
# if defined(BHO_NO_MEMBER_TEMPLATES) \
&& !defined(BHO_MSVC6_MEMBER_TEMPLATES) \
&& !defined(BHO_NO_STD_ALLOCATOR)
# define BHO_NO_STD_ALLOCATOR
# endif
//
// without ADL support then using declarations will break ADL as well:
//
#if defined(BHO_NO_ARGUMENT_DEPENDENT_LOOKUP) && !defined(BHO_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL)
# define BHO_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL
#endif
//
// Without typeid support we have no dynamic RTTI either:
//
#if defined(BHO_NO_TYPEID) && !defined(BHO_NO_RTTI)
# define BHO_NO_RTTI
#endif
//
// If we have a standard allocator, then we have a partial one as well:
//
#if !defined(BHO_NO_STD_ALLOCATOR)
# define BHO_HAS_PARTIAL_STD_ALLOCATOR
#endif
//
// We can't have a working std::use_facet if there is no std::locale:
//
# if defined(BHO_NO_STD_LOCALE) && !defined(BHO_NO_STD_USE_FACET)
# define BHO_NO_STD_USE_FACET
# endif
//
// We can't have a std::messages facet if there is no std::locale:
//
# if defined(BHO_NO_STD_LOCALE) && !defined(BHO_NO_STD_MESSAGES)
# define BHO_NO_STD_MESSAGES
# endif
//
// We can't have a working std::wstreambuf if there is no std::locale:
//
# if defined(BHO_NO_STD_LOCALE) && !defined(BHO_NO_STD_WSTREAMBUF)
# define BHO_NO_STD_WSTREAMBUF
# endif
//
// We can't have a <cwctype> if there is no <cwchar>:
//
# if defined(BHO_NO_CWCHAR) && !defined(BHO_NO_CWCTYPE)
# define BHO_NO_CWCTYPE
# endif
//
// We can't have a swprintf if there is no <cwchar>:
//
# if defined(BHO_NO_CWCHAR) && !defined(BHO_NO_SWPRINTF)
# define BHO_NO_SWPRINTF
# endif
//
// If Win32 support is turned off, then we must turn off
// threading support also, unless there is some other
// thread API enabled:
//
#if defined(BHO_DISABLE_WIN32) && defined(_WIN32) \
&& !defined(BHO_DISABLE_THREADS) && !defined(BHO_HAS_PTHREADS)
# define BHO_DISABLE_THREADS
#endif
//
// Turn on threading support if the compiler thinks that it's in
// multithreaded mode. We put this here because there are only a
// limited number of macros that identify this (if there's any missing
// from here then add to the appropriate compiler section):
//
#if (defined(__MT__) || defined(_MT) || defined(_REENTRANT) \
|| defined(_PTHREADS) || defined(__APPLE__) || defined(__DragonFly__)) \
&& !defined(BHO_HAS_THREADS)
# define BHO_HAS_THREADS
#endif
//
// Turn threading support off if BHO_DISABLE_THREADS is defined:
//
#if defined(BHO_DISABLE_THREADS) && defined(BHO_HAS_THREADS)
# undef BHO_HAS_THREADS
#endif
//
// Turn threading support off if we don't recognise the threading API:
//
#if defined(BHO_HAS_THREADS) && !defined(BHO_HAS_PTHREADS)\
&& !defined(BHO_HAS_WINTHREADS) && !defined(BHO_HAS_BETHREADS)\
&& !defined(BHO_HAS_MPTASKS)
# undef BHO_HAS_THREADS
#endif
//
// Turn threading detail macros off if we don't (want to) use threading
//
#ifndef BHO_HAS_THREADS
# undef BHO_HAS_PTHREADS
# undef BHO_HAS_PTHREAD_MUTEXATTR_SETTYPE
# undef BHO_HAS_PTHREAD_YIELD
# undef BHO_HAS_PTHREAD_DELAY_NP
# undef BHO_HAS_WINTHREADS
# undef BHO_HAS_BETHREADS
# undef BHO_HAS_MPTASKS
#endif
//
// If the compiler claims to be C99 conformant, then it had better
// have a <stdint.h>:
//
# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)
# define BHO_HAS_STDINT_H
# ifndef BHO_HAS_LOG1P
# define BHO_HAS_LOG1P
# endif
# ifndef BHO_HAS_EXPM1
# define BHO_HAS_EXPM1
# endif
# endif
//
// Define BHO_NO_SLIST and BHO_NO_HASH if required.
// Note that this is for backwards compatibility only.
//
# if !defined(BHO_HAS_SLIST) && !defined(BHO_NO_SLIST)
# define BHO_NO_SLIST
# endif
# if !defined(BHO_HAS_HASH) && !defined(BHO_NO_HASH)
# define BHO_NO_HASH
# endif
//
// Set BHO_SLIST_HEADER if not set already:
//
#if defined(BHO_HAS_SLIST) && !defined(BHO_SLIST_HEADER)
# define BHO_SLIST_HEADER <slist>
#endif
//
// Set BHO_HASH_SET_HEADER if not set already:
//
#if defined(BHO_HAS_HASH) && !defined(BHO_HASH_SET_HEADER)
# define BHO_HASH_SET_HEADER <hash_set>
#endif
//
// Set BHO_HASH_MAP_HEADER if not set already:
//
#if defined(BHO_HAS_HASH) && !defined(BHO_HASH_MAP_HEADER)
# define BHO_HASH_MAP_HEADER <hash_map>
#endif
// BHO_HAS_ABI_HEADERS
// This macro gets set if we have headers that fix the ABI,
// and prevent ODR violations when linking to external libraries:
#if defined(BHO_ABI_PREFIX) && defined(BHO_ABI_SUFFIX) && !defined(BHO_HAS_ABI_HEADERS)
# define BHO_HAS_ABI_HEADERS
#endif
#if defined(BHO_HAS_ABI_HEADERS) && defined(BHO_DISABLE_ABI_HEADERS)
# undef BHO_HAS_ABI_HEADERS
#endif
// BHO_NO_STDC_NAMESPACE workaround --------------------------------------//
// Because std::size_t usage is so common, even in boost headers which do not
// otherwise use the C library, the <cstddef> workaround is included here so
// that ugly workaround code need not appear in many other boost headers.
// NOTE WELL: This is a workaround for non-conforming compilers; <cstddef>
// must still be #included in the usual places so that <cstddef> inclusion
// works as expected with standard conforming compilers. The resulting
// double inclusion of <cstddef> is harmless.
# if defined(BHO_NO_STDC_NAMESPACE) && defined(__cplusplus)
# include <cstddef>
namespace std { using ::ptrdiff_t; using ::size_t; }
# endif
// Workaround for the unfortunate min/max macros defined by some platform headers
#define BHO_PREVENT_MACRO_SUBSTITUTION
#ifndef BHO_USING_STD_MIN
# define BHO_USING_STD_MIN() using std::min
#endif
#ifndef BHO_USING_STD_MAX
# define BHO_USING_STD_MAX() using std::max
#endif
// BHO_NO_STD_MIN_MAX workaround -----------------------------------------//
# if defined(BHO_NO_STD_MIN_MAX) && defined(__cplusplus)
namespace std {
template <class _Tp>
inline const _Tp& min BHO_PREVENT_MACRO_SUBSTITUTION (const _Tp& __a, const _Tp& __b) {
return __b < __a ? __b : __a;
}
template <class _Tp>
inline const _Tp& max BHO_PREVENT_MACRO_SUBSTITUTION (const _Tp& __a, const _Tp& __b) {
return __a < __b ? __b : __a;
}
}
# endif
// BHO_STATIC_CONSTANT workaround --------------------------------------- //
// On compilers which don't allow in-class initialization of static integral
// constant members, we must use enums as a workaround if we want the constants
// to be available at compile-time. This macro gives us a convenient way to
// declare such constants.
# ifdef BHO_NO_INCLASS_MEMBER_INITIALIZATION
# define BHO_STATIC_CONSTANT(type, assignment) enum { assignment }
# else
# define BHO_STATIC_CONSTANT(type, assignment) static const type assignment
# endif
// BHO_USE_FACET / HAS_FACET workaround ----------------------------------//
// When the standard library does not have a conforming std::use_facet there
// are various workarounds available, but they differ from library to library.
// The same problem occurs with has_facet.
// These macros provide a consistent way to access a locale's facets.
// Usage:
// replace
// std::use_facet<Type>(loc);
// with
// BHO_USE_FACET(Type, loc);
// Note do not add a std:: prefix to the front of BHO_USE_FACET!
// Use for BHO_HAS_FACET is analogous.
#if defined(BHO_NO_STD_USE_FACET)
# ifdef BHO_HAS_TWO_ARG_USE_FACET
# define BHO_USE_FACET(Type, loc) std::use_facet(loc, static_cast<Type*>(0))
# define BHO_HAS_FACET(Type, loc) std::has_facet(loc, static_cast<Type*>(0))
# elif defined(BHO_HAS_MACRO_USE_FACET)
# define BHO_USE_FACET(Type, loc) std::_USE(loc, Type)
# define BHO_HAS_FACET(Type, loc) std::_HAS(loc, Type)
# elif defined(BHO_HAS_STLP_USE_FACET)
# define BHO_USE_FACET(Type, loc) (*std::_Use_facet<Type >(loc))
# define BHO_HAS_FACET(Type, loc) std::has_facet< Type >(loc)
# endif
#else
# define BHO_USE_FACET(Type, loc) std::use_facet< Type >(loc)
# define BHO_HAS_FACET(Type, loc) std::has_facet< Type >(loc)
#endif
// BHO_NESTED_TEMPLATE workaround ------------------------------------------//
// Member templates are supported by some compilers even though they can't use
// the A::template member<U> syntax, as a workaround replace:
//
// typedef typename A::template rebind<U> binder;
//
// with:
//
// typedef typename A::BHO_NESTED_TEMPLATE rebind<U> binder;
#ifndef BHO_NO_MEMBER_TEMPLATE_KEYWORD
# define BHO_NESTED_TEMPLATE template
#else
# define BHO_NESTED_TEMPLATE
#endif
// BHO_UNREACHABLE_RETURN(x) workaround -------------------------------------//
// Normally evaluates to nothing, unless BHO_NO_UNREACHABLE_RETURN_DETECTION
// is defined, in which case it evaluates to return x; Use when you have a return
// statement that can never be reached.
#ifndef BHO_UNREACHABLE_RETURN
# ifdef BHO_NO_UNREACHABLE_RETURN_DETECTION
# define BHO_UNREACHABLE_RETURN(x) return x;
# else
# define BHO_UNREACHABLE_RETURN(x)
# endif
#endif
// BHO_DEDUCED_TYPENAME workaround ------------------------------------------//
//
// Some compilers don't support the use of `typename' for dependent
// types in deduced contexts, e.g.
//
// template <class T> void f(T, typename T::type);
// ^^^^^^^^
// Replace these declarations with:
//
// template <class T> void f(T, BHO_DEDUCED_TYPENAME T::type);
#ifndef BHO_NO_DEDUCED_TYPENAME
# define BHO_DEDUCED_TYPENAME typename
#else
# define BHO_DEDUCED_TYPENAME
#endif
#ifndef BHO_NO_TYPENAME_WITH_CTOR
# define BHO_CTOR_TYPENAME typename
#else
# define BHO_CTOR_TYPENAME
#endif
//
// If we're on a CUDA device (note DEVICE not HOST, irrespective of compiler) then disable __int128 and __float128 support if present:
//
#if defined(__CUDA_ARCH__) && defined(BHO_HAS_FLOAT128)
# undef BHO_HAS_FLOAT128
#endif
#if defined(__CUDA_ARCH__) && defined(BHO_HAS_INT128)
# undef BHO_HAS_INT128
#endif
// long long workaround ------------------------------------------//
// On gcc (and maybe other compilers?) long long is alway supported
// but it's use may generate either warnings (with -ansi), or errors
// (with -pedantic -ansi) unless it's use is prefixed by __extension__
//
#if defined(BHO_HAS_LONG_LONG) && defined(__cplusplus)
namespace bho{
# ifdef __GNUC__
__extension__ typedef long long long_long_type;
__extension__ typedef unsigned long long ulong_long_type;
# else
typedef long long long_long_type;
typedef unsigned long long ulong_long_type;
# endif
}
#endif
// same again for __int128:
#if defined(BHO_HAS_INT128) && defined(__cplusplus)
namespace bho{
# ifdef __GNUC__
__extension__ typedef __int128 int128_type;
__extension__ typedef unsigned __int128 uint128_type;
# else
typedef __int128 int128_type;
typedef unsigned __int128 uint128_type;
# endif
}
#endif
// same again for __float128:
#if defined(BHO_HAS_FLOAT128) && defined(__cplusplus)
namespace bho {
# ifdef __GNUC__
__extension__ typedef __float128 float128_type;
# else
typedef __float128 float128_type;
# endif
}
#endif
// BHO_[APPEND_]EXPLICIT_TEMPLATE_[NON_]TYPE macros --------------------------//
// These macros are obsolete. Port away and remove.
# define BHO_EXPLICIT_TEMPLATE_TYPE(t)
# define BHO_EXPLICIT_TEMPLATE_TYPE_SPEC(t)
# define BHO_EXPLICIT_TEMPLATE_NON_TYPE(t, v)
# define BHO_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v)
# define BHO_APPEND_EXPLICIT_TEMPLATE_TYPE(t)
# define BHO_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t)
# define BHO_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v)
# define BHO_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v)
// When BHO_NO_STD_TYPEINFO is defined, we can just import
// the global definition into std namespace,
// see https://svn.boost.org/trac10/ticket/4115
#if defined(BHO_NO_STD_TYPEINFO) && defined(__cplusplus) && defined(BHO_MSVC)
#include <typeinfo>
namespace std{ using ::type_info; }
// Since we do now have typeinfo, undef the macro:
#undef BHO_NO_STD_TYPEINFO
#endif
// ---------------------------------------------------------------------------//
// Helper macro BHO_STRINGIZE:
// Helper macro BHO_JOIN:
#include <asio2/bho/config/helper_macros.hpp>
//
// Set some default values for compiler/library/platform names.
// These are for debugging config setup only:
//
# ifndef BHO_COMPILER
# define BHO_COMPILER "Unknown ISO C++ Compiler"
# endif
# ifndef BHO_STDLIB
# define BHO_STDLIB "Unknown ISO standard library"
# endif
# ifndef BHO_PLATFORM
# if defined(unix) || defined(__unix) || defined(_XOPEN_SOURCE) \
|| defined(_POSIX_SOURCE)
# define BHO_PLATFORM "Generic Unix"
# else
# define BHO_PLATFORM "Unknown"
# endif
# endif
//
// Set some default values GPU support
//
# ifndef BHO_GPU_ENABLED
# define BHO_GPU_ENABLED
# endif
// BHO_RESTRICT ---------------------------------------------//
// Macro to use in place of 'restrict' keyword variants
#if !defined(BHO_RESTRICT)
# if defined(_MSC_VER)
# define BHO_RESTRICT __restrict
# if !defined(BHO_NO_RESTRICT_REFERENCES) && (_MSC_FULL_VER < 190023026)
# define BHO_NO_RESTRICT_REFERENCES
# endif
# elif defined(__GNUC__) && __GNUC__ > 3
// Clang also defines __GNUC__ (as 4)
# define BHO_RESTRICT __restrict__
# else
# define BHO_RESTRICT
# if !defined(BHO_NO_RESTRICT_REFERENCES)
# define BHO_NO_RESTRICT_REFERENCES
# endif
# endif
#endif
// BHO_MAY_ALIAS -----------------------------------------------//
// The macro expands to an attribute to mark a type that is allowed to alias other types.
// The macro is defined in the compiler-specific headers.
#if !defined(BHO_MAY_ALIAS)
# define BHO_NO_MAY_ALIAS
# define BHO_MAY_ALIAS
#endif
// BHO_FORCEINLINE ---------------------------------------------//
// Macro to use in place of 'inline' to force a function to be inline
#if !defined(BHO_FORCEINLINE)
# if defined(_MSC_VER)
# define BHO_FORCEINLINE __forceinline
# elif defined(__GNUC__) && __GNUC__ > 3
// Clang also defines __GNUC__ (as 4)
# define BHO_FORCEINLINE inline __attribute__ ((__always_inline__))
# else
# define BHO_FORCEINLINE inline
# endif
#endif
// BHO_NOINLINE ---------------------------------------------//
// Macro to use in place of 'inline' to prevent a function to be inlined
#if !defined(BHO_NOINLINE)
# if defined(_MSC_VER)
# define BHO_NOINLINE __declspec(noinline)
# elif defined(__GNUC__) && __GNUC__ > 3
// Clang also defines __GNUC__ (as 4)
# if defined(__CUDACC__)
// nvcc doesn't always parse __noinline__,
// see: https://svn.boost.org/trac/bho/ticket/9392
# define BHO_NOINLINE __attribute__ ((noinline))
# elif defined(HIP_VERSION)
// See https://github.com/boostorg/config/issues/392
# define BHO_NOINLINE __attribute__ ((noinline))
# else
# define BHO_NOINLINE __attribute__ ((__noinline__))
# endif
# else
# define BHO_NOINLINE
# endif
#endif
// BHO_NORETURN ---------------------------------------------//
// Macro to use before a function declaration/definition to designate
// the function as not returning normally (i.e. with a return statement
// or by leaving the function scope, if the function return type is void).
#if !defined(BHO_NORETURN)
# if defined(_MSC_VER)
# define BHO_NORETURN __declspec(noreturn)
# elif defined(__GNUC__) || defined(__CODEGEARC__) && defined(__clang__)
# define BHO_NORETURN __attribute__ ((__noreturn__))
# elif defined(__has_attribute) && defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x5130)
# if __has_attribute(noreturn)
# define BHO_NORETURN [[noreturn]]
# endif
# elif defined(__has_cpp_attribute)
# if __has_cpp_attribute(noreturn)
# define BHO_NORETURN [[noreturn]]
# endif
# endif
#endif
#if !defined(BHO_NORETURN)
# define BHO_NO_NORETURN
# define BHO_NORETURN
#endif
// Branch prediction hints
// These macros are intended to wrap conditional expressions that yield true or false
//
// if (BHO_LIKELY(var == 10))
// {
// // the most probable code here
// }
//
#if !defined(BHO_LIKELY)
# define BHO_LIKELY(x) x
#endif
#if !defined(BHO_UNLIKELY)
# define BHO_UNLIKELY(x) x
#endif
#if !defined(BHO_NO_CXX11_OVERRIDE)
# define BHO_OVERRIDE override
#else
# define BHO_OVERRIDE
#endif
// Type and data alignment specification
//
#if !defined(BHO_ALIGNMENT)
# if !defined(BHO_NO_CXX11_ALIGNAS)
# define BHO_ALIGNMENT(x) alignas(x)
# elif defined(_MSC_VER)
# define BHO_ALIGNMENT(x) __declspec(align(x))
# elif defined(__GNUC__)
# define BHO_ALIGNMENT(x) __attribute__ ((__aligned__(x)))
# else
# define BHO_NO_ALIGNMENT
# define BHO_ALIGNMENT(x)
# endif
#endif
// Lack of non-public defaulted functions is implied by the lack of any defaulted functions
#if !defined(BHO_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS) && defined(BHO_NO_CXX11_DEFAULTED_FUNCTIONS)
# define BHO_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS
#endif
// Lack of defaulted moves is implied by the lack of either rvalue references or any defaulted functions
#if !defined(BHO_NO_CXX11_DEFAULTED_MOVES) && (defined(BHO_NO_CXX11_DEFAULTED_FUNCTIONS) || defined(BHO_NO_CXX11_RVALUE_REFERENCES))
# define BHO_NO_CXX11_DEFAULTED_MOVES
#endif
// Defaulted and deleted function declaration helpers
// These macros are intended to be inside a class definition.
// BHO_DEFAULTED_FUNCTION accepts the function declaration and its
// body, which will be used if the compiler doesn't support defaulted functions.
// BHO_DELETED_FUNCTION only accepts the function declaration. It
// will expand to a private function declaration, if the compiler doesn't support
// deleted functions. Because of this it is recommended to use BHO_DELETED_FUNCTION
// in the end of the class definition.
//
// class my_class
// {
// public:
// // Default-constructible
// BHO_DEFAULTED_FUNCTION(my_class(), {})
// // Copying prohibited
// BHO_DELETED_FUNCTION(my_class(my_class const&))
// BHO_DELETED_FUNCTION(my_class& operator= (my_class const&))
// };
//
#if !(defined(BHO_NO_CXX11_DEFAULTED_FUNCTIONS) || defined(BHO_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS))
# define BHO_DEFAULTED_FUNCTION(fun, body) fun = default;
#else
# define BHO_DEFAULTED_FUNCTION(fun, body) fun body
#endif
#if !defined(BHO_NO_CXX11_DELETED_FUNCTIONS)
# define BHO_DELETED_FUNCTION(fun) fun = delete;
#else
# define BHO_DELETED_FUNCTION(fun) private: fun;
#endif
//
// Set BHO_NO_DECLTYPE_N3276 when BHO_NO_DECLTYPE is defined
//
#if defined(BHO_NO_CXX11_DECLTYPE) && !defined(BHO_NO_CXX11_DECLTYPE_N3276)
#define BHO_NO_CXX11_DECLTYPE_N3276 BHO_NO_CXX11_DECLTYPE
#endif
// -------------------- Deprecated macros for 1.50 ---------------------------
// These will go away in a future release
// Use BHO_NO_CXX11_HDR_UNORDERED_SET or BHO_NO_CXX11_HDR_UNORDERED_MAP
// instead of BHO_NO_STD_UNORDERED
#if defined(BHO_NO_CXX11_HDR_UNORDERED_MAP) || defined (BHO_NO_CXX11_HDR_UNORDERED_SET)
# ifndef BHO_NO_CXX11_STD_UNORDERED
# define BHO_NO_CXX11_STD_UNORDERED
# endif
#endif
// Use BHO_NO_CXX11_HDR_INITIALIZER_LIST instead of BHO_NO_INITIALIZER_LISTS
#if defined(BHO_NO_CXX11_HDR_INITIALIZER_LIST) && !defined(BHO_NO_INITIALIZER_LISTS)
# define BHO_NO_INITIALIZER_LISTS
#endif
// Use BHO_NO_CXX11_HDR_ARRAY instead of BHO_NO_0X_HDR_ARRAY
#if defined(BHO_NO_CXX11_HDR_ARRAY) && !defined(BHO_NO_0X_HDR_ARRAY)
# define BHO_NO_0X_HDR_ARRAY
#endif
// Use BHO_NO_CXX11_HDR_CHRONO instead of BHO_NO_0X_HDR_CHRONO
#if defined(BHO_NO_CXX11_HDR_CHRONO) && !defined(BHO_NO_0X_HDR_CHRONO)
# define BHO_NO_0X_HDR_CHRONO
#endif
// Use BHO_NO_CXX11_HDR_CODECVT instead of BHO_NO_0X_HDR_CODECVT
#if defined(BHO_NO_CXX11_HDR_CODECVT) && !defined(BHO_NO_0X_HDR_CODECVT)
# define BHO_NO_0X_HDR_CODECVT
#endif
// Use BHO_NO_CXX11_HDR_CONDITION_VARIABLE instead of BHO_NO_0X_HDR_CONDITION_VARIABLE
#if defined(BHO_NO_CXX11_HDR_CONDITION_VARIABLE) && !defined(BHO_NO_0X_HDR_CONDITION_VARIABLE)
# define BHO_NO_0X_HDR_CONDITION_VARIABLE
#endif
// Use BHO_NO_CXX11_HDR_FORWARD_LIST instead of BHO_NO_0X_HDR_FORWARD_LIST
#if defined(BHO_NO_CXX11_HDR_FORWARD_LIST) && !defined(BHO_NO_0X_HDR_FORWARD_LIST)
# define BHO_NO_0X_HDR_FORWARD_LIST
#endif
// Use BHO_NO_CXX11_HDR_FUTURE instead of BHO_NO_0X_HDR_FUTURE
#if defined(BHO_NO_CXX11_HDR_FUTURE) && !defined(BHO_NO_0X_HDR_FUTURE)
# define BHO_NO_0X_HDR_FUTURE
#endif
// Use BHO_NO_CXX11_HDR_INITIALIZER_LIST
// instead of BHO_NO_0X_HDR_INITIALIZER_LIST or BHO_NO_INITIALIZER_LISTS
#ifdef BHO_NO_CXX11_HDR_INITIALIZER_LIST
# ifndef BHO_NO_0X_HDR_INITIALIZER_LIST
# define BHO_NO_0X_HDR_INITIALIZER_LIST
# endif
# ifndef BHO_NO_INITIALIZER_LISTS
# define BHO_NO_INITIALIZER_LISTS
# endif
#endif
// Use BHO_NO_CXX11_HDR_MUTEX instead of BHO_NO_0X_HDR_MUTEX
#if defined(BHO_NO_CXX11_HDR_MUTEX) && !defined(BHO_NO_0X_HDR_MUTEX)
# define BHO_NO_0X_HDR_MUTEX
#endif
// Use BHO_NO_CXX11_HDR_RANDOM instead of BHO_NO_0X_HDR_RANDOM
#if defined(BHO_NO_CXX11_HDR_RANDOM) && !defined(BHO_NO_0X_HDR_RANDOM)
# define BHO_NO_0X_HDR_RANDOM
#endif
// Use BHO_NO_CXX11_HDR_RATIO instead of BHO_NO_0X_HDR_RATIO
#if defined(BHO_NO_CXX11_HDR_RATIO) && !defined(BHO_NO_0X_HDR_RATIO)
# define BHO_NO_0X_HDR_RATIO
#endif
// Use BHO_NO_CXX11_HDR_REGEX instead of BHO_NO_0X_HDR_REGEX
#if defined(BHO_NO_CXX11_HDR_REGEX) && !defined(BHO_NO_0X_HDR_REGEX)
# define BHO_NO_0X_HDR_REGEX
#endif
// Use BHO_NO_CXX11_HDR_SYSTEM_ERROR instead of BHO_NO_0X_HDR_SYSTEM_ERROR
#if defined(BHO_NO_CXX11_HDR_SYSTEM_ERROR) && !defined(BHO_NO_0X_HDR_SYSTEM_ERROR)
# define BHO_NO_0X_HDR_SYSTEM_ERROR
#endif
// Use BHO_NO_CXX11_HDR_THREAD instead of BHO_NO_0X_HDR_THREAD
#if defined(BHO_NO_CXX11_HDR_THREAD) && !defined(BHO_NO_0X_HDR_THREAD)
# define BHO_NO_0X_HDR_THREAD
#endif
// Use BHO_NO_CXX11_HDR_TUPLE instead of BHO_NO_0X_HDR_TUPLE
#if defined(BHO_NO_CXX11_HDR_TUPLE) && !defined(BHO_NO_0X_HDR_TUPLE)
# define BHO_NO_0X_HDR_TUPLE
#endif
// Use BHO_NO_CXX11_HDR_TYPE_TRAITS instead of BHO_NO_0X_HDR_TYPE_TRAITS
#if defined(BHO_NO_CXX11_HDR_TYPE_TRAITS) && !defined(BHO_NO_0X_HDR_TYPE_TRAITS)
# define BHO_NO_0X_HDR_TYPE_TRAITS
#endif
// Use BHO_NO_CXX11_HDR_TYPEINDEX instead of BHO_NO_0X_HDR_TYPEINDEX
#if defined(BHO_NO_CXX11_HDR_TYPEINDEX) && !defined(BHO_NO_0X_HDR_TYPEINDEX)
# define BHO_NO_0X_HDR_TYPEINDEX
#endif
// Use BHO_NO_CXX11_HDR_UNORDERED_MAP instead of BHO_NO_0X_HDR_UNORDERED_MAP
#if defined(BHO_NO_CXX11_HDR_UNORDERED_MAP) && !defined(BHO_NO_0X_HDR_UNORDERED_MAP)
# define BHO_NO_0X_HDR_UNORDERED_MAP
#endif
// Use BHO_NO_CXX11_HDR_UNORDERED_SET instead of BHO_NO_0X_HDR_UNORDERED_SET
#if defined(BHO_NO_CXX11_HDR_UNORDERED_SET) && !defined(BHO_NO_0X_HDR_UNORDERED_SET)
# define BHO_NO_0X_HDR_UNORDERED_SET
#endif
// ------------------ End of deprecated macros for 1.50 ---------------------------
// -------------------- Deprecated macros for 1.51 ---------------------------
// These will go away in a future release
// Use BHO_NO_CXX11_AUTO_DECLARATIONS instead of BHO_NO_AUTO_DECLARATIONS
#if defined(BHO_NO_CXX11_AUTO_DECLARATIONS) && !defined(BHO_NO_AUTO_DECLARATIONS)
# define BHO_NO_AUTO_DECLARATIONS
#endif
// Use BHO_NO_CXX11_AUTO_MULTIDECLARATIONS instead of BHO_NO_AUTO_MULTIDECLARATIONS
#if defined(BHO_NO_CXX11_AUTO_MULTIDECLARATIONS) && !defined(BHO_NO_AUTO_MULTIDECLARATIONS)
# define BHO_NO_AUTO_MULTIDECLARATIONS
#endif
// Use BHO_NO_CXX11_CHAR16_T instead of BHO_NO_CHAR16_T
#if defined(BHO_NO_CXX11_CHAR16_T) && !defined(BHO_NO_CHAR16_T)
# define BHO_NO_CHAR16_T
#endif
// Use BHO_NO_CXX11_CHAR32_T instead of BHO_NO_CHAR32_T
#if defined(BHO_NO_CXX11_CHAR32_T) && !defined(BHO_NO_CHAR32_T)
# define BHO_NO_CHAR32_T
#endif
// Use BHO_NO_CXX11_TEMPLATE_ALIASES instead of BHO_NO_TEMPLATE_ALIASES
#if defined(BHO_NO_CXX11_TEMPLATE_ALIASES) && !defined(BHO_NO_TEMPLATE_ALIASES)
# define BHO_NO_TEMPLATE_ALIASES
#endif
// Use BHO_NO_CXX11_CONSTEXPR instead of BHO_NO_CONSTEXPR
#if defined(BHO_NO_CXX11_CONSTEXPR) && !defined(BHO_NO_CONSTEXPR)
# define BHO_NO_CONSTEXPR
#endif
// Use BHO_NO_CXX11_DECLTYPE_N3276 instead of BHO_NO_DECLTYPE_N3276
#if defined(BHO_NO_CXX11_DECLTYPE_N3276) && !defined(BHO_NO_DECLTYPE_N3276)
# define BHO_NO_DECLTYPE_N3276
#endif
// Use BHO_NO_CXX11_DECLTYPE instead of BHO_NO_DECLTYPE
#if defined(BHO_NO_CXX11_DECLTYPE) && !defined(BHO_NO_DECLTYPE)
# define BHO_NO_DECLTYPE
#endif
// Use BHO_NO_CXX11_DEFAULTED_FUNCTIONS instead of BHO_NO_DEFAULTED_FUNCTIONS
#if defined(BHO_NO_CXX11_DEFAULTED_FUNCTIONS) && !defined(BHO_NO_DEFAULTED_FUNCTIONS)
# define BHO_NO_DEFAULTED_FUNCTIONS
#endif
// Use BHO_NO_CXX11_DELETED_FUNCTIONS instead of BHO_NO_DELETED_FUNCTIONS
#if defined(BHO_NO_CXX11_DELETED_FUNCTIONS) && !defined(BHO_NO_DELETED_FUNCTIONS)
# define BHO_NO_DELETED_FUNCTIONS
#endif
// Use BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS instead of BHO_NO_EXPLICIT_CONVERSION_OPERATORS
#if defined(BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS) && !defined(BHO_NO_EXPLICIT_CONVERSION_OPERATORS)
# define BHO_NO_EXPLICIT_CONVERSION_OPERATORS
#endif
// Use BHO_NO_CXX11_EXTERN_TEMPLATE instead of BHO_NO_EXTERN_TEMPLATE
#if defined(BHO_NO_CXX11_EXTERN_TEMPLATE) && !defined(BHO_NO_EXTERN_TEMPLATE)
# define BHO_NO_EXTERN_TEMPLATE
#endif
// Use BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS instead of BHO_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS
#if defined(BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS) && !defined(BHO_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS)
# define BHO_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS
#endif
// Use BHO_NO_CXX11_LAMBDAS instead of BHO_NO_LAMBDAS
#if defined(BHO_NO_CXX11_LAMBDAS) && !defined(BHO_NO_LAMBDAS)
# define BHO_NO_LAMBDAS
#endif
// Use BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS instead of BHO_NO_LOCAL_CLASS_TEMPLATE_PARAMETERS
#if defined(BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS) && !defined(BHO_NO_LOCAL_CLASS_TEMPLATE_PARAMETERS)
# define BHO_NO_LOCAL_CLASS_TEMPLATE_PARAMETERS
#endif
// Use BHO_NO_CXX11_NOEXCEPT instead of BHO_NO_NOEXCEPT
#if defined(BHO_NO_CXX11_NOEXCEPT) && !defined(BHO_NO_NOEXCEPT)
# define BHO_NO_NOEXCEPT
#endif
// Use BHO_NO_CXX11_NULLPTR instead of BHO_NO_NULLPTR
#if defined(BHO_NO_CXX11_NULLPTR) && !defined(BHO_NO_NULLPTR)
# define BHO_NO_NULLPTR
#endif
// Use BHO_NO_CXX11_RAW_LITERALS instead of BHO_NO_RAW_LITERALS
#if defined(BHO_NO_CXX11_RAW_LITERALS) && !defined(BHO_NO_RAW_LITERALS)
# define BHO_NO_RAW_LITERALS
#endif
// Use BHO_NO_CXX11_RVALUE_REFERENCES instead of BHO_NO_RVALUE_REFERENCES
#if defined(BHO_NO_CXX11_RVALUE_REFERENCES) && !defined(BHO_NO_RVALUE_REFERENCES)
# define BHO_NO_RVALUE_REFERENCES
#endif
// Use BHO_NO_CXX11_SCOPED_ENUMS instead of BHO_NO_SCOPED_ENUMS
#if defined(BHO_NO_CXX11_SCOPED_ENUMS) && !defined(BHO_NO_SCOPED_ENUMS)
# define BHO_NO_SCOPED_ENUMS
#endif
// Use BHO_NO_CXX11_STATIC_ASSERT instead of BHO_NO_STATIC_ASSERT
#if defined(BHO_NO_CXX11_STATIC_ASSERT) && !defined(BHO_NO_STATIC_ASSERT)
# define BHO_NO_STATIC_ASSERT
#endif
// Use BHO_NO_CXX11_STD_UNORDERED instead of BHO_NO_STD_UNORDERED
#if defined(BHO_NO_CXX11_STD_UNORDERED) && !defined(BHO_NO_STD_UNORDERED)
# define BHO_NO_STD_UNORDERED
#endif
// Use BHO_NO_CXX11_UNICODE_LITERALS instead of BHO_NO_UNICODE_LITERALS
#if defined(BHO_NO_CXX11_UNICODE_LITERALS) && !defined(BHO_NO_UNICODE_LITERALS)
# define BHO_NO_UNICODE_LITERALS
#endif
// Use BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX instead of BHO_NO_UNIFIED_INITIALIZATION_SYNTAX
#if defined(BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX) && !defined(BHO_NO_UNIFIED_INITIALIZATION_SYNTAX)
# define BHO_NO_UNIFIED_INITIALIZATION_SYNTAX
#endif
// Use BHO_NO_CXX11_VARIADIC_TEMPLATES instead of BHO_NO_VARIADIC_TEMPLATES
#if defined(BHO_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BHO_NO_VARIADIC_TEMPLATES)
# define BHO_NO_VARIADIC_TEMPLATES
#endif
// Use BHO_NO_CXX11_VARIADIC_MACROS instead of BHO_NO_VARIADIC_MACROS
#if defined(BHO_NO_CXX11_VARIADIC_MACROS) && !defined(BHO_NO_VARIADIC_MACROS)
# define BHO_NO_VARIADIC_MACROS
#endif
// Use BHO_NO_CXX11_NUMERIC_LIMITS instead of BHO_NO_NUMERIC_LIMITS_LOWEST
#if defined(BHO_NO_CXX11_NUMERIC_LIMITS) && !defined(BHO_NO_NUMERIC_LIMITS_LOWEST)
# define BHO_NO_NUMERIC_LIMITS_LOWEST
#endif
// ------------------ End of deprecated macros for 1.51 ---------------------------
//
// Helper macro for marking types and methods final
//
#if !defined(BHO_NO_CXX11_FINAL)
# define BHO_FINAL final
#else
# define BHO_FINAL
#endif
//
// Helper macros BHO_NOEXCEPT, BHO_NOEXCEPT_IF, BHO_NOEXCEPT_EXPR
// These aid the transition to C++11 while still supporting C++03 compilers
//
#ifdef BHO_NO_CXX11_NOEXCEPT
# define BHO_NOEXCEPT
# define BHO_NOEXCEPT_OR_NOTHROW throw()
# define BHO_NOEXCEPT_IF(Predicate)
# define BHO_NOEXCEPT_EXPR(Expression) false
#else
# define BHO_NOEXCEPT noexcept
# define BHO_NOEXCEPT_OR_NOTHROW noexcept
# define BHO_NOEXCEPT_IF(Predicate) noexcept((Predicate))
# define BHO_NOEXCEPT_EXPR(Expression) noexcept((Expression))
#endif
//
// Helper macro BHO_FALLTHROUGH
// Fallback definition of BHO_FALLTHROUGH macro used to mark intended
// fall-through between case labels in a switch statement. We use a definition
// that requires a semicolon after it to avoid at least one type of misuse even
// on unsupported compilers.
//
#ifndef BHO_FALLTHROUGH
# define BHO_FALLTHROUGH ((void)0)
#endif
//
// constexpr workarounds
//
#if defined(BHO_NO_CXX11_CONSTEXPR)
#define BHO_CONSTEXPR
#define BHO_CONSTEXPR_OR_CONST const
#else
#define BHO_CONSTEXPR constexpr
#define BHO_CONSTEXPR_OR_CONST constexpr
#endif
#if defined(BHO_NO_CXX14_CONSTEXPR)
#define BHO_CXX14_CONSTEXPR
#else
#define BHO_CXX14_CONSTEXPR constexpr
#endif
//
// C++17 inline variables
//
#if !defined(BHO_NO_CXX17_INLINE_VARIABLES)
#define BHO_INLINE_VARIABLE inline
#else
#define BHO_INLINE_VARIABLE
#endif
//
// C++17 if constexpr
//
#if !defined(BHO_NO_CXX17_IF_CONSTEXPR)
# define BHO_IF_CONSTEXPR if constexpr
#else
# define BHO_IF_CONSTEXPR if
#endif
#define BHO_INLINE_CONSTEXPR BHO_INLINE_VARIABLE BHO_CONSTEXPR_OR_CONST
//
// Unused variable/typedef workarounds:
//
#ifndef BHO_ATTRIBUTE_UNUSED
# define BHO_ATTRIBUTE_UNUSED
#endif
//
// [[nodiscard]]:
//
#if defined(__has_attribute) && defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x5130)
#if __has_attribute(nodiscard)
# define BHO_ATTRIBUTE_NODISCARD [[nodiscard]]
#endif
#if __has_attribute(no_unique_address)
# define BHO_ATTRIBUTE_NO_UNIQUE_ADDRESS [[no_unique_address]]
#endif
#elif defined(__has_cpp_attribute)
// clang-6 accepts [[nodiscard]] with -std=c++14, but warns about it -pedantic
#if __has_cpp_attribute(nodiscard) && !(defined(__clang__) && (__cplusplus < 201703L)) && !(defined(__GNUC__) && (__cplusplus < 201100))
# define BHO_ATTRIBUTE_NODISCARD [[nodiscard]]
#endif
#if __has_cpp_attribute(no_unique_address) && !(defined(__GNUC__) && (__cplusplus < 201100))
# define BHO_ATTRIBUTE_NO_UNIQUE_ADDRESS [[no_unique_address]]
#endif
#endif
#ifndef BHO_ATTRIBUTE_NODISCARD
# define BHO_ATTRIBUTE_NODISCARD
#endif
#ifndef BHO_ATTRIBUTE_NO_UNIQUE_ADDRESS
# define BHO_ATTRIBUTE_NO_UNIQUE_ADDRESS
#endif
#define BHO_STATIC_CONSTEXPR static BHO_CONSTEXPR_OR_CONST
//
// Set BHO_HAS_STATIC_ASSERT when BHO_NO_CXX11_STATIC_ASSERT is not defined
//
#if !defined(BHO_NO_CXX11_STATIC_ASSERT) && !defined(BHO_HAS_STATIC_ASSERT)
# define BHO_HAS_STATIC_ASSERT
#endif
//
// Set BHO_HAS_RVALUE_REFS when BHO_NO_CXX11_RVALUE_REFERENCES is not defined
//
#if !defined(BHO_NO_CXX11_RVALUE_REFERENCES) && !defined(BHO_HAS_RVALUE_REFS)
#define BHO_HAS_RVALUE_REFS
#endif
//
// Set BHO_HAS_VARIADIC_TMPL when BHO_NO_CXX11_VARIADIC_TEMPLATES is not defined
//
#if !defined(BHO_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BHO_HAS_VARIADIC_TMPL)
#define BHO_HAS_VARIADIC_TMPL
#endif
//
// Set BHO_NO_CXX11_FIXED_LENGTH_VARIADIC_TEMPLATE_EXPANSION_PACKS when
// BHO_NO_CXX11_VARIADIC_TEMPLATES is set:
//
#if defined(BHO_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BHO_NO_CXX11_FIXED_LENGTH_VARIADIC_TEMPLATE_EXPANSION_PACKS)
# define BHO_NO_CXX11_FIXED_LENGTH_VARIADIC_TEMPLATE_EXPANSION_PACKS
#endif
// This is a catch all case for obsolete compilers / std libs:
#if !defined(_YVALS) && !defined(_CPPLIB_VER) // msvc std lib already configured
#if (!defined(__has_include) || (__cplusplus < 201700))
# define BHO_NO_CXX17_HDR_OPTIONAL
# define BHO_NO_CXX17_HDR_STRING_VIEW
# define BHO_NO_CXX17_HDR_VARIANT
# define BHO_NO_CXX17_HDR_ANY
# define BHO_NO_CXX17_HDR_MEMORY_RESOURCE
# define BHO_NO_CXX17_HDR_CHARCONV
# define BHO_NO_CXX17_HDR_EXECUTION
# define BHO_NO_CXX17_HDR_FILESYSTEM
#else
#if !__has_include(<optional>)
# define BHO_NO_CXX17_HDR_OPTIONAL
#endif
#if !__has_include(<string_view>)
# define BHO_NO_CXX17_HDR_STRING_VIEW
#endif
#if !__has_include(<variant>)
# define BHO_NO_CXX17_HDR_VARIANT
#endif
#if !__has_include(<any>)
# define BHO_NO_CXX17_HDR_ANY
#endif
#if !__has_include(<memory_resource>)
# define BHO_NO_CXX17_HDR_MEMORY_RESOURCE
#endif
#if !__has_include(<charconv>)
# define BHO_NO_CXX17_HDR_CHARCONV
#endif
#if !__has_include(<execution>)
# define BHO_NO_CXX17_HDR_EXECUTION
#endif
#if !__has_include(<filesystem>)
# define BHO_NO_CXX17_HDR_FILESYSTEM
#endif
#endif
#endif
#if !defined(_YVALS) && !defined(_CPPLIB_VER) // msvc std lib already configured
#if (!defined(__has_include) || (__cplusplus < 201704))
# define BHO_NO_CXX20_HDR_BARRIER
# define BHO_NO_CXX20_HDR_FORMAT
# define BHO_NO_CXX20_HDR_SOURCE_LOCATION
# define BHO_NO_CXX20_HDR_BIT
# define BHO_NO_CXX20_HDR_LATCH
# define BHO_NO_CXX20_HDR_SPAN
# define BHO_NO_CXX20_HDR_COMPARE
# define BHO_NO_CXX20_HDR_NUMBERS
# define BHO_NO_CXX20_HDR_STOP_TOKEN
# define BHO_NO_CXX20_HDR_CONCEPTS
# define BHO_NO_CXX20_HDR_RANGES
# define BHO_NO_CXX20_HDR_SYNCSTREAM
# define BHO_NO_CXX20_HDR_COROUTINE
# define BHO_NO_CXX20_HDR_SEMAPHORE
#else
#if !__has_include(<barrier>)
# define BHO_NO_CXX20_HDR_BARRIER
#endif
#if !__has_include(<format>)
# define BHO_NO_CXX20_HDR_FORMAT
#endif
#if !__has_include(<source_Location>)
# define BHO_NO_CXX20_HDR_SOURCE_LOCATION
#endif
#if !__has_include(<bit>)
# define BHO_NO_CXX20_HDR_BIT
#endif
#if !__has_include(<latch>)
# define BHO_NO_CXX20_HDR_LATCH
#endif
#if !__has_include(<span>)
# define BHO_NO_CXX20_HDR_SPAN
#endif
#if !__has_include(<compare>)
# define BHO_NO_CXX20_HDR_COMPARE
#endif
#if !__has_include(<numbers>)
# define BHO_NO_CXX20_HDR_NUMBERS
#endif
#if !__has_include(<stop_token>)
# define BHO_NO_CXX20_HDR_STOP_TOKEN
#endif
#if !__has_include(<concepts>)
# define BHO_NO_CXX20_HDR_CONCEPTS
#endif
#if !__has_include(<ranges>)
# define BHO_NO_CXX20_HDR_RANGES
#endif
#if !__has_include(<syncstream>)
# define BHO_NO_CXX20_HDR_SYNCSTREAM
#endif
#if !__has_include(<coroutine>)
# define BHO_NO_CXX20_HDR_COROUTINE
#endif
#if !__has_include(<semaphore>)
# define BHO_NO_CXX20_HDR_SEMAPHORE
#endif
#endif
#endif
//
// Define composite agregate macros:
//
#include <asio2/bho/config/detail/cxx_composite.hpp>
//
// Define the std level that the compiler claims to support:
//
#ifndef BHO_CXX_VERSION
# define BHO_CXX_VERSION __cplusplus
#endif
//
// Define composite agregate macros:
//
#include <asio2/bho/config/detail/cxx_composite.hpp>
//
// Define the std level that the compiler claims to support:
//
#ifndef BHO_CXX_VERSION
# define BHO_CXX_VERSION __cplusplus
#endif
//
// Finish off with checks for macros that are depricated / no longer supported,
// if any of these are set then it's very likely that much of Boost will no
// longer work. So stop with a #error for now, but give the user a chance
// to continue at their own risk if they really want to:
//
#if defined(BHO_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(BHO_CONFIG_ALLOW_DEPRECATED)
# error "You are using a compiler which lacks features which are now a minimum requirement in order to use Boost, define BHO_CONFIG_ALLOW_DEPRECATED if you want to continue at your own risk!!!"
#endif
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_TCPS_SESSION_HPP__
#define __ASIO2_TCPS_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_session.hpp>
#include <asio2/tcp/impl/ssl_stream_cp.hpp>
#include <asio2/tcp/impl/ssl_context_cp.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class derived_t, class args_t = template_args_tcp_session>
class tcps_session_impl_t
: public tcp_session_impl_t<derived_t, args_t>
, public ssl_stream_cp <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
public:
using super = tcp_session_impl_t <derived_t, args_t>;
using self = tcps_session_impl_t<derived_t, args_t>;
using args_type = args_t;
using key_type = std::size_t;
using buffer_type = typename args_t::buffer_t;
using ssl_stream_comp = ssl_stream_cp<derived_t, args_t>;
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
explicit tcps_session_impl_t(
asio::ssl::context & ctx,
session_mgr_t<derived_t> & sessions,
listener_t & listener,
io_t & rwio,
std::size_t init_buf_size,
std::size_t max_buf_size
)
: super(sessions, listener, rwio, init_buf_size, max_buf_size)
, ssl_stream_comp(this->io_, ctx, asio::ssl::stream_base::server)
, ctx_(ctx)
{
}
/**
* @brief destructor
*/
~tcps_session_impl_t()
{
}
public:
/**
* @brief get this object hash key,used for session map
*/
inline key_type hash_key() const noexcept
{
return reinterpret_cast<key_type>(this);
}
/**
* @brief get the stream object refrence
*/
inline typename ssl_stream_comp::ssl_stream_type& stream() noexcept
{
return this->derived().ssl_stream();
}
protected:
template<typename C>
inline void _do_init(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
super::_do_init(this_ptr, ecs);
this->derived()._ssl_init(ecs, this->socket_, this->ctx_);
}
template<typename DeferEvent>
inline void _post_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_LOG_DEBUG("tcps_session::_post_shutdown: {} {}", ec.value(), ec.message());
this->derived()._ssl_stop(this_ptr, defer_event
{
[this, ec, this_ptr, e = chain.move_event()] (event_queue_guard<derived_t> g) mutable
{
super::_post_shutdown(ec, std::move(this_ptr), defer_event(std::move(e), std::move(g)));
}, chain.move_guard()
});
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
detail::ignore_unused(ec);
ASIO2_ASSERT(!ec);
ASIO2_ASSERT(this->derived().sessions().io().running_in_this_thread());
asio::dispatch(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
this->derived()._ssl_start(this_ptr, ecs, this->socket_, this->ctx_);
this->derived()._post_handshake(std::move(this_ptr), std::move(ecs), std::move(chain));
}));
}
inline void _fire_handshake(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_handshake must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
this->listener_.notify(event_type::handshake, this_ptr);
}
protected:
asio::ssl::context & ctx_;
};
}
namespace asio2
{
using tcps_session_args = detail::template_args_tcp_session;
template<class derived_t, class args_t>
using tcps_session_impl_t = detail::tcps_session_impl_t<derived_t, args_t>;
/**
* @brief ssl tcp session
*/
template<class derived_t>
class tcps_session_t : public detail::tcps_session_impl_t<derived_t, detail::template_args_tcp_session>
{
public:
using detail::tcps_session_impl_t<derived_t, detail::template_args_tcp_session>::tcps_session_impl_t;
};
/**
* @brief ssl tcp session
*/
class tcps_session : public tcps_session_t<tcps_session>
{
public:
using tcps_session_t<tcps_session>::tcps_session_t;
};
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct tcps_rate_session_args : public tcps_session_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
template<class derived_t>
class tcps_rate_session_t : public asio2::tcps_session_impl_t<derived_t, tcps_rate_session_args>
{
public:
using asio2::tcps_session_impl_t<derived_t, tcps_rate_session_args>::tcps_session_impl_t;
};
class tcps_rate_session : public asio2::tcps_rate_session_t<tcps_rate_session>
{
public:
using asio2::tcps_rate_session_t<tcps_rate_session>::tcps_rate_session_t;
};
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_TCPS_SESSION_HPP__
#endif
<file_sep>#ifndef BHO_MP11_MAP_HPP_INCLUDED
#define BHO_MP11_MAP_HPP_INCLUDED
// Copyright 2015-2017 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/mp11/detail/mp_map_find.hpp>
#include <asio2/bho/mp11/list.hpp>
#include <asio2/bho/mp11/integral.hpp>
#include <asio2/bho/mp11/utility.hpp>
#include <asio2/bho/mp11/algorithm.hpp>
#include <asio2/bho/mp11/function.hpp>
#include <asio2/bho/mp11/set.hpp>
#include <type_traits>
namespace bho
{
namespace mp11
{
// mp_map_contains<M, K>
template<class M, class K> using mp_map_contains = mp_not<std::is_same<mp_map_find<M, K>, void>>;
// mp_map_insert<M, T>
template<class M, class T> using mp_map_insert = mp_if< mp_map_contains<M, mp_first<T>>, M, mp_push_back<M, T> >;
// mp_map_replace<M, T>
namespace detail
{
template<class M, class T> struct mp_map_replace_impl;
template<template<class...> class M, class... U, class T> struct mp_map_replace_impl<M<U...>, T>
{
using K = mp_first<T>;
// mp_replace_if is inlined here using a struct _f because of msvc-14.0
template<class V> struct _f { using type = mp_if< std::is_same<mp_first<V>, K>, T, V >; };
using type = mp_if< mp_map_contains<M<U...>, K>, M<typename _f<U>::type...>, M<U..., T> >;
};
} // namespace detail
template<class M, class T> using mp_map_replace = typename detail::mp_map_replace_impl<M, T>::type;
// mp_map_update<M, T, F>
namespace detail
{
template<class M, class T, template<class...> class F> struct mp_map_update_impl
{
template<class U> using _f = std::is_same<mp_first<T>, mp_first<U>>;
// _f3<L<X, Y...>> -> L<X, F<X, Y...>>
template<class L> using _f3 = mp_assign<L, mp_list<mp_first<L>, mp_rename<L, F> > >;
using type = mp_if< mp_map_contains<M, mp_first<T>>, mp_transform_if<_f, _f3, M>, mp_push_back<M, T> >;
};
} // namespace detail
template<class M, class T, template<class...> class F> using mp_map_update = typename detail::mp_map_update_impl<M, T, F>::type;
template<class M, class T, class Q> using mp_map_update_q = mp_map_update<M, T, Q::template fn>;
// mp_map_erase<M, K>
namespace detail
{
template<class M, class K> struct mp_map_erase_impl
{
template<class T> using _f = std::is_same<mp_first<T>, K>;
using type = mp_remove_if<M, _f>;
};
} // namespace detail
template<class M, class K> using mp_map_erase = typename detail::mp_map_erase_impl<M, K>::type;
// mp_map_keys<M>
template<class M> using mp_map_keys = mp_transform<mp_first, M>;
// mp_is_map<M>
namespace detail
{
template<class L> struct mp_is_map_element: mp_false
{
};
template<template<class...> class L, class T1, class... T> struct mp_is_map_element<L<T1, T...>>: mp_true
{
};
template<class M> using mp_keys_are_set = mp_is_set<mp_map_keys<M>>;
template<class M> struct mp_is_map_impl
{
using type = mp_false;
};
template<template<class...> class M, class... T> struct mp_is_map_impl<M<T...>>
{
using type = mp_eval_if<mp_not<mp_all<mp_is_map_element<T>...>>, mp_false, mp_keys_are_set, M<T...>>;
};
} // namespace detail
template<class M> using mp_is_map = typename detail::mp_is_map_impl<M>::type;
} // namespace mp11
} // namespace bho
#endif // #ifndef BHO_MP11_MAP_HPP_INCLUDED
<file_sep>#ifndef ASIO2_ENABLE_SSL
#define ASIO2_ENABLE_SSL
#endif
#include <iostream>
#include <asio2/http/https_client.hpp>
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8443";
asio2::socks5::option<asio2::socks5::method::anonymous>
sock5_option{ "127.0.0.1",10808 };
// 1. download and save the file directly.
// The file is in this directory: /asio2/example/bin/x64/100mb.test.ssl
asio2::https_client::download(
"https://cachefly.cachefly.net/100mb.test",
"100mb.test.ssl");
// 2. you can save the file content by youself.
// I find that, we must specify the SSL version to tlsv13, otherwise it will fail.
std::fstream hugefile("CentOS-7-x86_64-DVD-2009.iso", std::ios::out | std::ios::binary | std::ios::trunc);
asio2::https_client::download(asio::ssl::context{ asio::ssl::context::tlsv13 },
"https://mirrors.tuna.tsinghua.edu.cn/centos/7.9.2009/isos/x86_64/CentOS-7-x86_64-DVD-2009.iso",
//[](auto& header) // http header callback. this param is optional. the body callback is required.
//{
// std::cout << header << std::endl;
//},
[&hugefile](std::string_view chunk) // http body callback.
{
hugefile.write(chunk.data(), chunk.size());
}
);
hugefile.close();
std::string_view url = "https://www.baidu.com/query?key=x!#$&'()*+,/:;=?@[ ]-_.~%^{}\"|<>`\\y";
asio::ssl::context ctx{ asio::ssl::context::sslv23 };
http::web_request req1;
asio2::https_client::execute(ctx, "www.baidu.com", "443", req1, std::chrono::seconds(5));
asio2::https_client::execute(ctx, "www.baidu.com", "443", req1);
asio2::https_client::execute("www.baidu.com", "443", req1, std::chrono::seconds(5));
asio2::https_client::execute("www.baidu.com", "443", req1);
http::web_request req2 = http::make_request(url);
asio2::https_client::execute(ctx, req2, std::chrono::seconds(5));
asio2::https_client::execute(ctx, req2);
asio2::https_client::execute(req2, std::chrono::seconds(5));
asio2::https_client::execute(req2);
asio2::https_client::execute(ctx, url, std::chrono::seconds(5));
asio2::https_client::execute(ctx, url);
asio2::https_client::execute(url, std::chrono::seconds(5));
asio2::https_client::execute(url, sock5_option);
auto reprss = asio2::https_client::execute("https://github.com/freefq/free", std::chrono::seconds(60), sock5_option);
std::fstream file;
file.open("freefq.html", std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);
file.write(reprss.body().data(), reprss.body().size());
file.close();
http::web_request req10;
req10.version(11);
req10.target("/");
req10.method(http::verb::post);
req10.set(http::field::accept, "*/*");
req10.set(http::field::accept_encoding, "gzip, deflate");
req10.set(http::field::accept_language, "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
req10.set(http::field::content_type, "application/x-www-form-urlencoded");
req10.set(http::field::user_agent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0");
req10.body() = "scope=all&id=gateway&secret=gateway";
req10.prepare_payload();
asio2::https_client::execute("www.baidu.com", "443", req10);
asio2::https_client client;
//client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_file(
"../../cert/ca.crt",
"../../cert/client.crt",
"../../cert/client.key",
"123456");
if (asio2::get_last_error())
std::cout << "load cert files failed: " << asio2::last_error_msg() << std::endl;
client.set_connect_timeout(std::chrono::seconds(10));
client.bind_recv([&](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req);
std::cout << "----------------------------------------" << std::endl;
std::cout << rep << std::endl;
}).bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n",
client.local_address().c_str(), client.local_port());
// send a request
client.async_send("GET / HTTP/1.1\r\n\r\n");
}).bind_disconnect([]()
{
printf("disconnect : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_handshake([&]()
{
printf("handshake : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
});
client.start(host, port);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_PLAT_MINGW32_H
#define BHO_PREDEF_PLAT_MINGW32_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_PLAT_MINGW32`
http://www.mingw.org/[MinGW] platform.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__MINGW32__+` | {predef_detection}
| `+__MINGW32_VERSION_MAJOR+`, `+__MINGW32_VERSION_MINOR+` | V.R.0
|===
*/ // end::reference[]
#define BHO_PLAT_MINGW32 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__MINGW32__)
# include <_mingw.h>
# if !defined(BHO_PLAT_MINGW32_DETECTION) && (defined(__MINGW32_VERSION_MAJOR) && defined(__MINGW32_VERSION_MINOR))
# define BHO_PLAT_MINGW32_DETECTION \
BHO_VERSION_NUMBER(__MINGW32_VERSION_MAJOR,__MINGW32_VERSION_MINOR,0)
# endif
# if !defined(BHO_PLAT_MINGW32_DETECTION)
# define BHO_PLAT_MINGW32_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_PLAT_MINGW32_DETECTION
# define BHO_PLAT_MINGW32_AVAILABLE
# if defined(BHO_PREDEF_DETAIL_PLAT_DETECTED)
# define BHO_PLAT_MINGW32_EMULATED BHO_PLAT_MINGW32_DETECTION
# else
# undef BHO_PLAT_MINGW32
# define BHO_PLAT_MINGW32 BHO_PLAT_MINGW32_DETECTION
# endif
# include <asio2/bho/predef/detail/platform_detected.h>
#endif
#define BHO_PLAT_MINGW32_NAME "MinGW"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_MINGW32,BHO_PLAT_MINGW32_NAME)
#ifdef BHO_PLAT_MINGW32_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_MINGW32_EMULATED,BHO_PLAT_MINGW32_NAME)
#endif
<file_sep>#ifndef BHO_CORE_IS_SAME_HPP_INCLUDED
#define BHO_CORE_IS_SAME_HPP_INCLUDED
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
// is_same<T1,T2>::value is true when T1 == T2
//
// Copyright 2014 <NAME>
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <asio2/bho/config.hpp>
namespace bho
{
namespace core
{
template< class T1, class T2 > struct is_same
{
BHO_STATIC_CONSTANT( bool, value = false );
};
template< class T > struct is_same< T, T >
{
BHO_STATIC_CONSTANT( bool, value = true );
};
} // namespace core
} // namespace bho
#endif // #ifndef BHO_CORE_IS_SAME_HPP_INCLUDED
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_MAKE_HPP__
#define __ASIO2_HTTP_MAKE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/http/request.hpp>
#include <asio2/http/response.hpp>
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::http
#else
namespace boost::beast::http
#endif
{
/**
* @brief make A typical HTTP request struct from the uri
* if the string is a url, it must start with http or https,
* eg : the url must be "https://www.github.com", the url can't be "www.github.com"
*/
template<class String>
http::web_request make_request(String&& uri)
{
http::web_request req;
asio2::clear_last_error();
std::string url = asio2::detail::to_string(std::forward<String>(uri));
// if uri is empty, break
if (url.empty())
{
asio2::set_last_error(::asio::error::invalid_argument);
return req;
}
bool has_crlf = (url.find("\r\n") != std::string::npos);
std::string buf = (has_crlf ? url : "");
req.url() = http::url{ std::move(url) };
// If a \r\n string is found, it is not a URL
// If get_last_error is not zero, it means that the uri is not a URL.
if (has_crlf && asio2::get_last_error())
{
http::request_parser<http::string_body> parser;
parser.eager(true);
parser.put(::asio::buffer(buf), asio2::get_last_error());
req = parser.get();
}
// It is a URL
else
{
if (asio2::get_last_error())
return req;
/* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment> */
std::string_view host = req.url().host();
std::string_view port = req.url().port();
std::string_view target = req.url().target();
// Set up an HTTP GET request message
req.method(http::verb::get);
req.version(11);
req.target(beast::string_view(target.data(), target.size()));
//req.set(http::field::server, BEAST_VERSION_STRING);
if (host.empty())
{
asio2::set_last_error(::asio::error::invalid_argument);
return req;
}
if (!port.empty() && port != "443" && port != "80")
req.set(http::field::host, std::string(host) + ":" + std::string(port));
else
req.set(http::field::host, host);
}
return req;
}
/**
* @brief make A typical HTTP request struct from the uri
*/
template<typename String, typename StrOrInt>
inline http::web_request make_request(String&& host, StrOrInt&& port,
std::string_view target, http::verb method = http::verb::get, unsigned version = 11)
{
http::web_request req;
asio2::clear_last_error();
std::string h = asio2::detail::to_string(std::forward<String>(host));
asio2::trim_both(h);
std::string p = asio2::detail::to_string(std::forward<StrOrInt>(port));
asio2::trim_both(p);
std::string_view schema{ h.data(), (std::min<std::string_view::size_type>)(4, h.size()) };
std::string url;
if (!asio2::iequals(schema, "http"))
{
if /**/ (p == "80")
url += "http://";
else if (p == "443")
url += "https://";
else
url += "http://";
}
url += h;
if (!p.empty() && p != "443" && p != "80")
{
url += ":";
url += p;
}
url += target;
req.url() = http::url{ std::move(url) };
// if url is invalid, break
if (asio2::get_last_error())
return req;
// Set up an HTTP GET request message
req.method(method);
req.version(version);
if (target.empty())
{
req.target(beast::string_view{ "/" });
}
else
{
if (http::has_unencode_char(target, 1))
{
std::string encoded = http::url_encode(target);
req.target(beast::string_view(encoded.data(), encoded.size()));
}
else
{
req.target(beast::string_view(target.data(), target.size()));
}
}
if (!p.empty() && p != "443" && p != "80")
{
req.set(http::field::host, h + ":" + p);
}
else
{
req.set(http::field::host, std::move(h));
}
//req.set(http::field::server, BEAST_VERSION_STRING);
return req;
}
template<class Body = http::string_body, class Fields = http::fields>
inline http::response<Body, Fields> make_response(std::string_view uri)
{
asio2::clear_last_error();
http::response_parser<Body> parser;
parser.eager(true);
parser.put(::asio::buffer(uri), asio2::get_last_error());
http::response<Body, Fields> rep = parser.get();
return rep;
}
template<class Body = http::string_body, class Fields = http::fields>
inline typename std::enable_if_t<std::is_same_v<Body, http::string_body>, http::response<Body, Fields>>
make_response(http::status code, std::string_view body, unsigned version = 11)
{
http::response<Body, Fields> rep;
rep.version(version);
//rep.set(http::field::server, BEAST_VERSION_STRING);
rep.result(code);
rep.body() = body;
http::try_prepare_payload(rep);
return rep;
}
template<class Body = http::string_body, class Fields = http::fields>
inline typename std::enable_if_t<std::is_same_v<Body, http::string_body>, http::response<Body, Fields>>
make_response(unsigned code, std::string_view body, unsigned version = 11)
{
return make_response(http::int_to_status(code), body, version);
}
}
#endif // !__ASIO2_HTTP_MAKE_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_STDCPP3_H
#define BHO_PREDEF_LIBRARY_STD_STDCPP3_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_GNU`
https://gcc.gnu.org/onlinedocs/libstdc%2b%2b/[GNU libstdc++] Standard {CPP} library.
Version number available as year (from 1970), month, and day.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__GLIBCXX__+` | {predef_detection}
| `+__GLIBCPP__+` | {predef_detection}
| `+__GLIBCXX__+` | V.R.P
| `+__GLIBCPP__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_LIB_STD_GNU BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__GLIBCPP__) || defined(__GLIBCXX__)
# undef BHO_LIB_STD_GNU
# if defined(__GLIBCXX__)
# define BHO_LIB_STD_GNU BHO_PREDEF_MAKE_YYYYMMDD(__GLIBCXX__)
# else
# define BHO_LIB_STD_GNU BHO_PREDEF_MAKE_YYYYMMDD(__GLIBCPP__)
# endif
#endif
#if BHO_LIB_STD_GNU
# define BHO_LIB_STD_GNU_AVAILABLE
#endif
#define BHO_LIB_STD_GNU_NAME "GNU"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_GNU,BHO_LIB_STD_GNU_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MATCH_CONDITION_HPP__
#define __ASIO2_MATCH_CONDITION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <string>
#include <string_view>
#include <utility>
#include <asio2/external/asio.hpp>
#include <asio2/base/detail/util.hpp>
namespace asio2::detail
{
namespace
{
using iterator = asio::buffers_iterator<asio::streambuf::const_buffers_type>;
using diff_type = typename iterator::difference_type;
std::pair<iterator, bool> dgram_match_role(iterator begin, iterator end) noexcept
{
for (iterator p = begin; p < end;)
{
// If 0~253, current byte are the payload length.
if (std::uint8_t(*p) < std::uint8_t(254))
{
std::uint8_t payload_size = static_cast<std::uint8_t>(*p);
++p;
if (end - p < static_cast<diff_type>(payload_size))
break;
return std::pair(p + static_cast<diff_type>(payload_size), true);
}
// If 254, the following 2 bytes interpreted as a 16-bit unsigned integer
// are the payload length.
if (std::uint8_t(*p) == std::uint8_t(254))
{
++p;
if (end - p < 2)
break;
std::uint16_t payload_size = *(reinterpret_cast<const std::uint16_t*>(p.operator->()));
// use little endian
if (!is_little_endian())
{
swap_bytes<sizeof(std::uint16_t)>(reinterpret_cast<std::uint8_t*>(
std::addressof(payload_size)));
}
// illegal data
if (payload_size < static_cast<std::uint16_t>(254))
return std::pair(begin, true);
p += 2;
if (end - p < static_cast<diff_type>(payload_size))
break;
return std::pair(p + static_cast<diff_type>(payload_size), true);
}
// If 255, the following 8 bytes interpreted as a 64-bit unsigned integer
// (the most significant bit MUST be 0) are the payload length.
if (std::uint8_t(*p) == 255)
{
++p;
if (end - p < 8)
break;
// the most significant bit MUST be 0
std::int64_t payload_size = *(reinterpret_cast<const std::int64_t*>(p.operator->()));
// use little endian
if (!is_little_endian())
{
swap_bytes<sizeof(std::int64_t)>(reinterpret_cast<std::uint8_t*>(
std::addressof(payload_size)));
}
// illegal data
if (payload_size <= static_cast<std::int64_t>((std::numeric_limits<std::uint16_t>::max)()))
return std::pair(begin, true);
p += 8;
if (end - p < static_cast<diff_type>(payload_size))
break;
return std::pair(p + static_cast<diff_type>(payload_size), true);
}
ASIO2_ASSERT(false);
}
return std::pair(begin, false);
}
}
}
namespace asio2::detail
{
//struct use_sync_t {};
struct use_kcp_t {};
struct use_dgram_t {};
struct hook_buffer_t {};
}
namespace asio2::detail
{
/**
* use condition_t to avoid having the same name as make_error_condition(condition c)
*/
template<class T>
class condition_t
{
public:
using type = T;
// must use explicit, Otherwise, there will be an error when there are the following
// statements: condition_t<char> c1; auto c2 = c1;
template<class C, std::enable_if_t<!std::is_base_of_v<condition_t, detail::remove_cvref_t<C>>, int> = 0>
explicit condition_t(C c) noexcept : c_(std::move(c)) {}
~condition_t() noexcept = default;
condition_t(condition_t&&) noexcept = default;
condition_t(condition_t const&) noexcept = delete;
condition_t& operator=(condition_t&&) noexcept = default;
condition_t& operator=(condition_t const&) noexcept = delete;
inline condition_t clone() noexcept { return condition_t{ this->c_ }; }
inline T& operator()() noexcept { return this->c_; }
inline T& lowest () noexcept { return this->c_; }
protected:
T c_;
};
// C++17 class template argument deduction guides
template<class T>
condition_t(T)->condition_t<std::remove_reference_t<T>>;
template<>
class condition_t<void>
{
public:
using type = void;
condition_t() noexcept = default;
~condition_t() noexcept = default;
condition_t(condition_t&&) noexcept = default;
condition_t(condition_t const&) noexcept = delete;
condition_t& operator=(condition_t&&) noexcept = default;
condition_t& operator=(condition_t const&) noexcept = delete;
inline condition_t clone() noexcept { return condition_t{}; }
inline void operator()() noexcept {}
inline void lowest () noexcept {}
};
template<>
class condition_t<use_dgram_t>
{
public:
using type = use_dgram_t;
explicit condition_t(use_dgram_t) noexcept {}
~condition_t() noexcept = default;
condition_t(condition_t&&) noexcept = default;
condition_t(condition_t const&) noexcept = delete;
condition_t& operator=(condition_t&&) noexcept = default;
condition_t& operator=(condition_t const&) noexcept = delete;
inline condition_t clone() noexcept { return condition_t{ use_dgram_t{} }; }
inline auto& operator()() noexcept { return dgram_match_role; }
inline auto& lowest () noexcept { return dgram_match_role; }
};
template<>
class condition_t<use_kcp_t>
{
public:
using type = use_kcp_t;
explicit condition_t(use_kcp_t) noexcept {}
~condition_t() noexcept = default;
condition_t(condition_t&&) noexcept = default;
condition_t(condition_t const&) noexcept = delete;
condition_t& operator=(condition_t&&) noexcept = default;
condition_t& operator=(condition_t const&) noexcept = delete;
inline condition_t clone() noexcept { return condition_t{ use_kcp_t{} }; }
inline asio::detail::transfer_at_least_t operator()() noexcept { return asio::transfer_at_least(1); }
inline asio::detail::transfer_at_least_t lowest () noexcept { return asio::transfer_at_least(1); }
};
template<>
class condition_t<hook_buffer_t>
{
public:
using type = hook_buffer_t;
explicit condition_t(hook_buffer_t) noexcept {}
~condition_t() noexcept = default;
condition_t(condition_t&&) noexcept = default;
condition_t(condition_t const&) noexcept = delete;
condition_t& operator=(condition_t&&) noexcept = default;
condition_t& operator=(condition_t const&) noexcept = delete;
inline condition_t clone() noexcept { return condition_t{ hook_buffer_t{} }; }
inline asio::detail::transfer_at_least_t operator()() noexcept { return asio::transfer_at_least(1); }
inline asio::detail::transfer_at_least_t lowest () noexcept { return asio::transfer_at_least(1); }
};
}
namespace asio2
{
//constexpr static detail::use_sync_t use_sync;
// https://github.com/skywind3000/kcp
constexpr static detail::use_kcp_t use_kcp;
constexpr static detail::use_dgram_t use_dgram;
constexpr static detail::hook_buffer_t hook_buffer;
}
#endif // !__ASIO2_MATCH_CONDITION_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_AOP_PUBLISH_HPP__
#define __ASIO2_MQTT_AOP_PUBLISH_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class caller_t, class args_t>
class mqtt_aop_publish
{
friend caller_t;
protected:
template<class Message>
inline void _do_check_publish_topic_alias(
error_code& ec, caller_t* caller, Message& msg, std::string& topic_name)
{
// << topic_alias >>
// A Topic Alias of 0 is not permitted. A sender MUST NOT send a PUBLISH packet containing a Topic Alias
// which has the value 0 [MQTT-3.3.2-8].
// << topic_alias_maximum >>
// This value indicates the highest value that the Client will accept as a Topic Alias sent by the Server.
// The Client uses this value to limit the number of Topic Aliases that it is willing to hold on this Connection.
// The Server MUST NOT send a Topic Alias in a PUBLISH packet to the Client greater than Topic Alias Maximum
// [MQTT-3.1.2-26]. A value of 0 indicates that the Client does not accept any Topic Aliases on this connection.
// If Topic Alias Maximum is absent or zero, the Server MUST NOT send any Topic Aliases to the Client [MQTT-3.1.2-27].
mqtt::v5::topic_alias* topic_alias = msg.properties().template get_if<mqtt::v5::topic_alias>();
if (topic_alias)
{
auto alias_value = topic_alias->value();
if (alias_value == 0 || alias_value > caller->topic_alias_maximum())
{
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
return;
}
if (!topic_name.empty())
{
caller->push_topic_alias(alias_value, topic_name);
}
else
{
if (!caller->find_topic_alias(alias_value, topic_name))
{
ec = mqtt::make_error_code(mqtt::error::topic_alias_invalid);
return;
}
}
}
}
template<class Message>
inline void _check_publish_topic_alias(
error_code& ec, caller_t* caller, Message& msg, std::string& topic_name)
{
using message_type = typename detail::remove_cvref_t<Message>;
// << topic_alias >>
// A Topic Alias of 0 is not permitted. A sender MUST NOT send a PUBLISH packet containing a Topic Alias
// which has the value 0 [MQTT-3.3.2-8].
// << topic_alias_maximum >>
// This value indicates the highest value that the Client will accept as a Topic Alias sent by the Server.
// The Client uses this value to limit the number of Topic Aliases that it is willing to hold on this Connection.
// The Server MUST NOT send a Topic Alias in a PUBLISH packet to the Client greater than Topic Alias Maximum
// [MQTT-3.1.2-26]. A value of 0 indicates that the Client does not accept any Topic Aliases on this connection.
// If Topic Alias Maximum is absent or zero, the Server MUST NOT send any Topic Aliases to the Client [MQTT-3.1.2-27].
if constexpr (std::is_same_v<message_type, mqtt::v5::publish>)
{
_do_check_publish_topic_alias(ec, caller, msg, topic_name);
}
else
{
detail::ignore_unused(ec, caller, msg, topic_name);
}
}
// server or client
template<class Message, class Response>
inline void _before_publish_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
// A PUBACK, PUBREC , PUBREL, or PUBCOMP packet MUST contain the same Packet Identifier
// as the PUBLISH packet that was originally sent [MQTT-2.2.1-5].
if (msg.has_packet_id())
{
rep.packet_id(msg.packet_id());
}
mqtt::qos_type qos = msg.qos();
// the qos 0 publish messgae don't need response
if (qos == mqtt::qos_type::at_most_once)
rep.set_send_flag(false);
if (!mqtt::is_valid_qos(qos))
{
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
return;
}
if (detail::to_underlying(qos) > caller->maximum_qos())
{
ec = mqtt::make_error_code(mqtt::error::qos_not_supported);
return;
}
if (msg.retain() && caller->retain_available() == false)
{
ec = mqtt::make_error_code(mqtt::error::retain_not_supported);
return;
}
// The Packet Identifier field is only present in PUBLISH Packets where the QoS level is 1 or 2.
if (detail::to_underlying(qos) > 0 && msg.has_packet_id() == false)
{
ec = mqtt::make_error_code(mqtt::error::malformed_packet); // error code : broker.hivemq.com
return;
}
if (detail::to_underlying(qos) == 0 && msg.has_packet_id() == true)
{
ec = mqtt::make_error_code(mqtt::error::malformed_packet); // error code : broker.hivemq.com
return;
}
std::string topic_name{ msg.topic_name() };
// must first determine whether topic_name is empty, beacuse v5::publish's topic_name maybe empty.
if (!topic_name.empty())
{
if (mqtt::is_topic_name_valid(topic_name) == false)
{
ec = mqtt::make_error_code(mqtt::error::topic_name_invalid);
return;
}
}
if (_check_publish_topic_alias(ec, caller, msg, topic_name); ec)
return;
// All Topic Names and Topic Filters MUST be at least one character long [MQTT-4.7.3-1]
if (topic_name.empty())
{
ec = mqtt::make_error_code(mqtt::error::topic_name_invalid);
return;
}
//// Potentially allow write access for bridge status, otherwise explicitly deny.
//// rc = mosquitto_topic_matches_sub("$SYS/broker/connection/+/state", topic, std::addressof(match));
//if (topic_name.compare(0, 4, "$SYS") == 0)
//{
// ec = mqtt::make_error_code(mqtt::error::topic_name_invalid);
// return;
//}
// Only allow sub/unsub to shared subscriptions
if (topic_name.compare(0, 6, "$share") == 0)
{
ec = mqtt::make_error_code(mqtt::error::topic_name_invalid);
return;
}
constexpr bool is_pubrec =
std::is_same_v<response_type, mqtt::v3::pubrec> ||
std::is_same_v<response_type, mqtt::v4::pubrec> ||
std::is_same_v<response_type, mqtt::v5::pubrec>;
// the client or session sent publish with qos 2 but don't recvd pubrec, and it sent publish
// a later again, so we need sent pubrec directly and return directly
if (msg.qos() == mqtt::qos_type::exactly_once && caller->exactly_once_processing(msg.packet_id()))
{
ASIO2_ASSERT(msg.has_packet_id());
ASIO2_ASSERT(is_pubrec);
// return, then the pubrec will be sent directly
return;
}
if constexpr (is_pubrec)
{
ASIO2_ASSERT(msg.has_packet_id());
ASIO2_ASSERT(msg.qos() == mqtt::qos_type::exactly_once);
caller->exactly_once_start(msg.packet_id());
}
else
{
std::ignore = true;
}
_multicast_publish(caller_ptr, caller, msg, std::move(topic_name));
}
template<class Message, bool IsClient = args_t::is_client>
inline std::enable_if_t<!IsClient, void>
_multicast_publish(
std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message&& msg, std::string topic_name)
{
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
// use post and push_event to ensure the publish message is sent to clients must
// after mqtt response is sent already.
asio::post(caller->io().context(), make_allocator(caller->wallocator(),
[this, caller, caller_ptr, msg = std::move(msg), topic_name = std::move(topic_name)]
() mutable
{
caller->push_event(
[this, caller, caller_ptr = std::move(caller_ptr), msg = std::move(msg),
topic_name = std::move(topic_name)]
(event_queue_guard<caller_t> g) mutable
{
detail::ignore_unused(g);
this->_do_multicast_publish(caller_ptr, caller, std::move(msg), std::move(topic_name));
});
}));
}
template<class Message, bool IsClient = args_t::is_client>
inline std::enable_if_t<IsClient, void>
_multicast_publish(
std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message&& msg, std::string topic_name)
{
detail::ignore_unused(caller_ptr, caller, msg, topic_name);
}
template<class Message>
inline void _do_multicast_publish(
std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message&& msg, std::string topic_name)
{
detail::ignore_unused(caller_ptr, caller, msg);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
// share_name topic_filter
std::set<std::tuple<std::string, std::string>> sent;
if (topic_name.empty())
topic_name = msg.topic_name();
ASIO2_ASSERT(!topic_name.empty());
caller->subs_map().match(topic_name,
[this, caller, &msg, &sent](std::string_view key, auto& node) mutable
{
detail::ignore_unused(this, key);
mqtt::subscription& sub = node.sub;
std::string_view share_name = sub.share_name();
std::string_view topic_filter = sub.topic_filter();
if (share_name.empty())
{
// Non shared subscriptions
auto session_ptr = node.caller.lock();
if (!session_ptr)
return;
// If NL (no local) subscription option is set and
// publisher is the same as subscriber, then skip it.
if (sub.no_local() && session_ptr->hash_key() == caller->hash_key())
return;
// send message
_send_publish_to_subscriber(std::move(session_ptr), node.sub, node.props, msg);
}
else
{
// Shared subscriptions
bool inserted;
std::tie(std::ignore, inserted) = sent.emplace(share_name, topic_filter);
if (inserted)
{
auto session_ptr = caller->shared_targets().get_target(share_name, topic_filter);
if (session_ptr)
{
_send_publish_to_subscriber(std::move(session_ptr), node.sub, node.props, msg);
}
}
}
});
if (msg.retain())
{
_do_retain_publish(caller_ptr, caller, msg, topic_name);
}
}
template<class Message>
inline void _do_retain_publish(
std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, Message&& msg, std::string topic_name)
{
detail::ignore_unused(caller_ptr, caller, msg);
using message_type = typename detail::remove_cvref_t<Message>;
/*
* If the message is marked as being retained, then we
* keep it in case a new subscription is added that matches
* this topic.
*
* @note: The MQTT standard 3.3.1.3 RETAIN makes it clear that
* retained messages are global based on the topic, and
* are not scoped by the client id. So any client may
* publish a retained message on any topic, and the most
* recently published retained message on a particular
* topic is the message that is stored on the server.
*
* @note: The standard doesn't make it clear that publishing
* a message with zero length, but the retain flag not
* set, does not result in any existing retained message
* being removed. However, internet searching indicates
* that most brokers have opted to keep retained messages
* when receiving contents of zero bytes, unless the so
* received message has the retain flag set, in which case
* the retained message is removed.
*/
if (msg.payload().empty())
{
caller->retained_messages().erase(topic_name);
}
else
{
std::shared_ptr<asio::steady_timer> expiry_timer;
if constexpr (std::is_same_v<message_type, mqtt::v5::publish>)
{
mqtt::v5::message_expiry_interval* mei =
msg.properties().template get_if<mqtt::v5::message_expiry_interval>();
if (mei)
{
expiry_timer = std::make_shared<asio::steady_timer>(
caller->io().context(), std::chrono::seconds(mei->value()));
expiry_timer->async_wait(
[caller, topic_name, wp = std::weak_ptr<asio::steady_timer>(expiry_timer)]
(error_code const& ec) mutable
{
if (auto sp = wp.lock())
{
if (!ec)
{
caller->retained_messages().erase(topic_name);
}
}
});
}
}
else
{
std::ignore = true;
}
caller->retained_messages().insert_or_assign(topic_name,
mqtt::rmnode{ msg, std::move(expiry_timer) });
}
}
template<class session_t, class Message>
inline void _send_publish_to_subscriber(
std::shared_ptr<session_t> session, mqtt::subscription& sub, mqtt::v5::properties_set& props,
Message& msg)
{
if (!session)
return;
mqtt::version ver = session->version();
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901026
// The Client and Server assign Packet Identifiers independently of each other.
if /**/ (ver == mqtt::version::v3)
{
_prepare_send_publish(std::move(session), sub, props, msg, mqtt::v3::publish{});
}
else if (ver == mqtt::version::v4)
{
_prepare_send_publish(std::move(session), sub, props, msg, mqtt::v4::publish{});
}
else if (ver == mqtt::version::v5)
{
_prepare_send_publish(std::move(session), sub, props, msg, mqtt::v5::publish{});
}
}
template<class session_t, class Message, class Response>
inline void _prepare_send_publish(
std::shared_ptr<session_t> session, mqtt::subscription& sub, mqtt::v5::properties_set& props,
Message& msg, Response&& rep)
{
using message_type = typename detail::remove_cvref_t<Message>;
using response_type = typename detail::remove_cvref_t<Response>;
// dup
rep.dup(msg.dup());
// qos
rep.qos((std::min)(msg.qos(), sub.qos()));
// retaion
// Bit 3 of the Subscription Options represents the Retain As Published option.
// Retained messages sent when the subscription is established have the RETAIN flag set to 1.
// If 1, Application Messages forwarded using this subscription keep the RETAIN
// flag they were published with.
if (sub.rap())
{
rep.retain(msg.retain());
}
// If 0, Application Messages forwarded using this subscription have the RETAIN
// flag set to 0.
else
{
rep.retain(false);
}
// topic, payload
rep.topic_name(msg.topic_name());
rep.payload(msg.payload());
// properties
if constexpr (std::is_same_v<response_type, mqtt::v5::publish>)
{
if constexpr (std::is_same_v<message_type, mqtt::v5::publish>)
{
rep.properties() = msg.properties();
}
else
{
std::ignore = true;
}
props.for_each([&rep](auto& prop) mutable
{
rep.properties().erase(prop);
rep.properties().add(prop);
});
}
else
{
std::ignore = true;
}
// prepare send
if (session->is_started())
{
if (session->offline_messages_.empty())
{
auto pub_qos = rep.qos();
if (pub_qos == mqtt::qos_type::at_least_once || pub_qos == mqtt::qos_type::exactly_once)
{
if (auto pid = session->idmgr_.get())
{
// TODO: Probably this should be switched to async_publish?
// Given the async_client / sync_client seperation
// and the way they have different function names,
// it wouldn't be possible for broker.hpp to be
// used with some hypothetical "async_server" in the future.
rep.packet_id(pid);
_do_send_publish(session, std::forward<Response>(rep));
}
else
{
// no packet id available
ASIO2_ASSERT(false);
// offline_messages_ is not empty or packet_id_exhausted
session->offline_messages_.push_back(session->io().context(),
std::forward<Response>(rep));
}
}
else
{
// A PUBLISH Packet MUST NOT contain a Packet Identifier if its QoS value is set to 0
ASIO2_ASSERT(rep.has_packet_id() == false);
_do_send_publish(session, std::forward<Response>(rep));
}
}
else
{
// send all offline messages first
_send_all_offline_message(session);
_do_send_publish(session, std::forward<Response>(rep));
}
}
else
{
session->offline_messages_.push_back(session->io().context(), std::forward<Response>(rep));
}
}
template<class session_t, class Response>
inline void _do_send_publish(std::shared_ptr<session_t> session, Response&& rep)
{
session->push_event([session, id = session->life_id(), rep = std::forward<Response>(rep)]
(event_queue_guard<caller_t> g) mutable
{
if (id != session->life_id())
{
set_last_error(asio::error::operation_aborted);
return;
}
session->_do_send(rep, [session, &rep, g = std::move(g)]
(const error_code& ec, std::size_t) mutable
{
// send failed, add it to offline messages
if (ec)
{
session->offline_messages_.push_back(session->io().context(), std::move(rep));
}
});
});
}
template<class session_t>
inline void _send_all_offline_message(std::shared_ptr<session_t> session)
{
session->offline_messages_.for_each([this, session](mqtt::omnode& node) mutable
{
std::visit([this, session](auto&& pub) mutable
{
this->_do_send_publish(session, std::move(pub));
}, node.message.base());
});
session->offline_messages_.clear();
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::publish& msg, mqtt::v3::puback& rep)
{
if (_before_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::publish& msg, mqtt::v4::puback& rep)
{
if (_before_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::publish& msg, mqtt::v5::puback& rep)
{
if (_before_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::publish& msg, mqtt::v3::pubrec& rep)
{
if (_before_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::publish& msg, mqtt::v4::pubrec& rep)
{
if (_before_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::publish& msg, mqtt::v5::pubrec& rep)
{
if (_before_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
template<class Message, class Response, bool IsClient = args_t::is_client>
inline std::enable_if_t<!IsClient, void>
_do_publish_router(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
template<class Message, class Response, bool IsClient = args_t::is_client>
inline std::enable_if_t<IsClient, void>
_do_publish_router(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
std::string_view topic_name = msg.topic_name();
// client don't need lock
caller->subs_map().match(topic_name, [this, caller, &om](std::string_view key, auto& node) mutable
{
detail::ignore_unused(this, caller, key);
mqtt::subscription& sub = node.sub;
[[maybe_unused]] std::string_view share_name = sub.share_name();
[[maybe_unused]] std::string_view topic_filter = sub.topic_filter();
if (share_name.empty())
{
if (node.callback)
node.callback(om);
}
else
{
}
});
}
// server or client
template<class Message, class Response>
inline void _after_publish_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
[[maybe_unused]] std::string topic_name{ msg.topic_name() };
// << topic_alias >>
// A Topic Alias of 0 is not permitted. A sender MUST NOT send a PUBLISH packet containing a Topic Alias
// which has the value 0 [MQTT-3.3.2-8].
// << topic_alias_maximum >>
// This value indicates the highest value that the Client will accept as a Topic Alias sent by the Server.
// The Client uses this value to limit the number of Topic Aliases that it is willing to hold on this Connection.
// The Server MUST NOT send a Topic Alias in a PUBLISH packet to the Client greater than Topic Alias Maximum
// [MQTT-3.1.2-26]. A value of 0 indicates that the Client does not accept any Topic Aliases on this connection.
// If Topic Alias Maximum is absent or zero, the Server MUST NOT send any Topic Aliases to the Client [MQTT-3.1.2-27].
if constexpr (std::is_same_v<message_type, mqtt::v5::publish>)
{
mqtt::v5::topic_alias* topic_alias = msg.properties().template get_if<mqtt::v5::topic_alias>();
if (topic_alias)
{
caller->find_topic_alias(topic_alias->value(), topic_name);
}
}
else
{
std::ignore = true;
}
_do_publish_router(ec, caller_ptr, caller, om, msg, rep);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::publish& msg, mqtt::v3::puback& rep)
{
if (_after_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::publish& msg, mqtt::v4::puback& rep)
{
if (_after_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::publish& msg, mqtt::v5::puback& rep)
{
if (_after_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::publish& msg, mqtt::v3::pubrec& rep)
{
if (_after_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::publish& msg, mqtt::v4::pubrec& rep)
{
if (_after_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::publish& msg, mqtt::v5::pubrec& rep)
{
if (_after_publish_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
};
}
#endif // !__ASIO2_MQTT_AOP_PUBLISH_HPP__
<file_sep>/*
Copyright <NAME> 2015
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_HARDWARE_SIMD_ARM_VERSIONS_H
#define BHO_PREDEF_HARDWARE_SIMD_ARM_VERSIONS_H
#include <asio2/bho/predef/version_number.h>
/* tag::reference[]
= `BHO_HW_SIMD_ARM_*_VERSION`
Those defines represent ARM SIMD extensions versions.
NOTE: You *MUST* compare them with the predef `BHO_HW_SIMD_ARM`.
*/ // end::reference[]
// ---------------------------------
/* tag::reference[]
= `BHO_HW_SIMD_ARM_NEON_VERSION`
The https://en.wikipedia.org/wiki/ARM_architecture#Advanced_SIMD_.28NEON.29[NEON]
ARM extension version number.
Version number is: *1.0.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_ARM_NEON_VERSION BHO_VERSION_NUMBER(1, 0, 0)
/* tag::reference[]
*/ // end::reference[]
#endif
<file_sep>/*
Copyright <NAME> 2018
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LANGUAGE_CUDA_H
#define BHO_PREDEF_LANGUAGE_CUDA_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LANG_CUDA`
https://en.wikipedia.org/wiki/CUDA[CUDA C/{CPP}] language.
If available, the version is detected as VV.RR.P.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__CUDACC__+` | {predef_detection}
| `+__CUDA__+` | {predef_detection}
| `CUDA_VERSION` | VV.RR.P
|===
*/ // end::reference[]
#define BHO_LANG_CUDA BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__CUDACC__) || defined(__CUDA__)
# undef BHO_LANG_CUDA
# include <cuda.h>
# if defined(CUDA_VERSION)
# define BHO_LANG_CUDA BHO_PREDEF_MAKE_10_VVRRP(CUDA_VERSION)
# else
# define BHO_LANG_CUDA BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_LANG_CUDA
# define BHO_LANG_CUDA_AVAILABLE
#endif
#define BHO_LANG_CUDA_NAME "CUDA C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LANG_CUDA,BHO_LANG_CUDA_NAME)
<file_sep>// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2001 - 2002.
// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2004.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Metrowerks C++ compiler setup:
// locale support is disabled when linking with the dynamic runtime
# ifdef _MSL_NO_LOCALE
# define BHO_NO_STD_LOCALE
# endif
# if __MWERKS__ <= 0x2301 // 5.3
# define BHO_NO_FUNCTION_TEMPLATE_ORDERING
# define BHO_NO_POINTER_TO_MEMBER_CONST
# define BHO_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS
# define BHO_NO_MEMBER_TEMPLATE_KEYWORD
# endif
# if __MWERKS__ <= 0x2401 // 6.2
//# define BHO_NO_FUNCTION_TEMPLATE_ORDERING
# endif
# if(__MWERKS__ <= 0x2407) // 7.x
# define BHO_NO_MEMBER_FUNCTION_SPECIALIZATIONS
# define BHO_NO_UNREACHABLE_RETURN_DETECTION
# endif
# if(__MWERKS__ <= 0x3003) // 8.x
# define BHO_NO_SFINAE
# endif
// the "|| !defined(BHO_STRICT_CONFIG)" part should apply to the last
// tested version *only*:
# if(__MWERKS__ <= 0x3207) || !defined(BHO_STRICT_CONFIG) // 9.6
# define BHO_NO_MEMBER_TEMPLATE_FRIENDS
# define BHO_NO_IS_ABSTRACT
# endif
#if !__option(wchar_type)
# define BHO_NO_INTRINSIC_WCHAR_T
#endif
#if !__option(exceptions) && !defined(BHO_NO_EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
#endif
#if (__INTEL__ && _WIN32) || (__POWERPC__ && macintosh)
# if __MWERKS__ == 0x3000
# define BHO_COMPILER_VERSION 8.0
# elif __MWERKS__ == 0x3001
# define BHO_COMPILER_VERSION 8.1
# elif __MWERKS__ == 0x3002
# define BHO_COMPILER_VERSION 8.2
# elif __MWERKS__ == 0x3003
# define BHO_COMPILER_VERSION 8.3
# elif __MWERKS__ == 0x3200
# define BHO_COMPILER_VERSION 9.0
# elif __MWERKS__ == 0x3201
# define BHO_COMPILER_VERSION 9.1
# elif __MWERKS__ == 0x3202
# define BHO_COMPILER_VERSION 9.2
# elif __MWERKS__ == 0x3204
# define BHO_COMPILER_VERSION 9.3
# elif __MWERKS__ == 0x3205
# define BHO_COMPILER_VERSION 9.4
# elif __MWERKS__ == 0x3206
# define BHO_COMPILER_VERSION 9.5
# elif __MWERKS__ == 0x3207
# define BHO_COMPILER_VERSION 9.6
# else
# define BHO_COMPILER_VERSION __MWERKS__
# endif
#else
# define BHO_COMPILER_VERSION __MWERKS__
#endif
//
// C++0x features
//
// See boost\config\suffix.hpp for BHO_NO_LONG_LONG
//
#if __MWERKS__ > 0x3206 && __option(rvalue_refs)
# define BHO_HAS_RVALUE_REFS
#else
# define BHO_NO_CXX11_RVALUE_REFERENCES
#endif
#define BHO_NO_CXX11_AUTO_DECLARATIONS
#define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#define BHO_NO_CXX11_CHAR16_T
#define BHO_NO_CXX11_CHAR32_T
#define BHO_NO_CXX11_CONSTEXPR
#define BHO_NO_CXX11_DECLTYPE
#define BHO_NO_CXX11_DECLTYPE_N3276
#define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#define BHO_NO_CXX11_DELETED_FUNCTIONS
#define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#define BHO_NO_CXX11_EXTERN_TEMPLATE
#define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define BHO_NO_CXX11_HDR_INITIALIZER_LIST
#define BHO_NO_CXX11_LAMBDAS
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_RAW_LITERALS
#define BHO_NO_CXX11_SCOPED_ENUMS
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_CXX11_SFINAE_EXPR
#define BHO_NO_CXX11_STATIC_ASSERT
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_UNICODE_LITERALS
#define BHO_NO_CXX11_VARIADIC_TEMPLATES
#define BHO_NO_CXX11_VARIADIC_MACROS
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#define BHO_NO_CXX11_USER_DEFINED_LITERALS
#define BHO_NO_CXX11_ALIGNAS
#define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#define BHO_NO_CXX11_INLINE_NAMESPACES
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_FINAL
#define BHO_NO_CXX11_OVERRIDE
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_UNRESTRICTED_UNION
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
#define BHO_COMPILER "Metrowerks CodeWarrior C++ version " BHO_STRINGIZE(BHO_COMPILER_VERSION)
//
// versions check:
// we don't support Metrowerks prior to version 5.3:
#if __MWERKS__ < 0x2301
# error "Compiler not supported or configured - please reconfigure"
#endif
//
// last known and checked version:
#if (__MWERKS__ > 0x3205)
# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown compiler version - please run the configure tests and report the results"
# endif
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from https://github.com/loveyacper/ananas
*/
#ifndef __ASIO2_DEFER_HPP__
#define __ASIO2_DEFER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <functional>
namespace asio2
{
class defer
{
protected:
template<typename F, typename Void, typename... Args>
struct is_callable : std::false_type {};
template<typename F, typename... Args>
struct is_callable<F, std::void_t<decltype(std::declval<std::decay_t<F>&>()
((std::declval<Args>())...)), char>, Args...> : std::true_type {};
public:
defer() noexcept = default;
// movable
defer(defer&&) noexcept = default;
defer& operator=(defer&&) noexcept = default;
// non copyable
defer(const defer&) = delete;
void operator=(const defer&) = delete;
template <typename Fun, typename... Args,
std::enable_if_t<is_callable<Fun, void, Args...>::value, int> = 0>
defer(Fun&& fun, Args&&... args)
{
this->fn_ = std::bind(std::forward<Fun>(fun), std::forward<Args>(args)...);
}
template <typename Constructor, typename Destructor,
std::enable_if_t<is_callable<Constructor, void>::value && is_callable<Destructor, void>::value, int> = 0>
defer(Constructor&& ctor, Destructor&& dtor)
{
(ctor)();
this->fn_ = std::forward<Destructor>(dtor);
}
~defer() noexcept
{
if (this->fn_) this->fn_();
}
protected:
std::function<void()> fn_;
};
#ifndef ASIO2_CONCAT
#define ASIO2_CONCAT(a, b) a##b
#endif
#define ASIO2_MAKE_DEFER(line) ::asio2::defer ASIO2_CONCAT(_asio2_defer_, line) = [&]()
#define ASIO2_DEFER ASIO2_MAKE_DEFER(__LINE__)
}
#endif // !__ASIO2_DEFER_HPP__
<file_sep>#include "unit_test.hpp"
#include <fmt/format.h>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/tcp/tcp_client.hpp>
static std::string_view chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
void tcp_dgram_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
// illegal data 254
{
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18027);
client_connect_counter++;
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
});
bool client_start_ret = client.async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
auto& clt = clients[i];
clients[i]->post([&clt]()
{
std::vector<std::uint8_t> msg;
int len = 200 + (std::rand() % 200);
msg.resize(len);
for (int i = 0; i < len; i++)
{
msg[i] = std::uint8_t(std::rand() % 0xff);
}
msg[0] = std::uint8_t(254);
if (asio2::detail::is_little_endian())
{
msg[1] = std::uint8_t(253);
msg[2] = std::uint8_t(0);
}
else
{
msg[1] = std::uint8_t(0);
msg[2] = std::uint8_t(253);
}
msg[3] = std::uint8_t(0);
msg[4] = std::uint8_t(0);
msg[5] = std::uint8_t(0);
msg[6] = std::uint8_t(0);
msg[7] = std::uint8_t(0);
msg[8] = std::uint8_t(0);
asio::write(clt->socket(), asio::buffer(msg));
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 0);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
auto& clt = clients[i];
clients[i]->post([&clt]()
{
std::vector<std::uint8_t> msg;
int len = 200 + (std::rand() % 200);
msg.resize(len);
for (int i = 0; i < len; i++)
{
msg[i] = std::uint8_t(std::rand() % 0xff);
}
msg[0] = std::uint8_t(254);
if (asio2::detail::is_little_endian())
{
msg[1] = std::uint8_t(253);
msg[2] = std::uint8_t(0);
}
else
{
msg[1] = std::uint8_t(0);
msg[2] = std::uint8_t(253);
}
msg[3] = std::uint8_t(0);
msg[4] = std::uint8_t(0);
msg[5] = std::uint8_t(0);
msg[6] = std::uint8_t(0);
msg[7] = std::uint8_t(0);
msg[8] = std::uint8_t(0);
asio::write(clt->socket(), asio::buffer(msg));
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 0);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// illegal data 255
{
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18027);
client_connect_counter++;
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
});
bool client_start_ret = client.async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
auto& clt = clients[i];
clients[i]->post([&clt]()
{
std::vector<std::uint8_t> msg;
int len = 200 + (std::rand() % 200);
msg.resize(len);
for (int i = 0; i < len; i++)
{
msg[i] = std::uint8_t(std::rand() % 0xff);
}
msg[0] = std::uint8_t(255);
if (asio2::detail::is_little_endian())
{
msg[1] = std::uint8_t(0xff);
msg[2] = std::uint8_t(0xff);
msg[3] = std::uint8_t(0);
msg[4] = std::uint8_t(0);
msg[5] = std::uint8_t(0);
msg[6] = std::uint8_t(0);
msg[7] = std::uint8_t(0);
msg[8] = std::uint8_t(0);
}
else
{
msg[1] = std::uint8_t(0);
msg[2] = std::uint8_t(0);
msg[3] = std::uint8_t(0);
msg[4] = std::uint8_t(0);
msg[5] = std::uint8_t(0);
msg[6] = std::uint8_t(0);
msg[7] = std::uint8_t(0xff);
msg[8] = std::uint8_t(0xff);
}
asio::write(clt->socket(), asio::buffer(msg));
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 0);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
auto& clt = clients[i];
clients[i]->post([&clt]()
{
std::vector<std::uint8_t> msg;
int len = 200 + (std::rand() % 200);
msg.resize(len);
for (int i = 0; i < len; i++)
{
msg[i] = std::uint8_t(std::rand() % 0xff);
}
msg[0] = std::uint8_t(255);
if (asio2::detail::is_little_endian())
{
msg[1] = std::uint8_t(0xff);
msg[2] = std::uint8_t(0xff);
msg[3] = std::uint8_t(0);
msg[4] = std::uint8_t(0);
msg[5] = std::uint8_t(0);
msg[6] = std::uint8_t(0);
msg[7] = std::uint8_t(0);
msg[8] = std::uint8_t(0);
}
else
{
msg[1] = std::uint8_t(0);
msg[2] = std::uint8_t(0);
msg[3] = std::uint8_t(0);
msg[4] = std::uint8_t(0);
msg[5] = std::uint8_t(0);
msg[6] = std::uint8_t(0);
msg[7] = std::uint8_t(0xff);
msg[8] = std::uint8_t(0xff);
}
asio::write(clt->socket(), asio::buffer(msg));
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 0);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test datagram send recv
{
struct ext_data
{
int num = 1;
};
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_send(std::move(msg));
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18027);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 20)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
client.async_send(std::move(msg));
});
bool client_start_ret = client.async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test auto reconnect by async_start in bind_connect
{
struct ext_data
{
int num = 1;
int connect_times = 1;
};
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_send(std::move(msg));
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
if (!asio2::get_last_error())
{
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18027);
}
if (asio2::get_last_error())
{
ext_data* ex = client.get_user_data<ext_data*>();
ex->connect_times++;
client.async_start("127.0.0.1", 18027, asio2::use_dgram);
}
else
{
client_connect_counter++;
}
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
//fmt::print("recv : {}\n", data.substr(0, 5));
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 20)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
client.async_send(std::move(msg));
});
ext_data ex;
ex.num = 1;
ex.connect_times = 1;
client.set_user_data(ex);
bool client_start_ret = client.async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.connect_times < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
}
bool server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
int total_connect_times = 0;
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
total_connect_times += ex.connect_times;
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == total_connect_times);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// stop the client or not is ok both.
if (loop % 3 == 0)
{
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
ext_data ex;
ex.num = 1;
ex.connect_times = 1;
clients[i]->set_user_data(ex);
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.connect_times < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
}
server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
total_connect_times = 0;
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
total_connect_times += ex.connect_times;
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == total_connect_times);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// stop the client or not is ok both.
if (loop % 2 == 0)
{
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test auto reconnect by async_start in bind_disconnect
{
struct ext_data
{
int num = 1;
int connect_times = 1;
bool prepare_exit = false;
};
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
if (ex.num > 20)
{
session_ptr->stop();
return;
}
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_send(std::move(msg));
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
if (!asio2::get_last_error())
{
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18027);
}
if (asio2::get_last_error())
{
ext_data* ex = client.get_user_data<ext_data*>();
ex->connect_times++;
if (ex->prepare_exit == false)
client.async_start("127.0.0.1", 18027, asio2::use_dgram);
}
else
{
client_connect_counter++;
}
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->prepare_exit == false)
client.async_start("127.0.0.1", 18027, asio2::use_dgram);
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
ext_data* ex = client.get_user_data<ext_data*>();
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
client.async_send(std::move(msg));
});
ext_data ex;
ex.num = 1;
ex.connect_times = 1;
client.set_user_data(ex);
bool client_start_ret = client.async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.connect_times < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
}
bool server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter.load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter.load(), server_start_counter == 1);
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
int total_connect_times = 0;
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
total_connect_times += ex.connect_times;
}
ASIO2_CHECK_VALUE(client_init_counter.load(), client_init_counter == total_connect_times);
ASIO2_CHECK_VALUE(client_connect_counter.load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter.load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter.load(), server_connect_counter == test_client_count);
client_init_counter = 0;
client_connect_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
ext_data* ex = clients[i]->get_user_data<ext_data*>();
ex->prepare_exit = true;
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter.load(), server_stop_counter == 1);
}
// test stop start in the io_context thread.
for (int x = 0; x < test_loop_times / 50; x++)
{
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18027);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
if (!asio2::get_last_error())
{
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18027);
}
client_connect_counter++;
std::string str;
str += '#';
int len = 10 + (std::rand() % 100);
for (int i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
client.async_send(std::move(str));
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
std::string str;
str += '#';
int len = 10 + (std::rand() % 100);
for (int i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
client.async_send(std::move(str));
});
bool client_start_ret = client.async_start("127.0.0.1", 18027, asio2::use_dgram);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
ASIO2_CHECK_VALUE(server_init_counter.load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter.load(), server_start_counter == 1);
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter.load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter.load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter.load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter.load(), server_connect_counter == test_client_count);
std::this_thread::sleep_for(std::chrono::milliseconds(25 + std::rand() % 25));
for (int i = 0; i < test_client_count; i++)
{
auto& client = *clients[i];
client.post([&]()
{
client.stop();
if (loop % 2 == 0)
client.start("127.0.0.1", 18027, asio2::use_dgram);
else
client.async_start("127.0.0.1", 18027, asio2::use_dgram);
});
}
std::this_thread::sleep_for(std::chrono::milliseconds(25 + std::rand() % 25));
std::vector<int> exits;
exits.resize(test_client_count, 0);
for (int i = 0; i < test_client_count; i++)
{
std::thread([&,i]()
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
exits[i] = 1;
}).detach();
}
for (int i = 0; i < test_client_count; i++)
{
while (exits[i] != 1)
{
ASIO2_TEST_WAIT_CHECK(clients[i]->get_pending_event_count());
}
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter.load(), server_stop_counter == 1);
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"tcp_dgram",
ASIO2_TEST_CASE(tcp_dgram_test)
)
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2002.
// (C) Copyright <NAME> 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Dinkumware standard library config:
#if !defined(_YVALS) && !defined(_CPPLIB_VER)
#include <asio2/bho/config/no_tr1/utility.hpp>
#if !defined(_YVALS) && !defined(_CPPLIB_VER)
#error This is not the Dinkumware lib!
#endif
#endif
#if defined(_CPPLIB_VER) && (_CPPLIB_VER >= 306)
// full dinkumware 3.06 and above
// fully conforming provided the compiler supports it:
# if !(defined(_GLOBAL_USING) && (_GLOBAL_USING+0 > 0)) && !defined(BHO_BORLANDC) && !defined(_STD) && !(defined(__ICC) && (__ICC >= 700)) // can be defined in yvals.h
# define BHO_NO_STDC_NAMESPACE
# endif
# if !(defined(_HAS_MEMBER_TEMPLATES_REBIND) && (_HAS_MEMBER_TEMPLATES_REBIND+0 > 0)) && !(defined(_MSC_VER) && (_MSC_VER > 1300)) && defined(BHO_MSVC)
# define BHO_NO_STD_ALLOCATOR
# endif
# define BHO_HAS_PARTIAL_STD_ALLOCATOR
# if defined(BHO_MSVC) && (BHO_MSVC < 1300)
// if this lib version is set up for vc6 then there is no std::use_facet:
# define BHO_NO_STD_USE_FACET
# define BHO_HAS_TWO_ARG_USE_FACET
// C lib functions aren't in namespace std either:
# define BHO_NO_STDC_NAMESPACE
// and nor is <exception>
# define BHO_NO_EXCEPTION_STD_NAMESPACE
# endif
// There's no numeric_limits<long long> support unless _LONGLONG is defined:
# if !defined(_LONGLONG) && (_CPPLIB_VER <= 310)
# define BHO_NO_MS_INT64_NUMERIC_LIMITS
# endif
// 3.06 appears to have (non-sgi versions of) <hash_set> & <hash_map>,
// and no <slist> at all
#else
# define BHO_MSVC_STD_ITERATOR 1
# define BHO_NO_STD_ITERATOR
# define BHO_NO_TEMPLATED_ITERATOR_CONSTRUCTORS
# define BHO_NO_STD_ALLOCATOR
# define BHO_NO_STDC_NAMESPACE
# define BHO_NO_STD_USE_FACET
# define BHO_NO_STD_OUTPUT_ITERATOR_ASSIGN
# define BHO_HAS_MACRO_USE_FACET
# ifndef _CPPLIB_VER
// Updated Dinkum library defines this, and provides
// its own min and max definitions, as does MTA version.
# ifndef __MTA__
# define BHO_NO_STD_MIN_MAX
# endif
# define BHO_NO_MS_INT64_NUMERIC_LIMITS
# endif
#endif
//
// std extension namespace is stdext for vc7.1 and later,
// the same applies to other compilers that sit on top
// of vc7.1 (Intel and Comeau):
//
#if defined(_MSC_VER) && (_MSC_VER >= 1310) && !defined(BHO_BORLANDC)
# define BHO_STD_EXTENSION_NAMESPACE stdext
#endif
#if (defined(_MSC_VER) && (_MSC_VER <= 1300) && !defined(BHO_BORLANDC)) || !defined(_CPPLIB_VER) || (_CPPLIB_VER < 306)
// if we're using a dinkum lib that's
// been configured for VC6/7 then there is
// no iterator traits (true even for icl)
# define BHO_NO_STD_ITERATOR_TRAITS
#endif
#if defined(__ICL) && (__ICL < 800) && defined(_CPPLIB_VER) && (_CPPLIB_VER <= 310)
// Intel C++ chokes over any non-trivial use of <locale>
// this may be an overly restrictive define, but regex fails without it:
# define BHO_NO_STD_LOCALE
#endif
#if ((defined(BHO_MSVC) && BHO_MSVC >= 1400) || (defined(__clang__) && defined(_MSC_VER))) && (_MSC_VER < 1800)
// Fix for VC++ 8.0 on up ( I do not have a previous version to test )
// or clang-cl. If exceptions are off you must manually include the
// <exception> header before including the <typeinfo> header. Admittedly
// trying to use Boost libraries or the standard C++ libraries without
// exception support is not suggested but currently clang-cl ( v 3.4 )
// does not support exceptions and must be compiled with exceptions off.
#if !_HAS_EXCEPTIONS
#include <exception>
#endif
#include <typeinfo>
#if !_HAS_EXCEPTIONS
# define BHO_NO_STD_TYPEINFO
#endif
#endif
#if defined(__ghs__) && !_HAS_NAMESPACE
# define BHO_NO_STD_TYPEINFO
#endif
// C++0x headers implemented in 520 (as shipped by Microsoft)
//
#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 520
# define BHO_NO_CXX11_HDR_ARRAY
# define BHO_NO_CXX11_HDR_CODECVT
# define BHO_NO_CXX11_HDR_FORWARD_LIST
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_RANDOM
# define BHO_NO_CXX11_HDR_REGEX
# define BHO_NO_CXX11_HDR_SYSTEM_ERROR
# define BHO_NO_CXX11_HDR_UNORDERED_MAP
# define BHO_NO_CXX11_HDR_UNORDERED_SET
# define BHO_NO_CXX11_HDR_TUPLE
# define BHO_NO_CXX11_HDR_TYPEINDEX
# define BHO_NO_CXX11_HDR_FUNCTIONAL
# define BHO_NO_CXX11_NUMERIC_LIMITS
# define BHO_NO_CXX11_SMART_PTR
#endif
#if ((!defined(_HAS_TR1_IMPORTS) || (_HAS_TR1_IMPORTS+0 == 0)) && !defined(BHO_NO_CXX11_HDR_TUPLE)) \
&& (!defined(_CPPLIB_VER) || _CPPLIB_VER < 610)
# define BHO_NO_CXX11_HDR_TUPLE
#endif
// C++0x headers implemented in 540 (as shipped by Microsoft)
//
#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 540
# define BHO_NO_CXX11_HDR_TYPE_TRAITS
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_RATIO
# define BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
# define BHO_NO_CXX11_HDR_EXCEPTION
#endif
// C++0x headers implemented in 610 (as shipped by Microsoft)
//
#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 610
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_ALLOCATOR
// 540 has std::align but it is not a conforming implementation
# define BHO_NO_CXX11_STD_ALIGN
#endif
// Before 650 std::pointer_traits has a broken rebind template
#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 650
# define BHO_NO_CXX11_POINTER_TRAITS
#elif defined(BHO_MSVC) && BHO_MSVC < 1910
# define BHO_NO_CXX11_POINTER_TRAITS
#endif
#if defined(__has_include)
#if !__has_include(<shared_mutex>)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#elif (__cplusplus < 201402) && !defined(_MSC_VER)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#elif !defined(_CPPLIB_VER) || (_CPPLIB_VER < 650)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
// C++14 features
#if !defined(_CPPLIB_VER) || (_CPPLIB_VER < 650)
# define BHO_NO_CXX14_STD_EXCHANGE
#endif
// C++17 features
#if !defined(_CPPLIB_VER) || (_CPPLIB_VER < 650) || !defined(BHO_MSVC) || (BHO_MSVC < 1910) || !defined(_HAS_CXX17) || (_HAS_CXX17 == 0)
# define BHO_NO_CXX17_STD_APPLY
# define BHO_NO_CXX17_ITERATOR_TRAITS
# define BHO_NO_CXX17_HDR_STRING_VIEW
# define BHO_NO_CXX17_HDR_OPTIONAL
# define BHO_NO_CXX17_HDR_VARIANT
# define BHO_NO_CXX17_HDR_ANY
# define BHO_NO_CXX17_HDR_MEMORY_RESOURCE
# define BHO_NO_CXX17_HDR_CHARCONV
# define BHO_NO_CXX17_HDR_EXECUTION
# define BHO_NO_CXX17_HDR_FILESYSTEM
#endif
#if !defined(_CPPLIB_VER) || (_CPPLIB_VER < 650) || !defined(_HAS_CXX17) || (_HAS_CXX17 == 0) || !defined(_MSVC_STL_UPDATE) || (_MSVC_STL_UPDATE < 201709)
# define BHO_NO_CXX17_STD_INVOKE
#endif
// C++20 features
#if !defined(_MSVC_STL_UPDATE) || (_MSVC_STL_UPDATE < 202008L) || !defined(_HAS_CXX20) || (_HAS_CXX20 == 0)
# define BHO_NO_CXX20_HDR_BARRIER
# define BHO_NO_CXX20_HDR_BIT
# define BHO_NO_CXX20_HDR_LATCH
# define BHO_NO_CXX20_HDR_SPAN
# define BHO_NO_CXX20_HDR_COMPARE
# define BHO_NO_CXX20_HDR_NUMBERS
# define BHO_NO_CXX20_HDR_CONCEPTS
# define BHO_NO_CXX20_HDR_COROUTINE
# define BHO_NO_CXX20_HDR_SEMAPHORE
#endif
#if !defined(_MSVC_STL_UPDATE) || (_MSVC_STL_UPDATE < 202011L) || !defined(_HAS_CXX20) || (_HAS_CXX20 == 0)
# define BHO_NO_CXX20_HDR_STOP_TOKEN
#endif
// C++20 features not yet implemented:
# define BHO_NO_CXX20_HDR_FORMAT
#if !defined(_MSVC_STL_UPDATE) || (_MSVC_STL_UPDATE < 202108L) || !defined(_HAS_CXX20) || (_HAS_CXX20 == 0)
# define BHO_NO_CXX20_HDR_SOURCE_LOCATION
# define BHO_NO_CXX20_HDR_SYNCSTREAM
#endif
// Incomplete:
# define BHO_NO_CXX20_HDR_RANGES
#if !(!defined(_CPPLIB_VER) || (_CPPLIB_VER < 650) || !defined(BHO_MSVC) || (BHO_MSVC < 1912) || !defined(_HAS_CXX17) || (_HAS_CXX17 == 0))
// Deprecated std::iterator:
# define BHO_NO_STD_ITERATOR
#endif
#if defined(BHO_INTEL) && (BHO_INTEL <= 1400)
// Intel's compiler can't handle this header yet:
# define BHO_NO_CXX11_HDR_ATOMIC
#endif
// 520..610 have std::addressof, but it doesn't support functions
//
#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 650
# define BHO_NO_CXX11_ADDRESSOF
#endif
// Bug specific to VC14,
// See https://connect.microsoft.com/VisualStudio/feedback/details/1348277/link-error-when-using-std-codecvt-utf8-utf16-char16-t
// and discussion here: http://blogs.msdn.com/b/vcblog/archive/2014/11/12/visual-studio-2015-preview-now-available.aspx?PageIndex=2
#if defined(_CPPLIB_VER) && (_CPPLIB_VER == 650) && (!defined(_MSVC_STL_VERSION) || (_MSVC_STL_VERSION < 142))
# define BHO_NO_CXX11_HDR_CODECVT
#endif
#if (_MSVC_LANG > 201700) && !defined(BHO_NO_CXX11_HDR_CODECVT)
//
// <codecvt> is deprected as of C++17, and by default MSVC emits hard errors
// if you try to use it, so mark it as unavailable:
//
# define BHO_NO_CXX11_HDR_CODECVT
#endif
#if defined(_CPPLIB_VER) && (_CPPLIB_VER >= 650)
// If _HAS_AUTO_PTR_ETC is defined to 0, std::auto_ptr and std::random_shuffle are not available.
// See https://www.visualstudio.com/en-us/news/vs2015-vs.aspx#C++
// and http://blogs.msdn.com/b/vcblog/archive/2015/06/19/c-11-14-17-features-in-vs-2015-rtm.aspx
# if defined(_HAS_AUTO_PTR_ETC) && (_HAS_AUTO_PTR_ETC == 0)
# define BHO_NO_AUTO_PTR
# define BHO_NO_CXX98_RANDOM_SHUFFLE
# define BHO_NO_CXX98_FUNCTION_BASE
# define BHO_NO_CXX98_BINDERS
# endif
#endif
//
// Things deprecated in C++20:
//
#if defined(_HAS_CXX20)
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
#endif
//
// Things not supported by the CLR:
#ifdef _M_CEE
#ifndef BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_MUTEX
#endif
#ifndef BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_HDR_ATOMIC
#endif
#ifndef BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_FUTURE
#endif
#ifndef BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
#endif
#ifndef BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_HDR_THREAD
#endif
#ifndef BHO_NO_CXX14_HDR_SHARED_MUTEX
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#ifndef BHO_NO_CXX14_STD_EXCHANGE
# define BHO_NO_CXX14_STD_EXCHANGE
#endif
#ifndef BHO_NO_FENV_H
# define BHO_NO_FENV_H
#endif
#endif
#ifdef _CPPLIB_VER
# define BHO_DINKUMWARE_STDLIB _CPPLIB_VER
#else
# define BHO_DINKUMWARE_STDLIB 1
#endif
#ifdef _CPPLIB_VER
# define BHO_STDLIB "Dinkumware standard library version " BHO_STRINGIZE(_CPPLIB_VER)
#else
# define BHO_STDLIB "Dinkumware standard library version 1.x"
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_SYS370_H
#define BHO_PREDEF_ARCHITECTURE_SYS370_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_SYS370`
http://en.wikipedia.org/wiki/System/370[System/370] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__370__+` | {predef_detection}
| `+__THW_370__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_SYS370 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__370__) || defined(__THW_370__)
# undef BHO_ARCH_SYS370
# define BHO_ARCH_SYS370 BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_SYS370
# define BHO_ARCH_SYS370_AVAILABLE
#endif
#if BHO_ARCH_SYS370
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_SYS370_NAME "System/370"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_SYS370,BHO_ARCH_SYS370_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_SGI_H
#define BHO_PREDEF_LIBRARY_STD_SGI_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_SGI`
http://www.sgi.com/tech/stl/[SGI] Standard {CPP} library.
If available version number as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__STL_CONFIG_H+` | {predef_detection}
| `+__SGI_STL+` | V.R.P
|===
*/ // end::reference[]
#define BHO_LIB_STD_SGI BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__STL_CONFIG_H)
# undef BHO_LIB_STD_SGI
# if defined(__SGI_STL)
# define BHO_LIB_STD_SGI BHO_PREDEF_MAKE_0X_VRP(__SGI_STL)
# else
# define BHO_LIB_STD_SGI BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_LIB_STD_SGI
# define BHO_LIB_STD_SGI_AVAILABLE
#endif
#define BHO_LIB_STD_SGI_NAME "SGI"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_SGI,BHO_LIB_STD_SGI_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_CLANG_H
#define BHO_PREDEF_COMPILER_CLANG_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_CLANG`
http://en.wikipedia.org/wiki/Clang[Clang] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__clang__+` | {predef_detection}
| `+__clang_major__+`, `+__clang_minor__+`, `+__clang_patchlevel__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_CLANG BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__clang__)
# define BHO_COMP_CLANG_DETECTION BHO_VERSION_NUMBER(__clang_major__,__clang_minor__,__clang_patchlevel__)
#endif
#ifdef BHO_COMP_CLANG_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_CLANG_EMULATED BHO_COMP_CLANG_DETECTION
# else
# undef BHO_COMP_CLANG
# define BHO_COMP_CLANG BHO_COMP_CLANG_DETECTION
# endif
# define BHO_COMP_CLANG_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_CLANG_NAME "Clang"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_CLANG,BHO_COMP_CLANG_NAME)
#ifdef BHO_COMP_CLANG_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_CLANG_EMULATED,BHO_COMP_CLANG_NAME)
#endif
<file_sep>#
# COPYRIGHT (C) 2017-2021, zhllxt
#
# author : zhllxt
# email : <EMAIL>
#
# Distributed under the GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
# (See accompanying file LICENSE or see <http://www.gnu.org/licenses/>)
#
add_subdirectory (asio2_rpc_qps_client)
add_subdirectory (asio2_rpc_qps_server)
add_subdirectory (rest_rpc_qps_client)
add_subdirectory (rest_rpc_qps_server)
<file_sep>/*
Copyright <NAME> 2011-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_CXX_H
#define BHO_PREDEF_LIBRARY_STD_CXX_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_CXX`
http://libcxx.llvm.org/[libc++] {CPP} Standard Library.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+_LIBCPP_VERSION+` | {predef_detection}
| `+_LIBCPP_VERSION+` | V.0.P
|===
*/ // end::reference[]
#define BHO_LIB_STD_CXX BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(_LIBCPP_VERSION)
# undef BHO_LIB_STD_CXX
# define BHO_LIB_STD_CXX BHO_PREDEF_MAKE_10_VVPPP(_LIBCPP_VERSION)
#endif
#if BHO_LIB_STD_CXX
# define BHO_LIB_STD_CXX_AVAILABLE
#endif
#define BHO_LIB_STD_CXX_NAME "libc++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_CXX,BHO_LIB_STD_CXX_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_UDP_SERVER_HPP__
#define __ASIO2_UDP_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/server.hpp>
#include <asio2/udp/udp_session.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SERVER;
template<class derived_t, class session_t>
class udp_server_impl_t : public server_impl_t<derived_t, session_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SERVER;
public:
using super = server_impl_t <derived_t, session_t>;
using self = udp_server_impl_t<derived_t, session_t>;
using session_type = session_t;
public:
/**
* @brief constructor
*/
explicit udp_server_impl_t(
std::size_t init_buf_size = udp_frame_size,
std::size_t max_buf_size = max_buffer_size,
std::size_t concurrency = 1
)
: super(concurrency)
, acceptor_(this->io_.context())
, remote_endpoint_()
, buffer_(init_buf_size, max_buf_size)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit udp_server_impl_t(
std::size_t init_buf_size,
std::size_t max_buf_size,
Scheduler&& scheduler
)
: super(std::forward<Scheduler>(scheduler))
, acceptor_(this->io_.context())
, remote_endpoint_()
, buffer_(init_buf_size, max_buf_size)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit udp_server_impl_t(Scheduler&& scheduler)
: udp_server_impl_t(udp_frame_size, max_buffer_size, std::forward<Scheduler>(scheduler))
{
}
/**
* @brief destructor
*/
~udp_server_impl_t()
{
this->stop();
}
/**
* @brief start the server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param service - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& service, Args&&... args)
{
return this->derived()._do_start(
std::forward<String>(host), std::forward<StrOrInt>(service),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
/**
* @brief stop the server
* You can call this function on the communication thread and anywhere to stop the server.
*/
inline void stop()
{
if (this->is_iopool_stopped())
return;
derived_t& derive = this->derived();
derive.io().unregobj(&derive);
derive.post([&derive]() mutable
{
derive._do_stop(asio::error::operation_aborted, derive.selfptr());
});
this->stop_iopool();
}
/**
* @brief check whether the server is started
*/
inline bool is_started() { return (super::is_started() && this->acceptor_.is_open()); }
/**
* @brief check whether the server is stopped
*/
inline bool is_stopped()
{
return (this->state_ == state_t::stopped && !this->acceptor_.is_open());
}
public:
/**
* @brief bind recv listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void(std::shared_ptr<asio2::udp_session>& session_ptr, std::string_view data)
*/
template<class F, class ...C>
inline derived_t & bind_recv(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::recv,
observer_t<std::shared_ptr<session_t>&, std::string_view>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind connect listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is invoked after the connection is fully established,
* and only after the connect/handshake/upgrade are completed.
* Function signature : void(std::shared_ptr<asio2::udp_session>& session_ptr)
*/
template<class F, class ...C>
inline derived_t & bind_connect(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::connect,
observer_t<std::shared_ptr<session_t>&>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind disconnect listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is invoked before the connection is disconnected, you can call
* get_last_error/last_error_msg, etc, to get the disconnected error information
* Function signature : void(std::shared_ptr<asio2::udp_session>& session_ptr)
*/
template<class F, class ...C>
inline derived_t & bind_disconnect(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::disconnect,
observer_t<std::shared_ptr<session_t>&>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind init listener,we should set socket options at here
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called after the socket is opened.
* You can set the socket option in this notification.
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_init(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::init, observer_t<>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind start listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called after the server starts up, whether successful or unsuccessful
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_start(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::start, observer_t<>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind stop listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called before the server is ready to stop
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_stop(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::stop, observer_t<>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind kcp handshake listener, just used fo kcp mode
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void(std::shared_ptr<asio2::udp_session>& session_ptr)
*/
template<class F, class ...C>
inline derived_t & bind_handshake(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::handshake,
observer_t<std::shared_ptr<session_t>&>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
public:
/**
* @brief get the acceptor refrence
*/
inline asio::ip::udp::socket & acceptor() noexcept { return this->acceptor_; }
protected:
template<typename String, typename StrOrInt, typename C>
inline bool _do_start(String&& host, StrOrInt&& port, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = this->derived();
// if log is enabled, init the log first, otherwise when "Too many open files" error occurs,
// the log file will be created failed too.
#if defined(ASIO2_ENABLE_LOG)
asio2::detail::get_logger();
#endif
this->start_iopool();
if (!this->is_iopool_started())
{
set_last_error(asio::error::operation_aborted);
return false;
}
asio::dispatch(derive.io().context(), [&derive, this_ptr = derive.selfptr()]() mutable
{
detail::ignore_unused(this_ptr);
// init the running thread id
derive.io().init_thread_id();
});
// use promise to get the result of async accept
std::promise<error_code> promise;
std::future<error_code> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[promise = std::move(promise)]() mutable
{
promise.set_value(get_last_error());
}
};
derive.post(
[this, this_ptr = derive.selfptr(), ecs = std::move(ecs), pg = std::move(pg),
host = std::forward<String>(host), port = std::forward<StrOrInt>(port)]
() mutable
{
derived_t& derive = this->derived();
state_t expected = state_t::stopped;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
// if the state is not stopped, set the last error to already_started
set_last_error(asio::error::already_started);
return;
}
// must read/write ecs in the io_context thread.
derive.ecs_ = ecs;
derive.io().regobj(&derive);
#if defined(_DEBUG) || defined(DEBUG)
this->sessions_.is_all_session_stop_called_ = false;
this->is_stop_called_ = false;
#endif
// convert to string maybe throw some exception.
std::string h = detail::to_string(std::move(host));
std::string p = detail::to_string(std::move(port));
expected = state_t::starting;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
ASIO2_ASSERT(false);
derive._handle_start(asio::error::operation_aborted, std::move(this_ptr), std::move(ecs));
return;
}
super::start();
// should hold the server shared ptr too, if server is constructed with iopool, and
// server is a tmp local variable, then the server maybe destroyed before sessions.
// so we need hold this ptr to ensure server must be destroyed after sessions.
this->counter_ptr_ = std::shared_ptr<void>((void*)1, [&derive, this_ptr](void*) mutable
{
derive._exec_stop(asio::error::operation_aborted, std::move(this_ptr));
});
error_code ec, ec_ignore;
// parse address and port
asio::ip::udp::resolver resolver(this->io_.context());
auto results = resolver.resolve(h, p,
asio::ip::resolver_base::flags::passive |
asio::ip::resolver_base::flags::address_configured, ec);
if (ec)
{
derive._handle_start(ec, std::move(this_ptr), std::move(ecs));
return;
}
if (results.empty())
{
derive._handle_start(asio::error::host_not_found, std::move(this_ptr), std::move(ecs));
return;
}
asio::ip::udp::endpoint endpoint = *results.begin();
this->acceptor_.cancel(ec_ignore);
this->acceptor_.close(ec_ignore);
this->acceptor_.open(endpoint.protocol(), ec);
if (ec)
{
derive._handle_start(ec, std::move(this_ptr), std::move(ecs));
return;
}
// when you close socket in linux system,and start socket
// immediate,you will get like this "the address is in use",
// and bind is failed,but i'm suer i close the socket correct
// already before,why does this happen? the reasion is the
// socket option "TIME_WAIT",although you close the socket,
// but the system not release the socket,util 2~4 seconds later,
// so we can use the SO_REUSEADDR option to avoid this problem,
// like below
// set port reuse
this->acceptor_.set_option(asio::ip::udp::socket::reuse_address(true), ec_ignore);
//// Join the multicast group. you can set this option in the on_init(_fire_init) function.
//this->acceptor_.set_option(
// // for ipv6, the host must be a ipv6 address like 0::0
// asio::ip::multicast::join_group(asio::ip::make_address("fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:1234")));
// // for ipv4, the host must be a ipv4 address like 0.0.0.0
// //asio::ip::multicast::join_group(asio::ip::make_address("172.16.58.3")));
clear_last_error();
derive._fire_init();
this->acceptor_.bind(endpoint, ec);
if (ec)
{
derive._handle_start(ec, std::move(this_ptr), std::move(ecs));
return;
}
derive._handle_start(ec, std::move(this_ptr), std::move(ecs));
});
if (!derive.io().running_in_this_thread())
{
set_last_error(future.get());
return static_cast<bool>(!get_last_error());
}
else
{
set_last_error(asio::error::in_progress);
}
// if the state is stopped , the return value is "is_started()".
// if the state is stopping, the return value is false, the last error is already_started
// if the state is starting, the return value is false, the last error is already_started
// if the state is started , the return value is true , the last error is already_started
return derive.is_started();
}
template<typename C>
inline void _handle_start(error_code ec, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
// Whether the startup succeeds or fails, always call fire_start notification
state_t expected = state_t::starting;
if (!ec)
if (!this->state_.compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
set_last_error(ec);
this->derived()._fire_start();
expected = state_t::started;
if (!ec)
if (!this->state_.compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
if (ec)
{
this->derived()._do_stop(ec, std::move(this_ptr));
return;
}
this->buffer_.consume(this->buffer_.size());
this->derived()._post_recv(std::move(this_ptr), std::move(ecs));
}
inline void _do_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
state_t expected = state_t::starting;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
return this->derived()._post_stop(ec, std::move(this_ptr), expected);
expected = state_t::started;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
return this->derived()._post_stop(ec, std::move(this_ptr), expected);
}
inline void _post_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state)
{
// asio don't allow operate the same socket in multi thread,
// if you close socket in one thread and another thread is
// calling socket's async_... function,it will crash.so we
// must care for operate the socket.when need close the
// socket ,we use the io_context to post a event,make sure the
// socket's close operation is in the same thread.
// psot a recv signal to ensure that all recv events has finished already.
this->derived().post(
[this, ec, old_state, this_ptr = std::move(this_ptr)]() mutable
{
detail::ignore_unused(this, ec, old_state, this_ptr);
// When the code runs here,no new session can be emplace or erase to session_mgr.
// stop all the sessions, the session::stop must be no blocking,
// otherwise it may be cause loop lock.
set_last_error(ec);
ASIO2_ASSERT(this->state_ == state_t::stopping);
// stop all the sessions, the session::stop must be no blocking,
// otherwise it may be cause loop lock.
this->sessions_.for_each([](std::shared_ptr<session_t> & session_ptr) mutable
{
session_ptr->stop();
});
#if defined(_DEBUG) || defined(DEBUG)
this->sessions_.is_all_session_stop_called_ = true;
#endif
if (this->counter_ptr_)
{
this->counter_ptr_.reset();
}
else
{
this->derived()._exec_stop(ec, std::move(this_ptr));
}
});
}
inline void _exec_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
{
// use asio::post to ensure this server's _handle_stop is called must be after
// all sessions _handle_stop has been called already.
// is use asio::dispatch, session's _handle_stop maybe called first.
asio::post(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, ec, this_ptr = std::move(this_ptr)]() mutable
{
state_t expected = state_t::stopping;
if (this->state_.compare_exchange_strong(expected, state_t::stopped))
{
this->derived()._handle_stop(ec, std::move(this_ptr));
}
else
{
ASIO2_ASSERT(false);
}
}));
}
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
{
set_last_error(ec);
this->derived()._fire_stop();
// call the base class stop function
super::stop();
error_code ec_ignore{};
// Call shutdown() to indicate that you will not write any more data to the socket.
this->acceptor_.shutdown(asio::socket_base::shutdown_both, ec_ignore);
this->acceptor_.cancel(ec_ignore);
// Call close,otherwise the _handle_recv will never return
this->acceptor_.close(ec_ignore);
ASIO2_ASSERT(this->state_ == state_t::stopped);
}
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
if (!this->derived().is_started())
{
if (this->derived().state() == state_t::started)
{
this->derived()._do_stop(asio2::get_last_error(), std::move(this_ptr));
}
return;
}
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->derived().post_recv_counter_.load() == 0);
this->derived().post_recv_counter_++;
#endif
this->acceptor_.async_receive_from(
this->buffer_.prepare(this->buffer_.pre_size()),
this->remote_endpoint_,
make_allocator(this->rallocator_, [this, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(const error_code& ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
this->derived().post_recv_counter_--;
#endif
this->derived()._handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}));
}
template<typename C>
inline void _handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
set_last_error(ec);
if (!this->derived().is_started())
{
if (this->derived().state() == state_t::started)
{
this->derived()._do_stop(ec, std::move(this_ptr));
}
return;
}
if (ec == asio::error::operation_aborted)
{
this->derived()._do_stop(ec, std::move(this_ptr));
return;
}
this->buffer_.commit(bytes_recvd);
if (!ec)
{
std::string_view data = std::string_view(static_cast<std::string_view::const_pointer>
(this->buffer_.data().data()), bytes_recvd);
// first we find whether the session is in the session_mgr pool already,if not ,
// we new a session and put it into the session_mgr pool
std::shared_ptr<session_t> session_ptr = this->sessions_.find(this->remote_endpoint_);
if (!session_ptr)
{
this->derived()._handle_accept(ec, data, session_ptr, ecs);
}
else
{
session_ptr->_handle_recv(ec, bytes_recvd, session_ptr, ecs);
}
}
else
{
#ifndef ASIO2_DISABLE_STOP_SESSION_WHEN_RECVD_0BYTES
// has error, and bytes_recvd == 0
if (bytes_recvd == 0)
{
std::shared_ptr<session_t> session_ptr = this->sessions_.find(this->remote_endpoint_);
if (session_ptr)
{
session_ptr->stop();
}
}
#endif
}
this->buffer_.consume(this->buffer_.size());
if (bytes_recvd == this->buffer_.pre_size())
{
this->buffer_.pre_size((std::min)(this->buffer_.pre_size() * 2, this->buffer_.max_size()));
}
this->derived()._post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename... Args>
inline std::shared_ptr<session_t> _make_session(Args&&... args)
{
return std::make_shared<session_t>(
std::forward<Args>(args)...,
this->sessions_,
this->listener_,
this->io_,
this->buffer_.pre_size(),
this->buffer_.max_size(),
this->buffer_,
this->acceptor_,
this->remote_endpoint_);
}
template<typename C>
inline void _handle_accept(
const error_code& ec, std::string_view first_data,
std::shared_ptr<session_t> session_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
session_ptr = this->derived()._make_session();
session_ptr->counter_ptr_ = this->counter_ptr_;
session_ptr->first_data_ = std::make_unique<std::string>(first_data);
session_ptr->kcp_conv_ = this->derived()._make_kcp_conv(first_data, ecs);
session_ptr->start(detail::to_shared_ptr(ecs->clone()));
}
template<typename C>
inline std::uint32_t _do_make_kcp_conv(std::string_view first_data, std::shared_ptr<ecs_t<C>>& ecs)
{
detail::ignore_unused(ecs);
std::uint32_t conv = 0;
if (kcp::is_kcphdr_syn(first_data))
{
kcp::kcphdr syn = kcp::to_kcphdr(first_data);
// the syn.th_ack is the kcp conv
if (syn.th_ack == 0)
{
conv = this->kcp_convs_.fetch_add(1);
if (conv == 0)
conv = this->kcp_convs_.fetch_add(1);
}
else
{
conv = syn.th_ack;
}
}
return conv;
}
template<typename C>
inline std::uint32_t _make_kcp_conv(std::string_view first_data, std::shared_ptr<ecs_t<C>>& ecs)
{
if constexpr (std::is_same_v<typename ecs_t<C>::condition_lowest_type, use_kcp_t>)
{
return this->_do_make_kcp_conv(first_data, ecs);
}
else
{
detail::ignore_unused(first_data, ecs);
return 0;
}
}
inline void _fire_init()
{
// the _fire_init must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(!get_last_error());
this->listener_.notify(event_type::init);
}
inline void _fire_start()
{
// the _fire_start must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_stop_called_ == false);
#endif
this->listener_.notify(event_type::start);
}
inline void _fire_stop()
{
// the _fire_stop must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_called_ = true;
#endif
this->listener_.notify(event_type::stop);
}
protected:
/// acceptor to accept client connection
asio::ip::udp::socket acceptor_;
/// endpoint for udp
asio::ip::udp::endpoint remote_endpoint_;
/// buffer
asio2::buffer_wrap<asio2::linear_buffer> buffer_;
std::atomic<std::uint32_t> kcp_convs_ = 1;
#if defined(_DEBUG) || defined(DEBUG)
bool is_stop_called_ = false;
#endif
};
}
namespace asio2
{
template<class derived_t, class session_t>
using udp_server_impl_t = detail::udp_server_impl_t<derived_t, session_t>;
/**
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
template<class session_t>
class udp_server_t : public detail::udp_server_impl_t<udp_server_t<session_t>, session_t>
{
public:
using detail::udp_server_impl_t<udp_server_t<session_t>, session_t>::udp_server_impl_t;
};
/**
* If this object is created as a shared_ptr like std::shared_ptr<asio2::udp_server> server;
* you must call the server->stop() manual when exit, otherwise maybe cause memory leaks.
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
using udp_server = udp_server_t<udp_session>;
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_UDP_SERVER_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RPC_SERVER_HPP__
#define __ASIO2_RPC_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if __has_include(<cereal/cereal.hpp>)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/config.hpp>
#include <asio2/udp/udp_server.hpp>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/tcp/tcps_server.hpp>
#include <asio2/http/ws_server.hpp>
#include <asio2/http/wss_server.hpp>
#include <asio2/rpc/rpc_session.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
template<class derived_t, class executor_t>
class rpc_server_impl_t
: public executor_t
, public rpc_invoker_t<typename executor_t::session_type, typename executor_t::session_type::args_type>
{
friend executor_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
public:
using super = executor_t;
using self = rpc_server_impl_t<derived_t, executor_t>;
using executor_type = executor_t;
using session_type = typename super::session_type;
protected:
using super::async_send;
public:
/**
* @brief constructor
*/
template<class ...Args>
explicit rpc_server_impl_t(
Args&&... args
)
: super(std::forward<Args>(args)...)
, rpc_invoker_t<typename executor_t::session_type, typename executor_t::session_type::args_type>()
{
}
/**
* @brief destructor
*/
~rpc_server_impl_t()
{
this->stop();
}
/**
* @brief start the server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param service - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& service, Args&&... args)
{
if constexpr (is_websocket_server<executor_t>::value)
{
return executor_t::template start(
std::forward<String>(host), std::forward<StrOrInt>(service),
std::forward<Args>(args)...);
}
else if constexpr (session_type::net_protocol == asio2::net_protocol::udp)
{
return executor_t::template start(
std::forward<String>(host), std::forward<StrOrInt>(service),
asio2::use_kcp, std::forward<Args>(args)...);
}
else
{
return executor_t::template start(
std::forward<String>(host), std::forward<StrOrInt>(service),
asio2::use_dgram, std::forward<Args>(args)...);
}
}
public:
/**
* @brief call a rpc function for each session
*/
template<class return_t, class Rep, class Period, class ...Args>
inline void call(std::chrono::duration<Rep, Period> timeout, const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template call<return_t>(timeout, name, args...);
});
}
/**
* @brief call a rpc function for each session
*/
template<class return_t, class ...Args>
inline void call(const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template call<return_t>(name, args...);
});
}
/**
* @brief asynchronous call a rpc function for each session
* Callback signature : void(return_t result)
* if result type is void, the Callback signature is : void()
* Because the result value type is not specified in the first template parameter,
* so the result value type must be specified in the Callback lambda.
*/
template<class Callback, class ...Args>
inline typename std::enable_if_t<is_callable_v<Callback>, void>
async_call(const Callback& fn, const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->async_call(fn, name, args...);
});
}
/**
* @brief asynchronous call a rpc function for each session
* Callback signature : void(return_t result)
* if result type is void, the Callback signature is : void()
* Because the result value type is not specified in the first template parameter,
* so the result value type must be specified in the Callback lambda
*/
template<class Callback, class Rep, class Period, class ...Args>
inline typename std::enable_if_t<is_callable_v<Callback>, void>
async_call(const Callback& fn, std::chrono::duration<Rep, Period> timeout,
const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->async_call(fn, timeout, name, args...);
});
}
/**
* @brief asynchronous call a rpc function for each session
* Callback signature : void(return_t result) the return_t
* is the first template parameter.
* if result type is void, the Callback signature is : void()
*/
template<class return_t, class Callback, class ...Args>
inline void async_call(const Callback& fn, const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template async_call<return_t>(fn, name, args...);
});
}
/**
* @brief asynchronous call a rpc function for each session
* Callback signature : void(return_t result) the return_t
* is the first template parameter.
* if result type is void, the Callback signature is : void()
*/
template<class return_t, class Callback, class Rep, class Period, class ...Args>
inline void async_call(const Callback& fn, std::chrono::duration<Rep, Period> timeout,
const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template async_call<return_t>(fn, timeout, name, args...);
});
}
/**
* @brief asynchronous call a rpc function for each session
* Don't care whether the call succeeds
*/
template<class ...Args>
inline void async_call(const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->async_call(name, args...);
});
}
protected:
template<typename... Args>
inline std::shared_ptr<session_type> _make_session(Args&&... args)
{
return super::_make_session(std::forward<Args>(args)..., *this);
}
protected:
};
}
namespace asio2
{
template<class derived_t, class session_t, asio2::net_protocol np = session_t::net_protocol>
class rpc_server_impl_t;
template<class derived_t, class session_t>
class rpc_server_impl_t<derived_t, session_t, asio2::net_protocol::udp>
: public detail::rpc_server_impl_t<derived_t, detail::udp_server_impl_t<derived_t, session_t>>
{
public:
using detail::rpc_server_impl_t<derived_t, detail::udp_server_impl_t<derived_t, session_t>>::
rpc_server_impl_t;
};
template<class derived_t, class session_t>
class rpc_server_impl_t<derived_t, session_t, asio2::net_protocol::tcp>
: public detail::rpc_server_impl_t<derived_t, detail::tcp_server_impl_t<derived_t, session_t>>
{
public:
using detail::rpc_server_impl_t<derived_t, detail::tcp_server_impl_t<derived_t, session_t>>::
rpc_server_impl_t;
};
template<class derived_t, class session_t>
class rpc_server_impl_t<derived_t, session_t, asio2::net_protocol::ws>
: public detail::rpc_server_impl_t<derived_t, detail::ws_server_impl_t<derived_t, session_t>>
{
public:
using detail::rpc_server_impl_t<derived_t, detail::ws_server_impl_t<derived_t, session_t>>::
rpc_server_impl_t;
};
template<class session_t>
class rpc_server_t : public rpc_server_impl_t<rpc_server_t<session_t>, session_t>
{
public:
using rpc_server_impl_t<rpc_server_t<session_t>, session_t>::rpc_server_impl_t;
};
template<asio2::net_protocol np>
class rpc_server_use : public rpc_server_t<rpc_session_use<np>>
{
public:
using rpc_server_t<rpc_session_use<np>>::rpc_server_t;
};
using rpc_kcp_server = rpc_server_use<asio2::net_protocol::udp>;
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpc_server = rpc_server_use<asio2::net_protocol::tcp>;
#else
/// Using websocket as the underlying communication support
using rpc_server = rpc_server_use<asio2::net_protocol::ws>;
#endif
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
template<class derived_t, class session_t, asio2::net_protocol np = session_t::net_protocol>
class rpc_rate_server_impl_t;
template<class derived_t, class session_t>
class rpc_rate_server_impl_t<derived_t, session_t, asio2::net_protocol::tcp>
: public detail::rpc_server_impl_t<derived_t, detail::tcp_server_impl_t<derived_t, session_t>>
{
public:
using detail::rpc_server_impl_t<derived_t, detail::tcp_server_impl_t<derived_t, session_t>>::
rpc_server_impl_t;
};
template<class derived_t, class session_t>
class rpc_rate_server_impl_t<derived_t, session_t, asio2::net_protocol::ws>
: public detail::rpc_server_impl_t<derived_t, detail::ws_server_impl_t<derived_t, session_t>>
{
public:
using detail::rpc_server_impl_t<derived_t, detail::ws_server_impl_t<derived_t, session_t>>::
rpc_server_impl_t;
};
template<class session_t>
class rpc_rate_server_t : public rpc_rate_server_impl_t<rpc_rate_server_t<session_t>, session_t>
{
public:
using rpc_rate_server_impl_t<rpc_rate_server_t<session_t>, session_t>::rpc_rate_server_impl_t;
};
template<asio2::net_protocol np>
class rpc_rate_server_use : public rpc_rate_server_t<rpc_rate_session_use<np>>
{
public:
using rpc_rate_server_t<rpc_rate_session_use<np>>::rpc_rate_server_t;
};
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpc_rate_server = rpc_rate_server_use<asio2::net_protocol::tcp>;
#else
/// Using websocket as the underlying communication support
using rpc_rate_server = rpc_rate_server_use<asio2::net_protocol::ws>;
#endif
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif
#endif // !__ASIO2_RPC_SERVER_HPP__
<file_sep>/*
Copyright <NAME> 2011-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_VMS_H
#define BHO_PREDEF_OS_VMS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_VMS`
http://en.wikipedia.org/wiki/Vms[VMS] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `VMS` | {predef_detection}
| `+__VMS+` | {predef_detection}
| `+__VMS_VER+` | V.R.P
|===
*/ // end::reference[]
#define BHO_OS_VMS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(VMS) || defined(__VMS) \
)
# undef BHO_OS_VMS
# if defined(__VMS_VER)
# define BHO_OS_VMS BHO_PREDEF_MAKE_10_VVRR00PP00(__VMS_VER)
# else
# define BHO_OS_VMS BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_OS_VMS
# define BHO_OS_VMS_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_VMS_NAME "VMS"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_VMS,BHO_OS_VMS_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_PLAT_MINGW_H
#define BHO_PREDEF_PLAT_MINGW_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_PLAT_MINGW`
http://en.wikipedia.org/wiki/MinGW[MinGW] platform, either variety.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__MINGW32__+` | {predef_detection}
| `+__MINGW64__+` | {predef_detection}
| `+__MINGW64_VERSION_MAJOR+`, `+__MINGW64_VERSION_MINOR+` | V.R.0
| `+__MINGW32_VERSION_MAJOR+`, `+__MINGW32_VERSION_MINOR+` | V.R.0
|===
*/ // end::reference[]
#define BHO_PLAT_MINGW BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__MINGW32__) || defined(__MINGW64__)
# include <_mingw.h>
# if !defined(BHO_PLAT_MINGW_DETECTION) && (defined(__MINGW64_VERSION_MAJOR) && defined(__MINGW64_VERSION_MINOR))
# define BHO_PLAT_MINGW_DETECTION \
BHO_VERSION_NUMBER(__MINGW64_VERSION_MAJOR,__MINGW64_VERSION_MINOR,0)
# endif
# if !defined(BHO_PLAT_MINGW_DETECTION) && (defined(__MINGW32_VERSION_MAJOR) && defined(__MINGW32_VERSION_MINOR))
# define BHO_PLAT_MINGW_DETECTION \
BHO_VERSION_NUMBER(__MINGW32_MAJOR_VERSION,__MINGW32_MINOR_VERSION,0)
# endif
# if !defined(BHO_PLAT_MINGW_DETECTION)
# define BHO_PLAT_MINGW_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_PLAT_MINGW_DETECTION
# define BHO_PLAT_MINGW_AVAILABLE
# if defined(BHO_PREDEF_DETAIL_PLAT_DETECTED)
# define BHO_PLAT_MINGW_EMULATED BHO_PLAT_MINGW_DETECTION
# else
# undef BHO_PLAT_MINGW
# define BHO_PLAT_MINGW BHO_PLAT_MINGW_DETECTION
# endif
# include <asio2/bho/predef/detail/platform_detected.h>
#endif
#define BHO_PLAT_MINGW_NAME "MinGW (any variety)"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_MINGW,BHO_PLAT_MINGW_NAME)
#ifdef BHO_PLAT_MINGW_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_MINGW_EMULATED,BHO_PLAT_MINGW_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_AOP_UNSUBACK_HPP__
#define __ASIO2_MQTT_AOP_UNSUBACK_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class caller_t, class args_t>
class mqtt_aop_unsuback
{
friend caller_t;
protected:
// must be server
template<class Message, bool IsClient = args_t::is_client>
inline std::enable_if_t<!IsClient, void>
_after_unsuback_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
ASIO2_ASSERT(false && "server should't recv the unsuback message");
// if server recvd unsuback message, disconnect
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
}
template<class Message, bool IsClient = args_t::is_client>
inline std::enable_if_t<IsClient, void>
_after_unsuback_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using key_type = std::pair<mqtt::control_packet_type, mqtt::two_byte_integer::value_type>;
key_type key{ mqtt::control_packet_type::unsubscribe, msg.packet_id() };
if (auto it = caller->unsubscribed_topics_.find(key); it != caller->unsubscribed_topics_.end())
{
mqtt::utf8_string_set& topics = it->second;
topics.for_each([caller](mqtt::utf8_string& topic) mutable
{
caller->subs_map().erase(topic, "");
});
caller->unsubscribed_topics_.erase(it);
}
}
// must be client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::unsuback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
// must be client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::unsuback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
// must be client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::unsuback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::unsuback& msg)
{
if (_after_unsuback_callback(ec, caller_ptr, caller, om, msg); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::unsuback& msg)
{
if (_after_unsuback_callback(ec, caller_ptr, caller, om, msg); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::unsuback& msg)
{
if (_after_unsuback_callback(ec, caller_ptr, caller, om, msg); ec)
return;
}
};
}
#endif // !__ASIO2_MQTT_AOP_UNSUBACK_HPP__
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// cygwin specific config options:
#define BHO_PLATFORM "Cygwin"
#define BHO_HAS_DIRENT_H
#define BHO_HAS_LOG1P
#define BHO_HAS_EXPM1
//
// Threading API:
// See if we have POSIX threads, if we do use them, otherwise
// revert to native Win threads.
#define BHO_HAS_UNISTD_H
#include <unistd.h>
#if defined(_POSIX_THREADS) && (_POSIX_THREADS+0 >= 0) && !defined(BHO_HAS_WINTHREADS)
# define BHO_HAS_PTHREADS
# define BHO_HAS_SCHED_YIELD
# define BHO_HAS_GETTIMEOFDAY
# define BHO_HAS_PTHREAD_MUTEXATTR_SETTYPE
//# define BHO_HAS_SIGACTION
#else
# if !defined(BHO_HAS_WINTHREADS)
# define BHO_HAS_WINTHREADS
# endif
# define BHO_HAS_FTIME
#endif
//
// find out if we have a stdint.h, there should be a better way to do this:
//
#include <sys/types.h>
#ifdef _STDINT_H
#define BHO_HAS_STDINT_H
#endif
#if __GNUC__ > 5 && !defined(BHO_HAS_STDINT_H)
# define BHO_HAS_STDINT_H
#endif
#include <cygwin/version.h>
#if (CYGWIN_VERSION_API_MAJOR == 0 && CYGWIN_VERSION_API_MINOR < 231)
/// Cygwin has no fenv.h
#define BHO_NO_FENV_H
#endif
// Cygwin has it's own <pthread.h> which breaks <shared_mutex> unless the correct compiler flags are used:
#ifndef BHO_NO_CXX14_HDR_SHARED_MUTEX
#include <pthread.h>
#if !(__XSI_VISIBLE >= 500 || __POSIX_VISIBLE >= 200112)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#endif
// boilerplate code:
#include <asio2/bho/config/detail/posix_features.hpp>
//
// Cygwin lies about XSI conformance, there is no nl_types.h:
//
#ifdef BHO_HAS_NL_TYPES_H
# undef BHO_HAS_NL_TYPES_H
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_DATA_PERSISTENCE_COMPONENT_HPP__
#define __ASIO2_DATA_PERSISTENCE_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <utility>
#include <string>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class data_persistence_cp
{
public:
/**
* @brief constructor
*/
data_persistence_cp() = default;
/**
* @brief destructor
*/
~data_persistence_cp() = default;
protected:
/**
* @brief Pre process the data before send it.
* You can overload this function in a derived class to implement additional
* processing of the data. eg: encrypt data with a custom encryption algorithm.
*/
template<class T>
inline auto data_filter_before_send(T&& data)
{
return std::forward<T>(data);
}
protected:
template<class T>
inline auto _data_persistence(T&& data)
{
using data_type = detail::remove_cvref_t<T>;
derived_t& derive = static_cast<derived_t&>(*this);
// std::string_view
if constexpr /**/ (detail::is_string_view_v<data_type>)
{
using value_type = typename data_type::value_type;
return derive.data_filter_before_send(std::basic_string<value_type>(data.data(), data.size()));
}
// char* , const char* , const char* const
else if constexpr (detail::is_char_pointer_v<data_type>)
{
using value_type = typename detail::remove_cvref_t<std::remove_pointer_t<data_type>>;
return derive.data_filter_before_send(std::basic_string<value_type>(std::forward<T>(data)));
}
// char[]
else if constexpr (detail::is_char_array_v<data_type>)
{
using value_type = typename detail::remove_cvref_t<std::remove_all_extents_t<data_type>>;
return derive.data_filter_before_send(std::basic_string<value_type>(std::forward<T>(data)));
}
// object like : std::string, std::vector
else if constexpr (
std::is_move_constructible_v <data_type> ||
std::is_trivially_move_constructible_v<data_type> ||
std::is_nothrow_move_constructible_v <data_type> ||
std::is_move_assignable_v <data_type> ||
std::is_trivially_move_assignable_v <data_type> ||
std::is_nothrow_move_assignable_v <data_type> )
{
return derive.data_filter_before_send(std::forward<T>(data));
}
else
{
// PodType (&data)[N] like : int buf[5], double buf[5]
auto buffer = asio::buffer(data);
return derive.data_filter_before_send(std::string(reinterpret_cast<const std::string::value_type*>(
const_cast<const void*>(buffer.data())), buffer.size()));
}
}
template<class CharT, class SizeT>
inline auto _data_persistence(CharT * s, SizeT count)
{
using value_type = typename detail::remove_cvref_t<CharT>;
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(std::basic_string<value_type>(s, count));
}
template<typename = void>
inline auto _data_persistence(asio::const_buffer& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(data)));
}
template<typename = void>
inline auto _data_persistence(const asio::const_buffer& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(data)));
}
template<typename = void>
inline auto _data_persistence(asio::const_buffer&& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
// "data" is rvalue reference, should use std::move()
return derive.data_filter_before_send(std::move(data));
}
template<typename = void>
inline auto _data_persistence(asio::mutable_buffer& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(data)));
}
template<typename = void>
inline auto _data_persistence(const asio::mutable_buffer& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(data)));
}
template<typename = void>
inline auto _data_persistence(asio::mutable_buffer&& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(std::move(data))));
}
#if !defined(ASIO_NO_DEPRECATED) && !defined(BOOST_ASIO_NO_DEPRECATED)
template<typename = void>
inline auto _data_persistence(asio::const_buffers_1& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(data)));
}
template<typename = void>
inline auto _data_persistence(const asio::const_buffers_1& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(data)));
}
template<typename = void>
inline auto _data_persistence(asio::const_buffers_1&& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(std::move(data))));
}
template<typename = void>
inline auto _data_persistence(asio::mutable_buffers_1& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(data)));
}
template<typename = void>
inline auto _data_persistence(const asio::mutable_buffers_1& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(data)));
}
template<typename = void>
inline auto _data_persistence(asio::mutable_buffers_1&& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.data_filter_before_send(derive._data_persistence(asio::const_buffer(std::move(data))));
}
#endif
protected:
};
}
#endif // !__ASIO2_DATA_PERSISTENCE_COMPONENT_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_EVENT_QUEUE_COMPONENT_HPP__
#define __ASIO2_EVENT_QUEUE_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <functional>
#include <string>
#include <future>
#include <queue>
#include <tuple>
#include <utility>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/base/detail/function.hpp>
namespace asio2::detail
{
template <class, class> class event_queue_cp;
template <class... > class defer_event;
template<class derived_t>
class event_queue_guard
{
template <class, class> friend class event_queue_cp;
template <class... > friend class defer_event;
public:
explicit event_queue_guard() noexcept
{
}
explicit event_queue_guard(std::nullptr_t) noexcept
{
}
protected:
// the valid guard can only be created by event_queue_cp
explicit event_queue_guard(derived_t& d) noexcept
: derive(std::addressof(d)), derive_ptr_(d.selfptr()), valid_(true)
{
}
public:
inline event_queue_guard(event_queue_guard&& o) noexcept
: derive(o.derive), derive_ptr_(std::move(o.derive_ptr_)), valid_(o.valid_)
{
o.valid_ = false;
}
event_queue_guard(const event_queue_guard&) = delete;
event_queue_guard& operator=(const event_queue_guard&) = delete;
event_queue_guard& operator=(event_queue_guard&&) = delete;
~event_queue_guard() noexcept
{
if (this->valid_)
{
derive->next_event(std::move(*this));
ASIO2_ASSERT(this->valid_ == false);
}
}
inline bool empty() const noexcept { return (!valid_); }
inline bool is_empty() const noexcept { return (!valid_); }
protected:
derived_t * derive = nullptr;
// must hold the derived object, maybe empty in client
// if didn't hold the derived object, when the callback is executed in the event queue,
// the derived object which holded by the callback maybe destroyed by std::move(), when
// event_queue_guard is destroyed, and will call derive.next_event; the "derive" maybe
// invalid already.
std::shared_ptr<derived_t> derive_ptr_;
// whether the guard is valid, when object is moved by std::move the guard will be invalid
bool valid_ = false;
};
template<class Function>
class [[maybe_unused]] defer_event<Function>
{
template <class...> friend class defer_event;
public:
template<class Fn>
defer_event(Fn&& fn) noexcept
: fn_(std::forward<Fn>(fn)), valid_(true)
{
}
inline defer_event(defer_event&& o) noexcept
: fn_(std::move(o.fn_)), valid_(o.valid_)
{
o.valid_ = false;
};
defer_event(const defer_event&) = delete;
defer_event& operator=(const defer_event&) = delete;
defer_event& operator=(defer_event&&) = delete;
~defer_event() noexcept
{
if (valid_)
{
valid_ = false;
(fn_)();
}
}
inline bool empty() const noexcept { return (!valid_); }
inline bool is_empty() const noexcept { return (!valid_); }
inline constexpr bool is_event_queue_guard_empty() const noexcept { return true; }
protected:
Function fn_;
bool valid_ = false;
};
template<>
class [[maybe_unused]] defer_event<void>
{
template <class...> friend class defer_event;
public:
defer_event() noexcept {}
defer_event(std::nullptr_t) noexcept {}
defer_event(defer_event&&) noexcept = default;
defer_event& operator=(defer_event&&) noexcept = default;
defer_event(const defer_event&) = delete;
defer_event& operator=(const defer_event&) = delete;
inline constexpr bool empty() const noexcept { return true; }
inline constexpr bool is_empty() const noexcept { return true; }
inline constexpr bool is_event_queue_guard_empty() const noexcept { return true; }
};
// defer event with event queue guard dummy
template<class derived_t>
struct defer_eqg_dummy
{
inline void operator()(event_queue_guard<derived_t>) {}
};
template<class Function, class derived_t>
class [[maybe_unused]] defer_event<Function, derived_t, std::false_type>
{
template <class...> friend class defer_event;
public:
template<class Fn>
defer_event(Fn&& fn, std::nullptr_t) noexcept
: fn_(std::forward<Fn>(fn))
, valid_(true)
{
}
inline defer_event(defer_event&& o) noexcept
: fn_(std::move(o.fn_)), valid_(o.valid_)
{
o.valid_ = false;
};
defer_event(const defer_event&) = delete;
defer_event& operator=(const defer_event&) = delete;
defer_event& operator=(defer_event&&) = delete;
~defer_event() noexcept
{
if (valid_)
{
valid_ = false;
(fn_)(event_queue_guard<derived_t>());
}
}
inline bool empty() const noexcept { return (!valid_); }
inline bool is_empty() const noexcept { return (!valid_); }
inline constexpr bool is_event_queue_guard_empty() const noexcept { return true; }
inline defer_event<Function, derived_t, std::false_type> move_event() noexcept
{
return std::move(*this);
}
inline event_queue_guard<derived_t> move_guard() noexcept
{
return event_queue_guard<derived_t>();
}
protected:
Function fn_;
bool valid_ = false;
};
template<class Function, class derived_t>
class [[maybe_unused]] defer_event<Function, derived_t, std::true_type>
{
template <class...> friend class defer_event;
public:
template<class Fn, class D = derived_t>
defer_event(Fn&& fn, event_queue_guard<D> guard) noexcept
: fn_(std::forward<Fn>(fn))
, valid_(true)
, guard_(std::move(guard))
{
}
template<class Fn, class D = derived_t>
defer_event(defer_event<Fn, D, std::false_type> o, event_queue_guard<D> guard) noexcept
: fn_ (std::move(o.fn_ ))
, valid_( o.valid_ )
, guard_(std::move(guard ))
{
o.valid_ = false;
}
inline defer_event(defer_event&& o) noexcept
: fn_(std::move(o.fn_)), valid_(o.valid_), guard_(std::move(o.guard_))
{
o.valid_ = false;
};
defer_event(const defer_event&) = delete;
defer_event& operator=(const defer_event&) = delete;
defer_event& operator=(defer_event&&) = delete;
~defer_event() noexcept
{
if (valid_)
{
valid_ = false;
(fn_)(std::move(guard_));
}
// guard will be destroy at here, then guard's destroctor will be called
}
inline bool empty() const noexcept { return (!valid_); }
inline bool is_empty() const noexcept { return (!valid_); }
inline bool is_event_queue_guard_empty() const noexcept { return guard_.empty(); }
inline defer_event<Function, derived_t, std::false_type> move_event() noexcept
{
defer_event<Function, derived_t, std::false_type> evt(std::move(fn_), nullptr);
evt.valid_ = this->valid_;
this->valid_ = false;
return evt;
}
inline event_queue_guard<derived_t> move_guard() noexcept
{
return std::move(guard_);
}
protected:
Function fn_;
bool valid_ = false;
event_queue_guard<derived_t> guard_;
};
template<class derived_t>
class [[maybe_unused]] defer_event<void, derived_t>
{
template <class...> friend class defer_event;
public:
defer_event() noexcept
{
}
template<class D = derived_t>
defer_event(event_queue_guard<D> guard) noexcept
: guard_(std::move(guard))
{
}
defer_event(defer_event&& o) noexcept = default;
defer_event(const defer_event&) = delete;
defer_event& operator=(const defer_event&) = delete;
defer_event& operator=(defer_event&&) = delete;
~defer_event() noexcept
{
// guard will be destroy at here, then guard's destroctor will be called
}
inline constexpr bool empty() const noexcept { return true; }
inline constexpr bool is_empty() const noexcept { return true; }
inline bool is_event_queue_guard_empty() const noexcept { return guard_.empty(); }
inline defer_event<defer_eqg_dummy<derived_t>, derived_t, std::false_type> move_event() noexcept
{
defer_event<defer_eqg_dummy<derived_t>, derived_t, std::false_type> evt(
defer_eqg_dummy<derived_t>{}, nullptr);
evt.valid_ = false;
return evt;
}
inline event_queue_guard<derived_t> move_guard() noexcept
{
return std::move(guard_);
}
protected:
event_queue_guard<derived_t> guard_;
};
template<class F>
defer_event(F)->defer_event<F>;
defer_event(std::nullptr_t)->defer_event<void>;
template<class F, class derived_t>
defer_event(F, event_queue_guard<derived_t>)->defer_event<F, derived_t, std::true_type>;
template<class F, class derived_t>
defer_event(defer_event<F, derived_t, std::false_type>, event_queue_guard<derived_t>)->
defer_event<F, derived_t, std::true_type>;
// This will cause error "non-deducible template parameter 'derived_t'" on macos clion
//template<class F, class derived_t>
//defer_event(F, std::nullptr_t)->defer_event<F, derived_t, std::false_type>;
// This will cause error "non-deducible template parameter 'derived_t'" on macos clion
//template<class derived_t>
//defer_event()->defer_event<void, derived_t>;
template<class derived_t>
defer_event(event_queue_guard<derived_t>)->defer_event<void, derived_t>;
template<class derived_t, class args_t = void>
class event_queue_cp
{
public:
/**
* @brief constructor
*/
event_queue_cp() noexcept {}
/**
* @brief destructor
*/
~event_queue_cp() = default;
/**
* @brief Get pending event count in the event queue.
*/
inline std::size_t get_pending_event_count() const noexcept
{
return this->events_.size();
}
/**
* post a task to the tail of the event queue
* Callback signature : void()
*/
template<class Callback>
inline derived_t& post_queued_event(Callback&& f)
{
using return_type = std::invoke_result_t<Callback>;
derived_t& derive = static_cast<derived_t&>(*this);
std::packaged_task<return_type()> task(std::forward<Callback>(f));
auto fn = [p = derive.selfptr(), t = std::move(task)](event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(p, g);
t();
};
// Make sure we run on the io_context thread
// beacuse the callback "f" hold the derived_ptr already,
// so this callback for asio::dispatch don't need hold the derived_ptr again.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, fn = std::move(fn)]() mutable
{
ASIO2_ASSERT(this->events_.size() < std::size_t(32767));
bool empty = this->events_.empty();
this->events_.emplace(std::move(fn));
if (empty)
{
(this->events_.front())(event_queue_guard<derived_t>{static_cast<derived_t&>(*this)});
}
}));
return (derive);
}
/**
* post a task to the tail of the event queue
* Callback signature : void()
*/
template<class Callback, typename Allocator>
inline auto post_queued_event(Callback&& f, asio::use_future_t<Allocator>) ->
std::future<std::invoke_result_t<Callback>>
{
using return_type = std::invoke_result_t<Callback>;
derived_t& derive = static_cast<derived_t&>(*this);
std::packaged_task<return_type()> task(std::forward<Callback>(f));
std::future<return_type> future = task.get_future();
auto fn = [p = derive.selfptr(), t = std::move(task)](event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(p, g);
t();
};
// Make sure we run on the io_context thread
// beacuse the callback "f" hold the derived_ptr already,
// so this callback for asio::dispatch don't need hold the derived_ptr again.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, fn = std::move(fn)]() mutable
{
ASIO2_ASSERT(this->events_.size() < std::size_t(32767));
bool empty = this->events_.empty();
this->events_.emplace(std::move(fn));
if (empty)
{
(this->events_.front())(event_queue_guard<derived_t>{static_cast<derived_t&>(*this)});
}
}));
return future;
}
protected:
/**
* push a task to the tail of the event queue
* Callback signature : void(event_queue_guard<derived_t> g)
* note : the callback must hold the derived_ptr itself
* note : the callback must can't be hold the event_queue_guard, otherwise maybe cause deadlock.
*/
template<class Callback>
inline derived_t& push_event(Callback&& f)
{
derived_t& derive = static_cast<derived_t&>(*this);
// Should we use post to ensure that the task must be executed in the order of push_event?
// If we don't do that, example :
// call push_event in thread main with task1 first, call push_event in thread 0 with task2 second,
// beacuse the task1 is not in the thread 0, so the task1 will be enqueued by asio::dispatch, but
// the task2 is in the thread 0, so the task2 will be enqueued directly, In this case,
// task 2 is before task 1 in the queue
#ifndef ASIO2_STRONG_EVENT_ORDER
// manual dispatch has better performance.
// Make sure we run on the io_context thread
if (derive.io().running_in_this_thread())
{
ASIO2_ASSERT(this->events_.size() < std::size_t(32767));
bool empty = this->events_.empty();
this->events_.emplace(std::forward<Callback>(f));
if (empty)
{
(this->events_.front())(event_queue_guard<derived_t>{derive});
}
return (derive);
}
#endif
// beacuse the callback "f" hold the derived_ptr already,
// so this callback for asio::dispatch don't need hold the derived_ptr again.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, f = std::forward<Callback>(f)]() mutable
{
ASIO2_ASSERT(this->events_.size() < std::size_t(32767));
bool empty = this->events_.empty();
this->events_.emplace(std::move(f));
if (empty)
{
(this->events_.front())(event_queue_guard<derived_t>{static_cast<derived_t&>(*this)});
}
}));
return (derive);
}
/**
* post a task to the tail of the event queue
* Callback signature : void(event_queue_guard<derived_t> g)
* note : the callback must hold the derived_ptr itself
* note : the callback must can't be hold the event_queue_guard, otherwise maybe cause deadlock.
*/
template<class Callback>
inline derived_t& post_event(Callback&& f)
{
derived_t& derive = static_cast<derived_t&>(*this);
// Make sure we run on the io_context thread
// beacuse the callback "f" hold the derived_ptr already,
// so this callback for asio::dispatch don't need hold the derived_ptr again.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, f = std::forward<Callback>(f)]() mutable
{
ASIO2_ASSERT(this->events_.size() < std::size_t(32767));
bool empty = this->events_.empty();
this->events_.emplace(std::move(f));
if (empty)
{
(this->events_.front())(event_queue_guard<derived_t>{static_cast<derived_t&>(*this)});
}
}));
return (derive);
}
/**
* dispatch a task
* if the guard is not valid, the task will pushed to the tail of the event queue(like push_event),
* otherwise the task will be executed directly.
* Callback signature : void(event_queue_guard<derived_t> g)
* note : the callback must hold the derived_ptr itself
* note : the callback must can't be hold the event_queue_guard, otherwise maybe cause deadlock.
*/
template<class Callback>
inline derived_t& disp_event(Callback&& f, event_queue_guard<derived_t> guard)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (guard.is_empty())
{
derive.push_event(std::forward<Callback>(f));
}
else
{
// when some exception occured, disp_event maybe called in the "catch(){ ... }",
// then this maybe not in the io_context thread.
//ASIO2_ASSERT(derive.io().running_in_this_thread());
// beacuse the callback "f" hold the derived_ptr already,
// so this callback for asio::dispatch don't need hold the derived_ptr again.
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[f = std::forward<Callback>(f), guard = std::move(guard)]() mutable
{
f(std::move(guard));
}));
}
return (derive);
}
/**
* Removes an element from the front of the event queue.
* and then execute the next element of the queue.
*/
template<typename = void>
inline derived_t& next_event(event_queue_guard<derived_t> g)
{
derived_t& derive = static_cast<derived_t&>(*this);
// manual dispatch has better performance.
// Make sure we run on the io_context thread
if (derive.io().running_in_this_thread())
{
ASIO2_ASSERT(!g.is_empty());
ASIO2_ASSERT(!this->events_.empty());
if (!this->events_.empty())
{
this->events_.pop();
if (!this->events_.empty())
{
(this->events_.front())(std::move(g));
}
else
{
// must set valid to false, otherwise when g is destroyed, it will enter
// next_event again, this will cause a infinite loop, and cause stack overflow.
g.valid_ = false;
}
}
ASIO2_ASSERT(g.is_empty());
return (derive);
}
// must hold the derived_ptr, beacuse next_event is called by event_queue_guard, when
// event_queue_guard is destroyed, the event queue and event_queue_guard maybe has't
// hold derived object both.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, p = derive.selfptr(), g = std::move(g)]() mutable
{
ASIO2_ASSERT(!g.is_empty());
ASIO2_ASSERT(!this->events_.empty());
if (!this->events_.empty())
{
this->events_.pop();
if (!this->events_.empty())
{
(this->events_.front())(std::move(g));
}
else
{
// must set valid to false, otherwise when g is destroyed, it will enter
// next_event again, this will cause a infinite loop, and cause stack overflow.
g.valid_ = false;
}
}
ASIO2_ASSERT(g.is_empty());
}));
return (derive);
}
protected:
std::queue<detail::function<
void(event_queue_guard<derived_t>), detail::function_size_traits<args_t>::value>> events_;
};
}
#endif // !__ASIO2_EVENT_QUEUE_COMPONENT_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_PALM_H
#define BHO_PREDEF_COMPILER_PALM_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_PALM`
Palm C/{CPP} compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+_PACC_VER+` | {predef_detection}
| `+_PACC_VER+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_PALM BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(_PACC_VER)
# define BHO_COMP_PALM_DETECTION BHO_PREDEF_MAKE_0X_VRRPP000(_PACC_VER)
#endif
#ifdef BHO_COMP_PALM_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_PALM_EMULATED BHO_COMP_PALM_DETECTION
# else
# undef BHO_COMP_PALM
# define BHO_COMP_PALM BHO_COMP_PALM_DETECTION
# endif
# define BHO_COMP_PALM_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_PALM_NAME "Palm C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_PALM,BHO_COMP_PALM_NAME)
#ifdef BHO_COMP_PALM_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_PALM_EMULATED,BHO_COMP_PALM_NAME)
#endif
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2002.
// (C) Copyright <NAME> 2002 - 2003.
// (C) Copyright <NAME> 2003.
// (C) Copyright <NAME> 2006 - 2007.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// HP aCC C++ compiler setup:
#if defined(__EDG__)
#include <asio2/bho/config/compiler/common_edg.hpp>
#endif
#if (__HP_aCC <= 33100)
# define BHO_NO_INTEGRAL_INT64_T
# define BHO_NO_OPERATORS_IN_NAMESPACE
# if !defined(_NAMESPACE_STD)
# define BHO_NO_STD_LOCALE
# define BHO_NO_STRINGSTREAM
# endif
#endif
#if (__HP_aCC <= 33300)
// member templates are sufficiently broken that we disable them for now
# define BHO_NO_MEMBER_TEMPLATES
# define BHO_NO_DEPENDENT_NESTED_DERIVATIONS
# define BHO_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE
#endif
#if (__HP_aCC <= 38000)
# define BHO_NO_TWO_PHASE_NAME_LOOKUP
#endif
#if (__HP_aCC > 50000) && (__HP_aCC < 60000)
# define BHO_NO_UNREACHABLE_RETURN_DETECTION
# define BHO_NO_TEMPLATE_TEMPLATES
# define BHO_NO_SWPRINTF
# define BHO_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS
# define BHO_NO_IS_ABSTRACT
# define BHO_NO_MEMBER_TEMPLATE_FRIENDS
#endif
// optional features rather than defects:
#if (__HP_aCC >= 33900)
# define BHO_HAS_LONG_LONG
# define BHO_HAS_PARTIAL_STD_ALLOCATOR
#endif
#if (__HP_aCC >= 50000 ) && (__HP_aCC <= 53800 ) || (__HP_aCC < 31300 )
# define BHO_NO_MEMBER_TEMPLATE_KEYWORD
#endif
// This macro should not be defined when compiling in strict ansi
// mode, but, currently, we don't have the ability to determine
// what standard mode we are compiling with. Some future version
// of aCC6 compiler will provide predefined macros reflecting the
// compilation options, including the standard mode.
#if (__HP_aCC >= 60000) || ((__HP_aCC > 38000) && defined(__hpxstd98))
# define BHO_NO_TWO_PHASE_NAME_LOOKUP
#endif
#define BHO_COMPILER "HP aCC version " BHO_STRINGIZE(__HP_aCC)
//
// versions check:
// we don't support HP aCC prior to version 33000:
#if __HP_aCC < 33000
# error "Compiler not supported or configured - please reconfigure"
#endif
//
// Extended checks for supporting aCC on PA-RISC
#if __HP_aCC > 30000 && __HP_aCC < 50000
# if __HP_aCC < 38000
// versions prior to version A.03.80 not supported
# error "Compiler version not supported - version A.03.80 or higher is required"
# elif !defined(__hpxstd98)
// must compile using the option +hpxstd98 with version A.03.80 and above
# error "Compiler option '+hpxstd98' is required for proper support"
# endif //PA-RISC
#endif
//
// C++0x features
//
// See boost\config\suffix.hpp for BHO_NO_LONG_LONG
//
#if !defined(__EDG__)
#define BHO_NO_CXX11_AUTO_DECLARATIONS
#define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#define BHO_NO_CXX11_CHAR16_T
#define BHO_NO_CXX11_CHAR32_T
#define BHO_NO_CXX11_CONSTEXPR
#define BHO_NO_CXX11_DECLTYPE
#define BHO_NO_CXX11_DECLTYPE_N3276
#define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#define BHO_NO_CXX11_DELETED_FUNCTIONS
#define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#define BHO_NO_CXX11_EXTERN_TEMPLATE
#define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define BHO_NO_CXX11_HDR_INITIALIZER_LIST
#define BHO_NO_CXX11_LAMBDAS
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_RAW_LITERALS
#define BHO_NO_CXX11_RVALUE_REFERENCES
#define BHO_NO_CXX11_SCOPED_ENUMS
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_CXX11_SFINAE_EXPR
#define BHO_NO_CXX11_STATIC_ASSERT
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_UNICODE_LITERALS
#define BHO_NO_CXX11_VARIADIC_TEMPLATES
#define BHO_NO_CXX11_USER_DEFINED_LITERALS
#define BHO_NO_CXX11_ALIGNAS
#define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#define BHO_NO_CXX11_INLINE_NAMESPACES
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_UNRESTRICTED_UNION
/*
See https://forums13.itrc.hp.com/service/forums/questionanswer.do?threadId=1443331 and
https://forums13.itrc.hp.com/service/forums/questionanswer.do?threadId=1443436
*/
#if (__HP_aCC < 62500) || !defined(HP_CXX0x_SOURCE)
#define BHO_NO_CXX11_VARIADIC_MACROS
#endif
#endif
//
// last known and checked version for HP-UX/ia64 is 61300
// last known and checked version for PA-RISC is 38000
#if ((__HP_aCC > 61300) || ((__HP_aCC > 38000) && defined(__hpxstd98)))
# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown compiler version - please run the configure tests and report the results"
# endif
#endif
<file_sep>#ifndef BHO_CONFIG_HEADER_DEPRECATED_HPP_INCLUDED
#define BHO_CONFIG_HEADER_DEPRECATED_HPP_INCLUDED
// Copyright 2017 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// BHO_HEADER_DEPRECATED("<alternative>")
//
// Expands to the equivalent of
// BHO_PRAGMA_MESSAGE("This header is deprecated. Use <alternative> instead.")
//
// Note that this header is C compatible.
#include <asio2/bho/config/pragma_message.hpp>
#if defined(BHO_ALLOW_DEPRECATED_HEADERS)
# define BHO_HEADER_DEPRECATED(a)
#else
# define BHO_HEADER_DEPRECATED(a) BHO_PRAGMA_MESSAGE("This header is deprecated. Use " a " instead.")
#endif
#endif // BHO_CONFIG_HEADER_DEPRECATED_HPP_INCLUDED
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_UDP_SEND_COMPONENT_HPP__
#define __ASIO2_UDP_SEND_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <functional>
#include <string>
#include <future>
#include <queue>
#include <tuple>
#include <utility>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/base/impl/data_persistence_cp.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
template<class derived_t, class args_t>
class udp_send_cp : public data_persistence_cp<derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
public:
/**
* @brief constructor
*/
udp_send_cp(io_t&) noexcept {}
/**
* @brief destructor
*/
~udp_send_cp() = default;
public:
/**
* @brief Asynchronous send data,supporting multi data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
*/
template<typename String, typename StrOrInt, class DataT>
inline typename std::enable_if_t<!std::is_same_v<detail::remove_cvref_t<String>,
asio::ip::udp::endpoint>, void>
async_send(String&& host, StrOrInt&& port, DataT&& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
derive._data_persistence(std::forward<DataT>(data)),
[](const error_code&, std::size_t) mutable {});
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType * : async_send("abc");
*/
template<typename String, typename StrOrInt, class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<!std::is_same_v<detail::remove_cvref_t<String>,
asio::ip::udp::endpoint> && detail::is_char_v<CharT>, void>
async_send(String&& host, StrOrInt&& port, CharT* s) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.async_send(std::forward<String>(host), std::forward<StrOrInt>(port),
s, s ? Traits::length(s) : 0);
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType (&data)[N] : double m[10]; async_send(m,5);
*/
template<typename String, typename StrOrInt, class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
!std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>, void>
async_send(String&& host, StrOrInt&& port, CharT * s, SizeT count) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
if (!s)
{
set_last_error(asio::error::invalid_argument);
return;
}
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
derive._data_persistence(s, count), [](const error_code&, std::size_t) mutable {});
}
/**
* @brief Asynchronous send data,supporting multi data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
* the pair.first save the send result error_code,the pair.second save the sent_bytes.
* note : Do not call this function in any listener callback function like this:
* auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
* the future.get() will never return.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
*/
template<typename String, typename StrOrInt, class DataT>
inline typename std::enable_if_t<
!std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>,
std::future<std::pair<error_code, std::size_t>>>
async_send(String&& host, StrOrInt&& port, DataT&& data, asio::use_future_t<>)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
std::shared_ptr<std::promise<std::pair<error_code, std::size_t>>> promise =
std::make_shared<std::promise<std::pair<error_code, std::size_t>>>();
std::future<std::pair<error_code, std::size_t>> future = promise->get_future();
derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
derive._data_persistence(std::forward<DataT>(data)),
[promise = std::move(promise)](const error_code& ec, std::size_t bytes_sent) mutable
{
// if multiple addresses is resolved for the host and port, then the promise
// will set_value many times, then will cause exception
try
{
promise->set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
}
catch (std::future_errc const& e)
{
set_last_error(e);
}
});
return future;
}
/**
* @brief Asynchronous send data
* the pair.first save the send result error_code,the pair.second save the sent_bytes.
* note : Do not call this function in any listener callback function like this:
* auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
* the future.get() will never return.
* PodType * : async_send("abc");
*/
template<typename String, typename StrOrInt, class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<
!std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint> && detail::is_char_v<CharT>,
std::future<std::pair<error_code, std::size_t>>>
async_send(String&& host, StrOrInt&& port, CharT * s, asio::use_future_t<> flag)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.async_send(std::forward<String>(host), std::forward<StrOrInt>(port), s,
s ? Traits::length(s) : 0, std::move(flag));
}
/**
* @brief Asynchronous send data
* the pair.first save the send result error_code,the pair.second save the sent_bytes.
* note : Do not call this function in any listener callback function like this:
* auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
* the future.get() will never return.
* PodType (&data)[N] : double m[10]; async_send(m,5);
*/
template<typename String, typename StrOrInt, class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
!std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>,
std::future<std::pair<error_code, std::size_t>>>
async_send(String&& host, StrOrInt&& port, CharT * s, SizeT count, asio::use_future_t<>)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
std::shared_ptr<std::promise<std::pair<error_code, std::size_t>>> promise =
std::make_shared<std::promise<std::pair<error_code, std::size_t>>>();
std::future<std::pair<error_code, std::size_t>> future = promise->get_future();
if (!s)
{
set_last_error(asio::error::invalid_argument);
promise->set_value(std::pair<error_code, std::size_t>(asio::error::invalid_argument, 0));
return future;
}
derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
derive._data_persistence(s, count),
[promise = std::move(promise)](const error_code& ec, std::size_t bytes_sent) mutable
{
// if multiple addresses is resolved for the host and port, then the promise
// will set_value many times, then will cause exception
try
{
promise->set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
}
catch (std::future_errc const& e)
{
set_last_error(e);
}
});
return future;
}
/**
* @brief Asynchronous send data,supporting multi data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
* Callback signature : void() or void(std::size_t bytes_sent)
*/
template<typename String, typename StrOrInt, class DataT, class Callback>
inline typename std::enable_if_t<is_callable_v<Callback> &&
!std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>, void>
async_send(String&& host, StrOrInt&& port, DataT&& data, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
derive._data_persistence(std::forward<DataT>(data)),
[fn = std::forward<Callback>(fn)](const error_code&, std::size_t bytes_sent) mutable
{
callback_helper::call(fn, bytes_sent);
});
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType * : async_send("abc");
* Callback signature : void() or void(std::size_t bytes_sent)
*/
template<typename String, typename StrOrInt, class Callback, class CharT,
class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<is_callable_v<Callback> &&
!std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint> &&
detail::is_char_v<CharT>, void>
async_send(String&& host, StrOrInt&& port, CharT * s, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.async_send(std::forward<String>(host), std::forward<StrOrInt>(port),
s, s ? Traits::length(s) : 0, std::forward<Callback>(fn));
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType (&data)[N] : double m[10]; async_send(m,5);
* Callback signature : void() or void(std::size_t bytes_sent)
*/
template<typename String, typename StrOrInt, class Callback, class CharT, class SizeT>
inline typename std::enable_if_t<is_callable_v<Callback> &&
!std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint> &&
std::is_integral_v<detail::remove_cvref_t<SizeT>>, void>
async_send(String&& host, StrOrInt&& port, CharT * s, SizeT count, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
if (!s)
{
derive._udp_send_cp_invoke_callback(asio::error::invalid_argument, std::forward<Callback>(fn));
return;
}
derive._do_resolve(std::forward<String>(host), std::forward<StrOrInt>(port),
derive._data_persistence(s, count),
[fn = std::forward<Callback>(fn)](const error_code&, std::size_t bytes_sent) mutable
{
callback_helper::call(fn, bytes_sent);
});
}
public:
/**
* @brief Asynchronous send data,supporting multi data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
*/
template<class Endpoint, class DataT>
inline typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, void>
async_send(Endpoint&& endpoint, DataT&& data) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
data = derive._data_persistence(std::forward<DataT>(data))]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
return;
}
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
return;
}
clear_last_error();
derive._do_send(endpoint, data, [g = std::move(g)](const error_code&, std::size_t) mutable {});
});
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType * : async_send("abc");
*/
template<class Endpoint, class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> &&
detail::is_char_v<CharT>, void>
async_send(Endpoint&& endpoint, CharT * s) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.async_send(std::forward<Endpoint>(endpoint), s, s ? Traits::length(s) : 0);
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType (&data)[N] : double m[10]; async_send(m,5);
*/
template<class Endpoint, class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, void>
async_send(Endpoint&& endpoint, CharT * s, SizeT count) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
if (!s)
{
set_last_error(asio::error::invalid_argument);
return;
}
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
data = derive._data_persistence(s, count)]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
return;
}
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
return;
}
clear_last_error();
derive._do_send(endpoint, data, [g = std::move(g)](const error_code&, std::size_t) mutable {});
});
}
/**
* @brief Asynchronous send data,supporting multi data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
* the pair.first save the send result error_code,the pair.second save the sent_bytes.
* note : Do not call this function in any listener callback function like this:
* auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
* the future.get() will never return.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
*/
template<class Endpoint, class DataT>
inline typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>,
std::future<std::pair<error_code, std::size_t>>>
async_send(Endpoint&& endpoint, DataT&& data, asio::use_future_t<>)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
std::shared_ptr<std::promise<std::pair<error_code, std::size_t>>> promise =
std::make_shared<std::promise<std::pair<error_code, std::size_t>>>();
std::future<std::pair<error_code, std::size_t>> future = promise->get_future();
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
data = derive._data_persistence(std::forward<DataT>(data)), promise = std::move(promise)]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
promise->set_value(std::pair<error_code, std::size_t>(asio::error::not_connected, 0));
return;
}
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
promise->set_value(std::pair<error_code, std::size_t>(asio::error::operation_aborted, 0));
return;
}
clear_last_error();
derive._do_send(endpoint, data, [&promise, g = std::move(g)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
promise->set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
});
});
return future;
}
/**
* @brief Asynchronous send data
* the pair.first save the send result error_code,the pair.second save the sent_bytes.
* note : Do not call this function in any listener callback function like this:
* auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
* the future.get() will never return.
* PodType * : async_send("abc");
*/
template<class Endpoint, class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> && detail::is_char_v<CharT>,
std::future<std::pair<error_code, std::size_t>>>
async_send(Endpoint&& endpoint, CharT * s, asio::use_future_t<> flag)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.async_send(std::forward<Endpoint>(endpoint), s,
s ? Traits::length(s) : 0, std::move(flag));
}
/**
* @brief Asynchronous send data
* the pair.first save the send result error_code,the pair.second save the sent_bytes.
* note : Do not call this function in any listener callback function like this:
* auto future = async_send(msg,asio::use_future); future.get(); it will cause deadlock and
* the future.get() will never return.
* PodType (&data)[N] : double m[10]; async_send(m,5);
*/
template<class Endpoint, class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>,
std::future<std::pair<error_code, std::size_t>>>
async_send(Endpoint&& endpoint, CharT * s, SizeT count, asio::use_future_t<>)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
std::shared_ptr<std::promise<std::pair<error_code, std::size_t>>> promise =
std::make_shared<std::promise<std::pair<error_code, std::size_t>>>();
std::future<std::pair<error_code, std::size_t>> future = promise->get_future();
if (!s)
{
set_last_error(asio::error::invalid_argument);
promise->set_value(std::pair<error_code, std::size_t>(asio::error::invalid_argument, 0));
return future;
}
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
data = derive._data_persistence(s, count), promise = std::move(promise)]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
promise->set_value(std::pair<error_code, std::size_t>(asio::error::not_connected, 0));
return;
}
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
promise->set_value(std::pair<error_code, std::size_t>(asio::error::operation_aborted, 0));
return;
}
clear_last_error();
derive._do_send(endpoint, data, [&promise, g = std::move(g)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
promise->set_value(std::pair<error_code, std::size_t>(ec, bytes_sent));
});
});
return future;
}
/**
* @brief Asynchronous send data,supporting multi data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* use like this : std::string m; async_send(std::move(m)); can reducing memory allocation.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
* Callback signature : void() or void(std::size_t bytes_sent)
*/
template<class Endpoint, class DataT, class Callback>
inline typename std::enable_if_t<is_callable_v<Callback> &&
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, void>
async_send(Endpoint&& endpoint, DataT&& data, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
data = derive._data_persistence(std::forward<DataT>(data)), fn = std::forward<Callback>(fn)]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
derive._udp_send_cp_invoke_callback(asio::error::not_connected, std::forward<Callback>(fn));
return;
}
if (id != derive.life_id())
{
derive._udp_send_cp_invoke_callback(asio::error::operation_aborted, std::forward<Callback>(fn));
return;
}
clear_last_error();
derive._do_send(endpoint, data, [&fn, g = std::move(g)]
(const error_code&, std::size_t bytes_sent) mutable
{
callback_helper::call(fn, bytes_sent);
});
});
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType * : async_send("abc");
* Callback signature : void() or void(std::size_t bytes_sent)
*/
template<class Endpoint, class Callback, class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<is_callable_v<Callback> &&
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> &&
detail::is_char_v<CharT>, void>
async_send(Endpoint&& endpoint, CharT * s, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.async_send(std::forward<Endpoint>(endpoint),
s, s ? Traits::length(s) : 0, std::forward<Callback>(fn));
}
/**
* @brief Asynchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType (&data)[N] : double m[10]; async_send(m,5);
* Callback signature : void() or void(std::size_t bytes_sent)
*/
template<class Endpoint, class Callback, class CharT, class SizeT>
inline typename std::enable_if_t<is_callable_v<Callback> &&
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> &&
std::is_integral_v<detail::remove_cvref_t<SizeT>>, void>
async_send(Endpoint&& endpoint, CharT * s, SizeT count, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
detail::integer_add_sub_guard asg(derive.io().pending());
// We must ensure that there is only one operation to send data
// at the same time,otherwise may be cause crash.
if (!s)
{
derive._udp_send_cp_invoke_callback(asio::error::invalid_argument, std::forward<Callback>(fn));
return;
}
derive.push_event(
[&derive, p = derive.selfptr(), id = derive.life_id(), endpoint = std::forward<Endpoint>(endpoint),
data = derive._data_persistence(s, count), fn = std::forward<Callback>(fn)]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
derive._udp_send_cp_invoke_callback(asio::error::not_connected, std::forward<Callback>(fn));
return;
}
if (id != derive.life_id())
{
derive._udp_send_cp_invoke_callback(asio::error::operation_aborted, std::forward<Callback>(fn));
return;
}
clear_last_error();
derive._do_send(endpoint, data, [&fn, g = std::move(g)]
(const error_code&, std::size_t bytes_sent) mutable
{
callback_helper::call(fn, bytes_sent);
});
});
}
public:
/**
* @brief Synchronous send data,supporting multi data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* Note : If this function is called in communication thread, it will degenerates into async_send
* and the return value is 0, you can use asio2::get_last_error() to check whether the
* send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
* means success, otherwise failed.
* use like this : std::string m; send(std::move(m)); can reducing memory allocation.
* PodType * : send("abc");
* PodType (&data)[N] : double m[10]; send(m);
* std::array<PodType, N> : std::array<int,10> m; send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; send(m);
*/
template<typename String, typename StrOrInt, class DataT>
inline typename std::enable_if_t<
!std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>, std::size_t>
send(String&& host, StrOrInt&& port, DataT&& data)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::future<std::pair<error_code, std::size_t>> future = derive.async_send(
std::forward<String>(host), std::forward<StrOrInt>(port),
std::forward<DataT>(data), asio::use_future);
// Whether we run on the io_context thread
if (derive.io().running_in_this_thread())
{
std::future_status status = future.wait_for(std::chrono::nanoseconds(0));
// async_send failed.
if (status == std::future_status::ready)
{
set_last_error(future.get().first);
return std::size_t(0);
}
// async_send success.
else
{
set_last_error(asio::error::in_progress);
return std::size_t(0);
}
}
std::pair<error_code, std::size_t> pair = future.get();
set_last_error(pair.first);
return pair.second;
}
/**
* @brief Synchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* Note : If this function is called in communication thread, it will degenerates into async_send
* and the return value is 0, you can use asio2::get_last_error() to check whether the
* send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
* means success, otherwise failed.
* PodType * : send("abc");
*/
template<typename String, typename StrOrInt, class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<!std::is_same_v<detail::remove_cvref_t<String>,
asio::ip::udp::endpoint> && detail::is_char_v<CharT>, std::size_t>
send(String&& host, StrOrInt&& port, CharT* s)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.send(std::forward<String>(host), std::forward<StrOrInt>(port),
s, s ? Traits::length(s) : 0);
}
/**
* @brief Synchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* Note : If this function is called in communication thread, it will degenerates into async_send
* and the return value is 0, you can use asio2::get_last_error() to check whether the
* send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
* means success, otherwise failed.
* PodType (&data)[N] : double m[10]; send(m,5);
*/
template<typename String, typename StrOrInt, class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
!std::is_same_v<detail::remove_cvref_t<String>, asio::ip::udp::endpoint>, std::size_t>
send(String&& host, StrOrInt&& port, CharT * s, SizeT count)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.send(std::forward<String>(host), std::forward<StrOrInt>(port),
derive._data_persistence(s, count));
}
public:
/**
* @brief Synchronous send data,supporting multi data formats,
* see asio::buffer(...) in /asio/buffer.hpp
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* Note : If this function is called in communication thread, it will degenerates into async_send
* and the return value is 0, you can use asio2::get_last_error() to check whether the
* send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
* means success, otherwise failed.
* use like this : std::string m; send(std::move(m)); can reducing memory allocation.
* PodType * : send("abc");
* PodType (&data)[N] : double m[10]; send(m);
* std::array<PodType, N> : std::array<int,10> m; send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; send(m);
*/
template<class Endpoint, class DataT>
inline typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, std::size_t>
send(Endpoint&& endpoint, DataT&& data)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::future<std::pair<error_code, std::size_t>> future = derive.async_send(
std::forward<Endpoint>(endpoint), std::forward<DataT>(data), asio::use_future);
// Whether we run on the io_context thread
if (derive.io().running_in_this_thread())
{
std::future_status status = future.wait_for(std::chrono::nanoseconds(0));
// async_send failed.
if (status == std::future_status::ready)
{
set_last_error(future.get().first);
return std::size_t(0);
}
// async_send success.
else
{
set_last_error(asio::error::in_progress);
return std::size_t(0);
}
}
std::pair<error_code, std::size_t> pair = future.get();
set_last_error(pair.first);
return pair.second;
}
/**
* @brief Synchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* Note : If this function is called in communication thread, it will degenerates into async_send
* and the return value is 0, you can use asio2::get_last_error() to check whether the
* send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
* means success, otherwise failed.
* PodType * : send("abc");
*/
template<class Endpoint, class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint> &&
detail::is_char_v<CharT>, std::size_t>
send(Endpoint&& endpoint, CharT * s)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.send(std::forward<Endpoint>(endpoint), s, s ? Traits::length(s) : 0);
}
/**
* @brief Synchronous send data
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* Note : If this function is called in communication thread, it will degenerates into async_send
* and the return value is 0, you can use asio2::get_last_error() to check whether the
* send is success, if asio2::get_last_error() is equal to asio::error::in_progress, it
* means success, otherwise failed.
* PodType (&data)[N] : double m[10]; send(m,5);
*/
template<class Endpoint, class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>> &&
std::is_same_v<detail::remove_cvref_t<Endpoint>, asio::ip::udp::endpoint>, std::size_t>
send(Endpoint&& endpoint, CharT * s, SizeT count)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.send(std::forward<Endpoint>(endpoint), derive._data_persistence(s, count));
}
protected:
template<typename String, typename StrOrInt, typename Data, typename Callback>
inline void _do_resolve(String&& host, StrOrInt&& port, Data&& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
using resolver_type = asio::ip::udp::resolver;
using endpoints_type = typename resolver_type::results_type;
//using endpoints_iterator = typename endpoints_type::iterator;
std::unique_ptr<resolver_type> resolver_ptr = std::make_unique<resolver_type>(
derive.io().context());
// Before async_resolve execution is complete, we must hold the resolver object.
// so we captured the resolver_ptr into the lambda callback function.
resolver_type * resolver_pointer = resolver_ptr.get();
resolver_pointer->async_resolve(std::forward<String>(host), detail::to_string(std::forward<StrOrInt>(port)),
[&derive, p = derive.selfptr(), resolver_ptr = std::move(resolver_ptr),
data = std::forward<Data>(data), callback = std::forward<Callback>(callback)]
(const error_code& ec, const endpoints_type& endpoints) mutable
{
set_last_error(ec);
if (ec)
{
callback(ec, 0);
}
else
{
decltype(endpoints.size()) i = 1;
for (auto iter = endpoints.begin(); iter != endpoints.end(); ++iter, ++i)
{
derive.push_event(
[&derive, p, id = derive.life_id(), endpoint = iter->endpoint(),
data = (endpoints.size() == i ? std::move(data) : data),
callback = (endpoints.size() == i ? std::move(callback) : callback)]
(event_queue_guard<derived_t> g) mutable
{
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
callback(asio::error::not_connected, 0);
return;
}
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
callback(asio::error::operation_aborted, 0);
return;
}
clear_last_error();
derive._do_send(endpoint, data, [g = std::move(g), f = std::move(callback)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
f(ec, bytes_sent);
});
});
}
}
});
}
template<class Callback>
inline void _udp_send_cp_invoke_callback(error_code ec, Callback&& fn)
{
derived_t& derive = static_cast<derived_t&>(*this);
set_last_error(ec);
// we should ensure that the callback must be called in the io_context thread.
derive.post([ec, fn = std::forward<Callback>(fn)]() mutable
{
set_last_error(ec);
callback_helper::call(fn, 0);
});
}
};
}
#endif // !__ASIO2_UDP_SEND_COMPONENT_HPP__
<file_sep>/*
Copyright <NAME> 2015
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_HARDWARE_SIMD_X86_VERSIONS_H
#define BHO_PREDEF_HARDWARE_SIMD_X86_VERSIONS_H
#include <asio2/bho/predef/version_number.h>
/* tag::reference[]
= `BHO_HW_SIMD_X86_*_VERSION`
Those defines represent x86 SIMD extensions versions.
NOTE: You *MUST* compare them with the predef `BHO_HW_SIMD_X86`.
*/ // end::reference[]
// ---------------------------------
/* tag::reference[]
= `BHO_HW_SIMD_X86_MMX_VERSION`
The https://en.wikipedia.org/wiki/MMX_(instruction_set)[MMX] x86 extension
version number.
Version number is: *0.99.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_MMX_VERSION BHO_VERSION_NUMBER(0, 99, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_SSE_VERSION`
The https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions[SSE] x86 extension
version number.
Version number is: *1.0.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_SSE_VERSION BHO_VERSION_NUMBER(1, 0, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_SSE2_VERSION`
The https://en.wikipedia.org/wiki/SSE2[SSE2] x86 extension version number.
Version number is: *2.0.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_SSE2_VERSION BHO_VERSION_NUMBER(2, 0, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_SSE3_VERSION`
The https://en.wikipedia.org/wiki/SSE3[SSE3] x86 extension version number.
Version number is: *3.0.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_SSE3_VERSION BHO_VERSION_NUMBER(3, 0, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_SSSE3_VERSION`
The https://en.wikipedia.org/wiki/SSSE3[SSSE3] x86 extension version number.
Version number is: *3.1.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_SSSE3_VERSION BHO_VERSION_NUMBER(3, 1, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_SSE4_1_VERSION`
The https://en.wikipedia.org/wiki/SSE4#SSE4.1[SSE4_1] x86 extension version
number.
Version number is: *4.1.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_SSE4_1_VERSION BHO_VERSION_NUMBER(4, 1, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_SSE4_2_VERSION`
The https://en.wikipedia.org/wiki/SSE4##SSE4.2[SSE4_2] x86 extension version
number.
Version number is: *4.2.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_SSE4_2_VERSION BHO_VERSION_NUMBER(4, 2, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_AVX_VERSION`
The https://en.wikipedia.org/wiki/Advanced_Vector_Extensions[AVX] x86
extension version number.
Version number is: *5.0.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_AVX_VERSION BHO_VERSION_NUMBER(5, 0, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_FMA3_VERSION`
The https://en.wikipedia.org/wiki/FMA_instruction_set[FMA3] x86 extension
version number.
Version number is: *5.2.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_FMA3_VERSION BHO_VERSION_NUMBER(5, 2, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_AVX2_VERSION`
The https://en.wikipedia.org/wiki/Advanced_Vector_Extensions#Advanced_Vector_Extensions_2[AVX2]
x86 extension version number.
Version number is: *5.3.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_AVX2_VERSION BHO_VERSION_NUMBER(5, 3, 0)
/* tag::reference[]
= `BHO_HW_SIMD_X86_MIC_VERSION`
The https://en.wikipedia.org/wiki/Xeon_Phi[MIC] (Xeon Phi) x86 extension
version number.
Version number is: *9.0.0*.
*/ // end::reference[]
#define BHO_HW_SIMD_X86_MIC_VERSION BHO_VERSION_NUMBER(9, 0, 0)
/* tag::reference[]
*/ // end::reference[]
#endif
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2002 - 2003.
// (C) Copyright <NAME> 2002.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Borland C++ compiler setup:
//
// versions check:
// we don't support Borland prior to version 5.4:
#if __BORLANDC__ < 0x540
# error "Compiler not supported or configured - please reconfigure"
#endif
// last known compiler version:
#if (__BORLANDC__ > 0x613)
//# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown compiler version - please run the configure tests and report the results"
//# else
//# pragma message( "boost: Unknown compiler version - please run the configure tests and report the results")
//# endif
#elif (__BORLANDC__ == 0x600)
# error "CBuilderX preview compiler is no longer supported"
#endif
//
// Support macros to help with standard library detection
#if (__BORLANDC__ < 0x560) || defined(_USE_OLD_RW_STL)
# define BHO_BCB_WITH_ROGUE_WAVE
#elif __BORLANDC__ < 0x570
# define BHO_BCB_WITH_STLPORT
#else
# define BHO_BCB_WITH_DINKUMWARE
#endif
//
// Version 5.0 and below:
# if __BORLANDC__ <= 0x0550
// Borland C++Builder 4 and 5:
# define BHO_NO_MEMBER_TEMPLATE_FRIENDS
# if __BORLANDC__ == 0x0550
// Borland C++Builder 5, command-line compiler 5.5:
# define BHO_NO_OPERATORS_IN_NAMESPACE
# endif
// Variadic macros do not exist for C++ Builder versions 5 and below
#define BHO_NO_CXX11_VARIADIC_MACROS
# endif
// Version 5.51 and below:
#if (__BORLANDC__ <= 0x551)
# define BHO_NO_CV_SPECIALIZATIONS
# define BHO_NO_CV_VOID_SPECIALIZATIONS
# define BHO_NO_DEDUCED_TYPENAME
// workaround for missing WCHAR_MAX/WCHAR_MIN:
#ifdef __cplusplus
#include <climits>
#include <cwchar>
#else
#include <limits.h>
#include <wchar.h>
#endif // __cplusplus
#ifndef WCHAR_MAX
# define WCHAR_MAX 0xffff
#endif
#ifndef WCHAR_MIN
# define WCHAR_MIN 0
#endif
#endif
// Borland C++ Builder 6 and below:
#if (__BORLANDC__ <= 0x564)
# if defined(NDEBUG) && defined(__cplusplus)
// fix broken <cstring> so that Boost.test works:
# include <cstring>
# undef strcmp
# endif
// fix broken errno declaration:
# include <errno.h>
# ifndef errno
# define errno errno
# endif
#endif
//
// new bug in 5.61:
#if (__BORLANDC__ >= 0x561) && (__BORLANDC__ <= 0x580)
// this seems to be needed by the command line compiler, but not the IDE:
# define BHO_NO_MEMBER_FUNCTION_SPECIALIZATIONS
#endif
// Borland C++ Builder 2006 Update 2 and below:
#if (__BORLANDC__ <= 0x582)
# define BHO_NO_SFINAE
# define BHO_BCB_PARTIAL_SPECIALIZATION_BUG
# define BHO_NO_TEMPLATE_TEMPLATES
# define BHO_NO_PRIVATE_IN_AGGREGATE
# ifdef _WIN32
# define BHO_NO_SWPRINTF
# elif defined(linux) || defined(__linux__) || defined(__linux)
// we should really be able to do without this
// but the wcs* functions aren't imported into std::
# define BHO_NO_STDC_NAMESPACE
// _CPPUNWIND doesn't get automatically set for some reason:
# pragma defineonoption BHO_CPPUNWIND -x
# endif
#endif
#if (__BORLANDC__ <= 0x613) // Beman has asked Alisdair for more info
// we shouldn't really need this - but too many things choke
// without it, this needs more investigation:
# define BHO_NO_LIMITS_COMPILE_TIME_CONSTANTS
# define BHO_NO_IS_ABSTRACT
# define BHO_NO_FUNCTION_TYPE_SPECIALIZATIONS
# define BHO_NO_USING_TEMPLATE
# define BHO_SP_NO_SP_CONVERTIBLE
// Temporary workaround
#define BHO_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif
// Borland C++ Builder 2008 and below:
# define BHO_NO_INTEGRAL_INT64_T
# define BHO_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL
# define BHO_NO_DEPENDENT_NESTED_DERIVATIONS
# define BHO_NO_MEMBER_TEMPLATE_FRIENDS
# define BHO_NO_TWO_PHASE_NAME_LOOKUP
# define BHO_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE
# define BHO_NO_NESTED_FRIENDSHIP
# define BHO_NO_TYPENAME_WITH_CTOR
#if (__BORLANDC__ < 0x600)
# define BHO_ILLEGAL_CV_REFERENCES
#endif
//
// Positive Feature detection
//
// Borland C++ Builder 2008 and below:
#if (__BORLANDC__ >= 0x599)
# pragma defineonoption BHO_CODEGEAR_0X_SUPPORT -Ax
#endif
//
// C++0x Macros:
//
#if !defined( BHO_CODEGEAR_0X_SUPPORT ) || (__BORLANDC__ < 0x610)
# define BHO_NO_CXX11_CHAR16_T
# define BHO_NO_CXX11_CHAR32_T
# define BHO_NO_CXX11_DECLTYPE
# define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
# define BHO_NO_CXX11_EXTERN_TEMPLATE
# define BHO_NO_CXX11_RVALUE_REFERENCES
# define BHO_NO_CXX11_SCOPED_ENUMS
# define BHO_NO_CXX11_STATIC_ASSERT
#else
# define BHO_HAS_ALIGNOF
# define BHO_HAS_CHAR16_T
# define BHO_HAS_CHAR32_T
# define BHO_HAS_DECLTYPE
# define BHO_HAS_EXPLICIT_CONVERSION_OPS
# define BHO_HAS_REF_QUALIFIER
# define BHO_HAS_RVALUE_REFS
# define BHO_HAS_STATIC_ASSERT
#endif
#define BHO_NO_CXX11_AUTO_DECLARATIONS
#define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#define BHO_NO_CXX11_CONSTEXPR
#define BHO_NO_CXX11_DECLTYPE_N3276
#define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#define BHO_NO_CXX11_DEFAULTED_MOVES
#define BHO_NO_CXX11_DELETED_FUNCTIONS
#define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define BHO_NO_CXX11_HDR_INITIALIZER_LIST
#define BHO_NO_CXX11_LAMBDAS
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_RAW_LITERALS
#define BHO_NO_CXX11_RVALUE_REFERENCES
#define BHO_NO_CXX11_SCOPED_ENUMS
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_CXX11_SFINAE_EXPR
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_UNICODE_LITERALS // UTF-8 still not supported
#define BHO_NO_CXX11_VARIADIC_TEMPLATES
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#define BHO_NO_CXX11_USER_DEFINED_LITERALS
#define BHO_NO_CXX11_ALIGNAS
#define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#define BHO_NO_CXX11_INLINE_NAMESPACES
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_FINAL
#define BHO_NO_CXX11_OVERRIDE
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_UNRESTRICTED_UNION
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
#if __BORLANDC__ >= 0x590
# define BHO_HAS_TR1_HASH
# define BHO_HAS_MACRO_USE_FACET
#endif
//
// Post 0x561 we have long long and stdint.h:
#if __BORLANDC__ >= 0x561
# ifndef __NO_LONG_LONG
# define BHO_HAS_LONG_LONG
# else
# define BHO_NO_LONG_LONG
# endif
// On non-Win32 platforms let the platform config figure this out:
# ifdef _WIN32
# define BHO_HAS_STDINT_H
# endif
#endif
// Borland C++Builder 6 defaults to using STLPort. If _USE_OLD_RW_STL is
// defined, then we have 0x560 or greater with the Rogue Wave implementation
// which presumably has the std::DBL_MAX bug.
#if defined( BHO_BCB_WITH_ROGUE_WAVE )
// <climits> is partly broken, some macros define symbols that are really in
// namespace std, so you end up having to use illegal constructs like
// std::DBL_MAX, as a fix we'll just include float.h and have done with:
#include <float.h>
#endif
//
// __int64:
//
#if (__BORLANDC__ >= 0x530) && !defined(__STRICT_ANSI__)
# define BHO_HAS_MS_INT64
#endif
//
// check for exception handling support:
//
#if !defined(_CPPUNWIND) && !defined(BHO_CPPUNWIND) && !defined(__EXCEPTIONS) && !defined(BHO_NO_EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
#endif
//
// all versions have a <dirent.h>:
//
#ifndef __STRICT_ANSI__
# define BHO_HAS_DIRENT_H
#endif
//
// all versions support __declspec:
//
#if defined(__STRICT_ANSI__)
// config/platform/win32.hpp will define BHO_SYMBOL_EXPORT, etc., unless already defined
# define BHO_SYMBOL_EXPORT
#endif
//
// ABI fixing headers:
//
#if __BORLANDC__ != 0x600 // not implemented for version 6 compiler yet
#ifndef BHO_ABI_PREFIX
# define BHO_ABI_PREFIX "asio2/bho/config/abi/borland_prefix.hpp"
#endif
#ifndef BHO_ABI_SUFFIX
# define BHO_ABI_SUFFIX "asio2/bho/config/abi/borland_suffix.hpp"
#endif
#endif
//
// Disable Win32 support in ANSI mode:
//
#if __BORLANDC__ < 0x600
# pragma defineonoption BHO_DISABLE_WIN32 -A
#elif defined(__STRICT_ANSI__)
# define BHO_DISABLE_WIN32
#endif
//
// MSVC compatibility mode does some nasty things:
// TODO: look up if this doesn't apply to the whole 12xx range
//
#if defined(_MSC_VER) && (_MSC_VER <= 1200)
# define BHO_NO_ARGUMENT_DEPENDENT_LOOKUP
# define BHO_NO_VOID_RETURNS
#endif
// Borland did not implement value-initialization completely, as I reported
// in 2007, Borland Report 51854, "Value-initialization: POD struct should be
// zero-initialized", http://qc.embarcadero.com/wc/qcmain.aspx?d=51854
// See also: http://www.boost.org/libs/utility/value_init.htm#compiler_issues
// (<NAME>, LKEB, April 2010)
#define BHO_NO_COMPLETE_VALUE_INITIALIZATION
#define BHO_BORLANDC __BORLANDC__
#define BHO_COMPILER "Classic Borland C++ version " BHO_STRINGIZE(__BORLANDC__)
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_DETAIL_BUFFERS_PAIR_HPP
#define BHO_BEAST_DETAIL_BUFFERS_PAIR_HPP
#include <asio2/external/asio.hpp>
#include <asio2/bho/assert.hpp>
#include <asio2/bho/config/workaround.hpp>
#include <type_traits>
namespace bho {
namespace beast {
namespace detail {
#if BHO_WORKAROUND(BHO_MSVC, < 1910)
# pragma warning (push)
# pragma warning (disable: 4521) // multiple copy constructors specified
# pragma warning (disable: 4522) // multiple assignment operators specified
#endif
template<bool isMutable>
class buffers_pair
{
public:
// VFALCO: This type is public otherwise
// net::buffers_iterator won't compile.
using value_type = typename
std::conditional<isMutable,
net::mutable_buffer,
net::const_buffer>::type;
using const_iterator = value_type const*;
buffers_pair() = default;
#if BHO_WORKAROUND(BHO_MSVC, < 1910)
buffers_pair(buffers_pair const& other)
: buffers_pair(
*other.begin(), *(other.begin() + 1))
{
}
buffers_pair&
operator=(buffers_pair const& other)
{
b_[0] = *other.begin();
b_[1] = *(other.begin() + 1);
return *this;
}
#else
buffers_pair(buffers_pair const& other) = default;
buffers_pair& operator=(buffers_pair const& other) = default;
#endif
template<
bool isMutable_ = isMutable,
class = typename std::enable_if<
! isMutable_>::type>
buffers_pair(buffers_pair<true> const& other)
: buffers_pair(
*other.begin(), *(other.begin() + 1))
{
}
template<
bool isMutable_ = isMutable,
class = typename std::enable_if<
! isMutable_>::type>
buffers_pair&
operator=(buffers_pair<true> const& other)
{
b_[0] = *other.begin();
b_[1] = *(other.begin() + 1);
return *this;
}
buffers_pair(value_type b0, value_type b1)
: b_{b0, b1}
{
}
const_iterator
begin() const noexcept
{
return &b_[0];
}
const_iterator
end() const noexcept
{
if(b_[1].size() > 0)
return &b_[2];
return &b_[1];
}
private:
value_type b_[2];
};
#if BHO_WORKAROUND(BHO_MSVC, < 1910)
# pragma warning (pop)
#endif
} // detail
} // beast
} // bho
#endif
<file_sep>#include "unit_test.hpp"
#include <asio2/websocket/ws_server.hpp>
#include <asio2/websocket/ws_client.hpp>
#include <fmt/format.h>
void websocket_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
{
asio2::ws_server server;
std::atomic<int> server_recv_counter = 0;
std::atomic<std::size_t> server_recv_size = 0;
server.bind_recv([&](std::shared_ptr<asio2::ws_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
server_recv_size += data.size();
ASIO2_CHECK(data.front() == '<' && data.back() == '>');
int len = std::stoi(std::string(data.substr(1, 5)));
ASIO2_CHECK(len == int(data.size() - 7));
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
session_ptr->ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::response_type& rep)
{
rep.set(http::field::authorization, " websocket-server-coro");
}));
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18039);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_upgrade_counter = 0;
server.bind_upgrade([&](auto & session_ptr)
{
server_upgrade_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(session_ptr->ws_stream().text());
session_ptr->ws_stream().binary(loop % 2 == 0);
if (loop % 2 == 0)
{
ASIO2_CHECK(session_ptr->ws_stream().binary());
}
else
{
ASIO2_CHECK(session_ptr->ws_stream().text());
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
asio2::ignore_unused(session_ptr);
ASIO2_CHECK(asio2::get_last_error());
// after test, on linux, when disconnect is called, and there has some data
// is transmiting(by async_send), the remote_address maybe empty.
// and under websocket, the socket maybe closed already in the websocket close frame.
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
//ASIO2_CHECK(session_ptr->local_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18039);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
asio2::ws_client client;
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(true, std::chrono::milliseconds(2000));
ASIO2_CHECK(client.is_auto_reconnect());
ASIO2_CHECK(client.get_auto_reconnect_delay() == std::chrono::milliseconds(2000));
std::atomic<std::size_t> client_send_size = 0;
std::atomic<std::size_t> client_recv_size = 0;
std::atomic<int> client_init_counter = 0;
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
client.ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::request_type& req)
{
req.set(http::field::authorization, " websocket-client-authorization");
}));
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
std::atomic<int> client_upgrade_counter = 0;
client.bind_upgrade([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18039);
client_upgrade_counter++;
});
std::atomic<int> client_connect_counter = 0;
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18039);
ASIO2_CHECK(client.ws_stream().text());
client.ws_stream().binary(loop % 2 == 0);
if (loop % 2 == 0)
{
ASIO2_CHECK(client.ws_stream().binary());
}
else
{
ASIO2_CHECK(client.ws_stream().text());
}
client_connect_counter++;
bool binary = (loop % 2 == 0);
std::string str;
str += '<';
int len = 128 + std::rand() % (300);
str += fmt::format("{:05d}", len);
for (int i = 0; i < len; i++)
{
if (binary)
{
str += (char)(std::rand() % 255);
}
else
{
// under text mode, the content must be chars
str += (char)((std::rand() % 26) + 'a');
}
}
str += '>';
client_send_size += str.size();
client.async_send(str);
});
std::atomic<int> client_disconnect_counter = 0;
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&](std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(client.is_started());
client_recv_size += data.size();
ASIO2_CHECK(data.front() == '<' && data.back() == '>');
int len = std::stoi(std::string(data.substr(1, 5)));
ASIO2_CHECK(len == int(data.size() - 7));
});
bool client_start_ret = client.start("127.0.0.1", 18039);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(client.is_started());
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == 1);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == 1);
// use this to ensure the ASIO2_CHECK(server.get_session_count() == std::size_t(1));
while (server_recv_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK(server.get_session_count() == std::size_t(1));
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == 1);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == 1);
//-----------------------------------------------------------------------------------------
while (server_recv_size != client_send_size)
{
ASIO2_TEST_WAIT_CHECK();
}
while (server_recv_size != client_recv_size)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK(server_recv_size == client_send_size);
ASIO2_CHECK(server_recv_size == client_recv_size);
client.stop();
ASIO2_CHECK(client.is_stopped());
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == 1);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == 1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
{
asio2::ws_server server;
std::size_t session_key = std::size_t(std::rand() % test_client_count);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::ws_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(data.front() == '<' && data.back() == '>');
int len = std::stoi(std::string(data.substr(1, 5)));
ASIO2_CHECK(len == int(data.size() - 7));
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18039);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
if (session_key == std::size_t(server_connect_counter.load()))
session_key = session_ptr->hash_key();
server_connect_counter++;
ASIO2_CHECK(session_ptr->ws_stream().text());
session_ptr->ws_stream().binary(loop % 2 == 0);
if (loop % 2 == 0)
{
ASIO2_CHECK(session_ptr->ws_stream().binary());
}
else
{
ASIO2_CHECK(session_ptr->ws_stream().text());
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18039);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::ws_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::ws_client>());
asio2::ws_client& client = *iter;
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(true, std::chrono::milliseconds(2000));
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18039);
ASIO2_CHECK(client.ws_stream().text());
client.ws_stream().binary(loop % 2 == 0);
if (loop % 2 == 0)
{
ASIO2_CHECK(client.ws_stream().binary());
}
else
{
ASIO2_CHECK(client.ws_stream().text());
}
client_connect_counter++;
bool binary = (loop % 2 == 0);
std::string str;
str += '<';
int len = 128 + std::rand() % (300);
str += fmt::format("{:05d}", len);
for (int i = 0; i < len; i++)
{
if (binary)
{
str += (char)(std::rand() % 255);
}
else
{
// under text mode, the content must be chars
str += (char)((std::rand() % 26) + 'a');
}
}
str += '>';
client.async_send(str);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
ASIO2_CHECK(data.front() == '<' && data.back() == '>');
int len = std::stoi(std::string(data.substr(1, 5)));
ASIO2_CHECK(len == int(data.size() - 7));
});
bool client_start_ret = client.async_start("127.0.0.1", 18039, "/admin");
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
auto session_ptr1 = server.find_session(session_key);
ASIO2_CHECK(session_ptr1 != nullptr);
std::size_t sent_bytes = session_ptr1->send("<000100123456789>");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == std::strlen("<000100123456789>"));
auto session_ptr2 = server.find_session_if([session_key](std::shared_ptr<asio2::ws_session>& session_ptr)
{
if (session_ptr->hash_key() == session_key)
return true;
return false;
});
ASIO2_CHECK(session_ptr1.get() == session_ptr2.get());
bool find_session_key = false;
server.foreach_session([session_ptr1, session_key, &find_session_key]
(std::shared_ptr<asio2::ws_session>& session_ptr) mutable
{
if (session_ptr.get() == session_ptr1.get())
{
ASIO2_CHECK(session_key == session_ptr->hash_key());
find_session_key = true;
}
std::size_t sent_bytes = session_ptr->send("<000100123456789>");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sent_bytes == std::strlen("<000100123456789>"));
});
ASIO2_CHECK(find_session_key);
session_ptr1.reset();
session_ptr2.reset();
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18039);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18039, "/admin");
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test auto reconnect
{
struct ext_data
{
int client_init_counter = 0;
int client_connect_counter = 0;
int client_disconnect_counter = 0;
std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now();
};
std::vector<std::shared_ptr<asio2::ws_client>> clients;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::ws_client>());
asio2::ws_client& client = *iter;
client.set_connect_timeout(std::chrono::milliseconds(100));
client.set_auto_reconnect(true, std::chrono::milliseconds(100));
ASIO2_CHECK(client.is_auto_reconnect());
ASIO2_CHECK(client.get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ASIO2_CHECK(client.get_connect_timeout() == std::chrono::milliseconds(100));
client.bind_init([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error());
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_connect_counter++;
if (ex.client_connect_counter == 1)
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - ex.start_time).count() - 100);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= test_timer_deviation);
}
else
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - ex.start_time).count() - 200);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= test_timer_deviation);
}
ex.start_time = std::chrono::high_resolution_clock::now();
if (ex.client_connect_counter == 3)
{
client.set_auto_reconnect(false);
ASIO2_CHECK(!client.is_auto_reconnect());
}
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
});
client.bind_disconnect([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
ext_data ex;
client.set_user_data(std::move(ex));
bool client_start_ret = client.async_start("127.0.0.1", 18039);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::not_connected);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter , ex.client_init_counter == 3);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 3);
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_disconnect_counter, ex.client_disconnect_counter == 0);
}
//-----------------------------------------------------------------------------------------
for (int i = 0; i < test_client_count; i++)
{
clients[i]->set_auto_reconnect(true);
ASIO2_CHECK(clients[i]->is_auto_reconnect());
ASIO2_CHECK(clients[i]->get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ASIO2_CHECK(clients[i]->get_connect_timeout() == std::chrono::milliseconds(100));
ext_data ex;
clients[i]->set_user_data(std::move(ex));
bool client_start_ret = clients[i]->start("127.0.0.1", 18039, "/admin");
ASIO2_CHECK(!client_start_ret);
ASIO2_CHECK_VALUE(asio2::last_error_msg().data(),
asio2::get_last_error() == asio::error::timed_out ||
asio2::get_last_error() == asio::error::connection_refused);
std::size_t bytes = clients[i]->send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::not_connected);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter , ex.client_init_counter == 3);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 3);
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_disconnect_counter, ex.client_disconnect_counter == 0);
}
//-----------------------------------------------------------------------------------------
asio2::ws_server server;
std::size_t session_key = std::size_t(std::rand() % test_client_count);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::ws_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send("abc", [session_ptr](std::size_t sent_bytes)
{
// when the client stopped, the async_send maybe failed.
if (!asio2::get_last_error())
{
// the session_ptr->is_started() maybe false,
//ASIO2_CHECK(session_ptr->is_started());
ASIO2_CHECK(sent_bytes == std::size_t(3));
}
});
std::size_t bytes = session_ptr->send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18039);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
if (session_key == std::size_t(server_connect_counter.load()))
session_key = session_ptr->hash_key();
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18039);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18039);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->set_auto_reconnect(true);
clients[i]->set_connect_timeout(std::chrono::milliseconds(5000));
ASIO2_CHECK(clients[i]->is_auto_reconnect());
ASIO2_CHECK(clients[i]->get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ASIO2_CHECK(clients[i]->get_connect_timeout() == std::chrono::milliseconds(5000));
asio2::ws_client& client = *clients[i];
client.bind_init([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_connect_counter++;
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
});
client.bind_disconnect([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
ext_data ex;
clients[i]->set_user_data(std::move(ex));
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18039);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter , ex.client_init_counter == 1);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 1);
}
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->user_data_any().has_value());
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"websocket",
ASIO2_TEST_CASE(websocket_test)
)
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_WEBSOCKET_DETAIL_SERVICE_IPP
#define BHO_BEAST_WEBSOCKET_DETAIL_SERVICE_IPP
#include <asio2/bho/beast/websocket/detail/service.hpp>
namespace bho {
namespace beast {
namespace websocket {
namespace detail {
service::
impl_type::
impl_type(net::execution_context& ctx)
: svc_(net::use_service<service>(ctx))
{
std::lock_guard<std::mutex> g(svc_.m_);
index_ = svc_.v_.size();
svc_.v_.push_back(this);
}
void
service::
impl_type::
remove()
{
std::lock_guard<std::mutex> g(svc_.m_);
auto& other = *svc_.v_.back();
other.index_ = index_;
svc_.v_[index_] = &other;
svc_.v_.pop_back();
}
//---
void
service::
shutdown()
{
std::vector<std::weak_ptr<impl_type>> v;
{
std::lock_guard<std::mutex> g(m_);
v.reserve(v_.size());
for(auto p : v_)
v.emplace_back(p->weak_from_this());
}
for(auto wp : v)
if(auto sp = wp.lock())
sp->shutdown();
}
} // detail
} // websocket
} // beast
} // bho
#endif
<file_sep>
# 使用asio2开发一个简易的http server
大约200行代码开发一个简易的静态的http server,同时支持http和https,源代码地址:[https://github.com/zhllxt/http_server_lite](https://github.com/zhllxt/http_server_lite)
下载该项目后,打开bin目录里的http_server_lite.exe,然后在你的浏览器输入[http://localhost](http://localhost)可以测试一下效果,实际上和这个网址里的效果是一样的:[https://technext.github.io/soffer/](https://technext.github.io/soffer/)
这个项目是用cmake构建的,跨平台,支持windows,macos,linux,arm,android等,所以只要了解基本的cmake用法,就可以编译你想要的平台下的http server了。github的仓库里只包含了windows下的可执行程序。
下面说一下项目的大致逻辑:
## 首先是配置文件
配置文件用的是json格式,可以配置多个站点,每个站点使用不同的端口,如下:
```cpp
[
// 第1个站点配置
{
"protocol": "http", // 协议类型, http 还是 https
"host": "0.0.0.0", // http server 监听的ip地址
"port": 80, // http server 监听的端口号
"path": "./wwwroot", // 站点所在的文件夹,可以是相对路径,也可以是绝对路径
"index": "index.html" // 默认的页面文件
},
// 第2个站点配置
{
"protocol": "https",
"host": "0.0.0.0",
"port": 443,
"path": "D:/website/main",
"index": "index.html",
"cert_file": "D:/website/main/cert/www.xxx.com.pem", // ssl证书文件
"key_file": "D:/website/main/cert/www.xxx.com.key" // ssl证书文件
},
// 第3个站点配置
{
"protocol": "http",
"host": "0.0.0.0",
"port": 8080,
"path": "D:/website/work",
"index": "index.html"
}
// 第n......个站点配置
]
```
## 具体代码
```cpp
#define ASIO2_ENABLE_SSL // 添加这个宏定义来让asio2支持ssl
#include <asio2/http/http_server.hpp>
#include <asio2/http/https_server.hpp>
#include <asio2/external/fmt.hpp>
#include <asio2/external/json.hpp>
#include <asio2/util/string.hpp>
#include <fstream>
int main()
{
// 使用nlohmann::json 这个库用来处理json非常方便
using json = nlohmann::json;
// 打开配置文件
std::ifstream file("config.json", std::ios::in | std::ios::binary);
if (!file)
{
fmt::print("open the config file 'config.json' failed.\n");
return 0;
}
// 构造一个json对象,用来解析配置文件
json cfg;
try
{
cfg = json::parse(file);
}
catch (json::exception const& e)
{
fmt::print("load the config file 'config.json' failed: {}\n", e.what());
return 0;
}
// 判断一下,配置文件的内容必须是一个数组类型的
if (!cfg.is_array())
{
fmt::print("the content of the config file 'config.json' is incorrect.\n");
return 0;
}
// 创建一个io线程池,为什么要使用io线程池?
// 因为asio2的每一个http server对象默认会启动cpu*2个数量的线程,假如cpu是4核,那就是
// 启动了8个线程,如果配置文件中配置了10个站点,那就会启动10个http server,那总共就开
// 启了80个线程,这显然不够合理。所以这里使用一个线程池,iopool线程池默认也是启动cpu*2
// 个数量的线程,后面会把这个iopool线程池传入到每个http server中,这样不管有多少个
// server,都共用这一个线程池即可。
asio2::iopool iopool;
// 必须先调用iopool的启动函数,否则后面在调用server.start时会阻塞住无法结束。
iopool.start();
// 用来记录总共启动了多少个http server
int server_count = 0;
// 构造一个lambda函数,不管是http server还是https server,后面都调用这个lambda函数来
// 做相关的server设置和server启动操作
auto start_server = [&server_count](auto server,
std::string host, std::uint16_t port, std::string path, std::string index) mutable
{
// 设置http server的站点的文件夹
// 这里变量server是一个shared_ptr类型的智能指针
server->set_root_directory(path);
// 设置回调函数,这里设置的是server的启动回调函数,可以在这里判断启动成功还是失败。
// 注意这里把server对象捕获到lambda函数里用的是原始指针,不能把智能指针本身捕获
// 到lambda函数里,会造成循环引用。因为框架已经保证了,当进到回调函数里时,server
// 对象一定是存在的,所以这里用原始指针没有什么问题。当然,仅从代码的表面的合理
// 性来看,用weak_ptr更符合代码规范(新手如果不太理解这段话,先放一边不用纠结)。
server->bind_start([host, port, &server_count, pserver = server.get()]() mutable
{
// 启动失败,打印失败信息
if (asio2::get_last_error())
fmt::print("start http server failure : {} {} {}\n",
host, port, asio2::last_error_msg());
else
{
// 启动成功
server_count++;
fmt::print("start http server success : {} {}\n",
pserver->listen_address(), pserver->listen_port());
}
}).bind_stop([host, port]()
{
fmt::print("stop http server success : {} {} {}\n",
host, port, asio2::last_error_msg());
});
// 绑定http处理程序,这里绑定是的"/",意思就是如果用户在浏览器中打开的是
// http://www.yousite.com这样的网址,那么我们的http server收到的url请求的
// 目标字符串实际上就是"/",此时我们就给他返回变量index对应的文件即可,
// 注意index是个字符串变量,是从config.json配置文件中读取出来的。
// 另外,这里的bind函数是一个模板函数,默认会对GET和POST的请求都作出响应。
server->bind("/", [index](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
// fill_file表示用一个文件来响应http请求
// 后面框架就会自动使用这个rep来回复对方。
rep.fill_file(index);
});
// 绑定星号通配符,这个意思是除了上面绑定的"/"请求之外,其它所有的请求都
// 由这个回调函数来处理,这个处理比较简单,我们把请求utl的目标取出来(即
// req.target()),并把这个目标当成一个文件名(因为这里我们只是一个静态的
// http server,所以就把http请求全部当成是请求文件就行了),然后调用
// response的fill_file函数,并把文件名传进去即可。
server->bind("*", [](http::web_request& req, http::web_response& rep)
{
rep.fill_file(req.target());
});
// 启动server
return server->start(host, port);
};
// 遍历json数组
for (auto& site : cfg)
{
try
{
// 解析json对象
std::string protocol = site["protocol"].get<std::string>();
std::string host = site["host"].get<std::string>();
std::uint16_t port = site["port"].get<std::uint16_t>();
std::string path = site["path"].get<std::string>();
std::string index = site["index"].get<std::string>();
if (protocol.empty())
{
fmt::print("Must specify protocol.\n");
continue;
}
if (host.empty())
{
host = "0.0.0.0";
fmt::print("The host is empty, will use {} to instead.\n", host);
}
if (path.empty())
{
fmt::print("Must specify path.\n");
continue;
}
if (index.empty())
{
index = "index.html";
fmt::print("The index is empty, will use {} to instead.\n", index);
}
if /**/ (asio2::iequals(protocol, "http"))
{
// 创建http server,在构造函数中传入了iopool线程池
std::shared_ptr<asio2::http_server> server = std::make_shared<asio2::http_server>(iopool);
// 设置并启动http server
start_server(server, host, port, path, index);
// 注意:这里创建了http server对象的智能指针之后,并没有保存它,当代码
// 执行到这里,似乎server 的生命周期就结束了,这会不会有问题呢?不会。
// 当给server传入了iopool参数,并调用了server.start之后,实际上
// server对象的智能指针已经被iopool所捕获了,所以后面程序结束前一定要
// 调用iopool.stop,否则这些server对象就不会被正确的释放。
}
else if (asio2::iequals(protocol, "https"))
{
std::string cert_file = site["cert_file"].get<std::string>();
std::string key_file = site["key_file"].get<std::string>();
if (cert_file.empty())
{
fmt::print("Must specify cert_file.\n");
continue;
}
if (key_file.empty())
{
fmt::print("Must specify key_file.\n");
continue;
}
// 创建https server,在构造函数中传入了ssl版本和iopool线程池
std::shared_ptr<asio2::https_server> server =
std::make_shared<asio2::https_server>(asio::ssl::context::sslv23, iopool);
try
{
// 绑定ssl证书
// 阿里云可以申请免费的ssl证书,有兴趣可以白嫖一下,试试把自己的站点加上
// ssl支持,阿里云的下载证书那里点下载“其它”即可,下载的压缩包里有个pem
// 结尾的文件和key结尾的文件,在config.json文件里配置一下就行了。
server->use_certificate_chain_file(cert_file);
server->use_private_key_file(key_file, asio::ssl::context::pem);
server->use_tmp_dh_file(cert_file);
}
catch (asio::system_error const& e)
{
fmt::print("start http server failure : {} {}, load ssl certificate file failed : {}\n",
host, port, e.what());
continue;
}
// 设置并启动http server
start_server(server, host, port, path, index);
}
else
{
fmt::print("start http server failure : {} {}, invalid protocol: {}\n", host, port, protocol);
}
}
catch (json::exception const& e)
{
fmt::print("read the config file 'config.json' failed: {}\n", e.what());
}
}
if (server_count == 0)
{
// 如果没有配置站点或server全部都启动失败了,这里打印信息后程序就结束了
fmt::print("No available http server was found in the config file.\n");
}
else
{
// 否则就阻塞住主进程,直到收到SIGINT或SIGTERM信号才会退出程序。
// 通常按ctrl + c会触发SIGINT信号,在linux系统下可以用命令
// kill -s SIGINT PID向此进程发送SIGINT信号来优雅的关闭此进程,
// PID是此进程的ID号,可以用ps -aux | grep "http"这种命令来
// 查询一下此进程的PID。
iopool.wait_signal(SIGINT, SIGTERM);
}
// 程序退出之前一定要调用iopool.stop
iopool.stop();
fmt::print("progress exited.\n");
return 0;
}
```
### 最后编辑于:2022-11-04
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_CONFIG_HPP__
#define __ASIO2_CONFIG_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
// Note : Version 2.6 and 2.7 only supports asio standalone, does not support boost::asio, because
// boost::optional and other boost classes are used in boost::beast, while std::optional is
// used in beast standalone. to make the two compatible, it requires too much work. so,
// boost::asio is not supported for version 2.6 and 2.7.
// But at version 2.8, it supports both asio standalone and boost::asio.
// define this to use asio standalone and beast standalone, otherwise use boost::asio and boost::beast.
#define ASIO2_HEADER_ONLY
// If you want to use the ssl, you need to define ASIO2_ENABLE_SSL.
// When use ssl,on windows need linker "libssl.lib;libcrypto.lib;Crypt32.lib;", on
// linux need linker "ssl;crypto;", if link failed under gcc, try ":libssl.a;:libcrypto.a;"
// ssl must be before crypto.
//#define ASIO2_ENABLE_SSL
// RPC component is using tcp dgram mode as the underlying communication support by default,
// If you want to using websocket as the underlying communication support, turn on this macro.
//#define ASIO2_USE_WEBSOCKET_RPC
// Whether to detect the validity of UTF8 string of mqtt
#define ASIO2_CHECK_UTF8
// Whether called the timer callback when the timer is awaked with some error.
// eg : stop_timer will awake the timer with error of asio::error::operation_aborted.
//#define ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR
#endif // !__ASIO2_CONFIG_HPP__
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2003.
// (C) Copyright <NAME> 2005.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Win32 specific config options:
#define BHO_PLATFORM "Win32"
// Get the information about the MinGW runtime, i.e. __MINGW32_*VERSION.
#if defined(__MINGW32__)
# include <_mingw.h>
#endif
#if defined(__GNUC__) && !defined(BHO_NO_SWPRINTF)
# define BHO_NO_SWPRINTF
#endif
// Default defines for BHO_SYMBOL_EXPORT and BHO_SYMBOL_IMPORT
// If a compiler doesn't support __declspec(dllexport)/__declspec(dllimport),
// its bho/config/compiler/ file must define BHO_SYMBOL_EXPORT and
// BHO_SYMBOL_IMPORT
#ifndef BHO_SYMBOL_EXPORT
# define BHO_HAS_DECLSPEC
# define BHO_SYMBOL_EXPORT __declspec(dllexport)
# define BHO_SYMBOL_IMPORT __declspec(dllimport)
#endif
#if defined(__MINGW32__) && ((__MINGW32_MAJOR_VERSION > 2) || ((__MINGW32_MAJOR_VERSION == 2) && (__MINGW32_MINOR_VERSION >= 0)))
# define BHO_HAS_STDINT_H
# ifndef __STDC_LIMIT_MACROS
# define __STDC_LIMIT_MACROS
# endif
# define BHO_HAS_DIRENT_H
# define BHO_HAS_UNISTD_H
#endif
#if defined(__MINGW32__) && (__GNUC__ >= 4)
// Mingw has these functions but there are persistent problems
// with calls to these crashing, so disable for now:
//# define BHO_HAS_EXPM1
//# define BHO_HAS_LOG1P
# define BHO_HAS_GETTIMEOFDAY
#endif
//
// Win32 will normally be using native Win32 threads,
// but there is a pthread library avaliable as an option,
// we used to disable this when BHO_DISABLE_WIN32 was
// defined but no longer - this should allow some
// files to be compiled in strict mode - while maintaining
// a consistent setting of BHO_HAS_THREADS across
// all translation units (needed for shared_ptr etc).
//
#ifndef BHO_HAS_PTHREADS
# define BHO_HAS_WINTHREADS
#endif
//
// WinCE configuration:
//
#if defined(_WIN32_WCE) || defined(UNDER_CE)
# define BHO_NO_ANSI_APIS
// Windows CE does not have a conforming signature for swprintf
# define BHO_NO_SWPRINTF
#else
# define BHO_HAS_GETSYSTEMTIMEASFILETIME
# define BHO_HAS_THREADEX
# define BHO_HAS_GETSYSTEMTIMEASFILETIME
#endif
//
// Windows Runtime
//
#if defined(WINAPI_FAMILY) && \
(WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
# define BHO_NO_ANSI_APIS
#endif
#ifndef BHO_DISABLE_WIN32
// WEK: Added
#define BHO_HAS_FTIME
#define BHO_WINDOWS 1
#endif
<file_sep>/*
** This file is auto generated by https://github.com/axys1/buildware.git
*/
#ifndef BUILDWARE_openssl_REDIRECT_H
#define BUILDWARE_openssl_REDIRECT_H
#if defined(_WIN32)
# if defined(_WIN64)
# include "win64/openssl/configuration.h"
# else
# include "win32/openssl/configuration.h"
# endif
#elif defined(__APPLE__)
# include <TargetConditionals.h>
# if TARGET_IPHONE_SIMULATOR == 1
# include "ios-x64/openssl/configuration.h"
# elif TARGET_OS_IPHONE == 1
# if defined(__arm64__)
# include "ios-arm64/openssl/configuration.h"
# elif defined(__arm__)
# include "ios-arm/openssl/configuration.h"
# endif
# elif TARGET_OS_MAC == 1
# include "mac/openssl/configuration.h"
# endif
#elif defined(__ANDROID__)
# if defined(__aarch64__) || defined(__arm64__)
# include "android-arm64/openssl/configuration.h"
# elif defined(__arm__)
# include "android-arm/openssl/configuration.h"
# else
# include "android-x86/openssl/configuration.h"
# endif
#elif defined(__linux__)
# include "linux/openssl/configuration.h"
#else
# error "unsupported platform"
#endif
#endif
<file_sep>#include <asio2/tcp/tcp_client.hpp>
std::string strmsg(127, 'A');
std::function<void()> sender;
int main()
{
asio2::tcp_client client;
strmsg += '\n';
sender = [&]()
{
client.async_call(strmsg, [](std::string_view)
{
if (!asio2::get_last_error())
sender();
});
};
client.bind_connect([&]()
{
if (!asio2::get_last_error())
sender();
});
asio2::rdc::option rdc_option
{
[](std::string_view) { return 0; }
};
client.start("127.0.0.1", "8110", '\n', rdc_option);
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RPC_PROTOCOL_HPP__
#define __ASIO2_RPC_PROTOCOL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <string>
#include <string_view>
#include <asio2/base/detail/util.hpp>
#include <asio2/rpc/detail/rpc_serialization.hpp>
namespace asio2::detail
{
struct use_tcp {};
struct use_websocket {};
/*
* request : message type + request id + function name + parameters value...
* response : message type + request id + function name + error code + result value
*
* message type : q - request, p - response
*
* if result type is void, then result type will wrapped to std::int8_t
*/
static constexpr char rpc_type_req = 'q';
static constexpr char rpc_type_rep = 'p';
class rpc_header
{
public:
using id_type = std::uint64_t;
rpc_header() noexcept {}
rpc_header(char type, id_type id, std::string_view name)
: type_(type), id_(id), name_(name) {}
~rpc_header() = default;
rpc_header(const rpc_header& r) : type_(r.type_), id_(r.id_), name_(r.name_) {}
rpc_header(rpc_header&& r) noexcept : type_(r.type_), id_(r.id_), name_(std::move(r.name_)) {}
inline rpc_header& operator=(const rpc_header& r)
{
type_ = r.type_;
id_ = r.id_;
name_ = r.name_;
return (*this);
}
inline rpc_header& operator=(rpc_header&& r) noexcept
{
type_ = r.type_;
id_ = r.id_;
name_ = std::move(r.name_);
return (*this);
}
//template <class Archive>
//inline void serialize(Archive & ar)
//{
// ar(type_, id_, name_);
//}
template <class Archive>
void save(Archive & ar) const
{
ar(type_, id_, name_);
}
template <class Archive>
void load(Archive & ar)
{
ar(type_, id_, name_);
}
inline char type() const noexcept { return this->type_; }
inline id_type id () const noexcept { return this->id_; }
inline const std::string& name() const noexcept { return this->name_; }
inline char get_type() const noexcept { return this->type_; }
inline id_type get_id () const noexcept { return this->id_; }
inline const std::string& get_name() const noexcept { return this->name_; }
inline bool is_request () noexcept { return this->type_ == rpc_type_req; }
inline bool is_response() noexcept { return this->type_ == rpc_type_rep; }
inline rpc_header& type(char type ) noexcept { this->type_ = type; return (*this); }
inline rpc_header& id (id_type id ) noexcept { this->id_ = id ; return (*this); }
inline rpc_header& name(std::string_view name) { this->name_ = name; return (*this); }
inline rpc_header& set_type(char type ) noexcept { this->type_ = type; return (*this); }
inline rpc_header& set_id (id_type id ) noexcept { this->id_ = id ; return (*this); }
inline rpc_header& set_name(std::string_view name) { this->name_ = name; return (*this); }
protected:
char type_;
id_type id_ = 0;
std::string name_;
};
template<class ...Args>
class rpc_request : public rpc_header
{
protected:
template<class T>
struct value_t
{
using type = T;
};
template<class... Ts>
struct value_t<std::basic_string_view<Ts...>>
{
using type = typename std::basic_string_view<Ts...>::value_type;
};
template<class T>
struct result_t
{
// if the parameters of rpc calling is raw pointer like char* , must convert it to std::string
// if the parameters of rpc calling is std::string_view , must convert it to std::string
// if the parameters of rpc calling is refrence like std::string& , must remove it's
// refrence to std::string
using ncvr_type = std::remove_cv_t<std::remove_reference_t<T>>;
using char_type = std::remove_cv_t<std::remove_reference_t<
std::remove_all_extents_t<std::remove_pointer_t<ncvr_type>>>>;
using type = std::conditional_t<
(std::is_pointer_v<ncvr_type> || std::is_array_v<ncvr_type>) && (
std::is_same_v<char_type, std::string::value_type> ||
std::is_same_v<char_type, std::wstring::value_type> ||
std::is_same_v<char_type, std::u16string::value_type> ||
std::is_same_v<char_type, std::u32string::value_type>)
, std::basic_string<char_type>
, std::conditional_t<is_template_instance_of_v<std::basic_string_view, ncvr_type>
, std::basic_string<typename value_t<ncvr_type>::type>
, ncvr_type>>;
};
public:
rpc_request() noexcept : rpc_header() { this->type_ = rpc_type_req; }
// can't use tp_(std::forward_as_tuple(std::forward<Args>(args)...))
// if use tp_(std::forward_as_tuple(std::forward<Args>(args)...)),
// when the args is nlohmann::json and under gcc 9.4.0, the json::object
// maybe changed to json::array, like this:
// {"name":"hello","age":10} will changed to [{"name":"hello","age":10}]
// i don't why?
rpc_request(std::string_view name, Args&&... args)
: rpc_header(rpc_type_req, 0, name), tp_(std::forward<Args>(args)...) {}
rpc_request(id_type id, std::string_view name, Args&&... args)
: rpc_header(rpc_type_req, id, name), tp_(std::forward<Args>(args)...) {}
~rpc_request() = default;
rpc_request(const rpc_request& r) : rpc_header(r), tp_(r.tp_) {}
rpc_request(rpc_request&& r) noexcept : rpc_header(std::move(r)), tp_(std::move(r.tp_)) {}
inline rpc_request& operator=(const rpc_request& r)
{
static_cast<rpc_header&>(*this) = r;
tp_ = r.tp_;
return (*this);
}
inline rpc_request& operator=(rpc_request&& r) noexcept
{
static_cast<rpc_header&>(*this) = std::move(r);
tp_ = std::move(r.tp_);
return (*this);
}
//template <class Archive>
//void serialize(Archive & ar)
//{
// ar(cereal::base_class<rpc_header>(this));
// detail::for_each_tuple(tp_, [&ar](auto& elem) mutable
// {
// ar(elem);
// });
//}
template <class Archive>
void save(Archive & ar) const
{
ar(cereal::base_class<rpc_header>(this));
detail::for_each_tuple(tp_, [&ar](const auto& elem) mutable
{
ar << elem;
});
}
template <class Archive>
void load(Archive & ar)
{
ar(cereal::base_class<rpc_header>(this));
detail::for_each_tuple(tp_, [&ar](auto& elem) mutable
{
ar >> elem;
});
}
protected:
std::tuple<typename result_t<Args>::type...> tp_;
};
template<class T>
class rpc_response : public rpc_header
{
public:
rpc_response() noexcept : rpc_header() { this->type_ = rpc_type_rep; }
rpc_response(id_type id, std::string_view name) : rpc_header(rpc_type_rep, id, name) {}
rpc_response(id_type id, std::string_view name, const error_code& ec, T&& ret)
: rpc_header(rpc_type_rep, id, name), ec_(ec), ret_(std::forward<T>(ret)) {}
~rpc_response() = default;
rpc_response(const rpc_response& r)
: rpc_header(r), ec_(r.ec_), ret_(r.ret_) {}
rpc_response(rpc_response&& r) noexcept
: rpc_header(std::move(r)), ec_(std::move(r.ec_)), ret_(std::move(r.ret_)) {}
inline rpc_response& operator=(const rpc_response& r)
{
static_cast<rpc_header&>(*this) = r;
ec_ = r.ec_;
ret_ = r.ret_;
return (*this);
}
inline rpc_response& operator=(rpc_response&& r) noexcept
{
static_cast<rpc_header&>(*this) = std::move(r);
ec_ = std::move(r.ec_);
ret_ = std::move(r.ret_);
return (*this);
}
//template <class Archive>
//void serialize(Archive & ar)
//{
// ar(cereal::base_class<rpc_header>(this));
// ar(ec_.value());
// ar(ret_);
//}
template <class Archive>
void save(Archive & ar) const
{
ar << cereal::base_class<rpc_header>(this);
ar << ec_.value();
ar << ret_;
}
template <class Archive>
void load(Archive & ar)
{
ar >> cereal::base_class<rpc_header>(this);
ar >> ec_.value();
ar >> ret_;
}
protected:
error_code ec_;
T ret_;
};
}
#endif // !__ASIO2_RPC_PROTOCOL_HPP__
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_CORE_DETAIL_ASYNC_BASE_HPP
#define BHO_BEAST_CORE_DETAIL_ASYNC_BASE_HPP
#include <asio2/bho/core/exchange.hpp>
namespace bho {
namespace beast {
namespace detail {
struct stable_base
{
static
void
destroy_list(stable_base*& list)
{
while(list)
{
auto next = list->next_;
list->destroy();
list = next;
}
}
stable_base* next_ = nullptr;
protected:
stable_base() = default;
virtual ~stable_base() = default;
virtual void destroy() = 0;
};
} // detail
} // beast
} // bho
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_AOP_PUBACK_HPP__
#define __ASIO2_MQTT_AOP_PUBACK_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class caller_t, class args_t>
class mqtt_aop_puback
{
friend caller_t;
protected:
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::puback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::puback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
// server or client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::puback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::puback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::puback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::puback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
};
}
#endif // !__ASIO2_MQTT_AOP_PUBACK_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_IA64_H
#define BHO_PREDEF_ARCHITECTURE_IA64_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_IA64`
http://en.wikipedia.org/wiki/Ia64[Intel Itanium 64] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__ia64__+` | {predef_detection}
| `+_IA64+` | {predef_detection}
| `+__IA64__+` | {predef_detection}
| `+__ia64+` | {predef_detection}
| `+_M_IA64+` | {predef_detection}
| `+__itanium__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_IA64 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__ia64__) || defined(_IA64) || \
defined(__IA64__) || defined(__ia64) || \
defined(_M_IA64) || defined(__itanium__)
# undef BHO_ARCH_IA64
# define BHO_ARCH_IA64 BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_IA64
# define BHO_ARCH_IA64_AVAILABLE
#endif
#if BHO_ARCH_IA64
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_IA64_NAME "Intel Itanium 64"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_IA64,BHO_ARCH_IA64_NAME)
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001 - 2002.
// (C) Copyright <NAME> 2001 - 2002.
// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2002.
// (C) Copyright <NAME> 2002 - 2003.
// (C) Copyright <NAME> 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// GNU C++ compiler setup.
//
// Define BHO_GCC so we know this is "real" GCC and not some pretender:
//
#define BHO_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if !defined(__CUDACC__)
#define BHO_GCC BHO_GCC_VERSION
#endif
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
# define BHO_GCC_CXX11
#endif
#if __GNUC__ == 3
# if defined (__PATHSCALE__)
# define BHO_NO_TWO_PHASE_NAME_LOOKUP
# define BHO_NO_IS_ABSTRACT
# endif
# if __GNUC_MINOR__ < 4
# define BHO_NO_IS_ABSTRACT
# endif
# define BHO_NO_CXX11_EXTERN_TEMPLATE
#endif
#if __GNUC__ < 4
//
// All problems to gcc-3.x and earlier here:
//
#define BHO_NO_TWO_PHASE_NAME_LOOKUP
# ifdef __OPEN64__
# define BHO_NO_IS_ABSTRACT
# endif
#endif
// GCC prior to 3.4 had #pragma once too but it didn't work well with filesystem links
#if BHO_GCC_VERSION >= 30400
#define BHO_HAS_PRAGMA_ONCE
#endif
#if BHO_GCC_VERSION < 40400
// Previous versions of GCC did not completely implement value-initialization:
// GCC Bug 30111, "Value-initialization of POD base class doesn't initialize
// members", reported by <NAME> in 2006,
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=30111 (fixed for GCC 4.4)
// GCC Bug 33916, "Default constructor fails to initialize array members",
// reported by <NAME> in 2007,
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=33916 (fixed for GCC 4.2.4)
// See also: http://www.boost.org/libs/utility/value_init.htm#compiler_issues
#define BHO_NO_COMPLETE_VALUE_INITIALIZATION
#endif
#if !defined(__EXCEPTIONS) && !defined(BHO_NO_EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
#endif
//
// Threading support: Turn this on unconditionally here (except for
// those platforms where we can know for sure). It will get turned off again
// later if no threading API is detected.
//
#if !defined(__MINGW32__) && !defined(linux) && !defined(__linux) && !defined(__linux__)
# define BHO_HAS_THREADS
#endif
//
// gcc has "long long"
// Except on Darwin with standard compliance enabled (-pedantic)
// Apple gcc helpfully defines this macro we can query
//
#if !defined(__DARWIN_NO_LONG_LONG)
# define BHO_HAS_LONG_LONG
#endif
//
// gcc implements the named return value optimization since version 3.1
//
#define BHO_HAS_NRVO
// Branch prediction hints
#define BHO_LIKELY(x) __builtin_expect(x, 1)
#define BHO_UNLIKELY(x) __builtin_expect(x, 0)
//
// Dynamic shared object (DSO) and dynamic-link library (DLL) support
//
#if __GNUC__ >= 4
# if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)
// All Win32 development environments, including 64-bit Windows and MinGW, define
// _WIN32 or one of its variant spellings. Note that Cygwin is a POSIX environment,
// so does not define _WIN32 or its variants, but still supports dllexport/dllimport.
# define BHO_HAS_DECLSPEC
# define BHO_SYMBOL_EXPORT __attribute__((__dllexport__))
# define BHO_SYMBOL_IMPORT __attribute__((__dllimport__))
# else
# define BHO_SYMBOL_EXPORT __attribute__((__visibility__("default")))
# define BHO_SYMBOL_IMPORT
# endif
# define BHO_SYMBOL_VISIBLE __attribute__((__visibility__("default")))
#else
// config/platform/win32.hpp will define BHO_SYMBOL_EXPORT, etc., unless already defined
# define BHO_SYMBOL_EXPORT
#endif
//
// RTTI and typeinfo detection is possible post gcc-4.3:
//
#if BHO_GCC_VERSION > 40300
# ifndef __GXX_RTTI
# ifndef BHO_NO_TYPEID
# define BHO_NO_TYPEID
# endif
# ifndef BHO_NO_RTTI
# define BHO_NO_RTTI
# endif
# endif
#endif
//
// Recent GCC versions have __int128 when in 64-bit mode.
//
// We disable this if the compiler is really nvcc with C++03 as it
// doesn't actually support __int128 as of CUDA_VERSION=7500
// even though it defines __SIZEOF_INT128__.
// See https://svn.boost.org/trac/bho/ticket/8048
// https://svn.boost.org/trac/bho/ticket/11852
// Only re-enable this for nvcc if you're absolutely sure
// of the circumstances under which it's supported:
//
#if defined(__CUDACC__)
# if defined(BHO_GCC_CXX11)
# define BHO_NVCC_CXX11
# else
# define BHO_NVCC_CXX03
# endif
#endif
#if defined(__SIZEOF_INT128__) && !defined(BHO_NVCC_CXX03)
# define BHO_HAS_INT128
#endif
//
// Recent GCC versions have a __float128 native type, we need to
// include a std lib header to detect this - not ideal, but we'll
// be including <cstddef> later anyway when we select the std lib.
//
// Nevertheless, as of CUDA 7.5, using __float128 with the host
// compiler in pre-C++11 mode is still not supported.
// See https://svn.boost.org/trac/bho/ticket/11852
//
#ifdef __cplusplus
#include <cstddef>
#else
#include <stddef.h>
#endif
#if defined(_GLIBCXX_USE_FLOAT128) && !defined(__STRICT_ANSI__) && !defined(BHO_NVCC_CXX03)
# define BHO_HAS_FLOAT128
#endif
// C++0x features in 4.3.n and later
//
#if (BHO_GCC_VERSION >= 40300) && defined(BHO_GCC_CXX11)
// C++0x features are only enabled when -std=c++0x or -std=gnu++0x are
// passed on the command line, which in turn defines
// __GXX_EXPERIMENTAL_CXX0X__.
# define BHO_HAS_DECLTYPE
# define BHO_HAS_RVALUE_REFS
# define BHO_HAS_STATIC_ASSERT
# define BHO_HAS_VARIADIC_TMPL
#else
# define BHO_NO_CXX11_DECLTYPE
# define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
# define BHO_NO_CXX11_RVALUE_REFERENCES
# define BHO_NO_CXX11_STATIC_ASSERT
#endif
// C++0x features in 4.4.n and later
//
#if (BHO_GCC_VERSION < 40400) || !defined(BHO_GCC_CXX11)
# define BHO_NO_CXX11_AUTO_DECLARATIONS
# define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
# define BHO_NO_CXX11_CHAR16_T
# define BHO_NO_CXX11_CHAR32_T
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
# define BHO_NO_CXX11_DELETED_FUNCTIONS
# define BHO_NO_CXX11_TRAILING_RESULT_TYPES
# define BHO_NO_CXX11_INLINE_NAMESPACES
# define BHO_NO_CXX11_VARIADIC_TEMPLATES
#endif
#if BHO_GCC_VERSION < 40500
# define BHO_NO_SFINAE_EXPR
#endif
// GCC 4.5 forbids declaration of defaulted functions in private or protected sections
#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ == 5) || !defined(BHO_GCC_CXX11)
# define BHO_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS
#endif
// C++0x features in 4.5.0 and later
//
#if (BHO_GCC_VERSION < 40500) || !defined(BHO_GCC_CXX11)
# define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
# define BHO_NO_CXX11_LAMBDAS
# define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
# define BHO_NO_CXX11_RAW_LITERALS
# define BHO_NO_CXX11_UNICODE_LITERALS
#endif
// C++0x features in 4.5.1 and later
//
#if (BHO_GCC_VERSION < 40501) || !defined(BHO_GCC_CXX11)
// scoped enums have a serious bug in 4.4.0, so define BHO_NO_CXX11_SCOPED_ENUMS before 4.5.1
// See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38064
# define BHO_NO_CXX11_SCOPED_ENUMS
#endif
// C++0x features in 4.6.n and later
//
#if (BHO_GCC_VERSION < 40600) || !defined(BHO_GCC_CXX11)
#define BHO_NO_CXX11_DEFAULTED_MOVES
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#endif
// C++0x features in 4.7.n and later
//
#if (BHO_GCC_VERSION < 40700) || !defined(BHO_GCC_CXX11)
// Note that while constexpr is partly supported in gcc-4.6 it's a
// pre-std version with several bugs:
# define BHO_NO_CXX11_CONSTEXPR
# define BHO_NO_CXX11_FINAL
# define BHO_NO_CXX11_TEMPLATE_ALIASES
# define BHO_NO_CXX11_USER_DEFINED_LITERALS
# define BHO_NO_CXX11_FIXED_LENGTH_VARIADIC_TEMPLATE_EXPANSION_PACKS
# define BHO_NO_CXX11_OVERRIDE
#endif
// C++0x features in 4.8.n and later
//
#if (BHO_GCC_VERSION < 40800) || !defined(BHO_GCC_CXX11)
# define BHO_NO_CXX11_THREAD_LOCAL
# define BHO_NO_CXX11_SFINAE_EXPR
#endif
// C++0x features in 4.8.1 and later
//
#if (BHO_GCC_VERSION < 40801) || !defined(BHO_GCC_CXX11)
# define BHO_NO_CXX11_DECLTYPE_N3276
# define BHO_NO_CXX11_REF_QUALIFIERS
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
// C++0x features in 4.9.n and later
//
#if (BHO_GCC_VERSION < 40900) || !defined(BHO_GCC_CXX11)
// Although alignas support is added in gcc 4.8, it does not accept
// dependent constant expressions as an argument until gcc 4.9.
# define BHO_NO_CXX11_ALIGNAS
#endif
// C++0x features in 5.1 and later
//
#if (BHO_GCC_VERSION < 50100) || !defined(BHO_GCC_CXX11)
# define BHO_NO_CXX11_UNRESTRICTED_UNION
#endif
// C++14 features in 4.9.0 and later
//
#if (BHO_GCC_VERSION < 40900) || (__cplusplus < 201300)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
# define BHO_NO_CXX14_GENERIC_LAMBDAS
# define BHO_NO_CXX14_DIGIT_SEPARATORS
# define BHO_NO_CXX14_DECLTYPE_AUTO
# if !((BHO_GCC_VERSION >= 40801) && (BHO_GCC_VERSION < 40900) && defined(BHO_GCC_CXX11))
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
# endif
#endif
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if (BHO_GCC_VERSION < 50200) || !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
#if __GNUC__ >= 7
# define BHO_FALLTHROUGH __attribute__((fallthrough))
#endif
#if (__GNUC__ < 11) && defined(__MINGW32__) && !defined(__MINGW64__)
// thread_local was broken on mingw for all 32bit compiler releases prior to 11.x, see
// https://sourceforge.net/p/mingw-w64/bugs/527/
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83562
// Not setting this causes program termination on thread exit.
#define BHO_NO_CXX11_THREAD_LOCAL
#endif
//
// Unused attribute:
#if __GNUC__ >= 4
# define BHO_ATTRIBUTE_UNUSED __attribute__((__unused__))
#endif
// Type aliasing hint. Supported since gcc 3.3.
#define BHO_MAY_ALIAS __attribute__((__may_alias__))
//
// __builtin_unreachable:
#if BHO_GCC_VERSION >= 40500
#define BHO_UNREACHABLE_RETURN(x) __builtin_unreachable();
#endif
#ifndef BHO_COMPILER
# define BHO_COMPILER "GNU C++ version " __VERSION__
#endif
// ConceptGCC compiler:
// http://www.generic-programming.org/software/ConceptGCC/
#ifdef __GXX_CONCEPTS__
# define BHO_HAS_CONCEPTS
# define BHO_COMPILER "ConceptGCC version " __VERSION__
#endif
// versions check:
// we don't know gcc prior to version 3.30:
#if (BHO_GCC_VERSION< 30300)
# error "Compiler not configured - please reconfigure"
#endif
//
// last known and checked version is 8.1:
#if (BHO_GCC_VERSION > 80100)
# if defined(BHO_ASSERT_CONFIG)
# error "Boost.Config is older than your compiler - please check for an updated Boost release."
# else
// we don't emit warnings here anymore since there are no defect macros defined for
// gcc post 3.4, so any failures are gcc regressions...
//# warning "boost: Unknown compiler version - please run the configure tests and report the results"
# endif
#endif
<file_sep>#include "unit_test.hpp"
#include <asio2/util/sha1.hpp>
#include <asio2/util/base64.hpp>
void sha1_test()
{
std::string src = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
{
ASIO2_CHECK(asio2::sha1(src).str(true ) == "ECCB8B0E82E3B9907D52FEB72ABAF813B539C77D");
ASIO2_CHECK(asio2::sha1(src).str(false) == "eccb8b0e82e3b9907d52feb72abaf813b539c77d");
}
//ASIO2_TEST_BEGIN_LOOP(test_loop_times);
//ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"sha1",
ASIO2_TEST_CASE(sha1_test)
)
<file_sep>// Copyright (c) 2016-2021 <NAME>
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BHO_PFR_DETAIL_CONFIG_HPP
#define BHO_PFR_DETAIL_CONFIG_HPP
#pragma once
#include <type_traits> // to get non standard platform macro definitions (__GLIBCXX__ for example)
// Reminder:
// * MSVC++ 14.2 _MSC_VER == 1927 <- Loophole is known to work (Visual Studio ????)
// * MSVC++ 14.1 _MSC_VER == 1916 <- Loophole is known to NOT work (Visual Studio 2017)
// * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
// * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
#if defined(_MSC_VER)
# if !defined(_MSVC_LANG) || _MSC_VER <= 1900
# error BHO.PFR library requires more modern MSVC compiler.
# endif
#elif __cplusplus < 201402L
# error BHO.PFR library requires at least C++14.
#endif
#ifndef BHO_PFR_USE_LOOPHOLE
# if defined(_MSC_VER)
# if _MSC_VER >= 1927
# define BHO_PFR_USE_LOOPHOLE 1
# else
# define BHO_PFR_USE_LOOPHOLE 0
# endif
# elif defined(__clang_major__) && __clang_major__ >= 8
# define BHO_PFR_USE_LOOPHOLE 0
# else
# define BHO_PFR_USE_LOOPHOLE 1
# endif
#endif
#ifndef BHO_PFR_USE_CPP17
# ifdef __cpp_structured_bindings
# define BHO_PFR_USE_CPP17 1
# elif defined(_MSVC_LANG)
# if _MSVC_LANG >= 201703L
# define BHO_PFR_USE_CPP17 1
# else
# define BHO_PFR_USE_CPP17 0
# endif
# else
# define BHO_PFR_USE_CPP17 0
# endif
#endif
#if (!BHO_PFR_USE_CPP17 && !BHO_PFR_USE_LOOPHOLE)
# if (defined(_MSC_VER) && _MSC_VER < 1916) ///< in Visual Studio 2017 v15.9 PFR library with classic engine normally works
# error BHO.PFR requires /std:c++latest or /std:c++17 flags on your compiler.
# endif
#endif
#ifndef BHO_PFR_USE_STD_MAKE_INTEGRAL_SEQUENCE
// Assume that libstdc++ since GCC-7.3 does not have linear instantiation depth in std::make_integral_sequence
# if defined( __GLIBCXX__) && __GLIBCXX__ >= 20180101
# define BHO_PFR_USE_STD_MAKE_INTEGRAL_SEQUENCE 1
# elif defined(_MSC_VER)
# define BHO_PFR_USE_STD_MAKE_INTEGRAL_SEQUENCE 1
//# elif other known working lib
# else
# define BHO_PFR_USE_STD_MAKE_INTEGRAL_SEQUENCE 0
# endif
#endif
#ifndef BHO_PFR_HAS_GUARANTEED_COPY_ELISION
# if defined(__cpp_guaranteed_copy_elision) && (!defined(_MSC_VER) || _MSC_VER > 1928)
# define BHO_PFR_HAS_GUARANTEED_COPY_ELISION 1
# else
# define BHO_PFR_HAS_GUARANTEED_COPY_ELISION 0
# endif
#endif
#if defined(__has_cpp_attribute)
# if __has_cpp_attribute(maybe_unused)
# define BHO_PFR_MAYBE_UNUSED [[maybe_unused]]
# endif
#endif
#ifndef BHO_PFR_MAYBE_UNUSED
# define BHO_PFR_MAYBE_UNUSED
#endif
#endif // BHO_PFR_DETAIL_CONFIG_HPP
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_MSL_H
#define BHO_PREDEF_LIBRARY_STD_MSL_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_MSL`
http://www.freescale.com/[Metrowerks] Standard {CPP} Library.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__MSL_CPP__+` | {predef_detection}
| `+__MSL__+` | {predef_detection}
| `+__MSL_CPP__+` | V.R.P
| `+__MSL__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_LIB_STD_MSL BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__MSL_CPP__) || defined(__MSL__)
# undef BHO_LIB_STD_MSL
# if defined(__MSL_CPP__)
# define BHO_LIB_STD_MSL BHO_PREDEF_MAKE_0X_VRPP(__MSL_CPP__)
# else
# define BHO_LIB_STD_MSL BHO_PREDEF_MAKE_0X_VRPP(__MSL__)
# endif
#endif
#if BHO_LIB_STD_MSL
# define BHO_LIB_STD_MSL_AVAILABLE
#endif
#define BHO_LIB_STD_MSL_NAME "Metrowerks"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_MSL,BHO_LIB_STD_MSL_NAME)
<file_sep>#include "unit_test.hpp"
#define ASIO2_DISABLE_STOP_SESSION_WHEN_RECVD_0BYTES
#include <unordered_set>
#include <asio2/external/fmt.hpp>
#include <asio2/udp/udp_server.hpp>
#include <asio2/udp/udp_client.hpp>
static std::string_view chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
struct hasher
{
inline std::size_t operator()(asio::ip::udp::endpoint const& ep) const noexcept
{
std::uint32_t addr = ep.address().to_v4().to_uint();
std::uint32_t v = asio2::detail::fnv1a_hash<std::uint32_t>((const unsigned char* const)&addr, sizeof(std::uint32_t));
std::uint16_t port = ep.port();
return asio2::detail::fnv1a_hash<std::uint32_t>(v, (const unsigned char* const)&port, sizeof(std::uint16_t));
}
};
class my_udp_client : public asio2::udp_client_t<my_udp_client>
{
public:
using asio2::udp_client_t<my_udp_client>::udp_client_t;
public:
using asio2::udp_client_t<my_udp_client>::kcp_;
void set_send_fin(bool v) { kcp_->send_fin_ = v; }
};
void udp_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
// test endpoint hash collision
{
{
std::unordered_map<asio::ip::udp::endpoint, std::size_t, hasher> map;
asio::ip::udp::endpoint s1(asio::ip::address_v4{ {0, 0, 23, 37 } }, 40889);
asio::ip::udp::endpoint s2(asio::ip::address_v4{ {0, 0, 23, 136} }, 129 );
auto h1 = hasher()(s1);
auto h2 = hasher()(s2);
ASIO2_CHECK(h1 == h2);
map.emplace(s1, 1);
ASIO2_CHECK(map.find(s1) != map.end());
ASIO2_CHECK(map.find(s2) == map.end());
map.emplace(s2, 2);
ASIO2_CHECK(map.find(s2) != map.end());
ASIO2_CHECK(map.find(s1)->second == 1);
ASIO2_CHECK(map.find(s2)->second == 2);
ASIO2_CHECK(map.size() == 2);
}
// after test, there are a lot of hash collisions.
std::uint64_t count = 0;
//std::unordered_set<std::uint32_t> sets;
//for (std::uint8_t a = 0; a < 0xff; a++)
//{
// for (std::uint8_t b = 0; b < 0xff; b++)
// {
// for (std::uint8_t c = 0; c < 0xff; c++)
// {
// for (std::uint8_t d = 0; d < 0xff; d++)
// {
// for (std::uint16_t port = 0; port < 0xffff; port++)
// {
// asio::ip::udp::endpoint s(asio::ip::address_v4{ {a,b,c,d} }, port);
// std::uint32_t hash = (std::uint32_t)hasher()(s);
// auto pair = sets.emplace(hash);
// if (!pair.second)
// {
// count++;
// printf("%d %d %d %d %d %u\n", a, b, c, d, port, hash);
// while (std::getchar() != '\n');
// }
// ASIO2_CHECK_VALUE(hash, pair.second);
// }
// }
// ASIO2_CHECK_VALUE(count, count == 0);
// }
// }
//}
ASIO2_CHECK_VALUE(count, count == 0);
}
// test udp kcp
{
struct ext_data
{
int num = 1;
};
asio2::udp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::udp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars[i];
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_send(std::move(msg));
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::udp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::udp_client>());
asio2::udp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_reuse_address());
client.set_no_delay(true);
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18036);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 20)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars[i];
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars[i];
}
client.async_send(std::move(msg));
});
bool client_start_ret = client.async_start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars[0];
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars[0];
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test udp kcp with client provided kcp conv
{
struct ext_data
{
int num = 1;
};
asio2::udp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::udp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars[i];
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_send(std::move(msg));
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::udp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::udp_client>());
asio2::udp_client& client = *iter;
client.set_kcp_conv(i + 100);
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_reuse_address());
client.set_no_delay(true);
});
client.bind_connect([&, i]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18036);
if (!asio2::get_last_error())
{
ASIO2_CHECK(client.get_kcp()->conv == std::uint32_t(i + 100));
}
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 20)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars[i];
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars[i];
}
client.async_send(std::move(msg));
});
bool client_start_ret = client.async_start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars[0];
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars[0];
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test udp kcp with reconnect by the same endpoint
{
struct ext_data
{
int num = 1;
};
asio2::udp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::udp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars[i];
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_send(std::move(msg));
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<my_udp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<my_udp_client>());
my_udp_client& client = *iter;
client.set_kcp_conv(i + 1000);
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&, i]()
{
client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_reuse_address());
// Specify the local port to which the socket is bind.
asio::ip::udp::endpoint ep(asio::ip::udp::v4(), std::uint16_t(1234 + i));
client.socket().bind(ep);
client.set_no_delay(true);
});
client.bind_connect([&, i]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18036);
if (!asio2::get_last_error())
{
ASIO2_CHECK(client.get_kcp()->conv == std::uint32_t(i + 1000));
}
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 10)
{
// before client.stop, the recvd kcp message should be reponsed ack, so
// we use a post to delay call client.stop, otherwise if we call
// client.stop() directly, the recvd kcp message will can't be reponsed,
// this will cause the kcp server will resent the message, and when
// this client restart again, this client maybe recvd the prev kcp
// message in the handshaking, it will cause the handshake failed.
client.post([&client]() { client.stop(); }, std::chrono::seconds(1));
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars[i];
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars[i];
}
client.async_send(std::move(msg));
});
bool client_start_ret = client.async_start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->set_send_fin(false);
}
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars[0];
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 11 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
server.foreach_session([](auto& session_ptr)
{
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
});
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18036, asio2::use_kcp);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->set_send_fin(true);
}
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars[0];
clients[i]->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 22 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test close session in no io_context thread.
{
asio2::udp_server server;
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
session_ptr->set_user_data(server_connect_counter.load());
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18036);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18036);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::udp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::udp_client>());
asio2::udp_client& client = *iter;
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18036);
client_connect_counter++;
std::size_t bytes = client.send("defg");
ASIO2_CHECK(bytes == 0);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
bool client_start_ret = client.start("127.0.0.1", 18036);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
std::vector<std::shared_ptr<asio2::udp_session>> sessions;
// find session maybe true, beacuse the next session maybe used the stopped session "this" address
//ASIO2_CHECK(!server.find_session(session_key));
server.foreach_session([&sessions](std::shared_ptr<asio2::udp_session>& session_ptr) mutable
{
ASIO2_CHECK(session_ptr->user_data_any().has_value());
sessions.emplace_back(session_ptr);
});
ASIO2_CHECK_VALUE(sessions.size(), sessions.size() == std::size_t(test_client_count));
for (std::size_t i = 0; i < sessions.size(); i++)
{
std::shared_ptr<asio2::udp_session>& session = sessions[i];
if (i % 2 == 0)
{
session->stop();
ASIO2_CHECK(session->is_stopped());
}
else
{
session->post([session]()
{
session->stop();
});
//ASIO2_CHECK(!session->is_stopped()); // maybe stopped==true
}
}
sessions.clear();
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
for (auto& c : clients)
{
c->stop();
ASIO2_CHECK(c->is_stopped());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"udp",
ASIO2_TEST_CASE(udp_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* C++0x : Storing any type of std::function in a std::map
* https://stackoverflow.com/questions/7624017/c0x-storing-any-type-of-stdfunction-in-a-stdmap
*/
#ifndef __ASIO2_LISTENER_HPP__
#define __ASIO2_LISTENER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <functional>
#include <array>
#include <tuple>
#include <type_traits>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/util.hpp>
namespace asio2::detail
{
enum class event_type : std::int8_t
{
recv,
send,
connect,
disconnect,
accept,
handshake,
upgrade,
init,
start,
stop,
max
};
class observer_base
{
public:
virtual ~observer_base() noexcept {}
};
template<class... Args>
class observer_t : public observer_base
{
public:
using func_type = std::function<void(Args...)>;
using args_type = std::tuple<Args...>;
explicit observer_t(const func_type & fn) : fn_(fn) {}
explicit observer_t( func_type && fn) : fn_(std::move(fn)) {}
explicit observer_t(const observer_t<Args...> & other) : fn_(other.fn_) {}
explicit observer_t( observer_t<Args...> && other) : fn_(std::move(other.fn_)) {}
template<class F, class ...C>
explicit observer_t(F&& f, C&&... c)
{
this->bind(std::forward<F>(f), std::forward<C>(c)...);
}
template<class F, class ...C>
inline void bind(F&& f, C&&... c)
{
if constexpr (sizeof...(C) == std::size_t(0))
{
this->fn_ = func_type(std::forward<F>(f));
}
else
{
if constexpr (std::is_member_function_pointer_v<detail::remove_cvref_t<F>>)
{
if constexpr (sizeof...(C) == std::size_t(1))
{
this->bind_memfn(std::forward<F>(f), std::forward<C>(c)...);
}
else
{
this->bind_memfn_front(std::forward<F>(f), std::forward<C>(c)...);
}
}
else
{
this->bind_fn_front(std::forward<F>(f), std::forward<C>(c)...);
}
}
}
template<class F, class C>
inline void bind_memfn(F&& f, C&& c)
{
if constexpr /**/ (std::is_pointer_v<detail::remove_cvref_t<C>>)
{
this->fn_ = [fn = std::forward<F>(f), s = std::forward<C>(c)](Args&&... args) mutable
{
(s->*fn)(std::forward<Args>(args)...);
};
}
else if constexpr (std::is_reference_v<std::remove_cv_t<C>>)
{
this->fn_ = [fn = std::forward<F>(f), s = std::forward<C>(c)](Args&&... args) mutable
{
(s.*fn)(std::forward<Args>(args)...);
};
}
else
{
static_assert(detail::always_false_v<F>,
"the class object parameters of C&& c must be pointer or refrence");
}
}
template<class F, class C, class... Ts>
inline void bind_memfn_front(F&& f, C&& c, Ts&&... ts)
{
if constexpr /**/ (std::is_pointer_v<detail::remove_cvref_t<C>>)
{
this->fn_ = [fn = std::forward<F>(f), s = std::forward<C>(c), tp = std::tuple(std::forward<Ts>(ts)...)]
(Args&&... args) mutable
{
invoke_memfn_front(fn, s, std::make_index_sequence<sizeof...(Ts)>{}, tp, std::forward<Args>(args)...);
};
}
else if constexpr (std::is_reference_v<std::remove_cv_t<C>>)
{
this->fn_ = [fn = std::forward<F>(f), s = std::forward<C>(c), tp = std::tuple(std::forward<Ts>(ts)...)]
(Args&&... args) mutable
{
invoke_memfn_front(fn, std::addressof(s), std::make_index_sequence<sizeof...(Ts)>{}, tp, std::forward<Args>(args)...);
};
}
else
{
static_assert(detail::always_false_v<F>,
"the class object parameters of C&& c must be pointer or refrence");
}
}
template<typename F, typename C, std::size_t... I, typename... Ts>
inline static void invoke_memfn_front(F& f, C* c, std::index_sequence<I...>, std::tuple<Ts...>& tp, Args&&... args)
{
(c->*f)(std::get<I>(tp)..., std::forward<Args>(args)...);
}
template<class F, class... Ts>
inline void bind_fn_front(F&& f, Ts&&... ts)
{
this->fn_ = [fn = std::forward<F>(f), tp = std::tuple(std::forward<Ts>(ts)...)]
(Args&&... args) mutable
{
invoke_fn_front(fn, std::make_index_sequence<sizeof...(Ts)>{}, tp, std::forward<Args>(args)...);
};
}
template<typename F, std::size_t... I, typename... Ts>
inline static void invoke_fn_front(F& f, std::index_sequence<I...>, std::tuple<Ts...>& tp, Args&&... args)
{
f(std::get<I>(tp)..., std::forward<Args>(args)...);
}
inline void operator()(Args&&... args)
{
if (this->fn_)
this->fn_(std::forward<Args>(args)...);
}
inline func_type move() noexcept { return std::move(this->fn_); }
protected:
func_type fn_;
};
class listener_t
{
public:
listener_t() {}
~listener_t() = default;
template<class T>
inline void bind(event_type e, T&& observer)
{
this->observers_[detail::to_underlying(e)] =
std::unique_ptr<observer_base>(new T(std::forward<T>(observer)));
}
template<class... Args>
inline void notify(event_type e, Args&&... args)
{
using observer_type = observer_t<Args...>;
observer_type* observer_ptr = static_cast<observer_type*>(
this->observers_[detail::to_underlying(e)].get());
if (observer_ptr)
{
(*observer_ptr)(std::forward<Args>(args)...);
}
}
inline std::unique_ptr<observer_base>& find(event_type e) noexcept
{
return this->observers_[detail::to_underlying(e)];
}
protected:
std::array<std::unique_ptr<observer_base>, detail::to_underlying(event_type::max)> observers_;
};
}
#endif // !__ASIO2_LISTENER_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_MICROTEC_H
#define BHO_PREDEF_COMPILER_MICROTEC_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_MRI`
http://www.mentor.com/microtec/[Microtec C/{CPP}] compiler.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+_MRI+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_COMP_MRI BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(_MRI)
# define BHO_COMP_MRI_DETECTION BHO_VERSION_NUMBER_AVAILABLE
#endif
#ifdef BHO_COMP_MRI_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_MRI_EMULATED BHO_COMP_MRI_DETECTION
# else
# undef BHO_COMP_MRI
# define BHO_COMP_MRI BHO_COMP_MRI_DETECTION
# endif
# define BHO_COMP_MRI_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_MRI_NAME "Microtec C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_MRI,BHO_COMP_MRI_NAME)
#ifdef BHO_COMP_MRI_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_MRI_EMULATED,BHO_COMP_MRI_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SHUTDOWN_COMPONENT_HPP__
#define __ASIO2_SHUTDOWN_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
// Asio end socket functions: cancel, shutdown, close, release :
// https://stackoverflow.com/questions/51468848/asio-end-socket-functions-cancel-shutdown-close-release
// The proper steps are:
// 1.Call shutdown() to indicate that you will not write any more data to the socket.
// 2.Continue to (async-) read from the socket until you get either an error or the connection is closed.
// 3.Now close() the socket (in the async read handler).
// If you don't do this, you may end up closing the connection while the other side is still sending data.
// This will result in an ungraceful close.
// http://www.purecpp.cn/detail?id=2303
// https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-shutdown
//
// To assure that all data is sent and received on a connected socket before it is closed,
// an application should use shutdown to close connection before calling closesocket.
// One method to wait for notification that the remote end has sent all its data and initiated
// a graceful disconnect uses the WSAEventSelect function as follows :
//
// 1. Call WSAEventSelect to register for FD_CLOSE notification.
// 2. Call shutdown with how=SD_SEND.
// 3. When FD_CLOSE received, call the recv or WSARecv until the function completes with success
// and indicates that zero bytes were received. If SOCKET_ERROR is returned, then the graceful
// disconnect is not possible.
// 4. Call closesocket.
//
// Another method to wait for notification that the remote end has sent all its data and initiated
// a graceful disconnect uses overlapped receive calls follows :
//
// 1. Call shutdown with how=SD_SEND.
// 2. Call recv or WSARecv until the function completes with success and indicates zero bytes were
// received. If SOCKET_ERROR is returned, then the graceful disconnect is not possible.
// 3. Call closesocket.
// https://stackoverflow.com/questions/60105082/using-shutdown-for-a-udp-socket
// Calling shutdown() on a UDP socket does nothing on the wire, and only affects the state of the
// socket object.
// after test on windows, call shutdown on udp socket, the recv won't return with a error.
namespace asio2::detail
{
template<class derived_t, class args_t>
class shutdown_cp
{
public:
using self = shutdown_cp<derived_t, args_t>;
public:
/**
* @brief constructor
*/
shutdown_cp() noexcept {}
/**
* @brief destructor
*/
~shutdown_cp() = default;
protected:
template<typename DeferEvent>
inline void _do_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
// call shutdown manual in client:
// 1. the session recv function will return with error of eof,
// call closesocket in the session recv function is ok.
// 2. the client recv function will return with error of eof
// call closesocket in the client recv function is ok.
// but at ssl mode:
// 1. we must call async_shutdown to execute the ssl stream close handshake first.
// 2. then we can call shutdown.
// when the recv function is returned with error of eof, there are two possible that
// can trigger this situation:
// 1. call shutdown manual.
// 2. recvd the shutdown notify of the another peer.
// so:
// 1. when we call shutdown manual, then the recv function will return with error eof,
// at this time, we shouldn't call shutdown and make shutdown timer again, we should
// call closesocket directly.
// 2. when we recvd the shutdown notify of the another peer, then the recv function will
// return with error eof, at this time, we shouldn't call shutdown and make shutdown
// timer again too, we should call closesocket directly too.
// so:
// we should check whether the shutdown timer is empty, if it is true, it means the
// shutdown is not yet called by manual, then we should call shutdown. if it is false,
// it means the shutdown is called already by manual, then we should call closesocket.
ASIO2_ASSERT(derive.io().running_in_this_thread());
ASIO2_LOG_DEBUG("shutdown_cp::_do_shutdown enter: {} {}", ec.value(), ec.message());
// if disconnect is in progress, and not finished, we can't do a new disconnect again.
// otherwise, this situation will has problem:
// client.post([&]()
// {
// client.stop();
// client.start(...);
// });
// after post a connect event, then a new disconnect event maybe pushed into the queue
// again, this will cause the start has no effect.
if (derive.shutdown_timer_ || derive.disconnecting_)
{
derive._stop_shutdown_timer(std::move(this_ptr));
return;
}
derive.disp_event(
[&derive, ec, this_ptr = std::move(this_ptr), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
set_last_error(ec);
// make a new chain, if the chain can't be passed to other functions, the chain
// should be destroyed at the end of this function, then the function of this
// chain will be called, otherwise this situation will be happen:
//
// client.post([&]()
// {
// client.stop();
// client.start(...);
// });
//
// client stop will post a event, and this event is before the client.start, and
// at this time the state maybe stopped, so the chain can't be passed to other
// fuctions, then the event guard will destroyed, then the next event "client.start"
// will be called, then the stop's callback "do stop" will be called, but at this
// time, the state is starting, which not equal to stopped.
//
defer_event chain(std::move(e), std::move(g));
ASIO2_LOG_DEBUG("shutdown_cp::_do_shutdown leave: {} {} state={}",
ec.value(), ec.message(), detail::to_string(derive.state().load()));
state_t expected = state_t::started;
if (derive.state().compare_exchange_strong(expected, state_t::started))
{
derive.disconnecting_ = true;
return derive._post_shutdown(ec, std::move(this_ptr), std::move(chain));
}
expected = state_t::starting;
if (derive.state().compare_exchange_strong(expected, state_t::starting))
{
derive.disconnecting_ = true;
return derive._post_shutdown(ec, std::move(this_ptr), std::move(chain));
}
}, chain.move_guard());
}
template<typename DeferEvent>
inline void _post_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
ASIO2_LOG_DEBUG("shutdown_cp::_post_shutdown: {} {}", ec.value(), ec.message());
if constexpr (std::is_same_v<typename derived_t::socket_type::protocol_type, asio::ip::tcp>)
{
derive._post_shutdown_tcp(ec, std::move(this_ptr), std::move(chain));
}
else
{
derive._handle_shutdown(ec, std::move(this_ptr), std::move(chain));
}
}
template<typename DeferEvent>
inline void _post_shutdown_tcp(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
// the socket maybe closed already in the connect timeout timer.
if (derive.socket().is_open())
{
error_code ec_linger{};
asio::socket_base::linger lnger{};
derive.socket().lowest_layer().get_option(lnger, ec_linger);
// call socket's close function to notify the _handle_recv function response with
// error > 0 ,then the socket can get notify to exit
// Call shutdown() to indicate that you will not write any more data to the socket.
if (!ec_linger && !(lnger.enabled() == true && lnger.timeout() == 0))
{
error_code ec_shutdown{};
derive.socket().shutdown(asio::socket_base::shutdown_send, ec_shutdown);
// if the reading is true , it means that the shutdown is called by manual.
// if the reading is false, it means that the shutdown is called by the recv
// error.
//
// after call shutdown, the recv function should be returned with error, but
// when use our http server and the client is pc broswer, even if we has called
// shutdown, the recv function still won't be returned, so we must use a timeout
// timer to ensure the closesocket can be called.
//
// and some times, even if we has called shutdown, the http session' recv fucntion
// will returned with no error.
if (!ec_shutdown && derive.reading_)
{
derive._make_shutdown_timer(ec, std::move(this_ptr), std::move(chain));
return;
}
}
}
derive._handle_shutdown(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _handle_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
ASIO2_LOG_DEBUG("shutdown_cp::_handle_shutdown: {} {}", ec.value(), ec.message());
this->shutdown_timer_.reset();
derive._do_close(ec, std::move(this_ptr), std::move(chain));
}
protected:
template<typename DeferEvent>
inline void _make_shutdown_timer(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, ec, this_ptr = std::move(this_ptr), chain = std::move(chain)]() mutable
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(this->shutdown_timer_ == nullptr);
if (this->shutdown_timer_)
{
this->shutdown_timer_->cancel();
}
this->shutdown_timer_ = std::make_shared<safe_timer>(derive.io().context());
derive._post_shutdown_timer(ec, std::move(this_ptr), std::move(chain),
derive.get_disconnect_timeout(), this->shutdown_timer_);
}));
}
template<typename DeferEvent, class Rep, class Period>
inline void _post_shutdown_timer(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain,
std::chrono::duration<Rep, Period> duration, std::shared_ptr<safe_timer> timer_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
// a new timer is maked, this is the prev timer, so return directly.
if (timer_ptr.get() != this->shutdown_timer_.get())
return;
safe_timer* ptimer = timer_ptr.get();
ptimer->timer.expires_after(duration);
ptimer->timer.async_wait(
[&derive, ec, this_ptr = std::move(this_ptr), chain = std::move(chain), timer_ptr = std::move(timer_ptr)]
(const error_code& timer_ec) mutable
{
derive._handle_shutdown_timer(
timer_ec, ec, std::move(this_ptr), std::move(chain), std::move(timer_ptr));
});
}
template<typename DeferEvent>
inline void _handle_shutdown_timer(
const error_code& timer_ec,
const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain,
std::shared_ptr<safe_timer> timer_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT((!timer_ec) || timer_ec == asio::error::operation_aborted);
// a new timer is maked, this is the prev timer, so return directly.
if (timer_ptr.get() != this->shutdown_timer_.get())
return;
// member variable timer should't be empty
if (!this->shutdown_timer_)
{
ASIO2_ASSERT(false);
return;
}
// current timer is canceled by manual
if (timer_ec == asio::error::operation_aborted || timer_ptr->canceled.test_and_set())
{
timer_ptr->canceled.clear();
ASIO2_LOG_DEBUG("shutdown_cp::_handle_shutdown_timer: canceled");
derive._handle_shutdown(ec, std::move(this_ptr), std::move(chain));
}
// timeout
else
{
timer_ptr->canceled.clear();
std::chrono::system_clock::duration silence = derive.get_silence_duration();
// if recvd data in shutdown timeout period, lengthened the timer to remained times.
if (silence < derive.get_disconnect_timeout())
{
derive._post_shutdown_timer(ec, std::move(this_ptr), std::move(chain),
derive.get_disconnect_timeout() - silence, std::move(timer_ptr));
}
else
{
ASIO2_LOG_DEBUG("shutdown_cp::_handle_shutdown_timer: timeout");
derive._handle_shutdown(ec, std::move(this_ptr), std::move(chain));
}
}
}
inline void _stop_shutdown_timer(std::shared_ptr<derived_t> this_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = std::move(this_ptr)]() mutable
{
if (this->shutdown_timer_)
{
this->shutdown_timer_->cancel();
}
}));
}
protected:
/// beacuse the shutdown timer is used only when shutdown, so we use a pointer
/// to reduce memory space occupied when running
std::shared_ptr<safe_timer> shutdown_timer_;
};
}
#endif // !__ASIO2_SHUTDOWN_COMPONENT_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_HTTPS_SESSION_HPP__
#define __ASIO2_HTTPS_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/http/http_session.hpp>
#include <asio2/tcp/impl/ssl_stream_cp.hpp>
namespace asio2::detail
{
struct template_args_https_session : public template_args_http_session
{
using stream_t = websocket::stream<asio::ssl::stream<typename template_args_http_session::socket_t&>&>;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class derived_t, class args_t = template_args_https_session>
class https_session_impl_t
: public http_session_impl_t<derived_t, args_t>
, public ssl_stream_cp <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
public:
using super = http_session_impl_t <derived_t, args_t>;
using self = https_session_impl_t<derived_t, args_t>;
using args_type = args_t;
using key_type = std::size_t;
using body_type = typename args_t::body_t;
using buffer_type = typename args_t::buffer_t;
using ws_stream_comp = ws_stream_cp <derived_t, args_t>;
using ssl_stream_comp = ssl_stream_cp<derived_t, args_t>;
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
explicit https_session_impl_t(
http_router_t<derived_t, args_t> & router,
std::filesystem::path & root_directory,
bool is_arg0_session,
bool support_websocket,
asio::ssl::context & ctx,
session_mgr_t<derived_t> & sessions,
listener_t & listener,
io_t & rwio,
std::size_t init_buf_size,
std::size_t max_buf_size
)
: super(router, root_directory, is_arg0_session, support_websocket,
sessions, listener, rwio, init_buf_size, max_buf_size)
, ssl_stream_comp(this->io_, ctx, asio::ssl::stream_base::server)
, ctx_(ctx)
{
}
/**
* @brief destructor
*/
~https_session_impl_t()
{
}
/**
* @brief get the stream object refrence
*/
inline typename ssl_stream_comp::ssl_stream_type& stream() noexcept
{
return this->derived().ssl_stream();
}
public:
/**
* @brief get this object hash key,used for session map
*/
inline key_type hash_key() const noexcept
{
return reinterpret_cast<key_type>(this);
}
protected:
template<typename C>
inline void _do_init(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
this->derived()._ssl_init(ecs, this->socket_, this->ctx_);
super::_do_init(this_ptr, ecs);
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
detail::ignore_unused(ec);
ASIO2_ASSERT(!ec);
ASIO2_ASSERT(this->derived().sessions().io().running_in_this_thread());
asio::dispatch(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
this->derived()._ssl_start(this_ptr, ecs, this->socket_, this->ctx_);
this->derived()._post_handshake(std::move(this_ptr), std::move(ecs), std::move(chain));
}));
}
template<typename DeferEvent>
inline void _post_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_LOG_DEBUG("https_session::_post_shutdown: {} {}", ec.value(), ec.message());
if (this->is_http())
{
this->derived()._ssl_stop(this_ptr, defer_event
{
[this, ec, this_ptr, e = chain.move_event()](event_queue_guard<derived_t> g) mutable
{
super::_post_shutdown(ec, std::move(this_ptr), defer_event(std::move(e), std::move(g)));
}, chain.move_guard()
});
}
else
{
this->derived()._ws_stop(this_ptr, defer_event
{
[this, ec, this_ptr, e = chain.move_event()](event_queue_guard<derived_t> g) mutable
{
this->derived()._ssl_stop(this_ptr, defer_event
{
[this, ec, this_ptr, e = std::move(e)](event_queue_guard<derived_t> g) mutable
{
super::super::_post_shutdown(
ec, std::move(this_ptr), defer_event(std::move(e), std::move(g)));
}, std::move(g)
});
}, chain.move_guard()
});
}
}
inline void _fire_handshake(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_handshake must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
this->listener_.notify(event_type::handshake, this_ptr);
}
protected:
asio::ssl::context & ctx_;
};
}
namespace asio2
{
using https_session_args = detail::template_args_https_session;
template<class derived_t, class args_t>
using https_session_impl_t = detail::https_session_impl_t<derived_t, args_t>;
template<class derived_t>
class https_session_t : public detail::https_session_impl_t<derived_t, detail::template_args_https_session>
{
public:
using detail::https_session_impl_t<derived_t, detail::template_args_https_session>::https_session_impl_t;
};
class https_session : public https_session_t<https_session>
{
public:
using https_session_t<https_session>::https_session_t;
};
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct https_rate_session_args : public https_session_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
using stream_t = websocket::stream<asio::ssl::stream<socket_t&>&>;
};
template<class derived_t>
class https_rate_session_t : public asio2::https_session_impl_t<derived_t, https_rate_session_args>
{
public:
using asio2::https_session_impl_t<derived_t, https_rate_session_args>::https_session_impl_t;
};
class https_rate_session : public asio2::https_rate_session_t<https_rate_session>
{
public:
using asio2::https_rate_session_t<https_rate_session>::https_rate_session_t;
};
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTPS_SESSION_HPP__
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_WS_CLIENT_HPP__
#define __ASIO2_WS_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_client.hpp>
#include <asio2/http/detail/http_util.hpp>
#include <asio2/http/impl/ws_stream_cp.hpp>
#include <asio2/http/impl/ws_send_op.hpp>
namespace asio2::detail
{
struct template_args_ws_client : public template_args_tcp_client
{
using stream_t = websocket::stream<typename template_args_tcp_client::socket_t&>;
using body_t = http::string_body;
using buffer_t = beast::flat_buffer;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class derived_t, class args_t = template_args_ws_client>
class ws_client_impl_t
: public tcp_client_impl_t<derived_t, args_t>
, public ws_stream_cp <derived_t, args_t>
, public ws_send_op <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using super = tcp_client_impl_t<derived_t, args_t>;
using self = ws_client_impl_t <derived_t, args_t>;
using args_type = args_t;
using body_type = typename args_t::body_t;
using buffer_type = typename args_t::buffer_t;
using ws_stream_comp = ws_stream_cp<derived_t, args_t>;
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
template<class... Args>
explicit ws_client_impl_t(Args&&... args)
: super(std::forward<Args>(args)...)
, ws_stream_cp<derived_t, args_t>()
, ws_send_op <derived_t, args_t>()
{
}
/**
* @brief destructor
*/
~ws_client_impl_t()
{
this->stop();
}
/**
* @brief return the websocket stream object refrence
*/
inline typename args_t::stream_t& stream() noexcept
{
return this->derived().ws_stream();
}
/**
* @brief start the client, blocking connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
* @param args - The args can be include the upgraged target.
* eg: start("127.0.0.1", 8883); start("127.0.0.1", 8883, "/admin");
* the "/admin" is the websocket upgraged target
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& port, Args&&... args)
{
if constexpr (sizeof...(Args) > std::size_t(0))
return this->derived().template _do_connect_with_target<false>(
std::forward<String>(host), std::forward<StrOrInt>(port),
std::forward<Args>(args)...);
else
return this->derived().template _do_connect<false>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
/**
* @brief start the client, asynchronous connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
* @param args - The args can be include the upgraged target.
* eg: async_start("127.0.0.1", 8883); async_start("127.0.0.1", 8883, "/admin");
* the "/admin" is the websocket upgraged target
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool async_start(String&& host, StrOrInt&& port, Args&&... args)
{
if constexpr (sizeof...(Args) > std::size_t(0))
return this->derived().template _do_connect_with_target<true>(
std::forward<String>(host), std::forward<StrOrInt>(port),
std::forward<Args>(args)...);
else
return this->derived().template _do_connect<true>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
/**
* @brief get the websocket upgraged response object
*/
inline const websocket::response_type& get_upgrade_response() noexcept { return this->upgrade_rep_; }
/**
* @brief get the websocket upgraged target
*/
inline const std::string& get_upgrade_target() noexcept { return this->upgrade_target_; }
/**
* @brief set the websocket upgraged target
*/
inline derived_t & set_upgrade_target(std::string target)
{
this->upgrade_target_ = std::move(target);
return (this->derived());
}
public:
/**
* @brief bind websocket upgrade listener
* @param fun - a user defined callback function.
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_upgrade(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::upgrade,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<bool IsAsync, typename String, typename StrOrInt, typename Arg1, typename... Args>
bool _do_connect_with_target(String&& host, StrOrInt&& port, Arg1&& arg1, Args&&... args)
{
if constexpr (detail::can_convert_to_string<detail::remove_cvref_t<Arg1>>::value)
{
this->derived().set_upgrade_target(std::forward<Arg1>(arg1));
return this->derived().template _do_connect<IsAsync>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
else
{
return this->derived().template _do_connect<IsAsync>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0',
std::forward<Arg1>(arg1), std::forward<Args>(args)...));
}
}
template<typename C>
inline void _do_init(std::shared_ptr<ecs_t<C>>& ecs)
{
super::_do_init(ecs);
this->derived()._ws_init(ecs, this->socket_);
}
template<typename DeferEvent>
inline void _post_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_LOG_DEBUG("ws_client::_post_shutdown: {} {}", ec.value(), ec.message());
this->derived()._ws_stop(this_ptr, defer_event
{
[this, ec, this_ptr, e = chain.move_event()] (event_queue_guard<derived_t> g) mutable
{
super::_post_shutdown(ec, std::move(this_ptr), defer_event(std::move(e), std::move(g)));
}, chain.move_guard()
});
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
set_last_error(ec);
derived_t& derive = this->derived();
if (ec)
{
return derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
derive._ws_start(this_ptr, ecs, this->socket_);
derive._post_control_callback(this_ptr, ecs);
derive._post_upgrade(std::move(this_ptr), std::move(ecs), this->upgrade_rep_, std::move(chain));
}
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
return this->derived()._ws_send(data, std::forward<Callback>(callback));
}
protected:
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._ws_post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._ws_handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}
inline void _fire_upgrade(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_upgrade must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
detail::ignore_unused(this_ptr);
this->listener_.notify(event_type::upgrade);
}
protected:
websocket::response_type upgrade_rep_;
std::string upgrade_target_ = "/";
};
}
namespace asio2
{
using ws_client_args = detail::template_args_ws_client;
template<class derived_t, class args_t>
using ws_client_impl_t = detail::ws_client_impl_t<derived_t, args_t>;
template<class derived_t>
class ws_client_t : public detail::ws_client_impl_t<derived_t, detail::template_args_ws_client>
{
public:
using detail::ws_client_impl_t<derived_t, detail::template_args_ws_client>::ws_client_impl_t;
};
class ws_client : public ws_client_t<ws_client>
{
public:
using ws_client_t<ws_client>::ws_client_t;
};
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct ws_rate_client_args : public ws_client_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
using stream_t = websocket::stream<socket_t&>;
};
template<class derived_t>
class ws_rate_client_t : public asio2::ws_client_impl_t<derived_t, ws_rate_client_args>
{
public:
using asio2::ws_client_impl_t<derived_t, ws_rate_client_args>::ws_client_impl_t;
};
class ws_rate_client : public asio2::ws_rate_client_t<ws_rate_client>
{
public:
using asio2::ws_rate_client_t<ws_rate_client>::ws_rate_client_t;
};
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_WS_CLIENT_HPP__
<file_sep>/*
Copyright <NAME> 2015
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_HARDWARE_SIMD_PPC_H
#define BHO_PREDEF_HARDWARE_SIMD_PPC_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/hardware/simd/ppc/versions.h>
/* tag::reference[]
= `BHO_HW_SIMD_PPC`
The SIMD extension for PowerPC (*if detected*).
Version number depends on the most recent detected extension.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__VECTOR4DOUBLE__+` | {predef_detection}
| `+__ALTIVEC__+` | {predef_detection}
| `+__VEC__+` | {predef_detection}
| `+__VSX__+` | {predef_detection}
|===
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__VECTOR4DOUBLE__+` | BHO_HW_SIMD_PPC_QPX_VERSION
| `+__ALTIVEC__+` | BHO_HW_SIMD_PPC_VMX_VERSION
| `+__VEC__+` | BHO_HW_SIMD_PPC_VMX_VERSION
| `+__VSX__+` | BHO_HW_SIMD_PPC_VSX_VERSION
|===
*/ // end::reference[]
#define BHO_HW_SIMD_PPC BHO_VERSION_NUMBER_NOT_AVAILABLE
#undef BHO_HW_SIMD_PPC
#if !defined(BHO_HW_SIMD_PPC) && defined(__VECTOR4DOUBLE__)
# define BHO_HW_SIMD_PPC BHO_HW_SIMD_PPC_QPX_VERSION
#endif
#if !defined(BHO_HW_SIMD_PPC) && defined(__VSX__)
# define BHO_HW_SIMD_PPC BHO_HW_SIMD_PPC_VSX_VERSION
#endif
#if !defined(BHO_HW_SIMD_PPC) && (defined(__ALTIVEC__) || defined(__VEC__))
# define BHO_HW_SIMD_PPC BHO_HW_SIMD_PPC_VMX_VERSION
#endif
#if !defined(BHO_HW_SIMD_PPC)
# define BHO_HW_SIMD_PPC BHO_VERSION_NUMBER_NOT_AVAILABLE
#else
# define BHO_HW_SIMD_PPC_AVAILABLE
#endif
#define BHO_HW_SIMD_PPC_NAME "PPC SIMD"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_HW_SIMD_PPC, BHO_HW_SIMD_PPC_NAME)
<file_sep>/*
Copyright <NAME> 2011-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#if !defined(BHO_PREDEF_LANGUAGE_H) || defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BHO_PREDEF_LANGUAGE_H
#define BHO_PREDEF_LANGUAGE_H
#endif
#include <asio2/bho/predef/language/stdc.h>
#include <asio2/bho/predef/language/stdcpp.h>
#include <asio2/bho/predef/language/objc.h>
#include <asio2/bho/predef/language/cuda.h>
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_UDP_RECV_OP_HPP__
#define __ASIO2_UDP_RECV_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/ecs.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class udp_recv_op
{
public:
/**
* @brief constructor
*/
udp_recv_op() noexcept {}
/**
* @brief destructor
*/
~udp_recv_op() = default;
protected:
/**
* @brief Pre process the data before recv callback was called.
* You can overload this function in a derived class to implement additional
* processing of the data. eg: decrypt data with a custom encryption algorithm.
*/
inline std::string_view data_filter_before_recv(std::string_view data)
{
return data;
}
protected:
template<typename C>
void _udp_post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
if (!derive.is_started())
{
if (derive.state() == state_t::started)
{
derive._do_disconnect(asio2::get_last_error(), std::move(this_ptr));
}
return;
}
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_recv_counter_.load() == 0);
derive.post_recv_counter_++;
#endif
derive.reading_ = true;
derive.socket().async_receive(derive.buffer().prepare(derive.buffer().pre_size()),
make_allocator(derive.rallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(const error_code & ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_recv_counter_--;
#endif
derive.reading_ = false;
derive._handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}));
}
template<typename C>
inline void _udp_do_handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
using condition_lowest_type = typename ecs_t<C>::condition_lowest_type;
derived_t& derive = static_cast<derived_t&>(*this);
if (!ec)
{
std::string_view data = std::string_view(static_cast<std::string_view::const_pointer>
(derive.buffer().data().data()), bytes_recvd);
if constexpr (!std::is_same_v<typename ecs_t<C>::condition_lowest_type, use_kcp_t>)
{
derive._fire_recv(this_ptr, ecs, data);
}
else
{
if (derive.kcp_)
{
derive.kcp_->_kcp_handle_recv(ec, data, this_ptr, ecs);
}
else
{
ASIO2_ASSERT(false);
derive._do_disconnect(asio::error::invalid_argument, this_ptr);
derive._stop_readend_timer(std::move(this_ptr));
}
}
}
else
{
ASIO2_LOG_DEBUG("_udp_handle_recv with error: {} {}", ec.value(), ec.message());
if (ec == asio::error::eof)
{
ASIO2_ASSERT(bytes_recvd == 0);
if (bytes_recvd)
{
// http://www.purecpp.cn/detail?id=2303
ASIO2_LOG_INFOR("_udp_handle_recv with eof: {}", bytes_recvd);
}
}
}
}
template<typename C>
inline void _udp_session_handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive._udp_do_handle_recv(ec, bytes_recvd, this_ptr, ecs);
}
template<typename C>
void _udp_client_handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (ec == asio::error::operation_aborted || ec == asio::error::connection_refused)
{
derive._do_disconnect(ec, this_ptr);
derive._stop_readend_timer(std::move(this_ptr));
return;
}
derive.buffer().commit(bytes_recvd);
derive._udp_do_handle_recv(ec, bytes_recvd, this_ptr, ecs);
derive.buffer().consume(derive.buffer().size());
if (bytes_recvd == derive.buffer().pre_size())
{
derive.buffer().pre_size((std::min)(derive.buffer().pre_size() * 2, derive.buffer().max_size()));
}
derive._post_recv(this_ptr, ecs);
}
template<typename C>
void _udp_handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
set_last_error(ec);
if (!derive.is_started())
{
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, this_ptr);
}
derive._stop_readend_timer(std::move(this_ptr));
return;
}
// every times recv data,we update the last alive time.
if (!ec)
{
derive.update_alive_time();
}
if constexpr (args_t::is_session)
{
derive._udp_session_handle_recv(ec, bytes_recvd, this_ptr, ecs);
}
else
{
derive._udp_client_handle_recv(ec, bytes_recvd, this_ptr, ecs);
}
}
protected:
};
}
#endif // !__ASIO2_UDP_RECV_OP_HPP__
<file_sep>#define ASIO2_ENABLE_HTTP_REQUEST_USER_DATA
#define ASIO2_ENABLE_HTTP_RESPONSE_USER_DATA
#include "unit_test.hpp"
#include <iostream>
#include <asio2/asio2.hpp>
struct aop_log
{
bool before(http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
return true;
}
bool after(std::shared_ptr<asio2::http_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(session_ptr, req, rep);
return true;
}
};
struct aop_check
{
bool before(std::shared_ptr<asio2::http_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(session_ptr, req, rep);
return true;
}
bool after(http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
return true;
}
};
void http_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
// test http url encode decode
{
std::string_view url = "http://www.baidu.com/query?key=x!#$&'()*,/:;=?@[ ]-_.~%^{}\"|<>`\\y";
std::string_view dst = "http://www.baidu.com/query?key=x%21%23%24&%27%28%29*%2C/%3A%3B=?%40%5B%20%5D-_.%7E%25%5E%7B%7D%22%7C%3C%3E%60%5Cy";
ASIO2_CHECK(http::url_encode(url) == dst);
ASIO2_CHECK(http::url_decode(dst) == url);
ASIO2_CHECK(http::has_unencode_char(url) == true);
ASIO2_CHECK(http::has_undecode_char(url) == false);
ASIO2_CHECK(http::has_unencode_char(dst) == false);
ASIO2_CHECK(http::has_undecode_char(dst) == true);
http::web_request req = http::make_request(url);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(http::has_multipart(req) == false);
ASIO2_CHECK(req.has_multipart() == false);
ASIO2_CHECK(req.is_upgrade() == false);
ASIO2_CHECK(req.schema() == "http");
ASIO2_CHECK(req.host () == "www.baidu.com");
ASIO2_CHECK(req.port () == "80");
ASIO2_CHECK(req.path () == "/query");
ASIO2_CHECK(req.query () == "key=x%21%23%24&%27%28%29*%2C/%3A%3B=?%40%5B%20%5D-_.%7E%25%5E%7B%7D%22%7C%3C%3E%60%5Cy");
ASIO2_CHECK(req.target() == "/query?key=x%21%23%24&%27%28%29*%2C/%3A%3B=?%40%5B%20%5D-_.%7E%25%5E%7B%7D%22%7C%3C%3E%60%5Cy");
ASIO2_CHECK(req.url().schema() == req.schema());
ASIO2_CHECK(req.url().host () == req.host ());
ASIO2_CHECK(req.url().port () == req.port ());
ASIO2_CHECK(req.url().path () == req.path ());
ASIO2_CHECK(req.url().query () == req.query ());
ASIO2_CHECK(req.url().target() == req.target());
ASIO2_CHECK(http::url_to_host (url) == "www.baidu.com");
ASIO2_CHECK(http::url_to_port (url) == "80");
ASIO2_CHECK(http::url_to_path (url) == "/query");
// get the query with no encoded url will return a incorrect result
//ASIO2_CHECK(http::url_to_query(url) == "key=x!#$&'()*,/:;=?@[ ]-_.~%^{}\"|<>`\\y");
ASIO2_CHECK(http::url_to_host (dst) == req.host ());
ASIO2_CHECK(http::url_to_port (dst) == req.port ());
ASIO2_CHECK(http::url_to_path (dst) == req.path ());
ASIO2_CHECK(http::url_to_query(dst) == req.query ());
}
{
std::string_view url = R"(http://www.baidu.com/childpathtest/json={"qeury":"name like '%abc%'","id":1})";
std::string_view dst = R"(http://www.baidu.com/childpathtest/json=%7B%22qeury%22%3A%22name%20like%20%27%25abc%25%27%22%2C%22id%22%3A1%7D)";
ASIO2_CHECK(http::url_encode(url) == dst);
ASIO2_CHECK(http::url_decode(dst) == url);
ASIO2_CHECK(asio2::http::url_to_path("/get_user?name=abc") == "/get_user");
ASIO2_CHECK(asio2::http::url_to_query("/get_user?name=abc") == "name=abc");
}
// test http url encode decode
{
std::string_view url = "http://127.0.0.1/index.asp?id=x!#$&name='()*+,/:;=?@[ ]-_.~%^{}\"|<>`\\y";
std::string_view dst = "http://127.0.0.1/index.asp?id=x%21%23%24&name=%27%28%29*%2B%2C/%3A%3B=?%40%5B%20%5D-_.%7E%25%5E%7B%7D%22%7C%3C%3E%60%5Cy";
ASIO2_CHECK(http::url_encode(url) == dst);
ASIO2_CHECK(http::url_decode(dst) == url);
ASIO2_CHECK(http::has_unencode_char(url) == true);
ASIO2_CHECK(http::has_undecode_char(url) == true); // "+"
ASIO2_CHECK(http::has_unencode_char(dst) == false);
ASIO2_CHECK(http::has_undecode_char(dst) == true);
http::web_request req = http::make_request(url);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(req.get_schema() == "http");
ASIO2_CHECK(req.get_host () == "127.0.0.1");
ASIO2_CHECK(req.get_port () == "80");
ASIO2_CHECK(req.get_path () == "/index.asp");
ASIO2_CHECK(req.get_query () == "id=x%21%23%24&name=%27%28%29*%2B%2C/%3A%3B=?%40%5B%20%5D-_.%7E%25%5E%7B%7D%22%7C%3C%3E%60%5Cy");
ASIO2_CHECK(req.target() == "/index.asp?id=x%21%23%24&name=%27%28%29*%2B%2C/%3A%3B=?%40%5B%20%5D-_.%7E%25%5E%7B%7D%22%7C%3C%3E%60%5Cy");
ASIO2_CHECK(req.url().schema() == req.schema());
ASIO2_CHECK(req.url().host () == req.host ());
ASIO2_CHECK(req.url().port () == req.port ());
ASIO2_CHECK(req.url().path () == req.path ());
ASIO2_CHECK(req.url().query () == req.query ());
ASIO2_CHECK(req.url().target() == req.target());
ASIO2_CHECK(http::url_to_host (url) == "127.0.0.1");
ASIO2_CHECK(http::url_to_port (url) == "80");
ASIO2_CHECK(http::url_to_path (url) == "/index.asp");
ASIO2_CHECK(http::url_to_host (dst) == req.host ());
ASIO2_CHECK(http::url_to_port (dst) == req.port ());
ASIO2_CHECK(http::url_to_path (dst) == req.path ());
ASIO2_CHECK(http::url_to_query(dst) == req.query ());
}
// test http url encode decode
{
std::string_view url = "https://github.com/search?q=utf8 user:zhllxt";
std::string_view dst = "https://github.com/search?q=utf8%20user%3Azhllxt";
ASIO2_CHECK(http::url_encode(url) == dst);
ASIO2_CHECK(http::url_decode(dst) == url);
ASIO2_CHECK(http::has_unencode_char(url) == true);
ASIO2_CHECK(http::has_undecode_char(url) == false);
ASIO2_CHECK(http::has_unencode_char(dst) == false);
ASIO2_CHECK(http::has_undecode_char(dst) == true);
http::web_request req = http::make_request(url);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(req.schema() == "https");
ASIO2_CHECK(req.host () == "github.com");
ASIO2_CHECK(req.port () == "443");
ASIO2_CHECK(req.path () == "/search");
ASIO2_CHECK(req.query () == "q=utf8%20user%3Azhllxt");
ASIO2_CHECK(req.target() == "/search?q=utf8%20user%3Azhllxt");
ASIO2_CHECK(req.url().schema() == req.schema());
ASIO2_CHECK(req.url().host () == req.host ());
ASIO2_CHECK(req.url().port () == req.port ());
ASIO2_CHECK(req.url().path () == req.path ());
ASIO2_CHECK(req.url().query () == req.query ());
ASIO2_CHECK(req.url().target() == req.target());
ASIO2_CHECK(http::url_to_host (url) == "github.com");
ASIO2_CHECK(http::url_to_port (url) == "443");
ASIO2_CHECK(http::url_to_path (url) == "/search");
ASIO2_CHECK(http::url_to_query(url) == "q=utf8 user:zhllxt");
ASIO2_CHECK(http::url_to_host (dst) == req.host ());
ASIO2_CHECK(http::url_to_port (dst) == req.port ());
ASIO2_CHECK(http::url_to_path (dst) == req.path ());
ASIO2_CHECK(http::url_to_query(dst) == req.query ());
}
// test http url encode decode
{
std::string_view url = "http://127.0.0.1:8080/search?q=c++ module user:zhllxt&s=f48fcb6f-f7d2-4ac0-b688-9931785f16bb";
std::string_view dst = "http://127.0.0.1:8080/search?q=c%2B%2B%20module%20user%3Azhllxt&s=f48fcb6f-f7d2-4ac0-b688-9931785f16bb";
ASIO2_CHECK(http::url_encode(url) == dst);
ASIO2_CHECK(http::url_decode(dst) == url);
ASIO2_CHECK(http::has_unencode_char(url) == true);
ASIO2_CHECK(http::has_undecode_char(url) == true); // "+"
ASIO2_CHECK(http::has_unencode_char(dst) == false);
ASIO2_CHECK(http::has_undecode_char(dst) == true);
http::web_request req = http::make_request(url);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(req.schema() == "http");
ASIO2_CHECK(req.host () == "127.0.0.1");
ASIO2_CHECK(req.port () == "8080");
ASIO2_CHECK(req.path () == "/search");
ASIO2_CHECK(req.query () == "q=c%2B%2B%20module%20user%3Azhllxt&s=f48fcb6f-f7d2-4ac0-b688-9931785f16bb");
ASIO2_CHECK(req.target() == "/search?q=c%2B%2B%20module%20user%3Azhllxt&s=f48fcb6f-f7d2-4ac0-b688-9931785f16bb");
ASIO2_CHECK(req.url().schema() == req.schema());
ASIO2_CHECK(req.url().host () == req.host ());
ASIO2_CHECK(req.url().port () == req.port ());
ASIO2_CHECK(req.url().path () == req.path ());
ASIO2_CHECK(req.url().query () == req.query ());
ASIO2_CHECK(req.url().target() == req.target());
ASIO2_CHECK(http::url_to_host (url) == "127.0.0.1");
ASIO2_CHECK(http::url_to_port (url) == "8080");
ASIO2_CHECK(http::url_to_path (url) == "/search");
ASIO2_CHECK(http::url_to_host (dst) == req.host ());
ASIO2_CHECK(http::url_to_port (dst) == req.port ());
ASIO2_CHECK(http::url_to_path (dst) == req.path ());
ASIO2_CHECK(http::url_to_query(dst) == req.query ());
}
// test url match
{
ASIO2_CHECK(http::url_match("*", "/index.asp") == true);
ASIO2_CHECK(http::url_match("/*", "/index.asp") == true);
ASIO2_CHECK(http::url_match("/*", "index.asp") == true);
ASIO2_CHECK(http::url_match("/index.asp", "/index.asp") == true);
ASIO2_CHECK(http::url_match("/index.asp", "index.asp") == false);
ASIO2_CHECK(http::url_match("index.asp", "/index.asp") == true);
ASIO2_CHECK(http::url_match("index.asp", "/admin/index.asp") == true);
ASIO2_CHECK(http::url_match("index.asp", "index.asp") == true);
ASIO2_CHECK(http::url_match("/index*", "/index.asp") == true);
ASIO2_CHECK(http::url_match("/index.*", "/index.asp") == true);
ASIO2_CHECK(http::url_match("/index*", "index.asp") == false);
ASIO2_CHECK(http::url_match("/index.*", "index.asp") == false);
ASIO2_CHECK(http::url_match("/api/index*", "/index.asp") == false);
ASIO2_CHECK(http::url_match("/api/index.*", "/index.asp") == false);
ASIO2_CHECK(http::url_match("/api/index*", "/api/index.asp") == true);
ASIO2_CHECK(http::url_match("/api/index.*", "/api/index.asp") == true);
ASIO2_CHECK(http::url_match("/api/index*", "/api/index.") == true);
ASIO2_CHECK(http::url_match("/api/index.*", "/api/index.") == true);
ASIO2_CHECK(http::url_match("/api/index*", "/api/index/") == true);
ASIO2_CHECK(http::url_match("/api/index.*", "/api/index/") == false);
ASIO2_CHECK(http::url_match("/api/index*", "/api/index/admin") == true);
ASIO2_CHECK(http::url_match("/api/index.*", "/api/index/admin") == false);
ASIO2_CHECK(http::url_match("/api/index/*", "/api/index/admin") == true);
ASIO2_CHECK(http::url_match("/api/index/*", "/api/index/admin/user") == true);
ASIO2_CHECK(http::url_match("/api/index/*/user", "/api/index/admin/user") == true);
ASIO2_CHECK(http::url_match("/api/index/*/user", "/api/index/admin/crud/user") == true);
ASIO2_CHECK(http::url_match("/api/index/*/user", "/api/index/admin/person") == false);
ASIO2_CHECK(http::url_match("/api/index/*/user", "/api/index/admin/crud/person") == false);
ASIO2_CHECK(http::url_match("/*/api/index/user", "/admin/api/index/user") == true);
ASIO2_CHECK(http::url_match("/*/api/index/user", "/admin/crud/api/index/user") == true);
ASIO2_CHECK(http::url_match("/*/api/index/user", "/admin/api/index/person") == false);
ASIO2_CHECK(http::url_match("/*/api/index/user", "/admin/crud/api/index/person") == false);
}
// test http_client::execute
{
std::string_view url = "http://www.baidu.com/query?x@y";
asio2::socks5::option<asio2::socks5::method::anonymous>
sock5_option{ "127.0.0.1",10808 };
//asio2::socks5::option<asio2::socks5::method::anonymous, asio2::socks5::method::password>
// sock5_option{ "s5.doudouip.cn",1088,"zjww-1","aaa123" };
asio::error_code ec;
http::request_t<http::string_body> req1;
auto rep = asio2::http_client::execute("www.baidu.com", "80", req1, std::chrono::seconds(5), sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::bad_request);
}
asio2::http_client::execute("www.baidu.com", "80", req1, std::chrono::seconds(5), nullptr);
asio2::http_client::execute("www.baidu.com", "80", req1, std::chrono::seconds(5), std::in_place);
asio2::http_client::execute("www.baidu.com", "80", req1, std::chrono::seconds(5), std::nullopt);
rep = asio2::http_client::execute("www.baidu.com", "80", req1, std::chrono::seconds(5));
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::bad_request);
}
rep = asio2::http_client::execute("www.baidu.com", "80", req1);
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::bad_request);
}
http::web_request req2 = http::make_request(url);
ec = asio2::get_last_error();
ASIO2_CHECK(!asio2::get_last_error());
rep = asio2::http_client::execute(req2, std::chrono::seconds(5));
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::not_found);
}
rep = asio2::http_client::execute(req2);
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::not_found);
}
url = "http://www.baidu.com";
rep = asio2::http_client::execute(url, std::chrono::seconds(5));
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
rep = asio2::http_client::execute(url);
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
rep = asio2::http_client::execute("www.baidu.com", "80", "/", std::chrono::seconds(5));
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
rep = asio2::http_client::execute("www.baidu.com", "80", "/");
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
req1.target("/");
req1.method(http::verb::get);
rep = asio2::http_client::execute("www.baidu.com", "80", req1, sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK_VALUE(rep.result(), rep.result() == http::status::ok || rep.result() == http::status::internal_server_error);
}
rep = asio2::http_client::execute(req2, std::chrono::seconds(5), sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::not_found);
}
rep = asio2::http_client::execute(req2, sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::not_found);
}
rep = asio2::http_client::execute(url, std::chrono::seconds(5), sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
rep = asio2::http_client::execute(url, sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
rep = asio2::http_client::execute("www.baidu.com", "80", "/", std::chrono::seconds(5), sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
rep = asio2::http_client::execute("www.baidu.com", "80", "/", sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
}
// test http_client::execute
{
std::shared_ptr<asio2::socks5::option<asio2::socks5::method::anonymous>>
sock5_option = std::make_shared<asio2::socks5::option<asio2::socks5::method::anonymous>>(
"127.0.0.1", 10808);
//asio2::socks5::option<asio2::socks5::method::anonymous, asio2::socks5::method::password>
// sock5_option{ "s5.doudouip.cn",1088,"zjww-1","aaa123" };
asio::error_code ec;
http::request_t<http::string_body> req1;
auto rep = asio2::http_client::execute("www.baidu.com", 80, req1, std::chrono::seconds(5), sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::bad_request);
}
rep = asio2::http_client::execute("www.baidu.com", 80, req1, std::chrono::seconds(5));
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::bad_request);
}
rep = asio2::http_client::execute("www.baidu.com", 80, req1);
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::bad_request);
}
rep = asio2::http_client::execute("www.baidu.com", 80, "/", std::chrono::seconds(5));
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
rep = asio2::http_client::execute("www.baidu.com", 80, "/");
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
req1.target("/");
req1.method(http::verb::get);
rep = asio2::http_client::execute("www.baidu.com", 80, req1, sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK_VALUE(rep.result(), rep.result() == http::status::ok || rep.result() == http::status::internal_server_error);
}
rep = asio2::http_client::execute("www.baidu.com", 80, "/", std::chrono::seconds(5), sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
rep = asio2::http_client::execute("www.baidu.com", 80, "/", sock5_option);
ec = asio2::get_last_error();
if (ec)
{
ASIO2_CHECK_VALUE(asio2::last_error_msg(), asio2::get_last_error() == asio::error::connection_refused ||
ec == asio::error::timed_out || ec == http::error::end_of_stream);
}
else
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep.version() == 11);
ASIO2_CHECK(rep.result() == http::status::ok);
}
}
{
asio::error_code ec;
// GET
auto req2 = http::make_request("GET / HTTP/1.1\r\nHost: 192.168.0.1\r\n\r\n");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(req2.method() == http::verb::get);
ASIO2_CHECK(req2.version() == 11);
ASIO2_CHECK(req2.at("Host") == "192.168.0.1");
ASIO2_CHECK(req2.at(http::field::host) == "192.168.0.1");
auto rep2 = asio2::http_client::execute("www.baidu.com", "80", req2, std::chrono::seconds(3));
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep2.version() == 11);
ASIO2_CHECK(rep2.result() == http::status::forbidden);
}
// POST
auto req4 = http::make_request("POST / HTTP/1.1\r\nHost: 192.168.0.1\r\n\r\n");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(req4.method() == http::verb::post);
ASIO2_CHECK(req4.version() == 11);
ASIO2_CHECK(req4.at("Host") == "192.168.0.1");
ASIO2_CHECK(req4.at(http::field::host) == "192.168.0.1");
auto rep4 = asio2::http_client::execute("www.baidu.com", "80", req4, std::chrono::seconds(3));
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep4.version() == 11);
ASIO2_CHECK(rep4.result() == http::status::forbidden);
}
// POST
http::request_t<http::string_body> req5(http::verb::post, "/", 11);
auto rep5 = asio2::http_client::execute("www.baidu.com", "80", req5);
if (!ec)
{
ec = asio2::get_last_error();
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep5.version() == 11);
ASIO2_CHECK(rep5.result() == http::status::found);
}
// POST
http::request_t<http::string_body> req6;
req6.method(http::verb::post);
req6.target("/");
auto rep6 = asio2::http_client::execute("www.baidu.com", "80", req6);
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep6.version() == 11);
ASIO2_CHECK(rep6.result() == http::status::found);
}
// POST
http::request_t<http::string_body> req7;
req7.method(http::verb::post);
req7.target("/");
req7.set(http::field::user_agent, "Chrome");
req7.set(http::field::content_type, "text/html");
req7.body() = "Hello World.";
req7.prepare_payload();
auto rep7 = asio2::http_client::execute("www.baidu.com", "80", req7);
ec = asio2::get_last_error();
if (!ec)
{
ASIO2_CHECK(std::distance(rep7.begin(), rep7.end()) != 0);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(rep7.version() == 11);
ASIO2_CHECK(rep7.result() == http::status::found);
// convert the response body to string
std::stringstream ss1;
ss1 << rep7.body();
auto body = ss1.str();
ASIO2_CHECK(!body.empty());
ASIO2_CHECK(body.find("<html>") != std::string::npos);
// convert the whole response to string
std::stringstream ss2;
ss2 << rep7;
auto text = ss2.str();
ASIO2_CHECK(!text.empty());
ASIO2_CHECK(text.find("<html>") != std::string::npos);
ASIO2_CHECK(text.find("HTTP/1.1") != std::string::npos);
}
}
// test http download
{
asio2::socks5::option<asio2::socks5::method::anonymous>
sock5_option{ "127.0.0.1",10808 };
std::string url = "http://www.baidu.com/img/flexible/logo/pc/result.png";
std::string pth = "result.png";
asio2::http_client::download(url, [](auto&) {}, [](std::string_view) {});
asio2::http_client::download(url, [](std::string_view) {});
asio2::http_client::download(url, pth);
auto req = http::make_request(url);
asio2::http_client::download(req.host(), req.port(), req, [](auto&) {}, [](std::string_view) {}, nullptr);
asio2::http_client::download(req.host(), req.port(), req, [](auto&) {}, [](std::string_view) {}, sock5_option);
}
{
asio2::http_server server;
server.support_websocket(true);
// set the root directory, here is: /asio2/example/wwwroot
std::filesystem::path root = std::filesystem::current_path()
.parent_path().parent_path().parent_path()
.append("example").append("wwwroot");
server.set_root_directory(std::move(root));
server.bind_recv([&](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
}).bind_connect([](auto & session_ptr)
{
asio2::ignore_unused(session_ptr);
//session_ptr->set_response_mode(asio2::response_mode::manual);
}).bind_disconnect([](auto & session_ptr)
{
asio2::ignore_unused(session_ptr);
}).bind_start([&]()
{
}).bind_stop([&]()
{
});
server.bind<http::verb::get, http::verb::post>("/", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
rep.fill_file("index.html");
rep.chunked(true);
}, aop_log{});
// If no method is specified, GET and POST are both enabled by default.
server.bind("*", [](http::web_request& req, http::web_response& rep)
{
rep.fill_file(req.target());
}, aop_check{});
// Test http multipart
server.bind<http::verb::get, http::verb::post>("/multipart", [](http::web_request& req, http::web_response& rep)
{
auto& body = req.body();
auto target = req.target();
std::stringstream ss;
ss << req;
auto str_req = ss.str();
asio2::ignore_unused(body, target, str_req);
for (auto it = req.begin(); it != req.end(); ++it)
{
}
auto mpbody = req.multipart();
for (auto it = mpbody.begin(); it != mpbody.end(); ++it)
{
}
if (req.has_multipart())
{
http::multipart_fields multipart_body = req.multipart();
auto& field_username = multipart_body["username"];
auto username = field_username.value();
auto& field_password = multipart_body["<PASSWORD>"];
auto password = field_password.value();
std::string str = http::to_string(multipart_body);
std::string type = "multipart/form-data; boundary="; type += multipart_body.boundary();
rep.fill_text(str, http::status::ok, type);
http::request_t<http::string_body> re;
re.method(http::verb::post);
re.set(http::field::content_type, type);
re.keep_alive(true);
re.target("/api/user/");
re.body() = str;
re.prepare_payload();
std::stringstream ress;
ress << re;
auto restr = ress.str();
asio2::ignore_unused(username, password, restr);
}
else
{
rep.fill_page(http::status::ok);
}
}, aop_log{});
server.bind<http::verb::get>("/del_user",
[](std::shared_ptr<asio2::http_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(session_ptr, req, rep);
rep.fill_page(http::status::ok, "del_user successed.");
}, aop_check{});
server.bind<http::verb::get, http::verb::post>("/api/user/*", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
//rep.fill_text("the user name is hanmeimei, .....");
}, aop_log{}, aop_check{});
server.bind<http::verb::get>("/defer", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
// use defer to make the reponse not send immediately, util the derfer shared_ptr
// is destroyed, then the response will be sent.
std::shared_ptr<http::response_defer> rep_defer = rep.defer();
std::thread([rep_defer, &rep]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(50));
rep = asio2::http_client::execute("http://www.baidu.com");
}).detach();
}, aop_log{}, aop_check{});
bool ws_open_flag = false, ws_close_flag = false;
server.bind("/ws", websocket::listener<asio2::http_session>{}.
on("message", [](std::shared_ptr<asio2::http_session>& session_ptr, std::string_view data)
{
session_ptr->async_send(data);
}).on("open", [&](std::shared_ptr<asio2::http_session>& session_ptr)
{
ws_open_flag = true;
session_ptr->post([]() {}, std::chrono::milliseconds(10));
// how to set custom websocket response data :
session_ptr->ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::response_type& rep)
{
rep.set(http::field::authorization, " http-server-coro");
}));
}).on("close", [&](std::shared_ptr<asio2::http_session>& session_ptr)
{
ws_close_flag = true;
asio2::ignore_unused(session_ptr);
}).on_ping([](std::shared_ptr<asio2::http_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
}).on_pong([](std::shared_ptr<asio2::http_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
}));
server.bind_not_found([](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req);
rep.fill_page(http::status::not_found);
});
server.start("127.0.0.1", 8080);
asio2::http_client::execute("127.0.0.1", "8080", "/", std::chrono::seconds(5));
asio2::http_client::execute("127.0.0.1", "8080", "/defer");
std::shared_ptr<asio2::socks5::option<asio2::socks5::method::anonymous>>
sock5_option = std::make_shared<asio2::socks5::option<asio2::socks5::method::anonymous>>(
"127.0.0.1", 10808);
//asio2::socks5::option<asio2::socks5::method::anonymous, asio2::socks5::method::password>
// sock5_option{ "s5.doudouip.cn",1088,"zjww-1","aaa123" };
asio2::http_client http_client;
int counter = 0;
http_client.bind_recv([&](http::web_request& req, http::web_response& rep)
{
// convert the response body to string
std::stringstream ss;
ss << rep.body();
counter++;
if (counter == 1)
{
ASIO2_CHECK(rep.result() == http::status::ok);
}
else
{
ASIO2_CHECK(rep.result() == http::status::not_found);
}
// Remove all fields
req.clear();
req.set(http::field::user_agent, "Chrome");
req.set(http::field::content_type, "text/html");
req.method(http::verb::get);
req.keep_alive(true);
req.target("/get_user?name=abc");
req.body() = "Hello World.";
req.prepare_payload();
http_client.async_send(std::move(req));
}).bind_connect([&]()
{
// connect success, send a request.
if (!asio2::get_last_error())
{
const char * msg = "GET / HTTP/1.1\r\n\r\n";
http_client.async_send(msg);
}
});
bool http_client_ret = http_client.start("127.0.0.1", 8080, std::move(sock5_option));
ASIO2_CHECK(http_client_ret);
while (http_client_ret && counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
asio2::ws_client ws_client;
ws_client.set_connect_timeout(std::chrono::seconds(5));
ws_client.bind_init([&]()
{
// how to set custom websocket request data :
ws_client.ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::request_type& req)
{
req.set(http::field::authorization, " websocket-authorization");
}));
}).bind_connect([&]()
{
std::string s;
s += '<';
int len = 128 + std::rand() % 512;
for (int i = 0; i < len; i++)
{
s += (char)((std::rand() % 26) + 'a');
}
s += '>';
ws_client.async_send(std::move(s));
}).bind_upgrade([&]()
{
ws_client.async_send("abc", [](std::size_t bytes)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(bytes == 3);
});
}).bind_recv([&](std::string_view data)
{
ws_client.async_send(data);
});
bool ws_client_ret = ws_client.start("127.0.0.1", 8080, "/ws");
ASIO2_CHECK(ws_client_ret);
ASIO2_CHECK(ws_open_flag);
std::this_thread::sleep_for(std::chrono::milliseconds(50 + std::rand() % 50));
ws_client.stop();
ASIO2_CHECK(ws_close_flag);
}
{
asio2::socks5::option<asio2::socks5::method::anonymous>
sock5_option{ "127.0.0.1", 10808 };
//asio2::socks5::option<asio2::socks5::method::anonymous, asio2::socks5::method::password>
// sock5_option{ "s5.doudouip.cn",1088,"zjww-1","aaa123" };
asio2::http_client http_client;
int counter = 0;
http_client.bind_recv([&](http::web_request& req, http::web_response& rep)
{
// convert the response body to string
std::stringstream ss;
ss << rep.body();
counter++;
if (counter == 1)
{
ASIO2_CHECK(rep.result() == http::status::ok);
}
else
{
ASIO2_CHECK(rep.result() == http::status::not_found);
}
// Remove all fields
req.clear();
req.set(http::field::user_agent, "Chrome");
req.set(http::field::content_type, "text/html");
req.method(http::verb::get);
req.keep_alive(true);
req.target("/get_user?name=abc");
req.body() = "Hello World.";
req.prepare_payload();
http_client.async_send(std::move(req));
}).bind_connect([&]()
{
// connect success, send a request.
if (!asio2::get_last_error())
{
const char * msg = "GET / HTTP/1.1\r\n\r\n";
http_client.async_send(msg);
}
});
bool http_client_ret = http_client.start("www.baidu.com", 80, std::move(sock5_option));
ASIO2_CHECK(http_client_ret);
while (http_client_ret && counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
std::this_thread::sleep_for(std::chrono::milliseconds(10 + std::rand() % 10));
}
{
// try open http://localhost:8080 in your browser
asio2::http_server server;
server.set_support_websocket(true);
// set the root directory, here is: /asio2/example/wwwroot
std::filesystem::path root = std::filesystem::current_path().parent_path().parent_path().append("wwwroot");
server.set_root_directory(std::move(root));
server.bind_recv([&](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
// all http and websocket request will goto here first.
}).bind_connect([](auto & session_ptr)
{
asio2::ignore_unused(session_ptr);
//session_ptr->set_response_mode(asio2::response_mode::manual);
}).bind_disconnect([](auto & session_ptr)
{
asio2::ignore_unused(session_ptr);
}).bind_start([&]()
{
}).bind_stop([&]()
{
});
server.bind<http::verb::get, http::verb::post>("/", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
rep.fill_file("index.html");
rep.chunked(true);
}, aop_log{});
// If no method is specified, GET and POST are both enabled by default.
server.bind("*", [](http::web_request& req, http::web_response& rep)
{
rep.fill_file(req.target());
}, aop_check{});
// Test http multipart
server.bind<http::verb::get, http::verb::post>("/multipart", [](http::web_request& req, http::web_response& rep)
{
auto& body = req.body();
auto target = req.target();
std::stringstream ss;
ss << req;
auto str_req = ss.str();
asio2::ignore_unused(body, target, str_req);
for (auto it = req.begin(); it != req.end(); ++it)
{
//std::cout << it->name_string() << " " << it->value() << std::endl;
}
auto mpbody = req.multipart();
for (auto it = mpbody.begin(); it != mpbody.end(); ++it)
{
//std::cout
// << "filename:" << it->filename() << " name:" << it->name()
// << " content_type:" << it->content_type() << std::endl;
}
if (req.has_multipart())
{
http::multipart_fields multipart_body = req.multipart();
auto& field_username = multipart_body["username"];
auto username = field_username.value();
auto& field_password = multipart_body["<PASSWORD>"];
auto password = field_password.value();
std::string str = http::to_string(multipart_body);
std::string type = "multipart/form-data; boundary="; type += multipart_body.boundary();
rep.fill_text(str, http::status::ok, type);
http::request_t<http::string_body> re;
re.method(http::verb::post);
re.set(http::field::content_type, type);
re.keep_alive(true);
re.target("/api/user/");
re.body() = str;
re.prepare_payload();
std::stringstream ress;
ress << re;
auto restr = ress.str();
asio2::ignore_unused(username, password, restr);
}
else
{
rep.fill_page(http::status::ok);
}
}, aop_log{});
server.bind<http::verb::get>("/del_user",
[](std::shared_ptr<asio2::http_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(session_ptr, req, rep);
rep.fill_page(http::status::ok, "del_user successed.");
}, aop_check{});
server.bind<http::verb::get, http::verb::post>("/api/user/*", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
//rep.fill_text("the user name is hanmeimei, .....");
}, aop_log{}, aop_check{});
server.bind<http::verb::get>("/defer", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
// use defer to make the reponse not send immediately, util the derfer shared_ptr
// is destroyed, then the response will be sent.
std::shared_ptr<http::response_defer> rep_defer = rep.defer();
std::thread([rep_defer, &rep]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
rep = asio2::http_client::execute("http://www.baidu.com");
}).detach();
}, aop_log{}, aop_check{});
// the /ws is the websocket upgraged target
server.bind("/ws", websocket::listener<asio2::http_session>{}.
on("message", [](std::shared_ptr<asio2::http_session>& session_ptr, std::string_view data)
{
session_ptr->async_send(data);
}).on("open", [](std::shared_ptr<asio2::http_session>& session_ptr)
{
// print the websocket request header.
//std::cout << session_ptr->request() << std::endl;
// Set the binary message write option.
session_ptr->ws_stream().binary(true);
// Set the text message write option.
//session_ptr->ws_stream().text(true);
// how to set custom websocket response data :
session_ptr->ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::response_type& rep)
{
rep.set(http::field::authorization, " http-server-coro");
}));
}).on("close", [](std::shared_ptr<asio2::http_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
}).on_ping([](std::shared_ptr<asio2::http_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
}).on_pong([](std::shared_ptr<asio2::http_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
}));
server.bind_not_found([](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req);
rep.fill_page(http::status::not_found);
});
server.start("0.0.0.0", 8080);
//-----------------------------------------------------------------------------------------
asio2::iopool iopool(4);
iopool.start();
std::vector<std::shared_ptr<asio2::ws_client>> ws_clients;
std::vector<std::shared_ptr<asio2::http_client>> http_clients;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_start_failed_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
std::shared_ptr<asio2::ws_client> client_ptr =
std::make_shared<asio2::ws_client>(iopool.get(i % iopool.size()));
std::shared_ptr<asio2::http_client> http_client_ptr =
std::make_shared<asio2::http_client>(iopool.get(i % iopool.size()));
ws_clients.emplace_back(client_ptr);
http_clients.emplace_back(http_client_ptr);
asio2::ws_client& client = *client_ptr;
asio2::http_client& http_client = *http_client_ptr;
http::web_request req(http::verb::get, "/", 11);
http_client.start("127.0.0.1", 8080);
http_client.async_send(req);
http_client.async_start("127.0.0.1", 8080);
http_client.async_send(req);
http_client.stop();
http_client.async_start("127.0.0.1", 8080);
http_client.async_send(req);
http_client.start("127.0.0.1", 8080);
http_client.async_send(req);
client.set_connect_timeout(std::chrono::seconds(5));
client.set_auto_reconnect(false);
client.bind_init([&]()
{
// Set the binary message write option.
client.ws_stream().binary(true);
// Set the text message write option.
//client.ws_stream().text(true);
// how to set custom websocket request data :
client.ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::request_type& req)
{
req.set(http::field::authorization, " websocket-client-authorization");
}));
}).bind_connect([&]()
{
if (asio2::get_last_error())
{
}
else
{
client_connect_counter++;
}
client.start_timer(1, 100, [&]()
{
client.async_send("<0123456789abcdefg0123456789abcdefg0123456789abcdefg0123456789abcdefg>");
});
//std::string s;
//s += '<';
//int len = 128 + std::rand() % 512;
//for (int i = 0; i < len; i++)
//{
// s += (char)((std::rand() % 26) + 'a');
//}
//s += '>';
//client.async_send(std::move(s), [](std::size_t bytes_sent) { std::ignore = bytes_sent; });
}).bind_upgrade([&]()
{
//if (asio2::get_last_error())
// std::cout << "upgrade failure : " << asio2::last_error_val() << " " << asio2::last_error_msg() << std::endl;
//else
// std::cout << "upgrade success : " << client.get_upgrade_response() << std::endl;
}).bind_recv([&](std::string_view data)
{
ASIO2_CHECK(!data.empty());
//client.async_send(data);
}).bind_disconnect([&]()
{
ASIO2_CHECK(asio2::get_last_error());
client_connect_counter--;
});
// the /ws is the websocket upgraged target
bool ws_client_ret = client.start("127.0.0.1", 8080, "/ws");
if (!ws_client_ret)
client_start_failed_counter++;
ASIO2_CHECK(ws_client_ret);
ASIO2_CHECK(!asio2::get_last_error());
}
while (server.get_session_count() < std::size_t(test_client_count * 2 - client_start_failed_counter))
{
ASIO2_TEST_WAIT_CHECK();
}
while (client_connect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count * 2));
ASIO2_CHECK_VALUE(client_connect_counter.load(), client_connect_counter == test_client_count);
asio2::timer timer(iopool.get(loop % iopool.size()));
timer.start_timer(1, 10, 1, [&]()
{
ASIO2_CHECK(timer.get_thread_id() == std::this_thread::get_id());
for (auto& client_ptr : ws_clients)
{
// if the client.stop function is not called in the client's io_context thread,
// the stop is async, it is not blocking, and will return immediately.
client_ptr->stop();
// if the client.stop function is not called in the client's io_context thread,
// after client.stop, the client must be stopped completed already.
if (client_ptr->get_thread_id() != std::this_thread::get_id())
{
ASIO2_CHECK(client_ptr->is_stopped());
}
// at here, the client state maybe not stopped, beacuse the stop maybe async.
// but this async_start event chain must will be executed after all stop event
// chain is completed. so when the async_start's push_event is executed, the
// client must be stopped already.
client_ptr->async_start("127.0.0.1", 8080, "/ws");
}
});
while (timer.is_timer_exists(1))
{
ASIO2_TEST_WAIT_CHECK();
}
while (server.get_session_count() < std::size_t(test_client_count * 2 - client_start_failed_counter))
{
ASIO2_TEST_WAIT_CHECK();
}
while (client_connect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count * 2));
ASIO2_CHECK_VALUE(client_connect_counter.load(), client_connect_counter == test_client_count);
timer.stop();
iopool.stop();
}
{
http::multipart_fields mf;
mf.set_boundary("--7115EB26E91C48FB99C067C640EB629C");
http::multipart_field f1;
f1.set_content_disposition("form-data");
f1.set_name("filename");
f1.set_content_transfer_encoding("binary");
f1.set_value("header.png");
mf.insert(std::move(f1));
http::multipart_field f2;
f2.set_content_disposition("form-data");
f2.set_name("filesize");
f2.set_content_transfer_encoding("binary");
f2.set_value("1024");
mf.insert(std::move(f2));
http::multipart_field f3;
f3.set_content_disposition("form-data");
f3.set_name("filedata");
f3.set_content_transfer_encoding("binary");
f3.set_content_type("image/png");
f3.set_filename("header.png");
f3.set_value(".... eg: here is the file data ....");
mf.insert(std::move(f3));
auto mfstr = http::to_string(mf);
http::web_request req;
req.target("/update_header_img.html");
req.method(http::verb::post);
req.set(http::field::content_type, "multipart/form-data; boundary=--7115EB26E91C48FB99C067C640EB629C");
req.body() = mfstr;
req.prepare_payload();
std::stringstream ss;
ss << req;
auto str = ss.str();
ASIO2_CHECK(!str.empty());
// or
http::basic_multipart_fields<std::string> mfs;
http::basic_multipart_field<std::string> fs;
asio2::ignore_unused(mfs, fs);
// ......
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"http",
ASIO2_TEST_CASE(http_test)
)
<file_sep>#ifndef ASIO2_ENABLE_SSL
#define ASIO2_ENABLE_SSL
#endif
#include <asio2/tcp/tcps_server.hpp>
std::string_view server_key = R"(
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,32DBC28981A12AF1
<KEY>
)";
std::string_view server_crt = R"(
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 1 (0x1)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=AU, ST=HENAN, L=ZHENGZHOU, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=3<EMAIL>@<EMAIL>
Validity
Not Before: Nov 26 08:21:41 2021 GMT
Not After : Nov 24 08:21:41 2031 GMT
Subject: C=AU, ST=HENAN, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=3<EMAIL>38@qq.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (1024 bit)
Modulus:
00:c4:ba:4e:5f:22:45:ac:74:8f:5a:c3:06:4b:b4:
fdf8:f53e:61e4::18:02:66:69:09:ec:2c:7a:
68:c9:a9:0a:b2:f4:ed:69:6b:ad:29:59:b7:a6:ff:
69:df:f6:e5:45:44:d7:70:a7:40:84:d6:19:dd:c4:
36:27:86:1d:6d:79:e0:91:e5:77:79:49:28:4f:06:
7f:31:70:8b:ec:c2:58:9c:f4:14:1d:29:bb:2c:5a:
fc00:e968:6179::de52:7100:34:fc:7b:eb:48:76:44:
fdf8:f53e:61e4::18:3d:8c:8d:ef:12:ef:d5:
fc00:e968:6179::de52:7100:a9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
9B:D5:B6:0E:47:C3:A7:B6:DA:84:3B:F0:CE:D1:50:D3:8F:4F:0A:8A
X509v3 Authority Key Identifier:
keyid:61:74:1F:7E:B1:0E:0D:F9:46:DD:6A:97:85:72:DE:1A:7D:A2:34:65
Signature Algorithm: sha256WithRSAEncryption
b6:1e:bb:f7:fa:c5:9f:07:6e:36:9d:2e:7d:39:8e:a1:ed:f1:
65:a0:0c:e4:bb:6d:bc:eb:58:d5:1d:c2:03:57:8a:41:0a:f1:
fc00:e968:6179::de52:7100:9d:dc:f3:47:88:c8:a7:ba:69:f9:
bb:45:1f:73:48:96:f9:d7:fc:da:73:f9:17:5f:2f:94:19:83:
27:4b:b0:3e:19:29:71:a2:fc:db:d2:5f:6e:4f:e5:f1:d8:35:
55:f8:d9:db:75:dc:fe:11:e0:9f:70:6e:a8:26:2a:ca:7e:25:
08:e1:d5:d8:e3:0b:10:48:c6:ae:c5:b4:7b:15:20:87:97:20:
31:ee:e1:6f:d7:be:41:5d:2a:22:b0:36:16:1d:7a:70:bc:1b:
d3:fdf8:f53e:61e4::18:95:9e:69:30:37:05:bb:62:cd:
3f:dd:2b:bb:72:16:48:75:91:33:33:ae:b7:d7:2d:bd:ce:66:
f3:6b:69:81:fa:0d:aa:0e:5a:09:9d:24:54:ac:21:9b:14:43:
44:12:56:8b:cc:13:b5:3b:5a:ba:4e:7b:81:42:1e:38:61:ff:
a0:a7:01:2f:0b:67:77:90:48:bb:8a:52:62:69:76:3c:a8:a1:
d6:13:1e:27:f6:02:58:ae:91:4b:9d:37:4e:31:55:73:18:4e:
d0:61:54:3b
-----BEGIN CERTIFICATE-----
<KEY>END CERTIFICATE-----
)";
std::string_view ca_crt = R"(
-----BEGIN CERTIFICATE-----
<KEY>
-----END CERTIFICATE-----
)";
std::string_view dh = R"(
-----BEGIN DH PARAMETERS-----
MIGHAoGBAPr5rFoiBSxOovqiT+2R06y<KEY>
-----END DH PARAMETERS-----
)";
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8002";
bool all_stopped = false;
asio2::tcps_server server;
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
server.bind_recv([&](auto & session_ptr, std::string_view s)
{
printf("recv : %zu %.*s\n", s.size(), (int)s.size(), s.data());
session_ptr->async_send(s);
}).bind_accept([&](auto& session_ptr)
{
// accept callback maybe has error like "Too many open files", etc...
if (!asio2::get_last_error())
{
// You can close the connection directly here.
if (session_ptr->remote_address() == "192.168.0.254")
session_ptr->stop();
else
printf("client accept : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}
else
{
printf("error occurred when calling the accept function : %d %s\n",
asio2::get_last_error_val(), asio2::get_last_error_msg().data());
}
}).bind_connect([&](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([&](auto & session_ptr)
{
// Used to test that all sessions must be closed before entering the on_stop(bind_stop) function.
ASIO2_ASSERT(all_stopped == false);
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
}).bind_handshake([&](auto & session_ptr)
{
if (asio2::get_last_error())
printf("handshake failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("handshake success : %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port());
}).bind_start([&]()
{
if (asio2::get_last_error())
printf("start tcps server failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("start tcps server success : %s %u\n",
server.listen_address().c_str(), server.listen_port());
//server.stop();
}).bind_stop([&]()
{
all_stopped = true;
printf("stop tcps server : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.start(host, port);
while (std::getchar() != '\n');
server.stop();
return 0;
}
<file_sep>/*
Copyright <NAME> 2013-2020
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#if !defined(BHO_PREDEF_OTHER_H) || defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BHO_PREDEF_OTHER_H
#define BHO_PREDEF_OTHER_H
#endif
#include <asio2/bho/predef/other/endian.h>
#include <asio2/bho/predef/other/wordsize.h>
#include <asio2/bho/predef/other/workaround.h>
#endif
<file_sep>/*
Copyright <NAME> 2015
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include <asio2/bho/predef/hardware/simd/x86.h>
#include <asio2/bho/predef/hardware/simd/x86_amd.h>
#include <asio2/bho/predef/hardware/simd/arm.h>
#include <asio2/bho/predef/hardware/simd/ppc.h>
#ifndef BHO_PREDEF_HARDWARE_SIMD_H
#define BHO_PREDEF_HARDWARE_SIMD_H
#include <asio2/bho/predef/version_number.h>
/* tag::reference[]
= Using the `BHO_HW_SIMD_*` predefs
SIMD predefs depend on compiler options. For example, you will have to add the
option `-msse3` to clang or gcc to enable SSE3. SIMD predefs are also inclusive.
This means that if SSE3 is enabled, then every other extensions with a lower
version number will implicitly be enabled and detected. However, some extensions
are CPU specific, they may not be detected nor enabled when an upper version is
enabled.
NOTE: SSE(1) and SSE2 are automatically enabled by default when using x86-64
architecture.
To check if any SIMD extension has been enabled, you can use:
[source]
----
#include <asio2/bho/predef/hardware/simd.h>
#include <iostream>
int main()
{
#if defined(BHO_HW_SIMD_AVAILABLE)
std::cout << "SIMD detected!" << std::endl;
#endif
return 0;
}
----
When writing SIMD specific code, you may want to check if a particular extension
has been detected. To do so you have to use the right architecture predef and
compare it. Those predef are of the form `BHO_HW_SIMD_"ARCH"` (where `"ARCH"`
is either `ARM`, `PPC`, or `X86`). For example, if you compile code for x86
architecture, you will have to use `BHO_HW_SIMD_X86`. Its value will be the
version number of the most recent SIMD extension detected for the architecture.
To check if an extension has been enabled:
[source]
----
#include <asio2/bho/predef/hardware/simd.h>
#include <iostream>
int main()
{
#if BHO_HW_SIMD_X86 >= BHO_HW_SIMD_X86_SSE3_VERSION
std::cout << "This is SSE3!" << std::endl;
#endif
return 0;
}
----
NOTE: The *_VERSION* defines that map version number to actual real
identifiers. This way it is easier to write comparisons without messing up with
version numbers.
To *"strictly"* check the most recent detected extension:
[source]
----
#include <asio2/bho/predef/hardware/simd.h>
#include <iostream>
int main()
{
#if BHO_HW_SIMD_X86 == BHO_HW_SIMD_X86_SSE3_VERSION
std::cout << "This is SSE3 and this is the most recent enabled extension!"
<< std::endl;
#endif
return 0;
}
----
Because of the version systems of predefs and of the inclusive property of SIMD
extensions macros, you can easily check for ranges of supported extensions:
[source]
----
#include <asio2/bho/predef/hardware/simd.h>
#include <iostream>
int main()
{
#if BHO_HW_SIMD_X86 >= BHO_HW_SIMD_X86_SSE2_VERSION &&\
BHO_HW_SIMD_X86 <= BHO_HW_SIMD_X86_SSSE3_VERSION
std::cout << "This is SSE2, SSE3 and SSSE3!" << std::endl;
#endif
return 0;
}
----
NOTE: Unlike gcc and clang, Visual Studio does not allow you to specify precisely
the SSE variants you want to use, the only detections that will take place are
SSE, SSE2, AVX and AVX2. For more informations,
see [@https://msdn.microsoft.com/en-us/library/b0084kay.aspx here].
*/ // end::reference[]
// We check if SIMD extension of multiples architectures have been detected,
// if yes, then this is an error!
//
// NOTE: _X86_AMD implies _X86, so there is no need to check for it here!
//
#if defined(BHO_HW_SIMD_ARM_AVAILABLE) && defined(BHO_HW_SIMD_PPC_AVAILABLE) ||\
defined(BHO_HW_SIMD_ARM_AVAILABLE) && defined(BHO_HW_SIMD_X86_AVAILABLE) ||\
defined(BHO_HW_SIMD_PPC_AVAILABLE) && defined(BHO_HW_SIMD_X86_AVAILABLE)
# error "Multiple SIMD architectures detected, this cannot happen!"
#endif
#if defined(BHO_HW_SIMD_X86_AVAILABLE) && defined(BHO_HW_SIMD_X86_AMD_AVAILABLE)
// If both standard _X86 and _X86_AMD are available,
// then take the biggest version of the two!
# if BHO_HW_SIMD_X86 >= BHO_HW_SIMD_X86_AMD
# define BHO_HW_SIMD BHO_HW_SIMD_X86
# else
# define BHO_HW_SIMD BHO_HW_SIMD_X86_AMD
# endif
#endif
#if !defined(BHO_HW_SIMD)
// At this point, only one of these two is defined
# if defined(BHO_HW_SIMD_X86_AVAILABLE)
# define BHO_HW_SIMD BHO_HW_SIMD_X86
# endif
# if defined(BHO_HW_SIMD_X86_AMD_AVAILABLE)
# define BHO_HW_SIMD BHO_HW_SIMD_X86_AMD
# endif
#endif
#if defined(BHO_HW_SIMD_ARM_AVAILABLE)
# define BHO_HW_SIMD BHO_HW_SIMD_ARM
#endif
#if defined(BHO_HW_SIMD_PPC_AVAILABLE)
# define BHO_HW_SIMD BHO_HW_SIMD_PPC
#endif
#if defined(BHO_HW_SIMD)
# define BHO_HW_SIMD_AVAILABLE
#else
# define BHO_HW_SIMD BHO_VERSION_NUMBER_NOT_AVAILABLE
#endif
#define BHO_HW_SIMD_NAME "Hardware SIMD"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_HW_SIMD, BHO_HW_SIMD_NAME)
<file_sep>#include <asio2/websocket/ws_client.hpp>
#include <iostream>
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8039";
asio2::ws_client client;
client.set_connect_timeout(std::chrono::seconds(5));
client.bind_init([&]()
{
// Set the binary message write option.
client.ws_stream().binary(true);
// Set the text message write option. The sent text must be utf8 format.
//client.ws_stream().text(true);
// how to set custom websocket request data :
client.ws_stream().set_option(
websocket::stream_base::decorator([](websocket::request_type& req)
{
req.set(http::field::authorization, "websocket-client-authorization");
}));
}).bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n", client.local_address().c_str(), client.local_port());
std::string s;
s += '<';
int len = 128 + std::rand() % 512;
for (int i = 0; i < len; i++)
{
s += (char)((std::rand() % 26) + 'a');
}
s += '>';
client.async_send(std::move(s), [](std::size_t bytes_sent) { std::ignore = bytes_sent; });
}).bind_upgrade([&]()
{
if (asio2::get_last_error())
std::cout << "upgrade failure : " << asio2::last_error_val() << " " << asio2::last_error_msg() << std::endl;
else
{
const websocket::response_type& rep = client.get_upgrade_response();
beast::string_view auth = rep.at(http::field::authentication_results);
std::cout << auth << std::endl;
ASIO2_ASSERT(auth == "200 OK");
std::cout << "upgrade success : " << rep << std::endl;
}
}).bind_recv([&](std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
std::string s;
s += '<';
int len = 128 + std::rand() % 512;
for (int i = 0; i < len; i++)
{
s += (char)((std::rand() % 26) + 'a');
}
s += '>';
client.async_send(std::move(s));
});
// the /ws is the websocket upgraged target
if (!client.start(host, port, "/ws"))
{
printf("connect websocket server failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}
// blocked forever util some signal delivered.
// Normally, pressing Ctrl + C will emit the SIGINT signal.
client.wait_signal(SIGINT);
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* qq : 37792738
* email : <EMAIL>
*
* https://github.com/Shot511/strutil
*
*/
#ifndef __ASIO2_STRING_HPP__
#define __ASIO2_STRING_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#if defined(__GNUC__) || defined(__GNUG__)
# pragma GCC diagnostic ignored "-Warray-bounds"
#endif
#include <cstdint>
#include <cstdarg>
#include <cstdio>
#include <cwchar>
#include <climits>
#include <cctype>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
#include <type_traits>
#include <algorithm>
#include <sstream>
#include <regex>
#include <map>
#include <asio2/base/detail/type_traits.hpp>
namespace asio2
{
/**
* @brief Converts any datatype into std::basic_string.
* @tparam T
* @param v - will be converted into std::basic_string.
* @return Converted value as std::basic_string.
*/
template<typename T>
inline auto to_basic_string(T&& v)
{
using type = typename detail::remove_cvref_t<T>;
using CharT = typename detail::char_type<type>::type;
if /**/ constexpr (detail::is_string_view_v<type>)
{
return std::basic_string<CharT>{ v.data(), v.size() };
}
else if constexpr (detail::is_string_v<type>)
{
return std::forward<T>(v);
}
else if constexpr (detail::is_char_v<type>)
{
return std::basic_string<CharT>{ 1, v };
}
else if constexpr (std::is_integral_v<type>)
{
std::basic_string<CharT> r;
std::string s = std::to_string(v);
for (auto c : s)
{
r += static_cast<CharT>(c);
}
return r;
}
else if constexpr (std::is_floating_point_v<type>)
{
std::basic_string<CharT> r;
std::string s = std::to_string(v);
for (auto c : s)
{
r += static_cast<CharT>(c);
}
return r;
}
else if constexpr (detail::is_char_pointer_v<type>)
{
if (v)
return std::basic_string<CharT>{ v };
else
return std::basic_string<CharT>{ };
}
else if constexpr (detail::is_char_array_v<type>)
{
return std::basic_string<CharT>{ reinterpret_cast<const CharT*>(v) };
}
else
{
std::basic_stringstream<CharT> ss;
ss << std::forward<T>(v);
return ss.str();
}
}
/**
* @brief Converts any datatype into std::basic_string_view.
* @tparam T
* @param v - will be converted into std::basic_string_view.
* @return Converted value as std::basic_string_view.
*/
template<typename T>
inline auto to_basic_string_view(const T& v)
{
using type = typename detail::remove_cvref_t<T>;
using CharT = typename detail::char_type<type>::type;
if /**/ constexpr (detail::is_string_view_v<type>)
{
return v;
}
else if constexpr (detail::is_string_v<type>)
{
return std::basic_string_view<CharT>{ v };
}
else if constexpr (detail::is_char_v<type>)
{
return std::basic_string_view<CharT>{ std::addressof(v), 1 };
}
else if constexpr (detail::is_char_pointer_v<type>)
{
return (v ? std::basic_string_view<CharT>{ v } : std::basic_string_view<CharT>{});
}
else if constexpr (detail::is_char_array_v<type>)
{
return std::basic_string_view<CharT>{ reinterpret_cast<const CharT*>(v) };
}
else
{
return std::basic_string_view<CharT>{ v };
}
}
/**
* @brief Converts any datatype into std::string.
* @tparam T
* @param v - will be converted into std::string.
* @return Converted value as std::string.
*/
template<typename T>
inline std::string to_string(T&& v)
{
using type = detail::remove_cvref_t<T>;
std::string s;
if /**/ constexpr (std::is_same_v<std::string_view, type>)
{
s = { v.data(), v.size() };
}
else if constexpr (std::is_same_v<std::string, type>)
{
s = std::forward<T>(v);
}
else if constexpr (std::is_integral_v<type>)
{
s = std::to_string(v);
}
else if constexpr (std::is_floating_point_v<type>)
{
s = std::to_string(v);
}
else if constexpr (detail::is_char_pointer_v<type>)
{
if (v) s = v;
}
else if constexpr (detail::is_char_array_v<type>)
{
s = std::forward<T>(v);
}
else
{
std::stringstream ss;
ss << std::forward<T>(v);
s = ss.str();
}
return s;
}
/**
* @brief Converts any datatype into std::string_view.
* @tparam T
* @param v - will be converted into std::string_view.
* @return Converted value as std::string_view.
*/
template<typename T>
inline std::string_view to_string_view(const T& v)
{
using type = detail::remove_cvref_t<T>;
if /**/ constexpr (std::is_same_v<std::string_view, type>)
{
return std::string_view{ v };
}
else if constexpr (std::is_same_v<std::string, type>)
{
return std::string_view{ v };
}
else if constexpr (detail::is_char_v<type>)
{
return std::string_view{ std::addressof(v), 1 };
}
else if constexpr (detail::is_char_pointer_v<type>)
{
return (v ? std::string_view{ v } : std::string_view{});
}
else if constexpr (detail::is_char_array_v<type>)
{
return std::string_view{ v };
}
else
{
return std::string_view{ v };
}
}
/**
* @brief Converts iterator range into std::string_view.
* @tparam T
* @param v - will be converted into std::string_view.
* @return Converted value as std::string_view.
*/
template<typename Iterator>
inline std::string_view to_string_view(const Iterator& first, const Iterator& last)
{
using iter_type = typename detail::remove_cvref_t<Iterator>;
using diff_type = typename std::iterator_traits<iter_type>::difference_type;
diff_type n = std::distance(first, last);
if (n <= static_cast<diff_type>(0))
{
return std::string_view{};
}
if constexpr (std::is_pointer_v<iter_type>)
{
return { first, static_cast<std::string_view::size_type>(n) };
}
else
{
return { first.operator->(), static_cast<std::string_view::size_type>(n) };
}
}
/**
* @brief Converts any datatype into a numeric.
* @tparam IntegerType - integer or floating
* @param v - will be converted into numeric.
* @return Converted value as numeric.
*/
template<typename IntegerType, typename T>
inline IntegerType to_numeric(T&& v) noexcept
{
using type = detail::remove_cvref_t<T>;
if /**/ constexpr (std::is_integral_v<type>)
{
return static_cast<IntegerType>(v);
}
else if constexpr (std::is_floating_point_v<type>)
{
return static_cast<IntegerType>(v);
}
else
{
std::string s = asio2::to_string(std::forward<T>(v));
int rx = 10;
if (s.size() >= std::size_t(2) && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
rx = 16;
return static_cast<IntegerType>(std::strtoull(s.data(), nullptr, rx));
}
}
/**
* @brief Converts std::string into any datatype.
* Datatype must support << operator.
* @tparam T
* @param str - std::string that will be converted into datatype T.
* @return Variable of datatype T.
*/
template<typename T>
inline T string_to(const std::string& str)
{
T result{};
std::istringstream(str) >> result;
return result;
}
/**
* @brief Returns `true` if two strings are equal, using a case-insensitive comparison.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline bool iequals(
std::basic_string_view<CharT, Traits> str1,
std::basic_string_view<CharT, Traits> str2) noexcept
{
auto n = str1.size();
if (str2.size() != n)
return false;
auto p1 = str1.data();
auto p2 = str2.data();
CharT a, b;
// fast loop
while (n--)
{
a = *p1++;
b = *p2++;
if (a != b)
goto slow;
}
return true;
slow:
do
{
if (std::tolower(a) != std::tolower(b))
return false;
a = *p1++;
b = *p2++;
} while (n--);
return true;
}
/**
* @brief Returns `true` if two strings are equal, using a case-insensitive comparison.
*/
template<class String1, class String2>
inline bool iequals(const String1& str1, const String2& str2) noexcept
{
return asio2::iequals(asio2::to_basic_string_view(str1), asio2::to_basic_string_view(str2));
}
/**
* @brief Compares two std::strings ignoring their case (lower/upper).
* @param str1 - string to compare
* @param str2 - string to compare
* @return True if str1 and str2 are equal, false otherwise.
*/
template<class String1, class String2>
inline bool compare_ignore_case(const String1& str1, const String2& str2)
{
return asio2::iequals(str1, str2);
}
/**
* std::string format
*/
inline std::string formatv(const char * format, va_list args)
{
std::string str;
if (format && *format)
{
// under windows and linux system,std::vsnprintf(nullptr, 0, format, args)
// can get the need buffer len for the output,
va_list args_copy;
va_copy(args_copy, args);
int len = std::vsnprintf(nullptr, 0, format, args_copy);
if (len > 0)
{
str.resize(len);
va_copy(args_copy, args);
std::vsprintf((char*)str.data(), format, args_copy);
}
}
return str;
}
/**
* std::wstring format
*/
inline std::wstring formatv(const wchar_t * format, va_list args)
{
std::wstring str;
if (format && *format)
{
va_list args_copy;
while (true)
{
str.resize(str.capacity());
va_copy(args_copy, args);
// if provided buffer size is less than required size,vswprintf will return -1
// so if len equal -1,we increase the buffer size again, and has to use a loop
// to get the correct output buffer len,
int len = std::vswprintf((wchar_t*)(&str[0]), str.size(), format, args_copy);
if (len == -1)
str.reserve(str.capacity() * 2);
else
{
str.resize(len);
break;
}
}
}
return str;
}
/**
* std::string format
*/
inline std::string format(const char * format, ...)
{
std::string str;
if (format && *format)
{
// under windows and linux system,std::vsnprintf(nullptr, 0, format, args)
// can get the need buffer len for the output,
va_list args;
va_start(args, format);
str = formatv(format, args);
va_end(args);
}
return str;
}
/**
* std::wstring format
*/
inline std::wstring format(const wchar_t * format, ...)
{
std::wstring str;
if (format && *format)
{
va_list args;
va_start(args, format);
str = formatv(format, args);
va_end(args);
}
return str;
}
/**
* @brief Converts string to lower case.
* @param str - string that needs to be converted.
* @return Lower case input string.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& to_lower(std::basic_string<CharT, Traits, Allocator>& str)
{
std::transform(str.begin(), str.end(), str.begin(), [](CharT c) -> CharT
{
return static_cast<CharT>(std::tolower(c));
});
return str;
}
/**
* @brief Converts string to upper case.
* @param str - string that needs to be converted.
* @return Upper case input string.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& to_upper(std::basic_string<CharT, Traits, Allocator>& str)
{
std::transform(str.begin(), str.end(), str.begin(), [](CharT c) -> CharT
{
return static_cast<CharT>(std::toupper(c));
});
return str;
}
/**
* @brief Converts the first character of a string to uppercase letter and lowercases all other characters, if any.
* @param str - input string to be capitalized.
* @return A string with the first letter capitalized and all other characters lowercased.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& capitalize(std::basic_string<CharT, Traits, Allocator>& str)
{
asio2::to_lower(str);
if (!str.empty())
{
str.front() = static_cast<CharT>(std::toupper(str.front()));
}
return str;
}
/**
* @brief Converts only the first character of a string to uppercase letter, all other characters stay unchanged.
* @param str - input string to be modified.
* @return A string with the first letter capitalized. All other characters stay unchanged.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& capitalize_first_char(
std::basic_string<CharT, Traits, Allocator>& str)
{
if (!str.empty())
{
str.front() = static_cast<CharT>(std::toupper(str.front()));
}
return str;
}
/**
* @brief Checks if input string str contains specified substring.
* @param str - string to be checked.
* @param substring - searched substring or character.
* @return True if substring or character was found in str, false otherwise.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline bool contains(std::basic_string_view<CharT, Traits> str, std::basic_string_view<CharT, Traits> substring)
{
return str.find(substring) != std::string_view::npos;
}
/**
* @brief Checks if input string str contains specified substring.
* @param str - string to be checked.
* @param substring - searched substring or character.
* @return True if substring was found in str, false otherwise.
*/
template<class String1, class String2>
inline bool contains(const String1& str, const String2& substring)
{
return asio2::contains(asio2::to_basic_string_view(str), asio2::to_basic_string_view(substring));
}
/**
* @brief trim each space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& trim_all(std::basic_string<CharT, Traits, Allocator>& str)
{
// https://zh.cppreference.com/w/cpp/algorithm/remove
str.erase(std::remove_if(str.begin(), str.end(), [](int x) {return std::isspace(x); }), str.end());
return str;
}
/**
* @brief trim left space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& trim_left(std::basic_string<CharT, Traits, Allocator>& str)
{
str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](int ch) { return !std::isspace(ch); }));
return str;
}
/**
* @brief trim left space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& ltrim(std::basic_string<CharT, Traits, Allocator>& str)
{
return asio2::trim_left(str);
}
/**
* @brief trim right space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& trim_right(std::basic_string<CharT, Traits, Allocator>& str)
{
str.erase(std::find_if(str.rbegin(), str.rend(), [](int ch) { return !std::isspace(ch); }).base(), str.end());
return str;
}
/**
* @brief trim right space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& rtrim(std::basic_string<CharT, Traits, Allocator>& str)
{
return asio2::trim_right(str);
}
/**
* @brief trim left and right space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& trim_both(std::basic_string<CharT, Traits, Allocator>& str)
{
trim_left(str);
trim_right(str);
return str;
}
/**
* @brief trim left and right space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& trim(std::basic_string<CharT, Traits, Allocator>& str)
{
return asio2::trim_both(str);
}
/**
* @brief Trims white spaces from the left side of string.
* @param str - input string to remove white spaces from.
* @return Copy of input str with trimmed white spaces.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator> trim_left_copy(std::basic_string<CharT, Traits, Allocator> str)
{
asio2::trim_left(str);
return str;
}
/**
* @brief Trims white spaces from the left side of string.
* @param str - input string to remove white spaces from.
* @return Copy of input str with trimmed white spaces.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator> ltrim_copy(std::basic_string<CharT, Traits, Allocator> str)
{
asio2::trim_left(str);
return str;
}
/**
* @brief Trims white spaces from the right side of string.
* @param str - input string to remove white spaces from.
* @return Copy of input str with trimmed white spaces.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator> trim_right_copy(std::basic_string<CharT, Traits, Allocator> str)
{
asio2::trim_right(str);
return str;
}
/**
* @brief Trims white spaces from the right side of string.
* @param str - input string to remove white spaces from.
* @return Copy of input str with trimmed white spaces.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator> rtrim_copy(std::basic_string<CharT, Traits, Allocator> str)
{
asio2::trim_right(str);
return str;
}
/**
* @brief Trims white spaces from the both sides of string.
* @param str - input string to remove white spaces from.
* @return Copy of input str with trimmed white spaces.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator> trim_copy(std::basic_string<CharT, Traits, Allocator> str)
{
asio2::trim(str);
return str;
}
/**
* @brief trim left space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline std::basic_string_view<CharT, Traits>& trim_left(std::basic_string_view<CharT, Traits>& str)
{
if (str.empty())
return str;
using size_type = typename std::basic_string_view<CharT, Traits>::size_type;
size_type pos = 0;
for (; pos < str.size(); ++pos)
{
if (!std::isspace(static_cast<unsigned char>(str[pos])))
break;
}
str.remove_prefix(pos);
return str;
}
/**
* @brief trim left space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline std::basic_string_view<CharT, Traits>& ltrim(std::basic_string_view<CharT, Traits>& str)
{
return asio2::trim_left(str);
}
/**
* @brief trim right space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline std::basic_string_view<CharT, Traits>& trim_right(std::basic_string_view<CharT, Traits>& str)
{
if (str.empty())
return str;
using size_type = typename std::basic_string_view<CharT, Traits>::size_type;
size_type pos = str.size() - 1;
for (; pos != size_type(-1); pos--)
{
if (!std::isspace(static_cast<unsigned char>(str[pos])))
break;
}
str.remove_suffix(str.size() - pos - 1);
return str;
}
/**
* @brief trim right space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline std::basic_string_view<CharT, Traits>& rtrim(std::basic_string_view<CharT, Traits>& str)
{
return asio2::trim_right(str);
}
/**
* @brief trim left and right space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline std::basic_string_view<CharT, Traits>& trim_both(std::basic_string_view<CharT, Traits>& str)
{
asio2::trim_left(str);
asio2::trim_right(str);
return str;
}
/**
* @brief trim left and right space character of the string: space \t \r \n and so on
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline std::basic_string_view<CharT, Traits>& trim(std::basic_string_view<CharT, Traits>& str)
{
return asio2::trim_both(str);
}
/**
* @brief Replaces (in-place) the first occurrence of target with replacement.
* @param str - input string that will be modified.
* @param target - substring that will be replaced with replacement.
* @param replacement - substring that will replace target.
* @return Replacemented input string.
*/
template<
class String1,
class String2,
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& replace_first(
std::basic_string<CharT, Traits, Allocator>& str,
const String1& target,
const String2& replacement)
{
auto t = asio2::to_basic_string_view(target);
auto r = asio2::to_basic_string_view(replacement);
const std::size_t start_pos = str.find(t);
if (start_pos == std::string::npos)
{
return str;
}
str.replace(start_pos, t.length(), r);
return str;
}
/**
* @brief Replaces (in-place) last occurrence of target with replacement.
* @param str - input string that will be modified.
* @param target - substring that will be replaced with replacement.
* @param replacement - substring that will replace target.
* @return Replacemented input string.
*/
template<
class String1,
class String2,
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& replace_last(
std::basic_string<CharT, Traits, Allocator>& str,
const String1& target,
const String2& replacement)
{
auto t = asio2::to_basic_string_view(target);
auto r = asio2::to_basic_string_view(replacement);
std::size_t start_pos = str.rfind(t);
if (start_pos == std::string::npos)
{
return str;
}
str.replace(start_pos, t.length(), r);
return str;
}
/**
* @brief Replaces (in-place) all occurrences of target with replacement.
* @param str - input string that will be modified.
* @param target - substring that will be replaced with replacement.
* @param replacement - substring that will replace target.
* @return Replacemented input string.
*/
template<
class String1,
class String2,
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& replace_all(
std::basic_string<CharT, Traits, Allocator>& str,
const String1& target,
const String2& replacement)
{
auto t = asio2::to_basic_string_view(target);
auto r = asio2::to_basic_string_view(replacement);
if (t.empty())
{
return str;
}
std::size_t start_pos = 0;
while ((start_pos = str.find(t, start_pos)) != std::string::npos)
{
str.replace(start_pos, t.length(), r);
start_pos += r.length();
}
return str;
}
/**
* @brief Replaces (in-place) all occurrences of target with replacement.
* @param str - input string that will be modified.
* @param target - substring that will be replaced with replacement.
* @param replacement - substring that will replace target.
* @return Replacemented input string.
*/
template<
class String1,
class String2,
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::basic_string<CharT, Traits, Allocator>& replace(
std::basic_string<CharT, Traits, Allocator>& str,
const String1& target,
const String2& replacement)
{
return asio2::replace_all(str, target, replacement);
}
/**
* @brief Checks if string str ends with specified suffix.
* @param str - input string that will be checked.
* @param suffix - searched suffix in str.
* @return True if suffix was found, false otherwise.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline bool ends_with(
std::basic_string_view<CharT, Traits> str,
std::basic_string_view<CharT, Traits> suffix)
{
const auto suffix_start = str.size() - suffix.size();
const auto result = str.find(suffix, suffix_start);
return (result == suffix_start) && (result != std::string_view::npos);
}
/**
* @brief Checks if string str ends with specified suffix.
* @param str - input string that will be checked.
* @param suffix - searched suffix in str.
* @return True if suffix was found, false otherwise.
*/
template<class String1, class String2>
inline bool ends_with(const String1& str1, const String2& str2)
{
return asio2::ends_with(asio2::to_basic_string_view(str1), asio2::to_basic_string_view(str2));
}
/**
* @brief Checks if string str starts with specified prefix.
* @param str - input string that will be checked.
* @param prefix - searched prefix in str.
* @return True if prefix was found, false otherwise.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>
>
inline bool starts_with(
std::basic_string_view<CharT, Traits> str,
std::basic_string_view<CharT, Traits> prefix)
{
return str.rfind(prefix, 0) == 0;
}
/**
* @brief Checks if string str starts with specified prefix.
* @param str - input string that will be checked.
* @param prefix - searched prefix in str.
* @return True if prefix was found, false otherwise.
*/
template<class String1, class String2>
inline bool starts_with(const String1& str1, const String2& str2)
{
return asio2::starts_with(asio2::to_basic_string_view(str1), asio2::to_basic_string_view(str2));
}
/**
* @brief Splits input string str according to input string delim.
* @param str - string that will be split.
* @param delim - the delimiter.
* @return std::vector<string> that contains all splitted tokens.
*/
template<
class String1,
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::vector<std::basic_string<CharT, Traits, Allocator>> split(
const std::basic_string<CharT, Traits, Allocator>& str,
const String1& delim)
{
auto d = asio2::to_basic_string_view(delim);
std::size_t pos_start = 0, pos_end, delim_len = d.length();
std::basic_string<CharT, Traits, Allocator> token;
std::vector<std::basic_string<CharT, Traits, Allocator>> tokens;
while ((pos_end = str.find(d, pos_start)) != std::string::npos)
{
token = str.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
tokens.emplace_back(std::move(token));
}
tokens.emplace_back(str.substr(pos_start));
return tokens;
}
/**
* @brief Splits input string str according to input string delim.
* @param str - string that will be split.
* @param delim - the delimiter.
* @return std::vector<string_view> that contains all splitted tokens.
*/
template<
class String1,
class CharT,
class Traits = std::char_traits<CharT>
>
inline std::vector<std::basic_string_view<CharT, Traits>> split(
const std::basic_string_view<CharT, Traits>& str,
const String1& delim)
{
auto d = asio2::to_basic_string_view(delim);
std::size_t pos_start = 0, pos_end, delim_len = d.length();
std::basic_string_view<CharT, Traits> token;
std::vector<std::basic_string_view<CharT, Traits>> tokens;
while ((pos_end = str.find(d, pos_start)) != std::string::npos)
{
token = str.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
tokens.emplace_back(std::move(token));
}
tokens.emplace_back(str.substr(pos_start));
return tokens;
}
/**
* @brief Splits input string str according to input string delim.
* @param str - string that will be split.
* @param delim - the delimiter.
* @return std::vector<string> that contains all splitted tokens.
*/
template<class String1, class String2>
inline auto split(const String1& str, const String2& delim)
{
using CharT = typename detail::char_type<String1>::type;
auto s = asio2::to_basic_string_view(str);
auto d = asio2::to_basic_string_view(delim);
std::size_t pos_start = 0, pos_end, delim_len = d.length();
std::basic_string<CharT> token;
std::vector<std::basic_string<CharT>> tokens;
while ((pos_end = s.find(d, pos_start)) != std::string::npos)
{
token = s.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
tokens.emplace_back(std::move(token));
}
tokens.emplace_back(s.substr(pos_start));
return tokens;
}
/**
* @brief Splits input string using regex as a delimiter.
* @param src - string that will be split.
* @param rgx_str - the set of delimiter characters.
* @return vector of resulting tokens.
*/
template<class String1, class String2>
inline auto regex_split(const String1& src, const String2& rgx_str)
{
using CharT = typename detail::char_type<String1>::type;
auto s = asio2::to_basic_string(src);
auto d = asio2::to_basic_string_view(rgx_str);
using IterType = typename std::basic_string<CharT>::const_iterator;
std::vector<std::basic_string<CharT>> elems;
const std::basic_regex<CharT> rgx(d.begin(), d.end());
std::regex_token_iterator<IterType> iter(s.begin(), s.end(), rgx, -1);
std::regex_token_iterator<IterType> end;
while (iter != end)
{
elems.emplace_back(*iter);
++iter;
}
return elems;
}
/**
* @brief Splits input string using regex as a delimiter.
* @param src - string that will be split.
* @param dest - map of matched delimiter and those being splitted.
* @param rgx_str - the set of delimiter characters.
* @return True if the parsing is successfully done.
*/
template<class String1, class String2>
inline auto regex_split_map(const String1& src, const String2& rgx_str)
{
using CharT = typename detail::char_type<String1>::type;
auto d = asio2::to_basic_string_view(rgx_str);
using IterType = typename std::basic_string<CharT>::const_iterator;
std::map<std::basic_string<CharT>, std::basic_string<CharT>> dest;
std::basic_string<CharT> tstr = src + static_cast<CharT>(' ');
std::basic_regex<CharT> rgx(d.begin(), d.end());
std::regex_token_iterator<IterType> niter(tstr.begin(), tstr.end(), rgx);
std::regex_token_iterator<IterType> viter(tstr.begin(), tstr.end(), rgx, -1);
std::regex_token_iterator<IterType> end;
++viter;
while (niter != end)
{
dest[*niter] = *viter;
++niter;
++viter;
}
return dest;
}
/**
* @brief Splits input string using any delimiter in the given set.
* @param str - string that will be split.
* @param delims - the set of delimiter characters.
* @return vector of resulting tokens.
*/
template<
class String1,
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::vector<std::basic_string<CharT, Traits, Allocator>> split_any(
const std::basic_string<CharT, Traits, Allocator>& str,
const String1& delims)
{
auto d = asio2::to_basic_string_view(delims);
std::basic_string<CharT, Traits, Allocator> token;
std::vector<std::basic_string<CharT, Traits, Allocator>> tokens;
std::size_t pos_start = 0;
for (std::size_t pos_end = 0; pos_end < str.length(); ++pos_end)
{
if (asio2::contains(d, str[pos_end]))
{
token = str.substr(pos_start, pos_end - pos_start);
tokens.emplace_back(std::move(token));
pos_start = pos_end + 1;
}
}
tokens.emplace_back(str.substr(pos_start));
return tokens;
}
/**
* @brief Splits input string using any delimiter in the given set.
* @param str - string that will be split.
* @param delims - the set of delimiter characters.
* @return vector of resulting tokens.
*/
template<
class String1,
class CharT,
class Traits = std::char_traits<CharT>
>
inline std::vector<std::basic_string_view<CharT, Traits>> split_any(
const std::basic_string_view<CharT, Traits>& str,
const String1& delims)
{
auto d = asio2::to_basic_string_view(delims);
std::basic_string_view<CharT, Traits> token;
std::vector<std::basic_string_view<CharT, Traits>> tokens;
std::size_t pos_start = 0;
for (std::size_t pos_end = 0; pos_end < str.length(); ++pos_end)
{
if (asio2::contains(d, str[pos_end]))
{
token = str.substr(pos_start, pos_end - pos_start);
tokens.emplace_back(std::move(token));
pos_start = pos_end + 1;
}
}
tokens.emplace_back(str.substr(pos_start));
return tokens;
}
/**
* @brief Splits input string using any delimiter in the given set.
* @param str - string that will be split.
* @param delims - the set of delimiter characters.
* @return vector of resulting tokens.
*/
template<class String1, class String2>
inline auto split_any(const String1& str, const String2& delims)
{
using CharT = typename detail::char_type<String1>::type;
auto s = asio2::to_basic_string_view(str);
auto d = asio2::to_basic_string_view(delims);
std::basic_string<CharT> token;
std::vector<std::basic_string<CharT>> tokens;
std::size_t pos_start = 0;
for (std::size_t pos_end = 0; pos_end < s.length(); ++pos_end)
{
if (asio2::contains(d, s[pos_end]))
{
token = s.substr(pos_start, pos_end - pos_start);
tokens.emplace_back(std::move(token));
pos_start = pos_end + 1;
}
}
tokens.emplace_back(s.substr(pos_start));
return tokens;
}
/**
* @brief Joins all elements of std::vector tokens of arbitrary datatypes
* into one string with delimiter delim.
* @tparam T - arbitrary datatype.
* @param tokens - vector of tokens.
* @param delim - the delimiter.
* @return string with joined elements of vector tokens with delimiter delim.
*/
template<
class T,
class String1
>
inline auto join(const std::vector<T>& tokens, const String1& delim)
{
using CharT = typename detail::char_type<String1>::type;
std::basic_ostringstream<CharT> result;
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
if (it != tokens.begin())
{
result << delim;
}
result << *it;
}
return result.str();
}
/**
* @brief Inplace removal of all empty strings in a vector<string>
* @param tokens - vector of strings.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline void drop_empty(std::vector<std::basic_string<CharT, Traits, Allocator>>& tokens)
{
auto last = std::remove_if(tokens.begin(), tokens.end(),
[](const std::basic_string<CharT, Traits, Allocator>& s) { return s.empty(); });
tokens.erase(last, tokens.end());
}
/**
* @brief Inplace removal of all empty strings in a vector<string>
* @param tokens - vector of strings.
* @return vector of non-empty tokens.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::vector<std::basic_string<CharT, Traits, Allocator>> drop_empty_copy(
std::vector<std::basic_string<CharT, Traits, Allocator>> tokens)
{
drop_empty(tokens);
return tokens;
}
/**
* @brief Inplace removal of all duplicate strings in a vector<string> where order is not to be maintained
* Taken from: C++ Primer V5
* @param tokens - vector of strings.
* @return vector of non-duplicate tokens.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline void drop_duplicate(std::vector<std::basic_string<CharT, Traits, Allocator>>& tokens)
{
std::sort(tokens.begin(), tokens.end());
auto end_unique = std::unique(tokens.begin(), tokens.end());
tokens.erase(end_unique, tokens.end());
}
/**
* @brief Removal of all duplicate strings in a vector<string> where order is not to be maintained
* Taken from: C++ Primer V5
* @param tokens - vector of strings.
* @return vector of non-duplicate tokens.
*/
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline std::vector<std::basic_string<CharT, Traits, Allocator>> drop_duplicate_copy(
std::vector<std::basic_string<CharT, Traits, Allocator>> tokens)
{
std::sort(tokens.begin(), tokens.end());
auto end_unique = std::unique(tokens.begin(), tokens.end());
tokens.erase(end_unique, tokens.end());
return tokens;
}
/**
* @brief Creates new string with repeated n times substring str.
* @param str - substring that needs to be repeated.
* @param n - number of iterations.
* @return string with repeated substring str.
*/
template<class String1>
inline auto repeat(const String1& str, unsigned n)
{
using CharT = typename detail::char_type<String1>::type;
std::basic_string<CharT> result;
for (unsigned i = 0; i < n; ++i)
{
result += str;
}
return result;
}
/**
* @brief Checks if input string str matches specified reular expression regex.
* @param str - string to be checked.
* @param regex - the std::regex regular expression.
* @return True if regex matches str, false otherwise.
*/
template<class String1>
inline bool matches(const String1& str, const std::basic_regex<typename detail::char_type<String1>::type>& regex)
{
return std::regex_match(str, regex);
}
/**
* @brief Sort input std::vector<string> strs in ascending order.
* @param strs - std::vector<string> to be checked.
*/
template<typename T>
inline void sorting_ascending(std::vector<T>& strs)
{
std::sort(strs.begin(), strs.end());
}
/**
* @brief Sorted input std::vector<string> strs in descending order.
* @param strs - std::vector<string> to be checked.
*/
template<typename T>
inline void sorting_descending(std::vector<T>& strs)
{
std::sort(strs.begin(), strs.end(), std::greater<T>());
}
/**
* @brief Reverse input std::vector<string> strs.
* @param strs - std::vector<string> to be checked.
*/
template<typename T>
inline void reverse_inplace(std::vector<T>& strs)
{
std::reverse(strs.begin(), strs.end());
}
/**
* @brief Reverse input std::vector<string> strs.
* @param strs - std::vector<string> to be checked.
*/
template<typename T>
inline std::vector<T> reverse_copy(std::vector<T> strs)
{
std::reverse(strs.begin(), strs.end());
return strs;
}
/**
* @brief Find substring in the string src, using a case-insensitive comparison.
* @return The finded index, or std::string::npos if not found.
*/
template<class String1, class String2>
inline std::size_t ifind(const String1& src, const String2& dest, std::string::size_type pos = 0) noexcept
{
auto s = asio2::to_basic_string_view(src);
auto d = asio2::to_basic_string_view(dest);
if (pos >= s.size() || d.empty())
return std::string::npos;
// Outer loop
for (auto OuterIt = std::next(s.begin(), pos); OuterIt != s.end(); ++OuterIt)
{
auto InnerIt = OuterIt;
auto SubstrIt = d.begin();
for (; InnerIt != s.end() && SubstrIt != d.end(); ++InnerIt, ++SubstrIt)
{
if (std::tolower(*InnerIt) != std::tolower(*SubstrIt))
break;
}
// Substring matching succeeded
if (SubstrIt == d.end())
return std::distance(s.begin(), OuterIt);
}
return std::string::npos;
}
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_STRING_HPP__
<file_sep>#ifndef BHO_BEAST_CORE_DETAIL_WORK_GUARD_HPP
#define BHO_BEAST_CORE_DETAIL_WORK_GUARD_HPP
#include <asio2/external/asio.hpp>
#include <asio2/bho/assert.hpp>
#include <optional>
namespace bho {
namespace beast {
namespace detail {
template<class Executor, class Enable = void>
struct select_work_guard;
template<class Executor>
using select_work_guard_t = typename
select_work_guard<Executor>::type;
#if !defined(ASIO_NO_TS_EXECUTORS)
template<class Executor>
struct select_work_guard
<
Executor,
typename std::enable_if
<
net::is_executor<Executor>::value
>::type
>
{
using type = net::executor_work_guard<Executor>;
};
#endif
template<class Executor>
struct execution_work_guard
{
using executor_type = typename std::decay<decltype(
net::prefer(std::declval<Executor const&>(),
net::execution::outstanding_work.tracked))>::type;
execution_work_guard(Executor const& exec)
: ex_(net::prefer(exec, net::execution::outstanding_work.tracked))
{
}
executor_type
get_executor() const noexcept
{
BHO_ASSERT(ex_.has_value());
return *ex_;
}
void reset() noexcept
{
ex_.reset();
}
private:
std::optional<executor_type> ex_;
};
template<class Executor>
struct select_work_guard
<
Executor,
typename std::enable_if
<
net::execution::is_executor<Executor>::value
#if defined(ASIO_NO_TS_EXECUTORS)
|| net::is_executor<Executor>::value
#else
&& !net::is_executor<Executor>::value
#endif
>::type
>
{
using type = execution_work_guard<Executor>;
};
template<class Executor>
select_work_guard_t<Executor>
make_work_guard(Executor const& exec) noexcept
{
return select_work_guard_t<Executor>(exec);
}
}
}
}
#endif // BHO_BEAST_CORE_DETAIL_WORK_GUARD_HPP
<file_sep>/*
Copyright <NAME> 2011-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_OS400_H
#define BHO_PREDEF_OS_OS400_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_OS400`
http://en.wikipedia.org/wiki/IBM_i[IBM OS/400] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__OS400__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_OS400 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__OS400__) \
)
# undef BHO_OS_OS400
# define BHO_OS_OS400 BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_OS400
# define BHO_OS_OS400_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_OS400_NAME "IBM OS/400"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_OS400,BHO_OS_OS400_NAME)
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_DETAIL_BIND_CONTINUATION_HPP
#define BHO_BEAST_DETAIL_BIND_CONTINUATION_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/beast/core/detail/remap_post_to_defer.hpp>
#include <asio2/external/asio.hpp>
#include <asio2/bho/core/empty_value.hpp>
#include <type_traits>
#include <utility>
namespace bho {
namespace beast {
namespace detail {
#if 0
/** Mark a completion handler as a continuation.
This function wraps a completion handler to associate it with an
executor whose `post` operation is remapped to the `defer` operation.
It is used by composed asynchronous operation implementations to
indicate that a completion handler submitted to an initiating
function represents a continuation of the current asynchronous
flow of control.
@param handler The handler to wrap.
The implementation takes ownership of the handler by performing a decay-copy.
@see
@li <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4242.html">[N4242] Executors and Asynchronous Operations, Revision 1</a>
*/
template<class CompletionHandler>
#if BHO_BEAST_DOXYGEN
__implementation_defined__
#else
net::executor_binder<
typename std::decay<CompletionHandler>::type,
detail::remap_post_to_defer<
net::associated_executor_t<CompletionHandler>>>
#endif
bind_continuation(CompletionHandler&& handler)
{
return net::bind_executor(
detail::remap_post_to_defer<
net::associated_executor_t<CompletionHandler>>(
net::get_associated_executor(handler)),
std::forward<CompletionHandler>(handler));
}
/** Mark a completion handler as a continuation.
This function wraps a completion handler to associate it with an
executor whose `post` operation is remapped to the `defer` operation.
It is used by composed asynchronous operation implementations to
indicate that a completion handler submitted to an initiating
function represents a continuation of the current asynchronous
flow of control.
@param ex The executor to use
@param handler The handler to wrap
The implementation takes ownership of the handler by performing a decay-copy.
@see
@li <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4242.html">[N4242] Executors and Asynchronous Operations, Revision 1</a>
*/
template<class Executor, class CompletionHandler>
#if BHO_BEAST_DOXYGEN
__implementation_defined__
#else
net::executor_binder<typename
std::decay<CompletionHandler>::type,
detail::remap_post_to_defer<Executor>>
#endif
bind_continuation(
Executor const& ex, CompletionHandler&& handler)
{
return net::bind_executor(
detail::remap_post_to_defer<Executor>(ex),
std::forward<CompletionHandler>(handler));
}
#else
// VFALCO I turned these off at the last minute because they cause
// the completion handler to be moved before the initiating
// function is invoked rather than after, which is a foot-gun.
//
// REMINDER: Uncomment the tests when this is put back
template<class F>
F&&
bind_continuation(F&& f)
{
return std::forward<F>(f);
}
#endif
} // detail
} // beast
} // bho
#endif
<file_sep>#
# Copyright (c) 2017-2023 zhllxt
#
# author : zhllxt
# email : <EMAIL>
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
GroupSources (include/asio2 "/")
GroupSources (3rd/asio "/")
aux_source_directory(. SRC_FILES)
source_group("" FILES ${SRC_FILES})
set(TARGET_NAME udp_client)
add_executable (
${TARGET_NAME}
${ASIO2_FILES}
${TARGET_NAME}.cpp
)
#SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ASIO2_EXES_DIR})
set_target_properties(${TARGET_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${ASIO2_EXES_DIR})
target_link_libraries(${TARGET_NAME} ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(${TARGET_NAME} ${GENERAL_LIBS})
<file_sep>#include <asio2/websocket/ws_server.hpp>
#include <iostream>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8039";
asio2::ws_server server;
server.bind_accept([&](std::shared_ptr<asio2::ws_session>& session_ptr)
{
// accept callback maybe has error like "Too many open files", etc...
if (!asio2::get_last_error())
{
// Set the binary message write option.
session_ptr->ws_stream().binary(true);
// Set the text message write option. The sent text must be utf8 format.
//session_ptr->ws_stream().text(true);
// how to set custom websocket response data :
// the decorator is just a callback function, when the upgrade response is send,
// this callback will be called.
session_ptr->ws_stream().set_option(
websocket::stream_base::decorator([session_ptr](websocket::response_type& rep)
{
// @see /asio2/example/websocket/client/websocket_client.cpp
const websocket::request_type& req = session_ptr->get_upgrade_request();
auto it = req.find(http::field::authorization);
if (it != req.end())
rep.set(http::field::authentication_results, "200 OK");
else
rep.set(http::field::authentication_results, "401 unauthorized");
}));
}
else
{
printf("error occurred when calling the accept function : %d %s\n",
asio2::get_last_error_val(), asio2::get_last_error_msg().data());
}
}).bind_recv([&](auto & session_ptr, std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}).bind_connect([](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([](auto & session_ptr)
{
asio2::ignore_unused(session_ptr);
printf("client leave : %s\n", asio2::last_error_msg().c_str());
}).bind_upgrade([](auto & session_ptr)
{
printf("client upgrade : %s %u %d %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
// how to get the upgrade request data :
// @see /asio2/example/websocket/client/websocket_client.cpp
const websocket::request_type& req = session_ptr->get_upgrade_request();
beast::string_view auth = req.at(http::field::authorization);
std::cout << auth << std::endl;
ASIO2_ASSERT(auth == "websocket-client-authorization");
}).bind_start([&]()
{
if (asio2::get_last_error())
printf("start websocket server failure : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("start websocket server success : %s %u\n",
server.listen_address().c_str(), server.listen_port());
}).bind_stop([&]()
{
printf("stop websocket server : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.start(host, port);
// blocked forever util some signal delivered.
// Normally, pressing Ctrl + C will emit the SIGINT signal.
server.wait_signal(SIGINT, SIGTERM);
return 0;
}
<file_sep>/*
Copyright <NAME> 2008-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_INTEL_H
#define BHO_PREDEF_COMPILER_INTEL_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_INTEL`
http://en.wikipedia.org/wiki/Intel_C%2B%2B[Intel C/{CPP}] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__INTEL_COMPILER+` | {predef_detection}
| `+__ICL+` | {predef_detection}
| `+__ICC+` | {predef_detection}
| `+__ECC+` | {predef_detection}
| `+__INTEL_COMPILER+` | V.R
| `+__INTEL_COMPILER+` and `+__INTEL_COMPILER_UPDATE+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_INTEL BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || \
defined(__ECC)
/* tag::reference[]
NOTE: Because of an Intel mistake in the release version numbering when
`__INTEL_COMPILER` is `9999` it is detected as version 12.1.0.
*/ // end::reference[]
# if !defined(BHO_COMP_INTEL_DETECTION) && defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 9999)
# define BHO_COMP_INTEL_DETECTION BHO_VERSION_NUMBER(12,1,0)
# endif
# if !defined(BHO_COMP_INTEL_DETECTION) && defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
# define BHO_COMP_INTEL_DETECTION BHO_VERSION_NUMBER( \
BHO_VERSION_NUMBER_MAJOR(BHO_PREDEF_MAKE_10_VVRR(__INTEL_COMPILER)), \
BHO_VERSION_NUMBER_MINOR(BHO_PREDEF_MAKE_10_VVRR(__INTEL_COMPILER)), \
__INTEL_COMPILER_UPDATE)
# endif
# if !defined(BHO_COMP_INTEL_DETECTION) && defined(__INTEL_COMPILER)
# define BHO_COMP_INTEL_DETECTION BHO_PREDEF_MAKE_10_VVRR(__INTEL_COMPILER)
# endif
# if !defined(BHO_COMP_INTEL_DETECTION)
# define BHO_COMP_INTEL_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_COMP_INTEL_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_INTEL_EMULATED BHO_COMP_INTEL_DETECTION
# else
# undef BHO_COMP_INTEL
# define BHO_COMP_INTEL BHO_COMP_INTEL_DETECTION
# endif
# define BHO_COMP_INTEL_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_INTEL_NAME "Intel C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_INTEL,BHO_COMP_INTEL_NAME)
#ifdef BHO_COMP_INTEL_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_INTEL_EMULATED,BHO_COMP_INTEL_NAME)
#endif
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
// This is a derivative work based on Zlib, copyright below:
/*
Copyright (C) 1995-2013 <NAME> and <NAME>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
<NAME> <NAME>
<EMAIL> <EMAIL>
The data format used by the zlib library is described by RFCs (Request for
Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
(zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
*/
#ifndef BHO_BEAST_ZLIB_DETAIL_INFLATE_STREAM_HPP
#define BHO_BEAST_ZLIB_DETAIL_INFLATE_STREAM_HPP
#include <asio2/bho/beast/zlib/error.hpp>
#include <asio2/bho/beast/zlib/zlib.hpp>
#include <asio2/bho/beast/zlib/detail/bitstream.hpp>
#include <asio2/bho/beast/zlib/detail/ranges.hpp>
#include <asio2/bho/beast/zlib/detail/window.hpp>
#if 0
#include <asio2/bho/beast/core/detail/type_traits.hpp>
#include <asio2/bho/throw_exception.hpp>
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
#include <stdexcept>
#endif
namespace bho {
namespace beast {
namespace zlib {
namespace detail {
class inflate_stream
{
protected:
inflate_stream()
{
w_.reset(15);
}
BHO_BEAST_DECL
void
doClear();
BHO_BEAST_DECL
void
doReset(int windowBits);
BHO_BEAST_DECL
void
doWrite(z_params& zs, Flush flush, error_code& ec);
void
doReset()
{
doReset(w_.bits());
}
private:
enum Mode
{
HEAD, // i: waiting for magic header
FLAGS, // i: waiting for method and flags (gzip)
TIME, // i: waiting for modification time (gzip)
OS, // i: waiting for extra flags and operating system (gzip)
EXLEN, // i: waiting for extra length (gzip)
EXTRA, // i: waiting for extra bytes (gzip)
NAME, // i: waiting for end of file name (gzip)
COMMENT, // i: waiting for end of comment (gzip)
HCRC, // i: waiting for header crc (gzip)
TYPE, // i: waiting for type bits, including last-flag bit
TYPEDO, // i: same, but skip check to exit inflate on new block
STORED, // i: waiting for stored size (length and complement)
COPY_, // i/o: same as COPY below, but only first time in
COPY, // i/o: waiting for input or output to copy stored block
TABLE, // i: waiting for dynamic block table lengths
LENLENS, // i: waiting for code length code lengths
CODELENS, // i: waiting for length/lit and distance code lengths
LEN_, // i: same as LEN below, but only first time in
LEN, // i: waiting for length/lit/eob code
LENEXT, // i: waiting for length extra bits
DIST, // i: waiting for distance code
DISTEXT,// i: waiting for distance extra bits
MATCH, // o: waiting for output space to copy string
LIT, // o: waiting for output space to write literal
CHECK, // i: waiting for 32-bit check value
LENGTH, // i: waiting for 32-bit length (gzip)
DONE, // finished check, done -- remain here until reset
BAD, // got a data error -- remain here until reset
SYNC // looking for synchronization bytes to restart inflate()
};
/* Structure for decoding tables. Each entry provides either the
information needed to do the operation requested by the code that
indexed that table entry, or it provides a pointer to another
table that indexes more bits of the code. op indicates whether
the entry is a pointer to another table, a literal, a length or
distance, an end-of-block, or an invalid code. For a table
pointer, the low four bits of op is the number of index bits of
that table. For a length or distance, the low four bits of op
is the number of extra bits to get after the code. bits is
the number of bits in this code or part of the code to drop off
of the bit buffer. val is the actual byte to output in the case
of a literal, the base length or distance, or the offset from
the current table to the next table. Each entry is four bytes.
op values as set by inflate_table():
00000000 - literal
0000tttt - table link, tttt != 0 is the number of table index bits
0001eeee - length or distance, eeee is the number of extra bits
01100000 - end of block
01000000 - invalid code
*/
struct code
{
std::uint8_t op; // operation, extra bits, table bits
std::uint8_t bits; // bits in this part of the code
std::uint16_t val; // offset in table or code value
};
/* Maximum size of the dynamic table. The maximum number of code
structures is 1444, which is the sum of 852 for literal/length codes
and 592 for distance codes. These values were found by exhaustive
searches using the program examples/enough.c found in the zlib
distribtution. The arguments to that program are the number of
symbols, the initial root table size, and the maximum bit length
of a code. "enough 286 9 15" for literal/length codes returns
returns 852, and "enough 30 6 15" for distance codes returns 592.
The initial root table size (9 or 6) is found in the fifth argument
of the inflate_table() calls in inflate.c and infback.c. If the
root table size is changed, then these maximum sizes would be need
to be recalculated and updated.
*/
static std::uint16_t constexpr kEnoughLens = 852;
static std::uint16_t constexpr kEnoughDists = 592;
static std::uint16_t constexpr kEnough = kEnoughLens + kEnoughDists;
struct codes
{
code const* lencode;
code const* distcode;
unsigned lenbits; // VFALCO use std::uint8_t
unsigned distbits;
};
// Type of code to build for inflate_table()
enum class build
{
codes,
lens,
dists
};
BHO_BEAST_DECL
static
void
inflate_table(
build type,
std::uint16_t* lens,
std::size_t codes,
code** table,
unsigned *bits,
std::uint16_t* work,
error_code& ec);
BHO_BEAST_DECL
static
codes const&
get_fixed_tables();
BHO_BEAST_DECL
void
fixedTables();
BHO_BEAST_DECL
void
inflate_fast(ranges& r, error_code& ec);
bitstream bi_;
Mode mode_ = HEAD; // current inflate mode
int last_ = 0; // true if processing last block
unsigned dmax_ = 32768U; // zlib header max distance (INFLATE_STRICT)
// sliding window
window w_;
// for string and stored block copying
unsigned length_; // literal or length of data to copy
unsigned offset_; // distance back to copy string from
// for table and code decoding
unsigned extra_; // extra bits needed
// dynamic table building
unsigned ncode_; // number of code length code lengths
unsigned nlen_; // number of length code lengths
unsigned ndist_; // number of distance code lengths
unsigned have_; // number of code lengths in lens[]
unsigned short lens_[320]; // temporary storage for code lengths
unsigned short work_[288]; // work area for code table building
code codes_[kEnough]; // space for code tables
code *next_ = codes_; // next available space in codes[]
int back_ = -1; // bits back of last unprocessed length/lit
unsigned was_; // initial length of match
// fixed and dynamic code tables
code const* lencode_ = codes_ ; // starting table for length/literal codes
code const* distcode_ = codes_; // starting table for distance codes
unsigned lenbits_; // index bits for lencode
unsigned distbits_; // index bits for distcode
};
} // detail
} // zlib
} // beast
} // bho
#ifdef BEAST_HEADER_ONLY
#include <asio2/bho/beast/zlib/detail/inflate_stream.ipp>
#endif
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_ALIVE_TIME_COMPONENT_HPP__
#define __ASIO2_ALIVE_TIME_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <chrono>
namespace asio2::detail
{
template<class derived_t, class args_t>
class alive_time_cp
{
public:
/**
* @brief constructor
*/
alive_time_cp() = default;
/**
* @brief destructor
*/
~alive_time_cp() = default;
alive_time_cp(alive_time_cp&&) noexcept = default;
alive_time_cp(alive_time_cp const&) = default;
alive_time_cp& operator=(alive_time_cp&&) noexcept = default;
alive_time_cp& operator=(alive_time_cp const&) = default;
public:
/**
* @brief get the time when the last alive event occurred, same as get_last_alive_time
*/
inline std::chrono::time_point<std::chrono::system_clock> last_alive_time() const noexcept
{
return this->get_last_alive_time();
}
/**
* @brief get the time when the last alive event occurred
*/
inline std::chrono::time_point<std::chrono::system_clock> get_last_alive_time() const noexcept
{
return this->last_alive_time_;
}
/**
* @brief reset last alive time to system_clock::now()
*/
inline derived_t & update_alive_time() noexcept
{
this->last_alive_time_ = std::chrono::system_clock::now();
return (static_cast<derived_t &>(*this));
}
/**
* @brief get silence duration of std::chrono::duration
*/
inline std::chrono::system_clock::duration get_silence_duration() const noexcept
{
return std::chrono::duration_cast<std::chrono::system_clock::duration>(
std::chrono::system_clock::now() - this->last_alive_time_);
}
protected:
/// last alive time
decltype(std::chrono::system_clock::now()) last_alive_time_ = std::chrono::system_clock::now();
};
}
#endif // !__ASIO2_ALIVE_TIME_COMPONENT_HPP__
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_CORE_DETAIL_BIND_DEFAULT_EXECUTOR_HPP
#define BHO_BEAST_CORE_DETAIL_BIND_DEFAULT_EXECUTOR_HPP
#include <asio2/external/asio.hpp>
#include <asio2/bho/core/empty_value.hpp>
#include <utility>
namespace bho {
namespace beast {
namespace detail {
template<class Handler, class Executor>
class bind_default_executor_wrapper
: private bho::empty_value<Executor>
{
Handler h_;
public:
template<class Handler_>
bind_default_executor_wrapper(
Handler_&& h,
Executor const& ex)
: bho::empty_value<Executor>(
bho::empty_init_t{}, ex)
, h_(std::forward<Handler_>(h))
{
}
template<class... Args>
void
operator()(Args&&... args)
{
h_(std::forward<Args>(args)...);
}
using allocator_type =
net::associated_allocator_t<Handler>;
allocator_type
get_allocator() const noexcept
{
return net::get_associated_allocator(h_);
}
using executor_type =
net::associated_executor_t<Handler, Executor>;
executor_type
get_executor() const noexcept
{
return net::get_associated_executor(
h_, this->get());
}
// The allocation hooks are still defined because they trivially forward to
// user hooks. Forward here ensures that the user will get a compile error
// if they build their code with ASIO_NO_DEPRECATED.
friend
net::asio_handler_allocate_is_deprecated
asio_handler_allocate(
std::size_t size, bind_default_executor_wrapper* p)
{
using net::asio_handler_allocate;
return asio_handler_allocate(
size, std::addressof(p->h_));
}
friend
net::asio_handler_deallocate_is_deprecated
asio_handler_deallocate(
void* mem, std::size_t size,
bind_default_executor_wrapper* p)
{
using net::asio_handler_deallocate;
return asio_handler_deallocate(mem, size,
std::addressof(p->h_));
}
friend
bool asio_handler_is_continuation(
bind_default_executor_wrapper* p)
{
using net::asio_handler_is_continuation;
return asio_handler_is_continuation(
std::addressof(p->h_));
}
};
template<class Executor, class Handler>
auto
bind_default_executor(Executor const& ex, Handler&& h) ->
bind_default_executor_wrapper<
typename std::decay<Handler>::type,
Executor>
{
return bind_default_executor_wrapper<
typename std::decay<Handler>::type,
Executor>(std::forward<Handler>(h), ex);
}
} // detail
} // beast
} // bho
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_SUBSCRIBE_ROUTER_HPP__
#define __ASIO2_MQTT_SUBSCRIBE_ROUTER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/mqtt/detail/mqtt_message_router.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class derived_t, class args_t>
class mqtt_subscribe_router_t
{
friend derived_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using self = mqtt_subscribe_router_t<derived_t, args_t>;
using args_type = args_t;
using subnode_type = typename args_type::template subnode<derived_t>;
using key_type = typename mqtt_message_router_t<derived_t, args_t>::key_type;
struct hasher
{
inline std::size_t operator()(key_type const& pair) const noexcept
{
std::size_t v = asio2::detail::fnv1a_hash<std::size_t>(
(const unsigned char*)(std::addressof(pair.first)), sizeof(pair.first));
return asio2::detail::fnv1a_hash<std::size_t>(v,
(const unsigned char*)(std::addressof(pair.second)), sizeof(pair.second));
}
};
/**
* @brief constructor
*/
mqtt_subscribe_router_t() = default;
/**
* @brief destructor
*/
~mqtt_subscribe_router_t() = default;
template<class ReturnT = void, class QosOrInt, class FunctionT>
typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<QosOrInt>, mqtt::qos_type> ||
std::is_integral_v<detail::remove_cvref_t<QosOrInt>>, ReturnT>
subscribe(std::string topic_filter, QosOrInt qos, FunctionT&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
mqtt::version ver = derive.version();
auto pid = derive.idmgr_.get();
if /**/ (ver == mqtt::version::v3)
{
mqtt::v3::subscribe msg;
msg.packet_id(pid);
msg.add_subscriptions(mqtt::subscription(std::move(topic_filter), qos));
return this->subscribe<ReturnT>(std::move(msg), std::forward<FunctionT>(callback));
}
else if (ver == mqtt::version::v4)
{
mqtt::v4::subscribe msg;
msg.packet_id(pid);
msg.add_subscriptions(mqtt::subscription(std::move(topic_filter), qos));
return this->subscribe<ReturnT>(std::move(msg), std::forward<FunctionT>(callback));
}
else if (ver == mqtt::version::v5)
{
mqtt::v5::subscribe msg;
msg.packet_id(pid);
msg.add_subscriptions(mqtt::subscription(std::move(topic_filter), qos));
return this->subscribe<ReturnT>(std::move(msg), std::forward<FunctionT>(callback));
}
else
{
derive.idmgr_.release(pid);
set_last_error(asio::error::invalid_argument);
ASIO2_ASSERT(false);
return derive.template _empty_result<ReturnT>();
}
}
template<class ReturnT = void, class Message, class FunctionT>
typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v3::subscribe> ||
std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v4::subscribe> ||
std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v5::subscribe>, ReturnT>
subscribe(Message&& msg, FunctionT&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
ASIO2_ASSERT(false);
return derive.template _empty_result<ReturnT>();
}
if (msg.subscriptions().data().empty())
{
set_last_error(asio::error::invalid_argument);
ASIO2_ASSERT(false);
return derive.template _empty_result<ReturnT>();
}
for (mqtt::subscription& sub : msg.subscriptions().data())
{
if (!mqtt::is_valid_qos(sub.qos()))
{
set_last_error(asio::error::invalid_argument);
ASIO2_ASSERT(false);
return derive.template _empty_result<ReturnT>();
}
}
clear_last_error();
[[maybe_unused]] key_type key = { msg.packet_type(), msg.packet_id() };
derive._dispatch_subscribe(std::forward<Message>(msg), std::forward<FunctionT>(callback));
if (derive.io().running_in_this_thread())
{
return derive.template _in_progress<ReturnT>();
}
ASIO2_ASSERT(!derive.io().running_in_this_thread());
if /**/ constexpr (std::is_same_v<ReturnT, void>)
{
return;
}
else if constexpr (std::is_same_v<ReturnT, bool>)
{
return derive._do_router(key, [](auto& msg) mutable
{
if constexpr (mqtt::is_suback_message<decltype(msg)>())
{
for (auto&& reason : msg.reason_codes().data())
{
if (!mqtt::is_valid_qos(reason.value()))
{
return false;
}
}
return true;
}
else
{
return false;
}
});
}
else if constexpr (std::is_same_v<ReturnT, mqtt::message>)
{
return derive._do_router(key);
}
else
{
static_assert(detail::always_false_v<ReturnT>);
}
}
template<class ReturnT = void>
ReturnT unsubscribe(std::string topic_filter)
{
derived_t& derive = static_cast<derived_t&>(*this);
mqtt::version ver = derive.version();
auto pid = derive.idmgr_.get();
if /**/ (ver == mqtt::version::v3)
{
return this->unsubscribe<ReturnT>(mqtt::v3::unsubscribe(pid, std::move(topic_filter)));
}
else if (ver == mqtt::version::v4)
{
return this->unsubscribe<ReturnT>(mqtt::v4::unsubscribe(pid, std::move(topic_filter)));
}
else if (ver == mqtt::version::v5)
{
return this->unsubscribe<ReturnT>(mqtt::v5::unsubscribe(pid, std::move(topic_filter)));
}
else
{
derive.idmgr_.release(pid);
set_last_error(asio::error::invalid_argument);
ASIO2_ASSERT(false);
return derive.template _empty_result<ReturnT>();
}
}
template<class ReturnT = void, class Message>
typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v3::unsubscribe> ||
std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v4::unsubscribe> ||
std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v5::unsubscribe>, ReturnT>
unsubscribe(Message&& msg)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
ASIO2_ASSERT(false);
return derive.template _empty_result<ReturnT>();
}
if (msg.topic_filters().data().empty())
{
set_last_error(asio::error::invalid_argument);
ASIO2_ASSERT(false);
return derive.template _empty_result<ReturnT>();
}
clear_last_error();
[[maybe_unused]] key_type key = { msg.packet_type(), msg.packet_id() };
// must ensure the member variable is read write in the io_context thread.
// save the subscribed key and topic filters, beacuse if the unsubscribed
// is sucussed, we need remove the topics from the sub map.
derive.dispatch([&derive, key, topics = msg.topic_filters()]() mutable
{
if (derive.subs_map().get_subscribe_count() > 0)
derive.unsubscribed_topics_.emplace(key, std::move(topics));
});
derive.async_send(std::forward<Message>(msg), [&derive, key]() mutable
{
// if send data failed, we need remove the added key and topics from the map.
if (asio2::get_last_error())
{
derive.unsubscribed_topics_.erase(key);
}
});
if (derive.io().running_in_this_thread())
{
return derive.template _in_progress<ReturnT>();
}
ASIO2_ASSERT(!derive.io().running_in_this_thread());
if /**/ constexpr (std::is_same_v<ReturnT, void>)
{
return;
}
else if constexpr (std::is_same_v<ReturnT, bool>)
{
return derive._do_router(key, [](auto& msg) mutable
{
if constexpr (mqtt::is_unsuback_message<decltype(msg)>())
{
// UNSUBACK Payload : The Payload contains a list of Reason Codes.
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901194
if constexpr (std::is_same_v<detail::remove_cvref_t<decltype(msg)>, mqtt::v5::unsuback>)
{
for (auto&& reason : msg.reason_codes().data())
{
mqtt::error e = static_cast<mqtt::error>(reason.value());
if (!(e == mqtt::error::success || e == mqtt::error::no_subscription_existed))
{
return false;
}
}
return true;
}
else
{
return true;
}
}
else
{
return false;
}
});
}
else if constexpr (std::is_same_v<ReturnT, mqtt::message>)
{
return derive._do_router(key);
}
else
{
static_assert(detail::always_false_v<ReturnT>);
}
}
template<class ReturnT = void, class QosOrInt>
ReturnT publish(std::string topic_name, std::string payload, QosOrInt qos)
{
derived_t& derive = static_cast<derived_t&>(*this);
mqtt::version ver = derive.version();
if /**/ (ver == mqtt::version::v3)
{
return this->publish<ReturnT>(mqtt::v3::publish(std::move(topic_name), std::move(payload), qos));
}
else if (ver == mqtt::version::v4)
{
return this->publish<ReturnT>(mqtt::v4::publish(std::move(topic_name), std::move(payload), qos));
}
else if (ver == mqtt::version::v5)
{
return this->publish<ReturnT>(mqtt::v5::publish(std::move(topic_name), std::move(payload), qos));
}
else
{
set_last_error(asio::error::invalid_argument);
ASIO2_ASSERT(false);
return derive.template _empty_result<ReturnT>();
}
}
template<class ReturnT = void, class Message>
typename std::enable_if_t<
std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v3::publish> ||
std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v4::publish> ||
std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v5::publish>, ReturnT>
publish(Message&& msg)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
ASIO2_ASSERT(false);
return derive.template _empty_result<ReturnT>();
}
if (msg.qos() > mqtt::qos_type::at_most_once && !msg.has_packet_id())
{
msg.packet_id(derive.idmgr_.get());
}
clear_last_error();
[[maybe_unused]] std::optional<key_type> key{};
if (msg.qos() > mqtt::qos_type::at_most_once && msg.has_packet_id())
key = { msg.packet_type(), msg.packet_id() };
derive.async_send(std::forward<Message>(msg));
// qos 0 don't need a response
if (!key.has_value())
{
return derive.template _empty_result<ReturnT>();
}
if (derive.io().running_in_this_thread())
{
return derive.template _in_progress<ReturnT>();
}
ASIO2_ASSERT(!derive.io().running_in_this_thread());
if /**/ constexpr (std::is_same_v<ReturnT, void>)
{
return;
}
else if constexpr (std::is_same_v<ReturnT, bool>)
{
return derive._do_bool_publish(key);
}
else if constexpr (std::is_same_v<ReturnT, mqtt::message>)
{
return derive._do_router(key.value());
}
else
{
static_assert(detail::always_false_v<ReturnT>);
}
}
protected:
template<class K>
bool _do_bool_publish(std::optional<K>& key)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive._do_router(key.value(), [](auto& msg) mutable
{
// qos 1 response
if constexpr (mqtt::is_puback_message<decltype(msg)>())
{
if constexpr (std::is_same_v<detail::remove_cvref_t<decltype(msg)>, mqtt::v5::puback>)
{
mqtt::error e = static_cast<mqtt::error>(msg.reason_code());
if (!(e == mqtt::error::success))
{
return false;
}
return true;
}
else
{
return true;
}
}
else if constexpr (mqtt::is_pubcomp_message<decltype(msg)>())
{
if constexpr (std::is_same_v<detail::remove_cvref_t<decltype(msg)>, mqtt::v5::pubcomp>)
{
mqtt::error e = static_cast<mqtt::error>(msg.reason_code());
if (!(e == mqtt::error::success))
{
return false;
}
return true;
}
else
{
return true;
}
}
else
{
return false;
}
});
}
template<class ReturnT>
inline ReturnT _empty_result()
{
if constexpr (std::is_same_v<ReturnT, void>)
{
return;
}
else
{
return ReturnT{};
}
}
template<class ReturnT>
inline ReturnT _in_progress()
{
if /**/ constexpr (std::is_same_v<ReturnT, void>)
{
set_last_error(asio::error::in_progress);
return;
}
else if constexpr (std::is_same_v<ReturnT, bool>)
{
set_last_error(asio::error::in_progress);
return true;
}
else if constexpr (std::is_same_v<ReturnT, mqtt::message>)
{
set_last_error(asio::error::in_progress);
return mqtt::message{};
}
else
{
static_assert(detail::always_false_v<ReturnT>);
}
}
/**
* callback signature : bool (auto& msg)
*/
template<class KeyT, class FunctionT>
bool _do_router(KeyT key, FunctionT&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::promise<bool> p;
std::future<bool> f = p.get_future();
derive._add_router(key, [&callback, p = std::move(p)](mqtt::message& m) mutable
{
std::visit([&callback, &p](auto& msg) mutable
{
p.set_value(callback(msg));
}, m.base());
});
std::future_status status = f.wait_for(derive.get_default_timeout());
if (status == std::future_status::ready)
{
derive._del_router(key);
return true;
}
set_last_error(asio::error::timed_out);
derive._del_router(key);
return false;
}
template<class KeyT>
mqtt::message _do_router(KeyT key)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::shared_ptr<mqtt::message> r = std::make_shared<mqtt::message>();
std::promise<void> p;
std::future<void> f = p.get_future();
derive._add_router(key, [r, p = std::move(p)](mqtt::message& m) mutable
{
*r = m;
p.set_value();
});
std::future_status status = f.wait_for(derive.get_default_timeout());
if (status == std::future_status::ready)
{
derive._del_router(key);
return std::move(*r);
}
set_last_error(asio::error::timed_out);
derive._del_router(key);
return mqtt::message{};
}
template<class Message, class FunctionT>
inline void _dispatch_subscribe(Message&& msg, FunctionT&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
derive.dispatch(
[&derive, msg = std::forward<Message>(msg), cb = std::forward<FunctionT>(callback)]() mutable
{
derive._do_subscribe(std::move(msg), std::move(cb));
});
}
template<class Message, class FunctionT>
void _do_subscribe(Message&& msg, FunctionT&& callback)
{
using message_type = typename detail::remove_cvref_t<Message>;
using fun_traits_type = function_traits<FunctionT>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
derived_t& derive = static_cast<derived_t&>(*this);
mqtt::v5::properties_set props;
if constexpr (std::is_same_v<message_type, mqtt::v5::subscribe>)
{
props = msg.properties();
}
else
{
std::ignore = true;
}
std::vector<mqtt::subscription>& subs = msg.subscriptions().data();
for (std::size_t i = 0; i < subs.size(); ++i)
{
mqtt::subscription& sub = subs[i];
bool end = (i + 1 == subs.size());
subnode_type node{ derive.selfptr(), sub, end ? std::move(props) : props };
if constexpr (std::is_same_v<arg0_type, mqtt::message>)
{
node.callback = end ? std::forward<FunctionT>(callback) : callback;
}
else
{
node.callback = [cb = end ? std::forward<FunctionT>(callback) : callback]
(mqtt::message& msg) mutable
{
arg0_type* p = std::get_if<arg0_type>(std::addressof(msg.base()));
if (p)
{
cb(*p);
}
};
}
std::string_view share_name = node.share_name();
std::string_view topic_filter = node.topic_filter();
auto[_1, inserted] = this->subs_map().insert_or_assign(topic_filter, "", std::move(node));
asio2::ignore_unused(share_name, topic_filter, _1, inserted);
}
derive.async_send(std::forward<Message>(msg));
}
inline mqtt::subscription_map<std::string_view, subnode_type>& subs_map() { return subs_map_; }
protected:
/// subscription information map
mqtt::subscription_map<std::string_view, subnode_type> subs_map_;
/// don't need mutex, beacuse client only has one thread, we use post to ensure this
/// variable was read write in the client io_context thread.
std::unordered_map<key_type, mqtt::utf8_string_set, hasher> unsubscribed_topics_;
};
}
#endif // !__ASIO2_MQTT_SUBSCRIBE_ROUTER_HPP__
<file_sep>/*
Copyright <NAME> 2008-2019
Copyright <NAME> 2014
Copyright (c) Microsoft Corporation 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_ARM_H
#define BHO_PREDEF_ARCHITECTURE_ARM_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_ARM`
http://en.wikipedia.org/wiki/ARM_architecture[ARM] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__ARM_ARCH+` | {predef_detection}
| `+__TARGET_ARCH_ARM+` | {predef_detection}
| `+__TARGET_ARCH_THUMB+` | {predef_detection}
| `+_M_ARM+` | {predef_detection}
| `+__arm__+` | {predef_detection}
| `+__arm64+` | {predef_detection}
| `+__thumb__+` | {predef_detection}
| `+_M_ARM64+` | {predef_detection}
| `+__aarch64__+` | {predef_detection}
| `+__AARCH64EL__+` | {predef_detection}
| `+__ARM_ARCH_7__+` | {predef_detection}
| `+__ARM_ARCH_7A__+` | {predef_detection}
| `+__ARM_ARCH_7R__+` | {predef_detection}
| `+__ARM_ARCH_7M__+` | {predef_detection}
| `+__ARM_ARCH_6K__+` | {predef_detection}
| `+__ARM_ARCH_6Z__+` | {predef_detection}
| `+__ARM_ARCH_6KZ__+` | {predef_detection}
| `+__ARM_ARCH_6T2__+` | {predef_detection}
| `+__ARM_ARCH_5TE__+` | {predef_detection}
| `+__ARM_ARCH_5TEJ__+` | {predef_detection}
| `+__ARM_ARCH_4T__+` | {predef_detection}
| `+__ARM_ARCH_4__+` | {predef_detection}
| `+__ARM_ARCH+` | V.0.0
| `+__TARGET_ARCH_ARM+` | V.0.0
| `+__TARGET_ARCH_THUMB+` | V.0.0
| `+_M_ARM+` | V.0.0
| `+__arm64+` | 8.0.0
| `+_M_ARM64+` | 8.0.0
| `+__aarch64__+` | 8.0.0
| `+__AARCH64EL__+` | 8.0.0
| `+__ARM_ARCH_7__+` | 7.0.0
| `+__ARM_ARCH_7A__+` | 7.0.0
| `+__ARM_ARCH_7R__+` | 7.0.0
| `+__ARM_ARCH_7M__+` | 7.0.0
| `+__ARM_ARCH_6K__+` | 6.0.0
| `+__ARM_ARCH_6Z__+` | 6.0.0
| `+__ARM_ARCH_6KZ__+` | 6.0.0
| `+__ARM_ARCH_6T2__+` | 6.0.0
| `+__ARM_ARCH_5TE__+` | 5.0.0
| `+__ARM_ARCH_5TEJ__+` | 5.0.0
| `+__ARM_ARCH_4T__+` | 4.0.0
| `+__ARM_ARCH_4__+` | 4.0.0
|===
*/ // end::reference[]
#define BHO_ARCH_ARM BHO_VERSION_NUMBER_NOT_AVAILABLE
#if \
defined(__ARM_ARCH) || defined(__TARGET_ARCH_ARM) || \
defined(__TARGET_ARCH_THUMB) || defined(_M_ARM) || \
defined(__arm__) || defined(__arm64) || defined(__thumb__) || \
defined(_M_ARM64) || defined(__aarch64__) || defined(__AARCH64EL__) || \
defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \
defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || \
defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || \
defined(__ARM_ARCH_6KZ__) || defined(__ARM_ARCH_6T2__) || \
defined(__ARM_ARCH_5TE__) || defined(__ARM_ARCH_5TEJ__) || \
defined(__ARM_ARCH_4T__) || defined(__ARM_ARCH_4__)
# undef BHO_ARCH_ARM
# if !defined(BHO_ARCH_ARM) && defined(__ARM_ARCH)
# define BHO_ARCH_ARM BHO_VERSION_NUMBER(__ARM_ARCH,0,0)
# endif
# if !defined(BHO_ARCH_ARM) && defined(__TARGET_ARCH_ARM)
# define BHO_ARCH_ARM BHO_VERSION_NUMBER(__TARGET_ARCH_ARM,0,0)
# endif
# if !defined(BHO_ARCH_ARM) && defined(__TARGET_ARCH_THUMB)
# define BHO_ARCH_ARM BHO_VERSION_NUMBER(__TARGET_ARCH_THUMB,0,0)
# endif
# if !defined(BHO_ARCH_ARM) && defined(_M_ARM)
# define BHO_ARCH_ARM BHO_VERSION_NUMBER(_M_ARM,0,0)
# endif
# if !defined(BHO_ARCH_ARM) && ( \
defined(__arm64) || defined(_M_ARM64) || defined(__aarch64__) || \
defined(__AARCH64EL__) )
# define BHO_ARCH_ARM BHO_VERSION_NUMBER(8,0,0)
# endif
# if !defined(BHO_ARCH_ARM) && ( \
defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \
defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) )
# define BHO_ARCH_ARM BHO_VERSION_NUMBER(7,0,0)
# endif
# if !defined(BHO_ARCH_ARM) && ( \
defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || \
defined(__ARM_ARCH_6KZ__) || defined(__ARM_ARCH_6T2__) )
# define BHO_ARCH_ARM BHO_VERSION_NUMBER(6,0,0)
# endif
# if !defined(BHO_ARCH_ARM) && ( \
defined(__ARM_ARCH_5TE__) || defined(__ARM_ARCH_5TEJ__) )
# define BHO_ARCH_ARM BHO_VERSION_NUMBER(5,0,0)
# endif
# if !defined(BHO_ARCH_ARM) && ( \
defined(__ARM_ARCH_4T__) || defined(__ARM_ARCH_4__) )
# define BHO_ARCH_ARM BHO_VERSION_NUMBER(4,0,0)
# endif
# if !defined(BHO_ARCH_ARM)
# define BHO_ARCH_ARM BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_ARM
# define BHO_ARCH_ARM_AVAILABLE
#endif
#if BHO_ARCH_ARM
# if BHO_ARCH_ARM >= BHO_VERSION_NUMBER(8,0,0)
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
# else
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#define BHO_ARCH_ARM_NAME "ARM"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_ARM,BHO_ARCH_ARM_NAME)
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2002.
// (C) Copyright <NAME> 2003.
// (C) Copyright <NAME> 2006 - 2007.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// hpux specific config options:
#define BHO_PLATFORM "HP-UX"
// In principle, HP-UX has a nice <stdint.h> under the name <inttypes.h>
// However, it has the following problem:
// Use of UINT32_C(0) results in "0u l" for the preprocessed source
// (verifyable with gcc 2.95.3)
#if (defined(__GNUC__) && (__GNUC__ >= 3)) || defined(__HP_aCC)
# define BHO_HAS_STDINT_H
#endif
#if !(defined(__HP_aCC) || !defined(_INCLUDE__STDC_A1_SOURCE))
# define BHO_NO_SWPRINTF
#endif
#if defined(__HP_aCC) && !defined(_INCLUDE__STDC_A1_SOURCE)
# define BHO_NO_CWCTYPE
#endif
#if defined(__GNUC__)
# if (__GNUC__ < 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ < 3))
// GNU C on HP-UX does not support threads (checked up to gcc 3.3)
# define BHO_DISABLE_THREADS
# elif !defined(BHO_DISABLE_THREADS)
// threads supported from gcc-3.3 onwards:
# define BHO_HAS_THREADS
# define BHO_HAS_PTHREADS
# endif
#elif defined(__HP_aCC) && !defined(BHO_DISABLE_THREADS)
# define BHO_HAS_PTHREADS
#endif
// boilerplate code:
#define BHO_HAS_UNISTD_H
#include <asio2/bho/config/detail/posix_features.hpp>
// the following are always available:
#ifndef BHO_HAS_GETTIMEOFDAY
# define BHO_HAS_GETTIMEOFDAY
#endif
#ifndef BHO_HAS_SCHED_YIELD
# define BHO_HAS_SCHED_YIELD
#endif
#ifndef BHO_HAS_PTHREAD_MUTEXATTR_SETTYPE
# define BHO_HAS_PTHREAD_MUTEXATTR_SETTYPE
#endif
#ifndef BHO_HAS_NL_TYPES_H
# define BHO_HAS_NL_TYPES_H
#endif
#ifndef BHO_HAS_NANOSLEEP
# define BHO_HAS_NANOSLEEP
#endif
#ifndef BHO_HAS_GETTIMEOFDAY
# define BHO_HAS_GETTIMEOFDAY
#endif
#ifndef BHO_HAS_DIRENT_H
# define BHO_HAS_DIRENT_H
#endif
#ifndef BHO_HAS_CLOCK_GETTIME
# define BHO_HAS_CLOCK_GETTIME
#endif
#ifndef BHO_HAS_SIGACTION
# define BHO_HAS_SIGACTION
#endif
#ifndef BHO_HAS_NRVO
# ifndef __parisc
# define BHO_HAS_NRVO
# endif
#endif
#ifndef BHO_HAS_LOG1P
# define BHO_HAS_LOG1P
#endif
#ifndef BHO_HAS_EXPM1
# define BHO_HAS_EXPM1
#endif
<file_sep>#ifndef ASIO2_ENABLE_SSL
#define ASIO2_ENABLE_SSL
#endif
#include <asio2/rpc/rpcs_client.hpp>
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8011";
asio2::rpcs_client client;
// set default rpc call timeout
client.set_default_timeout(std::chrono::seconds(3));
//------------------------------------------------------------------------------
// beacuse the server did not specify the verify_fail_if_no_peer_cert flag, so
// our client may not load the ssl certificate.
//------------------------------------------------------------------------------
//client.set_verify_mode(asio::ssl::verify_peer);
//client.set_cert_file("../../cert/ca.crt", "../../cert/client.crt", "../../cert/client.key", "123456");
client.bind_connect([&]()
{
if (asio2::get_last_error())
return;
// the type of the callback's second parameter is auto, so you have to specify
// the return type in the template function like 'async_call<int>'
int x = std::rand(), y = std::rand();
client.async_call<int>([x, y](auto v)
{
asio2::ignore_unused(x, y);
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == x + y);
}
printf("sum1 : %d - %d %s\n", v,
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "add", x, y);
}).bind_disconnect([]()
{
printf("disconnect : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
});
client.bind("sub", [](int a, int b) { return a - b; });
client.async_start(host, port);
client.start_timer("timer_id1", std::chrono::milliseconds(500), [&]()
{
std::string s1;
s1 += '<';
for (int i = 100 + std::rand() % (100); i > 0; i--)
{
s1 += (char)((std::rand() % 26) + 'a');
}
std::string s2;
for (int i = 100 + std::rand() % (100); i > 0; i--)
{
s2 += (char)((std::rand() % 26) + 'a');
}
s2 += '>';
client.async_call([s1, s2](std::string v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == s1 + s2);
}
printf("cat : %s - %d %s\n", v.c_str(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "cat", s1, s2);
});
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_LOGGER_HPP__
#define __ASIO2_LOGGER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <ctime>
#include <cstring>
#include <cstdarg>
#include <memory>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <fstream>
#include <string>
/*
*
* How to determine whether to use <filesystem> or <experimental/filesystem>
* https://stackoverflow.com/questions/53365538/how-to-determine-whether-to-use-filesystem-or-experimental-filesystem/53365539#53365539
*
*
*/
// We haven't checked which filesystem to include yet
#ifndef INCLUDE_STD_FILESYSTEM_EXPERIMENTAL
// Check for feature test macro for <filesystem>
# if defined(__cpp_lib_filesystem)
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 0
// Check for feature test macro for <experimental/filesystem>
# elif defined(__cpp_lib_experimental_filesystem)
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 1
// We can't check if headers exist...
// Let's assume experimental to be safe
# elif !defined(__has_include)
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 1
// Check if the header "<filesystem>" exists
# elif __has_include(<filesystem>)
// If we're compiling on Visual Studio and are not compiling with C++17, we need to use experimental
# ifdef _MSC_VER
// Check and include header that defines "_HAS_CXX17"
# if __has_include(<yvals_core.h>)
# include <yvals_core.h>
// Check for enabled C++17 support
# if defined(_HAS_CXX17) && _HAS_CXX17
// We're using C++17, so let's use the normal version
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 0
# endif
# endif
// If the marco isn't defined yet, that means any of the other VS specific checks failed, so we need to use experimental
# ifndef INCLUDE_STD_FILESYSTEM_EXPERIMENTAL
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 1
# endif
// Not on Visual Studio. Let's use the normal version
# else // #ifdef _MSC_VER
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 0
# endif
// Check if the header "<filesystem>" exists
# elif __has_include(<experimental/filesystem>)
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 1
// Fail if neither header is available with a nice error message
# else
# error Could not find system header "<filesystem>" or "<experimental/filesystem>"
# endif
// We priously determined that we need the exprimental version
# if INCLUDE_STD_FILESYSTEM_EXPERIMENTAL
// Include it
# include <experimental/filesystem>
// We need the alias from std::experimental::filesystem to std::filesystem
namespace std {
namespace filesystem = experimental::filesystem;
}
// We have a decent compiler and can use the normal version
# else
// Include it
# include <filesystem>
# endif
#endif // #ifndef INCLUDE_STD_FILESYSTEM_EXPERIMENTAL
#ifndef FMT_HEADER_ONLY
#define FMT_HEADER_ONLY
#endif
#include <fmt/format.h>
#include <fmt/chrono.h>
/*
* mutex,thread:
* Linux platform needs to add -lpthread option in link libraries
* filesystem:
* Linux platform needs to add -lstdc++fs option in link libraries, If it still doesn't work,
* try adding stdc++fs to Library Dependencies.
* try search file for libstdc++fs.a
*/
// when use logger in multi module(eg:exe and dll),should #define ASIO2_LOGGER_MULTI_MODULE
// #define ASIO2_LOGGER_MULTI_MODULE
/*
# don't use "FILE fwrite ..." to handle the file,because if you declare a logger object,
when call "fopen" in exe module, and call "fwite" in dll module,it will crash. use
std::ofstream can avoid this problem.
# why use "ASIO2_LOGGER_MULTI_MODULE" and create the file in a thread ? when call
std::ofstream::open in exe module,and close file in dll module,it will crash.
we should ensure that which module create the object,the object must destroy by
the same module. so we create a thread,when need recreate the file,we post a
notify event to the thread,and the thread will create the file in the module
which create the file.
# why don't use boost::log ? beacuse if you want use boost::log on multi module
(eg:exe and dll),the boost::log must be compilered by shared link(a dll),and
when the exe is compilered with MT/MTd,there will be a lot of compilation problems.
*/
namespace asio2
{
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable:4996)
#endif
/**
* a simple logger
*/
class logger
{
public:
// We define our own severity levels
enum class severity_level : std::int8_t
{
trace,
debug,
info,
warn,
error,
fatal,
report
};
enum dest
{ // constants for file opening options
dest_mask = 0xff
};
static constexpr dest console = (dest)0x01;
static constexpr dest file = (dest)0x02;
explicit logger(
const std::string & filename = std::string(),
severity_level level = severity_level::trace,
unsigned int dest = console | file,
std::size_t roll_size = 1024 * 1024 * 1024
)
: filename_(filename), level_(level), dest_(dest), roll_size_(roll_size)
{
if (this->roll_size_ < 1024)
this->roll_size_ = 1024;
if (this->level_ < severity_level::trace || this->level_ > severity_level::report)
this->level_ = severity_level::debug;
this->endl_ = { '\n' };
this->preferred_ = { '/' };
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || \
defined(_WINDOWS_) || defined(__WINDOWS__) || defined(__TOS_WIN__)
this->endl_ = { '\r','\n' };
this->preferred_ = { '\\' };
#endif
#if defined(ASIO2_LOGGER_MULTI_MODULE)
std::thread t([this]() mutable
{
while (true)
{
std::unique_lock<std::mutex> lock(this->mtx_);
this->cv_.wait(lock, [this]() { return this->is_stop_ || this->mkflag_; });
if (this->is_stop_)
return;
if (this->mkflag_)
{
this->mkfile();
this->mkflag_ = false;
}
}
});
this->thread_.swap(t);
#endif
this->mkfile();
}
~logger()
{
#if defined(ASIO2_LOGGER_MULTI_MODULE)
{
std::unique_lock<std::mutex> lock(this->mtx_);
this->is_stop_ = true;
}
this->cv_.notify_all();
if (this->thread_.joinable())
this->thread_.join();
#endif
std::lock_guard<std::mutex> g(this->mutex_);
if (this->file_.is_open())
{
this->file_.flush();
this->file_.close();
}
}
static logger & get() noexcept { static logger log; return log; }
inline const char * level2severity(severity_level level) noexcept
{
static const char * name[]{ "TRACE","DEBUG","INFOR","WARNS","ERROR","FATAL","REPOT", };
return ((level >= severity_level::trace && level <= severity_level::report) ?
name[static_cast<typename std::underlying_type<severity_level>::type>(level)] : "");
}
/**
* set the log ouput level,if you has't call this function,the defaul level is trace.
*/
inline logger & set_level(severity_level level) noexcept
{
std::lock_guard<std::mutex> g(this->mutex_);
this->level_ = level;
if (this->level_ < severity_level::trace || this->level_ > severity_level::report)
this->level_ = severity_level::debug;
return (*this);
}
/**
* set the log ouput level,if you has't call this function,the defaul level is trace.
* same as set_level
*/
inline logger & level(severity_level level) noexcept
{
return this->set_level(level);
}
/**
* get the log ouput level
*/
inline severity_level get_level() noexcept
{
std::lock_guard<std::mutex> g(this->mutex_);
return this->level_;
}
/**
* get the log ouput level, same as get_level
*/
inline severity_level level() noexcept
{
std::lock_guard<std::mutex> g(this->mutex_);
return this->level_;
}
/**
* set the log ouput dest, console or file or both.
*/
inline logger & set_dest(unsigned int dest) noexcept
{
std::lock_guard<std::mutex> g(this->mutex_);
this->dest_ = dest;
return (*this);
}
/**
* set the log ouput dest, console or file or both. same as set_dest
*/
inline logger & dest(unsigned int dest) noexcept
{
return this->set_dest(dest);
}
/**
* get the log ouput dest, console or file or both.
*/
inline unsigned int get_dest() noexcept
{
std::lock_guard<std::mutex> g(this->mutex_);
return this->dest_;
}
/**
* get the log ouput dest, console or file or both. same as get_dest
*/
inline unsigned int dest() noexcept
{
std::lock_guard<std::mutex> g(this->mutex_);
return this->dest_;
}
/**
* set a user custom function log target.
* @Fun : void(const std::string & text)
*/
template<class Fun>
inline logger & set_target(Fun&& target) noexcept
{
std::lock_guard<std::mutex> g(this->mutex_);
this->target_ = std::forward<Fun>(target);
return (*this);
}
/**
* set a user custom function log target. same as set_target
* @Fun : void(const std::string & text)
*/
template<class Fun>
inline logger & target(Fun&& target) noexcept
{
return this->set_target(std::forward<Fun>(target));
}
/**
* get the user custom function log target.
*/
inline std::function<void(const std::string & text)> & get_target() noexcept
{
return this->target_;
}
/**
* get the user custom function log target. same as get_target
*/
inline std::function<void(const std::string & text)> & target() noexcept
{
return this->target_;
}
/**
* convert the level value to string
*/
inline const char * level2string(severity_level level) noexcept
{
static const char * name[]{ "trace","debug","info","warn","error","fatal","report", };
return ((level >= severity_level::trace && level <= severity_level::report) ?
name[static_cast<typename std::underlying_type<severity_level>::type>(level)] : "");
}
template <typename S, typename... Args>
inline void log_trace(const S& format_str, Args&&... args)
{
if (logger::severity_level::trace >= this->level_)
{
this->log(logger::severity_level::trace, format_str, std::forward<Args>(args)...);
}
}
template <typename S, typename... Args>
inline void log_debug(const S& format_str, Args&&... args)
{
if (logger::severity_level::debug >= this->level_)
{
this->log(logger::severity_level::debug, format_str, std::forward<Args>(args)...);
}
}
template <typename S, typename... Args>
inline void log_info(const S& format_str, Args&&... args)
{
if (logger::severity_level::info >= this->level_)
{
this->log(logger::severity_level::info, format_str, std::forward<Args>(args)...);
}
}
template <typename S, typename... Args>
inline void log_warn(const S& format_str, Args&&... args)
{
if (logger::severity_level::warn >= this->level_)
{
this->log(logger::severity_level::warn, format_str, std::forward<Args>(args)...);
}
}
template <typename S, typename... Args>
inline void log_error(const S& format_str, Args&&... args)
{
if (logger::severity_level::error >= this->level_)
{
this->log(logger::severity_level::error, format_str, std::forward<Args>(args)...);
}
}
template <typename S, typename... Args>
inline void log_fatal(const S& format_str, Args&&... args)
{
if (logger::severity_level::fatal >= this->level_)
{
this->log(logger::severity_level::fatal, format_str, std::forward<Args>(args)...);
}
}
template <typename S, typename... Args>
inline void log_report(const S& format_str, Args&&... args)
{
if (logger::severity_level::report >= this->level_)
{
this->log(logger::severity_level::report, format_str, std::forward<Args>(args)...);
}
}
template <typename S, typename... Args>
void log(severity_level level, const S& format_str, Args&&... args)
{
std::lock_guard<std::mutex> g(this->mutex_);
if (level < this->level_)
return;
std::time_t t = std::time(nullptr);
std::string content;
if constexpr (sizeof...(Args) == 0)
{
content =
fmt::format("[{}] [{:%Y-%m-%d %H:%M:%S}] ", level2severity(level), *std::localtime(&t)) +
fmt::format("{}", format_str) +
this->endl_;
}
else
{
content =
fmt::format("[{}] [{:%Y-%m-%d %H:%M:%S}] ", level2severity(level), *std::localtime(&t)) +
fmt::format(format_str, std::forward<Args>(args)...) +
this->endl_;
}
// call user defined target function
if (this->target_)
{
this->target_(content);
}
// print log into the console window
if ((this->dest_ & dest::dest_mask) & console)
{
// don't use std::cout and printf together.
//std::cout << content << std::endl;
//std::printf("%.*s", static_cast<int>(content.size()), content.data());
fmt::print("{}", content);
}
// save log into the file
if ((this->dest_ & dest::dest_mask) & file)
{
if (this->file_.is_open())
{
this->file_.write(content.data(), content.size());
this->size_ += content.size();
// if file size is too large,close this file,and create a new file.
if (this->size_ > this->roll_size_)
{
#if defined(ASIO2_LOGGER_MULTI_MODULE)
this->mkflag_ = true;
while (this->mkflag_)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
this->cv_.notify_one();
}
#endif
this->mkfile();
}
}
}
}
inline void flush()
{
std::lock_guard<std::mutex> g(this->mutex_);
if (this->file_.is_open())
{
this->file_.flush();
}
}
protected:
logger & mkfile()
{
if (this->filename_.empty())
{
this->filename_ = std::filesystem::current_path().string();
if (this->filename_.back() != '\\' && this->filename_.back() != '/')
this->filename_ += this->preferred_;
this->filename_ += "log";
this->filename_ += this->preferred_;
std::filesystem::create_directories(std::filesystem::path(this->filename_));
time_t t;
time(&t); /* Get time in seconds */
struct tm tm = *localtime(&t); /* Convert time to struct */
char tmbuf[20] = { 0 };
strftime(tmbuf, 20, "%Y-%m-%d %H.%M.%S", std::addressof(tm));
this->filename_ += tmbuf;
this->filename_ += ".log";
}
else
{
// Compatible with three file name parameters :
// abc.log
// D:\log\abc.log
// /usr/log/abc.log
if (std::filesystem::is_directory(filename_))
{
if (this->filename_.back() != '\\' && this->filename_.back() != '/')
this->filename_ += this->preferred_;
this->filename_ += "log";
this->filename_ += this->preferred_;
std::filesystem::create_directories(std::filesystem::path(this->filename_));
time_t t;
time(&t); /* Get time in seconds */
struct tm tm = *localtime(&t); /* Convert time to struct */
char tmbuf[20] = { 0 };
strftime(tmbuf, 20, "%Y-%m-%d %H.%M.%S", std::addressof(tm));
this->filename_ += tmbuf;
this->filename_ += ".log";
}
else
{
std::string::size_type slash = this->filename_.find_last_of("\\/");
// abc.log
if (slash == std::string::npos)
{
std::string name = this->filename_;
this->filename_ = std::filesystem::current_path().string();
if (this->filename_.back() != '\\' && this->filename_.back() != '/')
this->filename_ += this->preferred_;
this->filename_ += "log";
this->filename_ += this->preferred_;
std::filesystem::create_directories(std::filesystem::path(this->filename_));
this->filename_ += name;
}
// D:\log\abc.log // /usr/log/abc.log
else
{
std::filesystem::create_directories(
std::filesystem::path(this->filename_.substr(0, slash)));
}
}
}
if (this->file_.is_open())
{
this->file_.flush();
this->file_.close();
}
this->size_ = 0;
this->file_.open(this->filename_,
std::ofstream::binary | std::ofstream::out | std::ofstream::app);
return (*this);
}
private:
/// no copy construct function
logger(const logger&) = delete;
/// no operator equal function
logger& operator=(const logger&) = delete;
protected:
std::string filename_;
severity_level level_ = severity_level::trace;
unsigned int dest_ = console | file;
std::size_t roll_size_ = 1024 * 1024 * 1024;
std::size_t size_ = 0;
std::ofstream file_;
std::string endl_;
std::string preferred_;
std::mutex mutex_;
std::function<void(const std::string & text)> target_;
#if defined(ASIO2_LOGGER_MULTI_MODULE)
std::thread thread_;
std::mutex mtx_;
std::condition_variable cv_;
bool is_stop_ = false;
bool mkflag_ = false;
#endif
};
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
}
#endif // !__ASIO2_LOGGER_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* refrenced from : /beast/core/detect_ssl.hpp
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* Note : this functionality not yet implemented
*
*/
#ifndef __ASIO2_MQTT_DETECT_WEBSOCKET_HPP__
#define __ASIO2_MQTT_DETECT_WEBSOCKET_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <type_traits>
#include <asio2/external/asio.hpp>
#include <asio2/external/beast.hpp>
#include <asio2/base/error.hpp>
#ifdef ASIO_STANDALONE
#include <asio/yield.hpp>
#else
#include <boost/asio/yield.hpp>
#endif
namespace asio2::detail
{
template<class DetectHandler, class AsyncReadStream, class DynamicBuffer>
class detect_websocket_op : public asio::coroutine
{
DetectHandler handler_;
AsyncReadStream& stream_;
// The callers buffer is used to hold all received data
DynamicBuffer& buffer_;
// We're going to need this in case we have to post the handler
error_code ec_;
beast::tribool result_ = false;
public:
// Completion handlers must be MoveConstructible.
detect_websocket_op(detect_websocket_op&&) = default;
// Construct the operation. The handler is deduced through
// the template type `DetectHandler`, this lets the same constructor
// work properly for both lvalues and rvalues.
//
detect_websocket_op(
DetectHandler&& handler,
AsyncReadStream& stream,
DynamicBuffer& buffer)
: handler_(std::forward<DetectHandler>(handler))
, stream_(stream)
, buffer_(buffer)
{
// This starts the operation. We pass `false` to tell the
// algorithm that it needs to use asio::post if it wants to
// complete immediately. This is required by Networking,
// as initiating functions are not allowed to invoke the
// completion handler on the caller's thread before
// returning.
(*this)({}, 0, false);
}
// Our main entry point. This will get called as our
// intermediate operations complete. Definition below.
//
// The parameter `cont` indicates if we are being called subsequently
// from the original invocation
//
void operator()(error_code ec, std::size_t bytes_transferred, bool cont = true)
{
// This introduces the scope of the stackless coroutine
reenter(*this)
{
// Loop until an error occurs or we get a definitive answer
for(;;)
{
// There could already be a hello in the buffer so check first
result_ = is_websocket_upgrade_request(buffer_.data());
// If we got an answer, then the operation is complete
if(! beast::indeterminate(result_))
break;
// Try to fill our buffer by reading from the stream.
// The function read_size calculates a reasonable size for the
// amount to read next, using existing capacity if possible to
// avoid allocating memory, up to the limit of 1536 bytes which
// is the size of a normal TCP frame.
//
// `async_read_some` expects a ReadHandler as the completion
// handler. The signature of a read handler is void(error_code, size_t),
// and this function matches that signature (the `cont` parameter has
// a default of true). We pass `std::move(*this)` as the completion
// handler for the read operation. This transfers ownership of this
// entire state machine back into the `async_read_some` operation.
// Care must be taken with this idiom, to ensure that parameters
// passed to the initiating function which could be invalidated
// by the move, are first moved to the stack before calling the
// initiating function.
yield stream_.async_read_some(buffer_.prepare(
read_size(buffer_, 1536)), std::move(*this));
// Commit what we read into the buffer's input area.
buffer_.commit(bytes_transferred);
// Check for an error
if(ec)
break;
}
// If `cont` is true, the handler will be invoked directly.
//
// Otherwise, the handler cannot be invoked directly, because
// initiating functions are not allowed to call the handler
// before returning. Instead, the handler must be posted to
// the I/O context. We issue a zero-byte read using the same
// type of buffers used in the ordinary read above, to prevent
// the compiler from creating an extra instantiation of the
// function template. This reduces compile times and the size
// of the program executable.
if(! cont)
{
// Save the error, otherwise it will be overwritten with
// a successful error code when this read completes
// immediately.
ec_ = ec;
// Zero-byte reads and writes are guaranteed to complete
// immediately with succcess. The type of buffers and the
// type of handler passed here need to exactly match the types
// used in the call to async_read_some above, to avoid
// instantiating another version of the function template.
yield stream_.async_read_some(buffer_.prepare(0), std::move(*this));
// Restore the saved error code
ec = ec_;
}
// Invoke the final handler.
// At this point, we are guaranteed that the original initiating
// function is no longer on our stack frame.
this->handler_(ec, static_cast<bool>(result_));
}
}
};
struct run_detect_websocket_op
{
template<class DetectHandler, class AsyncReadStream, class DynamicBuffer>
void operator()(DetectHandler&& h, AsyncReadStream* s, DynamicBuffer& b)
{
detect_websocket_op<DetectHandler, AsyncReadStream, DynamicBuffer>(
std::forward<DetectHandler>(h), *s, b);
}
};
template <class ConstBufferSequence>
beast::tribool is_websocket_upgrade_request(ConstBufferSequence const& buffers)
{
// Make sure buffers meets the requirements
static_assert(
asio::is_const_buffer_sequence<ConstBufferSequence>::value,
"ConstBufferSequence type requirements not met");
// Flatten the input buffers into a single contiguous range
// of bytes on the stack to make it easier to work with the data.
unsigned char buf[9];
auto const n = asio::buffer_copy(
asio::mutable_buffer(buf, sizeof(buf)), buffers);
// Can't do much without any bytes
if(n < 1)
return beast::indeterminate;
// Require the first byte to be 0x16, indicating a TLS handshake record
if(buf[0] != 0x16)
return false;
// We need at least 5 bytes to know the record payload size
if(n < 5)
return beast::indeterminate;
// Calculate the record payload size
std::uint32_t const length = (buf[3] << 8) + buf[4];
// A ClientHello message payload is at least 34 bytes.
// There can be multiple handshake messages in the same record.
if(length < 34)
return false;
// We need at least 6 bytes to know the handshake type
if(n < 6)
return beast::indeterminate;
// The handshake_type must be 0x01 == client_hello
if(buf[5] != 0x01)
return false;
// We need at least 9 bytes to know the payload size
if(n < 9)
return beast::indeterminate;
// Calculate the message payload size
std::uint32_t const size =
(buf[6] << 16) + (buf[7] << 8) + buf[8];
// The message payload can't be bigger than the enclosing record
if(size + 4 > length)
return false;
// This can only be a TLS client_hello message
return true;
}
template<class SyncReadStream, class DynamicBuffer>
bool detect_websocket(SyncReadStream& stream, DynamicBuffer& buffer, error_code& ec)
{
// Make sure arguments meet the requirements
static_assert(
is_sync_read_stream<SyncReadStream>::value,
"SyncReadStream type requirements not met");
static_assert(
asio::is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer type requirements not met");
// Loop until an error occurs or we get a definitive answer
for(;;)
{
// There could already be data in the buffer
// so we do this first, before reading from the stream.
auto const result = detail::is_websocket_upgrade_request(buffer.data());
// If we got an answer, return it
if(! beast::indeterminate(result))
{
// A definite answer is a success
ec = {};
return static_cast<bool>(result);
}
// Try to fill our buffer by reading from the stream.
// The function read_size calculates a reasonable size for the
// amount to read next, using existing capacity if possible to
// avoid allocating memory, up to the limit of 1536 bytes which
// is the size of a normal TCP frame.
std::size_t const bytes_transferred = stream.read_some(
buffer.prepare(beast::read_size(buffer, 1536)), ec);
// Commit what we read into the buffer's input area.
buffer.commit(bytes_transferred);
// Check for an error
if(ec)
break;
}
// error
return false;
}
// Here is the implementation of the asynchronous initiation function
template<
class AsyncReadStream,
class DynamicBuffer,
class CompletionToken = asio::default_completion_token_t<beast::executor_type<AsyncReadStream>>
>
auto async_detect_websocket(
AsyncReadStream& stream,
DynamicBuffer& buffer,
CompletionToken&& token = asio::default_completion_token_t<beast::executor_type<AsyncReadStream>>{}) ->
typename asio::async_result< /*< `async_result` customizes the return value based on the completion token >*/
typename std::decay<CompletionToken>::type,
void(error_code, bool)>::return_type /*< This is the signature for the completion handler >*/
{
// Make sure arguments meet the type requirements
static_assert(
is_async_read_stream<AsyncReadStream>::value,
"SyncReadStream type requirements not met");
static_assert(
asio::is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer type requirements not met");
// The function `asio::async_initate` uses customization points
// to allow one asynchronous initiating function to work with
// all sorts of notification systems, such as callbacks but also
// fibers, futures, coroutines, and user-defined types.
//
// It works by capturing all of the arguments using perfect
// forwarding, and then depending on the specialization of
// `asio::async_result` for the type of `CompletionToken`,
// the `initiation` object will be invoked with the saved
// parameters and the actual completion handler. Our
// initiating object is `run_detect_websocket_op`.
//
// Non-const references need to be passed as pointers,
// since we don't want a decay-copy.
return asio::async_initiate<CompletionToken, void(error_code, bool)>(
detail::run_detect_websocket_op{},
std::forward<CompletionToken>(token),
&stream, // pass the reference by pointer
buffer);
}
}
#ifdef ASIO_STANDALONE
#include <asio/unyield.hpp>
#else
#include <boost/asio/unyield.hpp>
#endif
#endif // !__ASIO2_MQTT_DETECT_WEBSOCKET_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RDC_INVOKER_HPP__
#define __ASIO2_RDC_INVOKER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <functional>
#include <string>
#include <string_view>
#include <tuple>
#include <map>
#include <type_traits>
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/util/string.hpp>
namespace asio2::detail
{
template<class SendDataT, class RecvDataT>
struct rdc_make_callback_t
{
using self = rdc_make_callback_t<SendDataT, RecvDataT>;
using callback_type = std::function<void(const error_code&, SendDataT, RecvDataT)>;
/**
* @brief bind a rdc function
*/
template<class F, class ...C>
static inline callback_type bind(F&& fun, C&&... obj)
{
return self::_bind(std::forward<F>(fun), std::forward<C>(obj)...);
}
protected:
template<class F>
static inline callback_type _bind(F f)
{
return std::bind(&self::template _proxy<F>, std::move(f),
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
}
template<class F, class C>
static inline callback_type _bind(F f, C& c)
{
return std::bind(&self::template _proxy<F, C>, std::move(f), std::addressof(c),
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
}
template<class F, class C>
static inline callback_type _bind(F f, C* c)
{
return std::bind(&self::template _proxy<F, C>, std::move(f), c,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
}
template<class F>
static inline void _proxy(F& f, const error_code& ec, SendDataT send_data, RecvDataT recv_data)
{
detail::ignore_unused(send_data);
using fun_traits_type = function_traits<F>;
using arg_type = typename std::remove_cv_t<typename fun_traits_type::template args<0>::type>;
set_last_error(ec);
if constexpr (std::is_reference_v<arg_type>)
{
f(recv_data);
}
else
{
if (ec)
{
arg_type result;
f(std::move(result));
return;
}
if /**/ constexpr (has_stream_operator<arg_type, RecvDataT>::value)
{
arg_type result;
result << recv_data;
f(std::move(result));
}
else if constexpr (has_equal_operator<arg_type, RecvDataT>::value)
{
arg_type result;
result = recv_data;
f(std::move(result));
}
else
{
arg_type result{ recv_data };
f(std::move(result));
}
}
}
template<class F, class C>
static inline void _proxy(F& f, C* c, const error_code& ec, SendDataT send_data, RecvDataT recv_data)
{
detail::ignore_unused(send_data);
using fun_traits_type = function_traits<F>;
using arg_type = typename std::remove_cv_t<typename fun_traits_type::template args<0>::type>;
set_last_error(ec);
if constexpr (std::is_reference_v<arg_type>)
{
(c->*f)(recv_data);
}
else
{
if (ec)
{
arg_type result;
(c->*f)(std::move(result));
return;
}
if /**/ constexpr (has_stream_operator<arg_type, RecvDataT>::value)
{
arg_type result;
result << recv_data;
(c->*f)(std::move(result));
}
else if constexpr (has_equal_operator<arg_type, RecvDataT>::value)
{
arg_type result;
result = recv_data;
(c->*f)(std::move(result));
}
else
{
arg_type result{ recv_data };
(c->*f)(std::move(result));
}
}
}
};
template<class IdT, class SendDataT, class RecvDataT>
class rdc_invoker_t
{
public:
using self = rdc_invoker_t<IdT, SendDataT, RecvDataT>;
using callback_type = typename rdc_make_callback_t<SendDataT, RecvDataT>::callback_type;
using value_type = std::tuple<std::shared_ptr<asio::steady_timer>, callback_type>;
using iterator_type = typename std::multimap<IdT, value_type>::iterator;
/**
* @brief constructor
*/
rdc_invoker_t() = default;
/**
* @brief destructor
*/
~rdc_invoker_t() = default;
rdc_invoker_t(rdc_invoker_t&&) = default;
rdc_invoker_t(rdc_invoker_t const&) = default;
rdc_invoker_t& operator=(rdc_invoker_t&&) = default;
rdc_invoker_t& operator=(rdc_invoker_t const&) = default;
/**
* @brief find binded rdc function iterator by id
*/
inline auto find(IdT const& id)
{
// can't use std::multimap::find
// std::multimap<Key,T,Compare,Allocator>::find
// Finds an element with key equivalent to key. If there are several elements
// with key in the container, any of them may be returned.
auto it = this->rdc_reqs_.lower_bound(id);
if (it == this->rdc_reqs_.end())
return it;
// [20220402] fix bug
// Returns an iterator pointing to the first element that is not less than
// (i.e. greater or equal to) key.
// when multimap has {2,2} {3,3} if you find key 1, the map will return {2,2}
if (it->first == id)
return it;
return this->rdc_reqs_.end();
}
/**
* @brief
*/
inline auto emplace(IdT id, std::shared_ptr<asio::steady_timer> timer, callback_type cb)
{
// std::multimap<Key,T,Compare,Allocator>::insert
// inserts value. If the container has elements with equivalent key,
// inserts at the upper bound of that range.(since C++11)
return this->rdc_reqs_.insert(std::pair(std::move(id), std::tuple(std::move(timer), std::move(cb))));
}
/**
* @brief
*/
inline auto emplace(IdT key, value_type val)
{
return this->rdc_reqs_.insert(std::pair(std::move(key), std::move(val)));
}
/**
* @brief
*/
inline auto end()
{
return this->rdc_reqs_.end();
}
/**
* @brief
*/
template<class Iter>
inline auto erase(Iter iter)
{
return this->rdc_reqs_.erase(iter);
}
/**
* @brief
*/
inline std::multimap<IdT, value_type>& reqs() noexcept
{
return this->rdc_reqs_;
}
protected:
std::multimap<IdT, value_type> rdc_reqs_;
};
}
#endif // !__ASIO2_RDC_INVOKER_HPP__
<file_sep>/*
Copyright <NAME> 2017
Copyright <NAME> 2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_PLAT_IOS_H
#define BHO_PREDEF_PLAT_IOS_H
#include <asio2/bho/predef/os/ios.h> // BHO_OS_IOS
#include <asio2/bho/predef/version_number.h> // BHO_VERSION_NUMBER_NOT_AVAILABLE
/* tag::reference[]
= `BHO_PLAT_IOS_DEVICE`
= `BHO_PLAT_IOS_SIMULATOR`
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `TARGET_IPHONE_SIMULATOR` | {predef_detection}
| `TARGET_OS_SIMULATOR` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_PLAT_IOS_DEVICE BHO_VERSION_NUMBER_NOT_AVAILABLE
#define BHO_PLAT_IOS_SIMULATOR BHO_VERSION_NUMBER_NOT_AVAILABLE
// https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h
#if BHO_OS_IOS
# include <TargetConditionals.h>
# if defined(TARGET_OS_SIMULATOR) && (TARGET_OS_SIMULATOR == 1)
# undef BHO_PLAT_IOS_SIMULATOR
# define BHO_PLAT_IOS_SIMULATOR BHO_VERSION_NUMBER_AVAILABLE
# elif defined(TARGET_IPHONE_SIMULATOR) && (TARGET_IPHONE_SIMULATOR == 1)
# undef BHO_PLAT_IOS_SIMULATOR
# define BHO_PLAT_IOS_SIMULATOR BHO_VERSION_NUMBER_AVAILABLE
# else
# undef BHO_PLAT_IOS_DEVICE
# define BHO_PLAT_IOS_DEVICE BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_PLAT_IOS_SIMULATOR
# define BHO_PLAT_IOS_SIMULATOR_AVAILABLE
# include <asio2/bho/predef/detail/platform_detected.h>
#endif
#if BHO_PLAT_IOS_DEVICE
# define BHO_PLAT_IOS_DEVICE_AVAILABLE
# include <asio2/bho/predef/detail/platform_detected.h>
#endif
#define BHO_PLAT_IOS_SIMULATOR_NAME "iOS Simulator"
#define BHO_PLAT_IOS_DEVICE_NAME "iOS Device"
#endif // BHO_PREDEF_PLAT_IOS_H
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_IOS_SIMULATOR,BHO_PLAT_IOS_SIMULATOR_NAME)
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_IOS_DEVICE,BHO_PLAT_IOS_DEVICE_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_DIAB_H
#define BHO_PREDEF_COMPILER_DIAB_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_DIAB`
http://www.windriver.com/products/development_suite/wind_river_compiler/[Diab C/{CPP}] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__DCC__+` | {predef_detection}
| `+__VERSION_NUMBER__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_DIAB BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__DCC__)
# define BHO_COMP_DIAB_DETECTION BHO_PREDEF_MAKE_10_VRPP(__VERSION_NUMBER__)
#endif
#ifdef BHO_COMP_DIAB_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_DIAB_EMULATED BHO_COMP_DIAB_DETECTION
# else
# undef BHO_COMP_DIAB
# define BHO_COMP_DIAB BHO_COMP_DIAB_DETECTION
# endif
# define BHO_COMP_DIAB_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_DIAB_NAME "Diab C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_DIAB,BHO_COMP_DIAB_NAME)
#ifdef BHO_COMP_DIAB_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_DIAB_EMULATED,BHO_COMP_DIAB_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_ALLOCATOR_HPP__
#define __ASIO2_ALLOCATOR_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <type_traits>
#include <utility>
#include <atomic>
#include <mutex>
#include <asio2/config.hpp>
#include <asio2/base/log.hpp>
namespace asio2::detail
{
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
template<typename = void>
inline void log_allocator_storage_size(bool is_lookfree, bool is_stack, std::size_t size)
{
static std::mutex mtx;
static std::map<std::size_t, std::size_t> unlock_stack_map;
static std::map<std::size_t, std::size_t> unlock_heaps_map;
static std::map<std::size_t, std::size_t> atomic_stack_map;
static std::map<std::size_t, std::size_t> atomic_heaps_map;
std::lock_guard guard(mtx);
if (is_lookfree)
{
if (is_stack)
unlock_stack_map[size]++;
else
unlock_heaps_map[size]++;
}
else
{
if (is_stack)
atomic_stack_map[size]++;
else
atomic_heaps_map[size]++;
}
static auto t1 = std::chrono::steady_clock::now();
auto t2 = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(t2 - t1).count() > 60)
{
t1 = std::chrono::steady_clock::now();
std::string str;
str += "\n";
str += "allocator storage size test: ";
if /**/ constexpr (sizeof(void*) == sizeof(std::uint64_t))
str += "x64";
else if constexpr (sizeof(void*) == sizeof(std::uint32_t))
str += "x86";
else
str += std::to_string(sizeof(void*)) + "bit";
str += ", ";
#if defined(_DEBUG) || defined(DEBUG)
str += "Debug";
#else
str += "Release";
#endif
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
str += ", SSL";
#endif
#if ASIO2_OS_LINUX || ASIO2_OS_UNIX
str += ", linux";
#elif ASIO2_OS_WINDOWS
str += ", windows";
#elif ASIO2_OS_MACOS
str += ", macos";
#endif
str += "\n";
str += "------------------------------------------------------------\n";
str += "unlock_stack_map\n";
for (auto [len, num] : unlock_stack_map)
{
str += " ";
str += std::to_string(len); str += " : ";
str += std::to_string(num); str += "\n";
}
str += "unlock_heaps_map\n";
for (auto [len, num] : unlock_heaps_map)
{
str += " ";
str += std::to_string(len); str += " : ";
str += std::to_string(num); str += "\n";
}
str += "atomic_stack_map\n";
for (auto [len, num] : atomic_stack_map)
{
str += " ";
str += std::to_string(len); str += " : ";
str += std::to_string(num); str += "\n";
}
str += "atomic_heaps_map\n";
for (auto [len, num] : atomic_heaps_map)
{
str += " ";
str += std::to_string(len); str += " : ";
str += std::to_string(num); str += "\n";
}
str += "------------------------------------------------------------\n";
str += "\n";
ASIO2_LOG_FATAL("{}", str);
}
}
template<typename = void>
inline void lockfree_allocator_threadsafe_test(std::size_t paddr, bool is_add)
{
static std::mutex mtx;
static std::unordered_map<std::size_t, std::thread::id> addr_thread_map;
std::lock_guard guard(mtx);
if (is_add)
{
auto it = addr_thread_map.find(paddr);
if (it == addr_thread_map.end())
{
addr_thread_map.emplace(paddr, std::this_thread::get_id());
}
else
{
if (it->second != std::this_thread::get_id())
{
ASIO2_ASSERT(false);
throw 0;
}
}
}
else
{
addr_thread_map.erase(paddr);
}
}
#endif
/// see : boost\libs\asio\example\cpp11\allocation\server.cpp
template<typename IsLockFree>
inline constexpr std::size_t calc_allocator_storage_size() noexcept
{
#if defined(ASIO2_ALLOCATOR_STORAGE_SIZE)
// if the user defined a custom allocator storage size, use it.
return std::size_t(ASIO2_ALLOCATOR_STORAGE_SIZE);
#elif defined(_DEBUG) || defined(DEBUG)
// debug mode just provide a simple size
if constexpr (IsLockFree::value)
{
return std::size_t(1024);
}
else
{
return std::size_t(2048);
}
#else
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
if constexpr (IsLockFree::value)
{
if constexpr (sizeof(void*) == sizeof(std::uint32_t))
return std::size_t(332);
else
return std::size_t(664);
}
else
{
if constexpr (sizeof(void*) == sizeof(std::uint32_t))
return std::size_t(520);
else
return std::size_t(1024);
}
#else
if constexpr (IsLockFree::value)
{
if constexpr (sizeof(void*) == sizeof(std::uint32_t))
return std::size_t(332);
else
return std::size_t(664);
}
else
{
if constexpr (sizeof(void*) == sizeof(std::uint32_t))
return std::size_t(512);
else
return std::size_t(1024);
}
#endif
#endif
}
template<std::size_t N>
struct allocator_size_op
{
static constexpr std::size_t size = N;
};
struct allocator_fixed_size_tag {};
template<std::size_t N>
struct allocator_fixed_size_op : public allocator_fixed_size_tag
{
static constexpr std::size_t size = N;
};
template<class args_t>
struct allocator_size_traits
{
template<class, class = void>
struct has_member_size : std::false_type {};
template<class T>
struct has_member_size<T, std::void_t<decltype(T::allocator_storage_size)>> : std::true_type {};
static constexpr std::size_t calc()
{
if constexpr (has_member_size<args_t>::value)
{
return args_t::allocator_storage_size;
}
else
{
return 0;
}
}
static constexpr std::size_t value = calc();
};
// allocator storage sizer
template<class args_t>
using assizer = allocator_size_op<allocator_size_traits<args_t>::value>;
template<typename IsLockFree, typename SizeN>
inline constexpr std::size_t get_allocator_storage_size() noexcept
{
if constexpr (std::is_base_of_v<allocator_fixed_size_tag, detail::remove_cvref_t<SizeN>>)
{
return SizeN::size;
}
else
{
#if defined(ASIO2_ALLOCATOR_STORAGE_SIZE)
// if the user defined a custom allocator storage size, use it.
return std::size_t(ASIO2_ALLOCATOR_STORAGE_SIZE);
#else
if constexpr (SizeN::size >= std::size_t(64) && SizeN::size <= std::size_t(1024 * 1024))
{
return SizeN::size;
}
else
{
return calc_allocator_storage_size<IsLockFree>();
}
#endif
}
}
/**
* @brief Class to manage the memory to be used for handler-based custom allocation.
* It contains a single block of memory which may be returned for allocation
* requests. If the memory is in use when an allocation request is made, the
* allocator delegates allocation to the global heap.
* @tparam IsLockFree - is lock free or not.
* @tparam SizeN - the single block of memory size.
*/
template<
typename IsLockFree = std::true_type,
typename SizeN = allocator_size_op<calc_allocator_storage_size<IsLockFree>()>>
class handler_memory;
/**
* @brief Class to manage the memory to be used for handler-based custom allocation.
* It contains a single block of memory which may be returned for allocation
* requests. If the memory is in use when an allocation request is made, the
* allocator delegates allocation to the global heap.
* @tparam IsLockFree - is lock free or not.
* @tparam SizeN - the single block of memory size.
*/
template<typename SizeN>
class handler_memory<std::true_type, SizeN>
{
public:
static constexpr std::size_t storage_size = get_allocator_storage_size<std::true_type, SizeN>();
explicit handler_memory() noexcept : in_use_(false) {}
handler_memory(const handler_memory&) = delete;
handler_memory& operator=(const handler_memory&) = delete;
inline void* allocate(std::size_t size)
{
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
lockfree_allocator_threadsafe_test(std::size_t(this), true);
#endif
if (!in_use_ && size < sizeof(storage_))
{
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
log_allocator_storage_size(true, true, size);
#endif
in_use_ = true;
return &storage_;
}
else
{
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
log_allocator_storage_size(true, false, size);
#endif
return ::operator new(size);
}
}
inline void deallocate(void* pointer) noexcept
{
// must erase when deallocate, otherwise if call server.stop -> server.start
// then the test map will incorrect.
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
lockfree_allocator_threadsafe_test(std::size_t(this), false);
#endif
if (pointer == &storage_)
{
in_use_ = false;
}
else
{
::operator delete(pointer);
}
}
private:
// Storage space used for handler-based custom memory allocation.
typename std::aligned_storage<storage_size + sizeof(void*)>::type storage_{};
// Whether the handler-based custom allocation storage has been used.
bool in_use_{};
};
/**
* @brief Class to manage the memory to be used for handler-based custom allocation.
* It contains a single block of memory which may be returned for allocation
* requests. If the memory is in use when an allocation request is made, the
* allocator delegates allocation to the global heap.
* @tparam IsLockFree - is lock free or not.
* @tparam SizeN - the single block of memory size.
*/
template<typename SizeN>
class handler_memory<std::false_type, SizeN>
{
public:
static constexpr std::size_t storage_size = get_allocator_storage_size<std::false_type, SizeN>();
handler_memory() noexcept { in_use_.clear(); }
handler_memory(const handler_memory&) = delete;
handler_memory& operator=(const handler_memory&) = delete;
inline void* allocate(std::size_t size)
{
if (size < sizeof(storage_) && (!in_use_.test_and_set()))
{
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
log_allocator_storage_size(false, true, size);
#endif
return &storage_;
}
else
{
#if defined(ASIO2_ENABLE_LOG) && defined(ASIO2_ENABLE_LOG_STORAGE_SIZE)
log_allocator_storage_size(false, false, size);
#endif
return ::operator new(size);
}
}
inline void deallocate(void* pointer) noexcept
{
if (pointer == &storage_)
{
in_use_.clear();
}
else
{
::operator delete(pointer);
}
}
private:
// Storage space used for handler-based custom memory allocation.
typename std::aligned_storage<storage_size + sizeof(void*)>::type storage_{};
// Whether the handler-based custom allocation storage has been used.
std::atomic_flag in_use_{};
};
#if defined(ASIO2_ENABLE_LOG)
static_assert(handler_memory<std::true_type >::storage_size == calc_allocator_storage_size<std::true_type >());
static_assert(handler_memory<std::false_type>::storage_size == calc_allocator_storage_size<std::false_type>());
#endif
// The allocator to be associated with the handler objects. This allocator only
// needs to satisfy the C++11 minimal allocator requirements.
template <typename T, typename N, typename B>
class handler_allocator
{
public:
using value_type = T;
explicit handler_allocator(handler_memory<N, B>& mem) noexcept
: memory_(mem)
{
}
template <typename U, typename No, typename Bo>
handler_allocator(const handler_allocator<U, No, Bo>& other) noexcept
: memory_(other.memory_)
{
}
inline bool operator==(const handler_allocator& other) const noexcept
{
return &memory_ == &other.memory_;
}
inline bool operator!=(const handler_allocator& other) const noexcept
{
return &memory_ != &other.memory_;
}
inline T* allocate(std::size_t n) const
{
return static_cast<T*>(memory_.allocate(sizeof(T) * n));
}
inline void deallocate(T* p, std::size_t /*n*/) const noexcept
{
return memory_.deallocate(p);
}
private:
template <typename, typename, typename> friend class handler_allocator;
// The underlying memory.
handler_memory<N, B>& memory_{};
};
// Wrapper class template for handler objects to allow handler memory
// allocation to be customised. The allocator_type type and get_allocator()
// member function are used by the asynchronous operations to obtain the
// allocator. Calls to operator() are forwarded to the encapsulated handler.
template <typename Handler, typename N, typename B>
class custom_alloc_handler
{
public:
using allocator_type = handler_allocator<Handler, N, B>;
custom_alloc_handler(handler_memory<N, B>& m, Handler&& h) noexcept
: memory_(m)
, handler_(std::forward<Handler>(h))
{
}
inline allocator_type get_allocator() const noexcept
{
return allocator_type(memory_);
}
template <typename ...Args>
inline void operator()(Args&&... args)
{
handler_(std::forward<Args>(args)...);
}
private:
handler_memory<N, B>& memory_{};
Handler handler_;
};
// Helper function to wrap a handler object to add custom allocation.
// Must not be used in multithreading,Otherwise, it will cause program crash.
template <typename Handler, typename N, typename B>
inline custom_alloc_handler<Handler, N, B> make_allocator(handler_memory<N, B>& m, Handler&& h)
{
return custom_alloc_handler<Handler, N, B>(m, std::forward<Handler>(h));
}
}
#endif // !__ASIO2_ALLOCATOR_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_EXTERNAL_THROW_EXCEPTION_HPP__
#define __ASIO2_EXTERNAL_THROW_EXCEPTION_HPP__
#include <asio2/config.hpp>
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/throw_exception.hpp>)
#include <boost/throw_exception.hpp>
#ifndef ASIO2_THROW_EXCEPTION
#define ASIO2_THROW_EXCEPTION BOOST_THROW_EXCEPTION
#endif
#else
#include <asio2/bho/throw_exception.hpp>
#ifndef ASIO2_THROW_EXCEPTION
#define ASIO2_THROW_EXCEPTION BHO_THROW_EXCEPTION
#endif
#endif
#endif
<file_sep>// Three-state boolean logic library
// Copyright <NAME> 2002-2004. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BHO_LOGIC_TRIBOOL_IO_HPP
#define BHO_LOGIC_TRIBOOL_IO_HPP
#include <asio2/bho/logic/tribool.hpp>
#include <asio2/bho/config/workaround.hpp>
#include <asio2/bho/noncopyable.hpp>
#if defined(_MSC_VER)
# pragma once
#endif
#ifndef BHO_NO_STD_LOCALE
# include <locale>
#endif
#include <string>
#include <iostream>
namespace bho { namespace logic {
#ifdef BHO_NO_STD_LOCALE
/**
* \brief Returns a string containing the default name for the \c
* false value of a tribool with the given character type T.
*
* This function only exists when the C++ standard library
* implementation does not support locales.
*/
template<typename T> std::basic_string<T> default_false_name();
/**
* \brief Returns the character string "false".
*
* This function only exists when the C++ standard library
* implementation does not support locales.
*/
template<>
inline std::basic_string<char> default_false_name<char>()
{ return "false"; }
# if !defined(BHO_NO_CWCHAR)
/**
* \brief Returns the wide character string L"false".
*
* This function only exists when the C++ standard library
* implementation does not support locales.
*/
template<>
inline std::basic_string<wchar_t> default_false_name<wchar_t>()
{ return L"false"; }
# endif
/**
* \brief Returns a string containing the default name for the \c true
* value of a tribool with the given character type T.
*
* This function only exists when the C++ standard library
* implementation does not support locales.
*/
template<typename T> std::basic_string<T> default_true_name();
/**
* \brief Returns the character string "true".
*
* This function only exists when the C++ standard library
* implementation does not support locales.
*/
template<>
inline std::basic_string<char> default_true_name<char>()
{ return "true"; }
# if !defined(BHO_NO_CWCHAR)
/**
* \brief Returns the wide character string L"true".
*
* This function only exists * when the C++ standard library
* implementation does not support * locales.
*/
template<>
inline std::basic_string<wchar_t> default_true_name<wchar_t>()
{ return L"true"; }
# endif
#endif
/**
* \brief Returns a string containing the default name for the indeterminate
* value of a tribool with the given character type T.
*
* This routine is used by the input and output streaming operators
* for tribool when there is no locale support or the stream's locale
* does not contain the indeterminate_name facet.
*/
template<typename T> std::basic_string<T> get_default_indeterminate_name();
/// Returns the character string "indeterminate".
template<>
inline std::basic_string<char> get_default_indeterminate_name<char>()
{ return "indeterminate"; }
#if !defined(BHO_NO_CWCHAR)
/// Returns the wide character string L"indeterminate".
template<>
inline std::basic_string<wchar_t> get_default_indeterminate_name<wchar_t>()
{ return L"indeterminate"; }
#endif
// http://www.cantrip.org/locale.html
#ifndef BHO_NO_STD_LOCALE
/**
* \brief A locale facet specifying the name of the indeterminate
* value of a tribool.
*
* The facet is used to perform I/O on tribool values when \c
* std::boolalpha has been specified. This class template is only
* available if the C++ standard library implementation supports
* locales.
*/
template<typename CharT>
class indeterminate_name : public std::locale::facet, private bho::noncopyable
{
public:
typedef CharT char_type;
typedef std::basic_string<CharT> string_type;
/// Construct the facet with the default name
indeterminate_name() : name_(get_default_indeterminate_name<CharT>()) {}
/// Construct the facet with the given name for the indeterminate value
explicit indeterminate_name(const string_type& initial_name)
: name_(initial_name) {}
/// Returns the name for the indeterminate value
string_type name() const { return name_; }
/// Uniquily identifies this facet with the locale.
static std::locale::id id;
private:
string_type name_;
};
template<typename CharT> std::locale::id indeterminate_name<CharT>::id;
#endif
/**
* \brief Writes the value of a tribool to a stream.
*
* When the value of @p x is either \c true or \c false, this routine
* is semantically equivalent to:
* \code out << static_cast<bool>(x); \endcode
*
* When @p x has an indeterminate value, it outputs either the integer
* value 2 (if <tt>(out.flags() & std::ios_base::boolalpha) == 0</tt>)
* or the name of the indeterminate value. The name of the
* indeterminate value comes from the indeterminate_name facet (if it
* is defined in the output stream's locale), or from the
* get_default_indeterminate_name function (if it is not defined in the
* locale or if the C++ standard library implementation does not
* support locales).
*
* \returns @p out
*/
template<typename CharT, typename Traits>
inline std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& out, tribool x)
{
if (!indeterminate(x)) {
out << static_cast<bool>(x);
} else {
typename std::basic_ostream<CharT, Traits>::sentry cerberus(out);
if (cerberus) {
if (out.flags() & std::ios_base::boolalpha) {
#ifndef BHO_NO_STD_LOCALE
if (BHO_HAS_FACET(indeterminate_name<CharT>, out.getloc())) {
const indeterminate_name<CharT>& facet =
BHO_USE_FACET(indeterminate_name<CharT>, out.getloc());
out << facet.name();
} else {
out << get_default_indeterminate_name<CharT>();
}
#else
out << get_default_indeterminate_name<CharT>();
#endif
}
else
out << 2;
}
}
return out;
}
/**
* \brief Writes the indeterminate tribool value to a stream.
*
* This routine outputs either the integer
* value 2 (if <tt>(out.flags() & std::ios_base::boolalpha) == 0</tt>)
* or the name of the indeterminate value. The name of the
* indeterminate value comes from the indeterminate_name facet (if it
* is defined in the output stream's locale), or from the
* get_default_indeterminate_name function (if it is not defined in the
* locale or if the C++ standard library implementation does not
* support locales).
*
* \returns @p out
*/
template<typename CharT, typename Traits>
inline std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& out,
bool (*)(tribool, detail::indeterminate_t))
{ return out << tribool(indeterminate); }
/**
* \brief Reads a tribool value from a stream.
*
* When <tt>(out.flags() & std::ios_base::boolalpha) == 0</tt>, this
* function reads a \c long value from the input stream @p in and
* converts that value to a tribool. If that value is 0, @p x becomes
* \c false; if it is 1, @p x becomes \c true; if it is 2, @p becomes
* \c indetermine; otherwise, the operation fails (and the fail bit is
* set on the input stream @p in).
*
* When <tt>(out.flags() & std::ios_base::boolalpha) != 0</tt>, this
* function first determines the names of the false, true, and
* indeterminate values. The false and true names are extracted from
* the \c std::numpunct facet of the input stream's locale (if the C++
* standard library implementation supports locales), or from the \c
* default_false_name and \c default_true_name functions (if there is
* no locale support). The indeterminate name is extracted from the
* appropriate \c indeterminate_name facet (if it is available in the
* input stream's locale), or from the \c get_default_indeterminate_name
* function (if the C++ standard library implementation does not
* support locales, or the \c indeterminate_name facet is not
* specified for this locale object). The input is then matched to
* each of these names, and the tribool @p x is assigned the value
* corresponding to the longest name that matched. If no name is
* matched or all names are empty, the operation fails (and the fail
* bit is set on the input stream @p in).
*
* \returns @p in
*/
template<typename CharT, typename Traits>
inline std::basic_istream<CharT, Traits>&
operator>>(std::basic_istream<CharT, Traits>& in, tribool& x)
{
if (in.flags() & std::ios_base::boolalpha) {
typename std::basic_istream<CharT, Traits>::sentry cerberus(in);
if (cerberus) {
typedef std::basic_string<CharT> string_type;
#ifndef BHO_NO_STD_LOCALE
const std::numpunct<CharT>& numpunct_facet =
BHO_USE_FACET(std::numpunct<CharT>, in.getloc());
string_type falsename = numpunct_facet.falsename();
string_type truename = numpunct_facet.truename();
string_type othername;
if (BHO_HAS_FACET(indeterminate_name<CharT>, in.getloc())) {
othername =
BHO_USE_FACET(indeterminate_name<CharT>, in.getloc()).name();
} else {
othername = get_default_indeterminate_name<CharT>();
}
#else
string_type falsename = default_false_name<CharT>();
string_type truename = default_true_name<CharT>();
string_type othername = get_default_indeterminate_name<CharT>();
#endif
typename string_type::size_type pos = 0;
bool falsename_ok = true, truename_ok = true, othername_ok = true;
// Modeled after the code from Library DR 17
while ((falsename_ok && pos < falsename.size())
|| (truename_ok && pos < truename.size())
|| (othername_ok && pos < othername.size())) {
typename Traits::int_type c = in.get();
if (c == Traits::eof())
return in;
bool matched = false;
if (falsename_ok && pos < falsename.size()) {
if (Traits::eq(Traits::to_char_type(c), falsename[pos]))
matched = true;
else
falsename_ok = false;
}
if (truename_ok && pos < truename.size()) {
if (Traits::eq(Traits::to_char_type(c), truename[pos]))
matched = true;
else
truename_ok = false;
}
if (othername_ok && pos < othername.size()) {
if (Traits::eq(Traits::to_char_type(c), othername[pos]))
matched = true;
else
othername_ok = false;
}
if (matched) { ++pos; }
if (pos > falsename.size()) falsename_ok = false;
if (pos > truename.size()) truename_ok = false;
if (pos > othername.size()) othername_ok = false;
}
if (pos == 0)
in.setstate(std::ios_base::failbit);
else {
if (falsename_ok) x = false;
else if (truename_ok) x = true;
else if (othername_ok) x = indeterminate;
else in.setstate(std::ios_base::failbit);
}
}
} else {
long value;
if (in >> value) {
switch (value) {
case 0: x = false; break;
case 1: x = true; break;
case 2: x = indeterminate; break;
default: in.setstate(std::ios_base::failbit); break;
}
}
}
return in;
}
} } // end namespace bho::logic
#endif // BHO_LOGIC_TRIBOOL_IO_HPP
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_MAKE_PRINTABLE_HPP
#define BHO_BEAST_MAKE_PRINTABLE_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/beast/core/buffer_traits.hpp>
#include <asio2/external/asio.hpp>
#include <ostream>
namespace bho {
namespace beast {
namespace detail {
template<class Buffers>
class make_printable_adaptor
{
Buffers b_;
public:
explicit
make_printable_adaptor(Buffers const& b)
: b_(b)
{
}
template<class B>
friend
std::ostream&
operator<<(std::ostream& os,
make_printable_adaptor<B> const& v);
};
template<class Buffers>
std::ostream&
operator<<(std::ostream& os,
make_printable_adaptor<Buffers> const& v)
{
for(
auto it = net::buffer_sequence_begin(v.b_),
end = net::buffer_sequence_end(v.b_);
it != end;
++it)
{
net::const_buffer cb = *it;
os.write(static_cast<char const*>(
cb.data()), cb.size());
}
return os;
}
} // detail
/** Helper to permit a buffer sequence to be printed to a std::ostream
This function is used to wrap a buffer sequence to allow it to
be interpreted as characters and written to a `std::ostream` such
as `std::cout`. No character translation is performed; unprintable
and null characters will be transferred as-is to the output stream.
@par Example
This function prints the size and contents of a buffer sequence
to standard output:
@code
template <class ConstBufferSequence>
void
print (ConstBufferSequence const& buffers)
{
std::cout <<
"Buffer size: " << buffer_bytes(buffers) << " bytes\n"
"Buffer data: '" << make_printable(buffers) << "'\n";
}
@endcode
@param buffers An object meeting the requirements of
<em>ConstBufferSequence</em> to be streamed. The implementation
will make a copy of this object. Ownership of the underlying
memory is not transferred, the application is still responsible
for managing its lifetime.
*/
template<class ConstBufferSequence>
#if BHO_BEAST_DOXYGEN
__implementation_defined__
#else
detail::make_printable_adaptor<ConstBufferSequence>
#endif
make_printable(ConstBufferSequence const& buffers)
{
static_assert(net::is_const_buffer_sequence<
ConstBufferSequence>::value,
"ConstBufferSequence type requirements not met");
return detail::make_printable_adaptor<
ConstBufferSequence>{buffers};
}
} // beast
} // bho
#endif
<file_sep>/*
Copyright <NAME> 2018
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_PTX_H
#define BHO_PREDEF_ARCHITECTURE_PTX_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_PTX`
https://en.wikipedia.org/wiki/Parallel_Thread_Execution[PTX] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__CUDA_ARCH__+` | {predef_detection}
| `+__CUDA_ARCH__+` | V.R.0
|===
*/ // end::reference[]
#define BHO_ARCH_PTX BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__CUDA_ARCH__)
# undef BHO_ARCH_PTX
# define BHO_ARCH_PTX BHO_PREDEF_MAKE_10_VR0(__CUDA_ARCH__)
#endif
#if BHO_ARCH_PTX
# define BHO_ARCH_PTX_AVAILABLE
#endif
#if BHO_ARCH_PTX
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_PTX_NAME "PTX"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_PTX,BHO_ARCH_PTX_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_TOPIC_ALIAS_HPP__
#define __ASIO2_MQTT_TOPIC_ALIAS_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <unordered_map>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class derived_t, class args_t>
class mqtt_topic_alias_t
{
friend derived_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
protected:
using self = mqtt_topic_alias_t<derived_t, args_t>;
/**
* @brief constructor
*/
mqtt_topic_alias_t()
{
}
/**
* @brief destructor
*/
~mqtt_topic_alias_t() = default;
public:
template<class String>
inline derived_t& push_topic_alias(std::uint16_t alias_value, String&& topic_name)
{
derived_t& derive = static_cast<derived_t&>(*this);
asio2::unique_locker guard(this->topic_alias_mutex_);
topic_aliases_[alias_value] = detail::to_string(std::forward<String>(topic_name));
return static_cast<derived_t&>(*this);
}
inline bool find_topic_alias(std::uint16_t alias_value, std::string& topic_name)
{
derived_t& derive = static_cast<derived_t&>(*this);
asio2::shared_locker guard(this->topic_alias_mutex_);
auto iter = topic_aliases_.find(alias_value);
if (iter != topic_aliases_.end())
{
topic_name = iter->second;
return true;
}
return false;
}
protected:
/// use rwlock to make thread safe
mutable asio2::shared_mutexer topic_alias_mutex_;
///
std::unordered_map<std::uint16_t, std::string> topic_aliases_ ASIO2_GUARDED_BY(topic_alias_mutex_);
};
}
#endif // !__ASIO2_MQTT_TOPIC_ALIAS_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_ROUTER_HPP__
#define __ASIO2_HTTP_ROUTER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <queue>
#include <any>
#include <future>
#include <tuple>
#include <map>
#include <unordered_map>
#include <type_traits>
#include <asio2/external/asio.hpp>
#include <asio2/external/beast.hpp>
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/filesystem.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/http/detail/http_util.hpp>
#include <asio2/http/detail/http_cache.hpp>
#include <asio2/http/request.hpp>
#include <asio2/http/response.hpp>
#include <asio2/util/string.hpp>
namespace asio2::detail
{
template<class, class> class http_router_t;
}
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::websocket
#else
namespace boost::beast::websocket
#endif
{
namespace detail
{
struct listener_tag {};
}
template<class caller_t>
class listener : public detail::listener_tag
{
template<class, class> friend class asio2::detail::http_router_t;
// Cannot access the protected member of bho::beast::websocket::listener<caller_t>::operator ()
template<typename, typename> friend struct asio2::detail::function_traits;
public:
using self = listener<caller_t>;
listener() = default;
listener(listener&&) noexcept = default;
listener(listener const&) = default;
listener& operator=(listener&&) noexcept = default;
listener& operator=(listener const&) = default;
template<class F>
inline listener& on_message(F&& f)
{
this->_bind(websocket::frame::message, std::forward<F>(f));
return (*this);
}
template<class F>
inline listener& on_ping(F&& f)
{
this->_bind(websocket::frame::ping, std::forward<F>(f));
return (*this);
}
template<class F>
inline listener& on_pong(F&& f)
{
this->_bind(websocket::frame::pong, std::forward<F>(f));
return (*this);
}
template<class F>
inline listener& on_open(F&& f)
{
this->_bind(websocket::frame::open, std::forward<F>(f));
return (*this);
}
template<class F>
inline listener& on_close(F&& f)
{
this->_bind(websocket::frame::close, std::forward<F>(f));
return (*this);
}
template<class F, class C>
inline listener& on_message(F&& f, C* c)
{
auto mf = std::bind(std::forward<F>(f), c, std::placeholders::_1, std::placeholders::_2);
this->_bind(websocket::frame::message, std::move(mf));
return (*this);
}
template<class F, class C>
inline listener& on_ping(F&& f, C* c)
{
auto mf = std::bind(std::forward<F>(f), c, std::placeholders::_1, std::placeholders::_2);
this->_bind(websocket::frame::ping, std::move(mf));
return (*this);
}
template<class F, class C>
inline listener& on_pong(F&& f, C* c)
{
auto mf = std::bind(std::forward<F>(f), c, std::placeholders::_1, std::placeholders::_2);
this->_bind(websocket::frame::pong, std::move(mf));
return (*this);
}
template<class F, class C>
inline listener& on_open(F&& f, C* c)
{
auto mf = std::bind(std::forward<F>(f), c, std::placeholders::_1, std::placeholders::_2);
this->_bind(websocket::frame::open, std::move(mf));
return (*this);
}
template<class F, class C>
inline listener& on_close(F&& f, C* c)
{
auto mf = std::bind(std::forward<F>(f), c, std::placeholders::_1, std::placeholders::_2);
this->_bind(websocket::frame::close, std::move(mf));
return (*this);
}
template<class F, class C>
inline listener& on_message(F&& f, C& c)
{
return this->on_message(std::forward<F>(f), std::addressof(c));
}
template<class F, class C>
inline listener& on_ping(F&& f, C& c)
{
return this->on_ping(std::forward<F>(f), std::addressof(c));
}
template<class F, class C>
inline listener& on_pong(F&& f, C& c)
{
return this->on_pong(std::forward<F>(f), std::addressof(c));
}
template<class F, class C>
inline listener& on_open(F&& f, C& c)
{
return this->on_open(std::forward<F>(f), std::addressof(c));
}
template<class F, class C>
inline listener& on_close(F&& f, C& c)
{
return this->on_close(std::forward<F>(f), std::addressof(c));
}
template<class F>
inline listener& on(std::string_view type, F&& f)
{
if (beast::iequals(type, "message")) this->_bind(websocket::frame::message, std::forward<F>(f));
else if (beast::iequals(type, "ping" )) this->_bind(websocket::frame::ping , std::forward<F>(f));
else if (beast::iequals(type, "pong" )) this->_bind(websocket::frame::pong , std::forward<F>(f));
else if (beast::iequals(type, "open" )) this->_bind(websocket::frame::open , std::forward<F>(f));
else if (beast::iequals(type, "close" )) this->_bind(websocket::frame::close , std::forward<F>(f));
return (*this);
}
template<class F, class C>
inline listener& on(std::string_view type, F&& f, C* c)
{
auto mf = std::bind(std::forward<F>(f), c, std::placeholders::_1, std::placeholders::_2);
if (beast::iequals(type, "message")) this->_bind(websocket::frame::message, std::move(mf));
else if (beast::iequals(type, "ping" )) this->_bind(websocket::frame::ping , std::move(mf));
else if (beast::iequals(type, "pong" )) this->_bind(websocket::frame::pong , std::move(mf));
else if (beast::iequals(type, "open" )) this->_bind(websocket::frame::open , std::move(mf));
else if (beast::iequals(type, "close" )) this->_bind(websocket::frame::close , std::move(mf));
return (*this);
}
template<class F, class C>
inline listener& on(std::string_view type, F&& f, C& c)
{
return this->on(std::move(type), std::forward<F>(f), std::addressof(c));
}
public:
// under gcc 8.2.0, if this "operator()" is protected, it compiled error :
// is protected within this context : function_traits<decltype(&Callable::operator())>{};
inline void operator()(std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response&)
{
ASIO2_ASSERT(caller->is_websocket());
auto& f = cbs_[asio2::detail::to_underlying(req.ws_frame_type_)];
if (f) f(caller, req.ws_frame_data_);
}
protected:
template<class F>
inline void _bind(websocket::frame type, F&& f)
{
this->cbs_[asio2::detail::to_underlying(type)] = std::bind(
&self::template _proxy<F>, this, std::forward<F>(f),
std::placeholders::_1, std::placeholders::_2);
}
template<class F>
inline void _proxy(F& f, std::shared_ptr<caller_t>& caller, std::string_view data)
{
asio2::detail::ignore_unused(data);
if constexpr (asio2::detail::is_template_callable_v<F, std::shared_ptr<caller_t>&, std::string_view>)
{
f(caller, data);
}
else
{
f(caller);
}
}
protected:
std::array<std::function<void(std::shared_ptr<caller_t>&, std::string_view)>,
asio2::detail::to_underlying(frame::close) + 1> cbs_;
};
}
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class caller_t, class args_t>
class http_router_t
{
friend caller_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
template<class T, class R, class... Args>
struct has_member_before : std::false_type {};
template<class T, class... Args>
struct has_member_before<T, decltype(std::declval<std::decay_t<T>>().
before((std::declval<Args>())...)), Args...> : std::true_type {};
template<class T, class R, class... Args>
struct has_member_after : std::false_type {};
template<class T, class... Args>
struct has_member_after<T, decltype(std::declval<std::decay_t<T>>().
after((std::declval<Args>())...)), Args...> : std::true_type {};
/////////////////////////////////////////////////////////////////////////////
// cinatra-master/include/cinatra/utils.hpp
template <typename T, typename Tuple>
struct has_type;
template <typename T, typename... Us>
struct has_type<T, std::tuple<Us...>> : std::disjunction<std::is_same<T, Us>...> {};
template< typename T>
struct filter_helper
{
static constexpr auto func()
{
return std::tuple<>();
}
template< class... Args >
static constexpr auto func(T&&, Args&&...args)
{
return filter_helper::func(std::forward<Args>(args)...);
}
template< class... Args >
static constexpr auto func(const T&, Args&&...args)
{
return filter_helper::func(std::forward<Args>(args)...);
}
template< class X, class... Args >
static constexpr auto func(X&& x, Args&&...args)
{
return std::tuple_cat(std::make_tuple(std::forward<X>(x)),
filter_helper::func(std::forward<Args>(args)...));
}
};
template<typename T, typename... Args>
inline auto filter_cache(Args&&... args)
{
return filter_helper<T>::func(std::forward<Args>(args)...);
}
/////////////////////////////////////////////////////////////////////////////
public:
using self = http_router_t<caller_t, args_t>;
using opret = http::response<http::flex_body>*;
using opfun = std::function<opret(std::shared_ptr<caller_t>&, http::web_request&, http::web_response&)>;
/**
* @brief constructor
*/
http_router_t()
{
this->not_found_router_ = std::make_shared<opfun>(
[](std::shared_ptr<caller_t>&, http::web_request& req, http::web_response& rep) mutable
{
std::string desc;
desc.reserve(64);
desc += "The resource for ";
desc += req.method_string();
desc += " \"";
desc += http::url_decode(req.target());
desc += "\" was not found";
rep.fill_page(http::status::not_found, std::move(desc), {}, req.version());
return std::addressof(rep.base());
});
#if defined(_DEBUG) || defined(DEBUG)
// used to test ThreadSafetyAnalysis
asio2::ignore_unused(this->http_cache_.empty());
asio2::ignore_unused(this->http_cache_.get_cache_count());
#endif
}
/**
* @brief destructor
*/
~http_router_t() = default;
/**
* @brief bind a function for http router
* @param name - uri name in string format.
* @param fun - Function object.
* @param caop - A pointer or reference to a class object, and aop object list.
* if fun is member function, the first caop param must the class object's pointer or refrence.
*/
template<http::verb... M, class F, class ...CAOP>
typename std::enable_if_t<!std::is_base_of_v<websocket::detail::listener_tag,
detail::remove_cvref_t<F>>, self&>
inline bind(std::string name, F&& fun, CAOP&&... caop)
{
asio2::trim_both(name);
if (name == "*")
name = "/*";
if (name.empty())
{
ASIO2_ASSERT(false);
return (*this);
}
if constexpr (sizeof...(M) == std::size_t(0))
{
this->_bind<http::verb::get, http::verb::post>(
std::move(name), std::forward<F>(fun), std::forward<CAOP>(caop)...);
}
else
{
this->_bind<M...>(
std::move(name), std::forward<F>(fun), std::forward<CAOP>(caop)...);
}
return (*this);
}
/**
* @brief bind a function for websocket router
* @param name - uri name in string format.
* @param listener - callback listener.
* @param aop - aop object list.
*/
template<class ...AOP>
inline self& bind(std::string name, websocket::listener<caller_t> listener, AOP&&... aop)
{
asio2::trim_both(name);
ASIO2_ASSERT(!name.empty());
if (!name.empty())
this->_bind(std::move(name), std::move(listener), std::forward<AOP>(aop)...);
return (*this);
}
/**
* @brief set the 404 not found router function
*/
template<class F, class ...C>
inline self& bind_not_found(F&& f, C&&... obj)
{
this->_bind_not_found(std::forward<F>(f), std::forward<C>(obj)...);
return (*this);
}
/**
* @brief set the 404 not found router function
*/
template<class F, class ...C>
inline self& bind_404(F&& f, C&&... obj)
{
this->_bind_not_found(std::forward<F>(f), std::forward<C>(obj)...);
return (*this);
}
public:
/**
* @brief set the root directory where we load the files.
*/
inline self& set_root_directory(std::filesystem::path path)
{
this->root_directory_ = std::move(path);
return (*this);
}
/**
* @brief get the root directory where we load the files.
*/
inline const std::filesystem::path& get_root_directory() noexcept
{
return this->root_directory_;
}
/**
* @brief set whether websocket is supported, default is true
*/
inline self& set_support_websocket(bool v) noexcept
{
this->support_websocket_ = v;
return (*this);
}
/**
* @brief set whether websocket is supported, default is true, same as set_support_websocket
*/
inline self& support_websocket(bool v) noexcept
{
return this->set_support_websocket(v);
}
/**
* @brief get whether websocket is supported, default is true
*/
inline bool is_support_websocket() noexcept
{
return this->support_websocket_;
}
protected:
inline self& _router() noexcept { return (*this); }
template<http::verb... M>
inline decltype(auto) _make_uris(std::string name)
{
std::size_t index = 0;
std::array<std::string, sizeof...(M)> uris;
//while (!name.empty() && name.back() == '*')
// name.erase(std::prev(name.end()));
while (name.size() > static_cast<std::string::size_type>(1) && name.back() == '/')
name.erase(std::prev(name.end()));
ASIO2_ASSERT(!name.empty());
if (!name.empty())
{
((uris[index++] = std::string{ this->_to_char(M) } +name), ...);
}
return uris;
}
template<http::verb... M, class F, class... AOP>
typename std::enable_if_t<!std::is_base_of_v<websocket::detail::listener_tag,
detail::remove_cvref_t<F>>, void>
inline _bind(std::string name, F f, AOP&&... aop)
{
constexpr bool CacheFlag = has_type<http::enable_cache_t, std::tuple<std::decay_t<AOP>...>>::value;
auto tp = filter_cache<http::enable_cache_t>(std::forward<AOP>(aop)...);
using Tup = decltype(tp);
#if defined(ASIO2_ENABLE_LOG)
static_assert(!has_type<http::enable_cache_t, Tup>::value);
#endif
std::shared_ptr<opfun> op = std::make_shared<opfun>(
std::bind(&self::template _proxy<CacheFlag, F, Tup>, this,
std::move(f), std::move(tp),
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
this->_bind_uris(name, std::move(op), this->_make_uris<M...>(name));
}
template<http::verb... M, class F, class C, class... AOP>
typename std::enable_if_t<!std::is_base_of_v<websocket::detail::listener_tag,
detail::remove_cvref_t<F>> && std::is_same_v<C, typename function_traits<F>::class_type>, void>
inline _bind(std::string name, F f, C* c, AOP&&... aop)
{
constexpr bool CacheFlag = has_type<http::enable_cache_t, std::tuple<std::decay_t<AOP>...>>::value;
auto tp = filter_cache<http::enable_cache_t>(std::forward<AOP>(aop)...);
using Tup = decltype(tp);
#if defined(ASIO2_ENABLE_LOG)
static_assert(!has_type<http::enable_cache_t, Tup>::value);
#endif
std::shared_ptr<opfun> op = std::make_shared<opfun>(
std::bind(&self::template _proxy<CacheFlag, F, C, Tup>, this,
std::move(f), c, std::move(tp),
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
this->_bind_uris(name, std::move(op), this->_make_uris<M...>(name));
}
template<http::verb... M, class F, class C, class... AOP>
typename std::enable_if_t<!std::is_base_of_v<websocket::detail::listener_tag,
detail::remove_cvref_t<F>> && std::is_same_v<C, typename function_traits<F>::class_type>, void>
inline _bind(std::string name, F f, C& c, AOP&&... aop)
{
this->_bind<M...>(std::move(name), std::move(f), std::addressof(c), std::forward<AOP>(aop)...);
}
template<class... AOP>
inline void _bind(std::string name, websocket::listener<caller_t> listener, AOP&&... aop)
{
auto tp = filter_cache<http::enable_cache_t>(std::forward<AOP>(aop)...);
using Tup = decltype(tp);
#if defined(ASIO2_ENABLE_LOG)
static_assert(!has_type<http::enable_cache_t, Tup>::value);
#endif
std::shared_ptr<opfun> op = std::make_shared<opfun>(
std::bind(&self::template _proxy<Tup>, this,
std::move(listener), std::move(tp),
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
// https://datatracker.ietf.org/doc/rfc6455/
// Once a connection to the server has been established (including a
// connection via a proxy or over a TLS-encrypted tunnel), the client
// MUST send an opening handshake to the server. The handshake consists
// of an HTTP Upgrade request, along with a list of required and
// optional header fields. The requirements for this handshake are as
// follows.
// 2. The method of the request MUST be GET, and the HTTP version MUST
// be at least 1.1.
this->_bind_uris(name, std::move(op), std::array<std::string, 1>{std::string{ "Z" } +name});
}
template<class URIS>
inline void _bind_uris(std::string& name, std::shared_ptr<opfun> op, URIS uris)
{
for (auto& uri : uris)
{
if (uri.empty())
continue;
if (name.back() == '*')
{
ASIO2_ASSERT(this->wildcard_routers_.find(uri) == this->wildcard_routers_.end());
this->wildcard_routers_[std::move(uri)] = op;
}
else
{
ASIO2_ASSERT(this->strictly_routers_.find(uri) == this->strictly_routers_.end());
this->strictly_routers_[std::move(uri)] = op;
}
}
}
//template<http::verb... M, class C, class R, class...Ps, class... AOP>
//inline void _bind(std::string name, R(C::*memfun)(Ps...), C* c, AOP&&... aop)
//{
//}
template<bool CacheFlag, class F, class Tup>
typename std::enable_if_t<!CacheFlag, opret>
inline _proxy(F& f, Tup& aops,
std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
using fun_traits_type = function_traits<F>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
if (!_call_aop_before(aops, caller, req, rep))
return std::addressof(rep.base());
if constexpr (std::is_same_v<std::shared_ptr<caller_t>, arg0_type>)
{
f(caller, req, rep);
}
else
{
f(req, rep);
}
_call_aop_after(aops, caller, req, rep);
return std::addressof(rep.base());
}
template<bool CacheFlag, class F, class C, class Tup>
typename std::enable_if_t<!CacheFlag, opret>
inline _proxy(F& f, C* c, Tup& aops,
std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
using fun_traits_type = function_traits<F>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
if (!_call_aop_before(aops, caller, req, rep))
return std::addressof(rep.base());
if constexpr (std::is_same_v<std::shared_ptr<caller_t>, arg0_type>)
{
if (c) (c->*f)(caller, req, rep);
}
else
{
if (c) (c->*f)(req, rep);
}
_call_aop_after(aops, caller, req, rep);
return std::addressof(rep.base());
}
template<class Tup>
inline opret _proxy(websocket::listener<caller_t>& listener, Tup& aops,
std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
ASIO2_ASSERT(req.ws_frame_type_ != websocket::frame::unknown);
if (req.ws_frame_type_ == websocket::frame::open)
{
if (!_call_aop_before(aops, caller, req, rep))
return nullptr;
}
if (req.ws_frame_type_ != websocket::frame::unknown)
{
listener(caller, req, rep);
}
if (req.ws_frame_type_ == websocket::frame::open)
{
if (!_call_aop_after(aops, caller, req, rep))
return nullptr;
}
return std::addressof(rep.base());
}
template<bool CacheFlag, class F, class Tup>
typename std::enable_if_t<CacheFlag, opret>
inline _proxy(F& f, Tup& aops,
std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
using fun_traits_type = function_traits<F>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
using pcache_node = decltype(this->http_cache_.find(""));
if (http::is_cache_enabled(req.base()))
{
pcache_node pcn = this->http_cache_.find(req.target());
if (!pcn)
{
if (!_call_aop_before(aops, caller, req, rep))
return std::addressof(rep.base());
if constexpr (std::is_same_v<std::shared_ptr<caller_t>, arg0_type>)
{
f(caller, req, rep);
}
else
{
f(req, rep);
}
if (_call_aop_after(aops, caller, req, rep) && rep.result() == http::status::ok)
{
http::web_response::super msg{ std::move(rep.base()) };
if (msg.body().to_text())
{
http::try_prepare_payload(msg);
this->http_cache_.shrink_to_fit();
pcn = this->http_cache_.emplace(req.target(), std::move(msg));
return std::addressof(pcn->msg);
}
else
{
rep.base() = std::move(msg);
}
}
return std::addressof(rep.base());
}
else
{
ASIO2_ASSERT(!pcn->msg.body().is_file());
pcn->update_alive_time();
return std::addressof(pcn->msg);
}
}
else
{
if (!_call_aop_before(aops, caller, req, rep))
return std::addressof(rep.base());
if constexpr (std::is_same_v<std::shared_ptr<caller_t>, arg0_type>)
{
f(caller, req, rep);
}
else
{
f(req, rep);
}
_call_aop_after(aops, caller, req, rep);
return std::addressof(rep.base());
}
}
template<bool CacheFlag, class F, class C, class Tup>
typename std::enable_if_t<CacheFlag, opret>
inline _proxy(F& f, C* c, Tup& aops,
std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
using fun_traits_type = function_traits<F>;
using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
typename fun_traits_type::template args<0>::type>>;
using pcache_node = decltype(this->http_cache_.find(""));
if (http::is_cache_enabled(req.base()))
{
pcache_node pcn = this->http_cache_.find(req.target());
if (!pcn)
{
if (!_call_aop_before(aops, caller, req, rep))
return std::addressof(rep.base());
if constexpr (std::is_same_v<std::shared_ptr<caller_t>, arg0_type>)
{
if (c) (c->*f)(caller, req, rep);
}
else
{
if (c) (c->*f)(req, rep);
}
if (_call_aop_after(aops, caller, req, rep) && rep.result() == http::status::ok)
{
http::web_response::super msg{ std::move(rep.base()) };
if (msg.body().to_text())
{
http::try_prepare_payload(msg);
this->http_cache_.shrink_to_fit();
pcn = this->http_cache_.emplace(req.target(), std::move(msg));
return std::addressof(pcn->msg);
}
else
{
rep.base() = std::move(msg);
}
}
return std::addressof(rep.base());
}
else
{
ASIO2_ASSERT(!pcn->msg.body().is_file());
pcn->update_alive_time();
return std::addressof(pcn->msg);
}
}
else
{
if (!_call_aop_before(aops, caller, req, rep))
return std::addressof(rep.base());
if constexpr (std::is_same_v<std::shared_ptr<caller_t>, arg0_type>)
{
if (c) (c->*f)(caller, req, rep);
}
else
{
if (c) (c->*f)(req, rep);
}
_call_aop_after(aops, caller, req, rep);
return std::addressof(rep.base());
}
}
template<class F>
inline void _bind_not_found(F f)
{
this->not_found_router_ = std::make_shared<opfun>(
std::bind(&self::template _not_found_proxy<F>, this, std::move(f),
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}
template<class F, class C>
inline void _bind_not_found(F f, C* c)
{
this->not_found_router_ = std::make_shared<opfun>(
std::bind(&self::template _not_found_proxy<F, C>, this, std::move(f), c,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}
template<class F, class C>
inline void _bind_not_found(F f, C& c)
{
this->_bind_not_found(std::move(f), std::addressof(c));
}
template<class F>
inline opret _not_found_proxy(F& f, std::shared_ptr<caller_t>& caller,
http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(caller);
if constexpr (detail::is_template_callable_v<F, std::shared_ptr<caller_t>&,
http::web_request&, http::web_response&>)
{
f(caller, req, rep);
}
else
{
f(req, rep);
}
return std::addressof(rep.base());
}
template<class F, class C>
inline opret _not_found_proxy(F& f, C* c, std::shared_ptr<caller_t>& caller,
http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(caller);
if constexpr (detail::is_template_callable_v<F, std::shared_ptr<caller_t>&,
http::web_request&, http::web_response&>)
{
if (c) (c->*f)(caller, req, rep);
}
else
{
if (c) (c->*f)(req, rep);
}
return std::addressof(rep.base());
}
template <typename... Args, typename F, std::size_t... I>
inline void _for_each_tuple(std::tuple<Args...>& t, const F& f, std::index_sequence<I...>)
{
(f(std::get<I>(t)), ...);
}
template<class Tup>
inline bool _do_call_aop_before(
Tup& aops, std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(aops, caller, req, rep);
asio2::detail::get_current_object<std::shared_ptr<caller_t>>() = caller;
bool continued = true;
_for_each_tuple(aops, [&continued, &caller, &req, &rep](auto& aop)
{
asio2::detail::ignore_unused(caller, req, rep);
if (!continued)
return;
if constexpr (has_member_before<decltype(aop), bool,
std::shared_ptr<caller_t>&, http::web_request&, http::web_response&>::value)
{
continued = aop.before(caller, req, rep);
}
else if constexpr (has_member_before<decltype(aop), bool,
http::web_request&, http::web_response&>::value)
{
continued = aop.before(req, rep);
}
else
{
std::ignore = true;
}
}, std::make_index_sequence<std::tuple_size_v<Tup>>{});
return continued;
}
template<class Tup>
inline bool _call_aop_before(
Tup& aops, std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(aops, caller, req, rep);
if constexpr (!std::tuple_size_v<Tup>)
{
return true;
}
else
{
return this->_do_call_aop_before(aops, caller, req, rep);
}
}
template<class Tup>
inline bool _do_call_aop_after(
Tup& aops, std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(aops, caller, req, rep);
asio2::detail::get_current_object<std::shared_ptr<caller_t>>() = caller;
bool continued = true;
_for_each_tuple(aops, [&continued, &caller, &req, &rep](auto& aop)
{
asio2::detail::ignore_unused(caller, req, rep);
if (!continued)
return;
if constexpr (has_member_after<decltype(aop), bool,
std::shared_ptr<caller_t>&, http::web_request&, http::web_response&>::value)
{
continued = aop.after(caller, req, rep);
}
else if constexpr (has_member_after<decltype(aop), bool,
http::web_request&, http::web_response&>::value)
{
continued = aop.after(req, rep);
}
else
{
std::ignore = true;
}
}, std::make_index_sequence<std::tuple_size_v<Tup>>{});
return continued;
}
template<class Tup>
inline bool _call_aop_after(
Tup& aops, std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(aops, caller, req, rep);
if constexpr (!std::tuple_size_v<Tup>)
{
return true;
}
else
{
return this->_do_call_aop_after(aops, caller, req, rep);
}
}
inline std::string _make_uri(std::string_view root, std::string_view path)
{
std::string uri;
if (http::has_undecode_char(path, 1))
{
std::string decoded = http::url_decode(path);
path = decoded;
while (path.size() > static_cast<std::string_view::size_type>(1) && path.back() == '/')
{
path.remove_suffix(1);
}
uri.reserve(root.size() + path.size());
uri += root;
uri += path;
}
else
{
while (path.size() > static_cast<std::string_view::size_type>(1) && path.back() == '/')
{
path.remove_suffix(1);
}
uri.reserve(root.size() + path.size());
uri += root;
uri += path;
}
return uri;
}
template<bool IsHttp>
inline std::shared_ptr<opfun>& _find(http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(rep);
std::string uri;
if constexpr (IsHttp)
{
uri = this->_make_uri(this->_to_char(req.method()), req.path());
}
else
{
uri = this->_make_uri(std::string_view{ "Z" }, req.path());
}
{
auto it = this->strictly_routers_.find(uri);
if (it != this->strictly_routers_.end())
{
return (it->second);
}
}
// Find the best match url from tail to head
if (!wildcard_routers_.empty())
{
for (auto it = this->wildcard_routers_.rbegin(); it != this->wildcard_routers_.rend(); ++it)
{
auto& k = it->first;
ASIO2_ASSERT(k.size() >= std::size_t(3));
if (!uri.empty() && !k.empty() && uri.front() == k.front() && uri.size() >= (k.size() - 2)
&& uri[k.size() - 3] == k[k.size() - 3] && http::url_match(k, uri))
{
return (it->second);
}
}
}
return this->dummy_router_;
}
inline opret _route(std::shared_ptr<caller_t>& caller, http::web_request& req, http::web_response& rep)
{
if (caller->websocket_router_)
{
return (*(caller->websocket_router_))(caller, req, rep);
}
std::shared_ptr<opfun>& router_ptr = this->template _find<true>(req, rep);
if (router_ptr)
{
return (*router_ptr)(caller, req, rep);
}
if (this->not_found_router_ && (*(this->not_found_router_)))
(*(this->not_found_router_))(caller, req, rep);
return std::addressof(rep.base());
}
inline constexpr std::string_view _to_char(http::verb method) noexcept
{
using namespace std::literals;
// Use a special name to avoid conflicts with global variable names
constexpr std::string_view _hrmchars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"sv;
return _hrmchars.substr(detail::to_underlying(method), 1);
}
protected:
std::filesystem::path root_directory_ = std::filesystem::current_path();
bool support_websocket_ = true;
std::unordered_map<std::string, std::shared_ptr<opfun>> strictly_routers_;
std:: map<std::string, std::shared_ptr<opfun>> wildcard_routers_;
std::shared_ptr<opfun> not_found_router_;
inline static std::shared_ptr<opfun> dummy_router_;
detail::http_cache_t<caller_t, args_t> http_cache_;
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTP_ROUTER_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SERVER_HPP__
#define __ASIO2_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdint>
#include <memory>
#include <chrono>
#include <atomic>
#include <string>
#include <string_view>
#include <asio2/base/iopool.hpp>
#include <asio2/base/log.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/session_mgr.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/object.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/base/detail/ecs.hpp>
#include <asio2/base/impl/thread_id_cp.hpp>
#include <asio2/base/impl/user_data_cp.hpp>
#include <asio2/base/impl/user_timer_cp.hpp>
#include <asio2/base/impl/post_cp.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
#include <asio2/base/impl/condition_event_cp.hpp>
namespace asio2
{
class server
{
public:
inline constexpr static bool is_session() noexcept { return false; }
inline constexpr static bool is_client () noexcept { return false; }
inline constexpr static bool is_server () noexcept { return true ; }
};
}
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
template<class derived_t, class session_t>
class server_impl_t
: public asio2::server
, public object_t <derived_t>
, public iopool_cp <derived_t>
, public thread_id_cp <derived_t>
, public event_queue_cp <derived_t>
, public user_data_cp <derived_t>
, public user_timer_cp <derived_t>
, public post_cp <derived_t>
, public condition_event_cp<derived_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
public:
using super = object_t <derived_t>;
using self = server_impl_t<derived_t, session_t>;
using iopoolcp = iopool_cp <derived_t>;
using args_type = typename session_t::args_type;
using key_type = std::size_t;
public:
/**
* @brief constructor
*/
template<class ThreadCountOrScheduler>
explicit server_impl_t(ThreadCountOrScheduler&& tcos)
: object_t <derived_t>()
, iopool_cp <derived_t>(std::forward<ThreadCountOrScheduler>(tcos))
, user_data_cp <derived_t>()
, user_timer_cp<derived_t>()
, post_cp <derived_t>()
, rallocator_()
, wallocator_()
, listener_ ()
, io_ (iopoolcp::_get_io(0))
, sessions_ (io_, this->state_)
{
}
/**
* @brief destructor
*/
~server_impl_t()
{
}
/**
* @brief start the server
*/
inline bool start() noexcept
{
ASIO2_ASSERT(this->io_.running_in_this_thread());
return true;
}
/**
* @brief stop the server
*/
inline void stop()
{
ASIO2_ASSERT(this->io_.running_in_this_thread());
// can't use post, we need ensure when the derived stop is called, the chain
// must be executed completed.
this->derived().dispatch([this]() mutable
{
// close user custom timers
this->_dispatch_stop_all_timers();
// close all posted timed tasks
this->_dispatch_stop_all_timed_events();
// close all async_events
this->notify_all_condition_events();
// destroy user data, maybe the user data is self shared_ptr,
// if don't destroy it, will cause loop refrence.
// read/write user data in other thread which is not the io_context
// thread maybe cause crash.
this->user_data_.reset();
// destroy the ecs
this->ecs_.reset();
});
}
/**
* @brief check whether the server is started
*/
inline bool is_started() noexcept
{
return (this->state_ == state_t::started);
}
/**
* @brief check whether the server is stopped
*/
inline bool is_stopped() noexcept
{
return (this->state_ == state_t::stopped);
}
/**
* @brief get this object hash key
*/
inline key_type hash_key() const noexcept
{
return reinterpret_cast<key_type>(this);
}
/**
* @brief Asynchronous send data for each session
* supporting multi data formats,see asio::buffer(...) in /asio/buffer.hpp
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType * : async_send("abc");
* PodType (&data)[N] : double m[10]; async_send(m);
* std::array<PodType, N> : std::array<int,10> m; async_send(m);
* std::vector<PodType, Allocator> : std::vector<float> m; async_send(m);
* std::basic_string<Elem, Traits, Allocator> : std::string m; async_send(m);
*/
template<class T>
inline derived_t & async_send(const T& data)
{
this->sessions_.for_each([&data](std::shared_ptr<session_t>& session_ptr) mutable
{
session_ptr->async_send(data);
});
return this->derived();
}
/**
* @brief Asynchronous send data for each session
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType * : async_send("abc");
*/
template<class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<detail::is_char_v<CharT>, derived_t&> async_send(CharT* s)
{
return this->async_send(s, s ? Traits::length(s) : 0);
}
/**
* @brief Asynchronous send data for each session
* You can call this function on the communication thread and anywhere,it's multi thread safed.
* PodType (&data)[N] : double m[10]; async_send(m,5);
*/
template<class CharT, class SizeT>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<SizeT>>, derived_t&>
async_send(CharT* s, SizeT count)
{
if (s)
{
this->sessions_.for_each([s, count](std::shared_ptr<session_t>& session_ptr) mutable
{
session_ptr->async_send(s, count);
});
}
return this->derived();
}
public:
/**
* @brief get the acceptor refrence, derived classes must override this function
*/
inline auto & acceptor() noexcept { return this->derived().acceptor(); }
/**
* @brief get the listen address, same as get_listen_address
*/
inline std::string listen_address() noexcept
{
return this->get_listen_address();
}
/**
* @brief get the listen address
*/
inline std::string get_listen_address() noexcept
{
try
{
return this->acceptor().local_endpoint().address().to_string();
}
catch (system_error & e) { set_last_error(e); }
return std::string();
}
/**
* @brief get the listen port, same as get_listen_port
*/
inline unsigned short listen_port() noexcept
{
return this->get_listen_port();
}
/**
* @brief get the listen port
*/
inline unsigned short get_listen_port() noexcept
{
return this->acceptor().local_endpoint(get_last_error()).port();
}
/**
* @brief get connected session count, same as get_session_count
*/
inline std::size_t session_count() noexcept { return this->get_session_count(); }
/**
* @brief get connected session count
*/
inline std::size_t get_session_count() noexcept { return this->sessions_.size(); }
/**
* @brief Applies the given function object fn for each session.
* @param fn - The handler to be called for each session.
* Function signature :
* void(std::shared_ptr<asio2::xxx_session>& session_ptr)
*/
template<class Fun>
inline derived_t & foreach_session(Fun&& fn)
{
this->sessions_.for_each(std::forward<Fun>(fn));
return this->derived();
}
/**
* @brief find the session by session's hash key
*/
template<class KeyType>
inline std::shared_ptr<session_t> find_session(const KeyType& key)
{
return this->sessions_.find(key);
}
/**
* @brief find the session by user custom role
* @param fn - The handler to be called when search the session.
* Function signature :
* bool(std::shared_ptr<asio2::xxx_session>& session_ptr)
* @return std::shared_ptr<asio2::xxx_session>
*/
template<class Fun>
inline std::shared_ptr<session_t> find_session_if(Fun&& fn)
{
return std::shared_ptr<session_t>(this->sessions_.find_if(std::forward<Fun>(fn)));
}
/**
* @brief get the io object refrence
*/
inline io_t & io() noexcept { return this->io_; }
protected:
/**
* @brief get the recv/read allocator object refrence
*/
inline auto & rallocator() noexcept { return this->rallocator_; }
/**
* @brief get the send/write/post allocator object refrence
*/
inline auto & wallocator() noexcept { return this->wallocator_; }
inline session_mgr_t<session_t> & sessions() noexcept { return this->sessions_; }
inline listener_t & listener() noexcept { return this->listener_; }
inline std::atomic<state_t> & state () noexcept { return this->state_; }
protected:
// The memory to use for handler-based custom memory allocation. used for acceptor.
handler_memory<std::true_type , assizer<args_type>> rallocator_;
/// The memory to use for handler-based custom memory allocation. used fo send/write/post.
handler_memory<std::false_type, assizer<args_type>> wallocator_;
/// listener
listener_t listener_;
/// The io_context wrapper used to handle the accept event.
io_t & io_;
/// state
std::atomic<state_t> state_ = state_t::stopped;
/// session_mgr
session_mgr_t<session_t> sessions_;
/// use this to ensure that server stop only after all sessions are closed
std::shared_ptr<void> counter_ptr_;
/// the pointer of ecs_t
std::shared_ptr<ecs_base> ecs_;
#if defined(_DEBUG) || defined(DEBUG)
std::atomic<int> post_send_counter_ = 0;
std::atomic<int> post_recv_counter_ = 0;
#endif
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_SERVER_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : mqtt_cpp/include/mqtt/broker/offline_message.hpp
*/
#ifndef __ASIO2_MQTT_OFFLINE_MESSAGE_HPP__
#define __ASIO2_MQTT_OFFLINE_MESSAGE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <string>
#include <string_view>
#include <type_traits>
#include <list>
#include <algorithm>
#include <variant>
#include <asio2/base/iopool.hpp>
#include <asio2/mqtt/message.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
namespace asio2::mqtt
{
// The offline message structure holds messages that have been published on a
// topic that a not-currently-connected client is subscribed to.
// When a new connection is made with the client id for this saved data,
// these messages will be published to that client, and only that client.
template<class Value>
class offline_messages
{
public:
offline_messages() = default;
~offline_messages() = default;
//void send_all(endpoint_t& ep)
//{
// auto& idx = messages_.get<tag_seq>();
// while (!idx.empty())
// {
// if (idx.front().send(ep))
// {
// idx.pop_front();
// }
// else
// {
// break;
// }
// }
//}
//void send_by_packet_id_release(endpoint_t& ep)
//{
// auto& idx = messages_.get<tag_seq>();
// while (!idx.empty())
// {
// if (idx.front().send(ep))
// {
// // if packet_id is consumed, then finish
// idx.pop_front();
// }
// else
// {
// break;
// }
// }
//}
//bool send(endpoint_t& ep) const
//{
// auto props = props_;
// if (message_expiry_timer_)
// {
// auto d = std::chrono::duration_cast<std::chrono::seconds>(
// message_expiry_timer_->expiry() - std::chrono::steady_clock::now()).count();
// if (d < 0)
// d = 0;
// set_property<v5::property::message_expiry_interval>(
// props,
// v5::property::message_expiry_interval(
// static_cast<uint32_t>(d)));
// }
// mqtt::qos_type qos_value = publish_.qos();
// if (qos_value == mqtt::qos_type::at_least_once || qos_value == mqtt::qos_type::exactly_once)
// {
// if (auto pid = ep.acquire_unique_packet_id_no_except())
// {
// ep.publish(pid.value(), topic_, contents_, pubopts_, std::move(props));
// return true;
// }
// }
// else
// {
// ep.publish(topic_, contents_, pubopts_, std::move(props));
// return true;
// }
// return false;
//}
void clear()
{
messages_.clear();
}
bool empty() const
{
return messages_.empty();
}
template<class Message>
void push_back(asio::io_context& ioc, Message&& msg)
{
using message_type = typename asio2::detail::remove_cvref_t<Message>;
auto it = messages_.emplace(messages_.end(), std::forward<Message>(msg), nullptr);
if constexpr (std::is_same_v<message_type, mqtt::v5::publish>)
{
mqtt::v5::message_expiry_interval* mei =
msg.properties().template get_if<mqtt::v5::message_expiry_interval>();
if (mei)
{
std::shared_ptr<asio::steady_timer> expiry_timer =
std::make_shared<asio::steady_timer>(ioc, std::chrono::seconds(mei->value()));
expiry_timer->async_wait(
[this, it, wp = std::weak_ptr<asio::steady_timer>(expiry_timer)](error_code ec) mutable
{
if (auto sp = wp.lock())
{
if (!ec)
{
messages_.erase(it);
}
}
});
it->message_expiry_timer = std::move(expiry_timer);
}
}
else
{
asio2::ignore_unused(ioc, msg, it);
}
}
template<class Callback>
void for_each(Callback&& cb)
{
for (auto& v : messages_)
{
cb(v);
}
}
protected:
///
std::list<Value> messages_;
};
struct omnode
{
public:
template<class Message>
explicit omnode(Message&& msg, std::shared_ptr<asio::steady_timer> expiry_timer)
: message(std::forward<Message>(msg))
, message_expiry_timer(std::move(expiry_timer))
{
}
mqtt::message message;
std::shared_ptr<asio::steady_timer> message_expiry_timer;
};
}
#endif // !__ASIO2_MQTT_OFFLINE_MESSAGE_HPP__
<file_sep>// Copyright(c) 2015-present, <NAME>, mguludag and spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
//
// Custom sink for QPlainTextEdit or QTextEdit and its childs(QTextBrowser...
// etc) Building and using requires Qt library.
//
#include "spdlog/common.h"
#include "spdlog/details/log_msg.h"
#include "spdlog/details/synchronous_factory.h"
#include "spdlog/sinks/base_sink.h"
#include <QTextEdit>
#include <QPlainTextEdit>
//
// qt_sink class
//
namespace spdlog {
namespace sinks {
template<typename Mutex>
class qt_sink : public base_sink<Mutex>
{
public:
qt_sink(QObject *qt_object, const std::string &meta_method)
{
qt_object_ = qt_object;
meta_method_ = meta_method;
}
~qt_sink()
{
flush_();
}
protected:
void sink_it_(const details::log_msg &msg) override
{
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted);
string_view_t str = string_view_t(formatted.data(), formatted.size());
QMetaObject::invokeMethod(qt_object_, meta_method_.c_str(), Qt::AutoConnection,
Q_ARG(QString, QString::fromUtf8(str.data(), static_cast<int>(str.size())).trimmed()));
}
void flush_() override {}
private:
QObject *qt_object_ = nullptr;
std::string meta_method_;
};
#include "spdlog/details/null_mutex.h"
#include <mutex>
using qt_sink_mt = qt_sink<std::mutex>;
using qt_sink_st = qt_sink<spdlog::details::null_mutex>;
} // namespace sinks
//
// Factory functions
//
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_mt(const std::string &logger_name, QTextEdit *qt_object, const std::string &meta_method = "append")
{
return Factory::template create<sinks::qt_sink_mt>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_st(const std::string &logger_name, QTextEdit *qt_object, const std::string &meta_method = "append")
{
return Factory::template create<sinks::qt_sink_st>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_mt(
const std::string &logger_name, QPlainTextEdit *qt_object, const std::string &meta_method = "appendPlainText")
{
return Factory::template create<sinks::qt_sink_mt>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_st(
const std::string &logger_name, QPlainTextEdit *qt_object, const std::string &meta_method = "appendPlainText")
{
return Factory::template create<sinks::qt_sink_st>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_mt(const std::string &logger_name, QObject *qt_object, const std::string &meta_method)
{
return Factory::template create<sinks::qt_sink_mt>(logger_name, qt_object, meta_method);
}
template<typename Factory = spdlog::synchronous_factory>
inline std::shared_ptr<logger> qt_logger_st(const std::string &logger_name, QObject *qt_object, const std::string &meta_method)
{
return Factory::template create<sinks::qt_sink_st>(logger_name, qt_object, meta_method);
}
} // namespace spdlog
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_AOP_SUBACK_HPP__
#define __ASIO2_MQTT_AOP_SUBACK_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class caller_t, class args_t>
class mqtt_aop_suback
{
friend caller_t;
protected:
// server or client
template<class Message>
inline void _before_suback_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
if (msg.reason_codes().count() == 0)
{
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
}
}
// must be client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::suback& msg)
{
if (_before_suback_callback(ec, caller_ptr, caller, om, msg); ec)
return;
}
// must be client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::suback& msg)
{
if (_before_suback_callback(ec, caller_ptr, caller, om, msg); ec)
return;
}
// must be client
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::suback& msg)
{
if (_before_suback_callback(ec, caller_ptr, caller, om, msg); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::suback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::suback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::suback& msg)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg);
}
};
}
#endif // !__ASIO2_MQTT_AOP_SUBACK_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_EXTERNAL_PREDEF_H__
#define __ASIO2_EXTERNAL_PREDEF_H__
#include <asio2/config.hpp>
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/predef.h>)
#include <boost/predef.h>
#ifndef ASIO2_OS_IOS
#define ASIO2_OS_IOS BOOST_OS_IOS
#endif
#ifndef ASIO2_OS_LINUX
#define ASIO2_OS_LINUX BOOST_OS_LINUX
#endif
#ifndef ASIO2_OS_MACOS
#define ASIO2_OS_MACOS BOOST_OS_MACOS
#endif
#ifndef ASIO2_OS_UNIX
#define ASIO2_OS_UNIX BOOST_OS_UNIX
#endif
#ifndef ASIO2_OS_WINDOWS
#define ASIO2_OS_WINDOWS BOOST_OS_WINDOWS
#endif
#ifndef ASIO2_ENDIAN_BIG_BYTE
#define ASIO2_ENDIAN_BIG_BYTE BOOST_ENDIAN_BIG_BYTE
#endif
#ifndef ASIO2_ENDIAN_BIG_WORD
#define ASIO2_ENDIAN_BIG_WORD BOOST_ENDIAN_BIG_WORD
#endif
#ifndef ASIO2_ENDIAN_LITTLE_BYTE
#define ASIO2_ENDIAN_LITTLE_BYTE BOOST_ENDIAN_LITTLE_BYTE
#endif
#ifndef ASIO2_ENDIAN_LITTLE_WORD
#define ASIO2_ENDIAN_LITTLE_WORD BOOST_ENDIAN_LITTLE_WORD
#endif
#ifndef ASIO2_ARCH_WORD_BITS_64
#define ASIO2_ARCH_WORD_BITS_64 BOOST_ARCH_WORD_BITS_64
#endif
#ifndef ASIO2_ARCH_WORD_BITS_32
#define ASIO2_ARCH_WORD_BITS_32 BOOST_ARCH_WORD_BITS_32
#endif
#ifndef ASIO2_ARCH_WORD_BITS_16
#define ASIO2_ARCH_WORD_BITS_16 BOOST_ARCH_WORD_BITS_16
#endif
#ifndef ASIO2_ARCH_WORD_BITS
#define ASIO2_ARCH_WORD_BITS BOOST_ARCH_WORD_BITS
#endif
#else
#include <asio2/bho/predef.h>
#ifndef ASIO2_OS_IOS
#define ASIO2_OS_IOS BHO_OS_IOS
#endif
#ifndef ASIO2_OS_LINUX
#define ASIO2_OS_LINUX BHO_OS_LINUX
#endif
#ifndef ASIO2_OS_MACOS
#define ASIO2_OS_MACOS BHO_OS_MACOS
#endif
#ifndef ASIO2_OS_UNIX
#define ASIO2_OS_UNIX BHO_OS_UNIX
#endif
#ifndef ASIO2_OS_WINDOWS
#define ASIO2_OS_WINDOWS BHO_OS_WINDOWS
#endif
#ifndef ASIO2_ENDIAN_BIG_BYTE
#define ASIO2_ENDIAN_BIG_BYTE BHO_ENDIAN_BIG_BYTE
#endif
#ifndef ASIO2_ENDIAN_BIG_WORD
#define ASIO2_ENDIAN_BIG_WORD BHO_ENDIAN_BIG_WORD
#endif
#ifndef ASIO2_ENDIAN_LITTLE_BYTE
#define ASIO2_ENDIAN_LITTLE_BYTE BHO_ENDIAN_LITTLE_BYTE
#endif
#ifndef ASIO2_ENDIAN_LITTLE_WORD
#define ASIO2_ENDIAN_LITTLE_WORD BHO_ENDIAN_LITTLE_WORD
#endif
#ifndef ASIO2_ARCH_WORD_BITS_64
#define ASIO2_ARCH_WORD_BITS_64 BHO_ARCH_WORD_BITS_64
#endif
#ifndef ASIO2_ARCH_WORD_BITS_32
#define ASIO2_ARCH_WORD_BITS_32 BHO_ARCH_WORD_BITS_32
#endif
#ifndef ASIO2_ARCH_WORD_BITS_16
#define ASIO2_ARCH_WORD_BITS_16 BHO_ARCH_WORD_BITS_16
#endif
#ifndef ASIO2_ARCH_WORD_BITS
#define ASIO2_ARCH_WORD_BITS BHO_ARCH_WORD_BITS
#endif
#endif
#endif
<file_sep>/*
Copyright <NAME> 2008-2021
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_X86_64_H
#define BHO_PREDEF_ARCHITECTURE_X86_64_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_X86_64`
https://en.wikipedia.org/wiki/X86-64[X86-64] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__x86_64+` | {predef_detection}
| `+__x86_64__+` | {predef_detection}
| `+__amd64__+` | {predef_detection}
| `+__amd64+` | {predef_detection}
| `+_M_X64+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_X86_64 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__x86_64) || defined(__x86_64__) || \
defined(__amd64__) || defined(__amd64) || \
defined(_M_X64)
# undef BHO_ARCH_X86_64
# define BHO_ARCH_X86_64 BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_X86_64
# define BHO_ARCH_X86_64_AVAILABLE
#endif
#if BHO_ARCH_X86_64
# undef BHO_ARCH_WORD_BITS_64
# define BHO_ARCH_WORD_BITS_64 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_X86_64_NAME "Intel x86-64"
#include <asio2/bho/predef/architecture/x86.h>
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_X86_64,BHO_ARCH_X86_64_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_RPCS_CLIENT_HPP__
#define __ASIO2_RPCS_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if __has_include(<cereal/cereal.hpp>)
#include <asio2/rpc/rpc_client.hpp>
namespace asio2
{
namespace detail
{
template<asio2::net_protocol np> struct template_args_rpcs_client;
template<>
struct template_args_rpcs_client<asio2::net_protocol::tcps> : public template_args_tcp_client
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::tcps;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
template<>
struct template_args_rpcs_client<asio2::net_protocol::wss> : public template_args_wss_client
{
static constexpr asio2::net_protocol net_protocol = asio2::net_protocol::wss;
static constexpr bool rdc_call_cp_enabled = false;
static constexpr std::size_t function_storage_size = 72;
};
}
using rpcs_client_args_tcp = detail::template_args_rpcs_client<asio2::net_protocol::tcps>;
using rpcs_client_args_ws = detail::template_args_rpcs_client<asio2::net_protocol::wss >;
template<class derived_t, asio2::net_protocol np> class rpcs_client_t;
template<class derived_t>
class rpcs_client_t<derived_t, asio2::net_protocol::tcps> : public detail::rpc_client_impl_t<derived_t,
detail::tcps_client_impl_t<derived_t, detail::template_args_rpcs_client<asio2::net_protocol::tcps>>>
{
public:
using detail::rpc_client_impl_t<derived_t, detail::tcps_client_impl_t<derived_t,
detail::template_args_rpcs_client<asio2::net_protocol::tcps>>>::rpc_client_impl_t;
};
template<class derived_t>
class rpcs_client_t<derived_t, asio2::net_protocol::wss> : public detail::rpc_client_impl_t<derived_t,
detail::wss_client_impl_t<derived_t, detail::template_args_rpcs_client<asio2::net_protocol::wss>>>
{
public:
using detail::rpc_client_impl_t<derived_t, detail::wss_client_impl_t<
derived_t, detail::template_args_rpcs_client<asio2::net_protocol::wss>>>::rpc_client_impl_t;
};
template<asio2::net_protocol np>
class rpcs_client_use : public rpcs_client_t<rpcs_client_use<np>, np>
{
public:
using rpcs_client_t<rpcs_client_use<np>, np>::rpcs_client_t;
};
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpcs_client = rpcs_client_use<asio2::net_protocol::tcps>;
#else
/// Using websocket as the underlying communication support
using rpcs_client = rpcs_client_use<asio2::net_protocol::wss>;
#endif
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct rpcs_rate_client_args_tcp : public rpcs_client_args_tcp
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
};
struct rpcs_rate_client_args_ws : public rpcs_client_args_ws
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
using stream_t = websocket::stream<asio::ssl::stream<socket_t&>&>;
};
template<class derived_t, asio2::net_protocol np> class rpcs_rate_client_t;
template<class derived_t>
class rpcs_rate_client_t<derived_t, asio2::net_protocol::tcps> : public detail::rpc_client_impl_t<derived_t,
detail::tcps_client_impl_t<derived_t, rpcs_rate_client_args_tcp>>
{
public:
using detail::rpc_client_impl_t<derived_t,
detail::tcps_client_impl_t<derived_t, rpcs_rate_client_args_tcp>>::rpc_client_impl_t;
};
template<class derived_t>
class rpcs_rate_client_t<derived_t, asio2::net_protocol::wss> : public detail::rpc_client_impl_t<derived_t,
detail::wss_client_impl_t<derived_t, rpcs_rate_client_args_ws>>
{
public:
using detail::rpc_client_impl_t<derived_t,
detail::wss_client_impl_t<derived_t, rpcs_rate_client_args_ws>>::rpc_client_impl_t;
};
template<asio2::net_protocol np>
class rpcs_rate_client_use : public rpcs_rate_client_t<rpcs_rate_client_use<np>, np>
{
public:
using rpcs_rate_client_t<rpcs_rate_client_use<np>, np>::rpcs_rate_client_t;
};
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
using rpcs_rate_client = rpcs_rate_client_use<asio2::net_protocol::tcps>;
#else
/// Using websocket as the underlying communication support
using rpcs_rate_client = rpcs_rate_client_use<asio2::net_protocol::wss>;
#endif
}
#endif
#endif
#endif // !__ASIO2_RPCS_CLIENT_HPP__
#endif
<file_sep>#include <asio2/rpc/rpc_client.hpp>
#include <asio2/external/json.hpp>
asio2::rpc_client* pclient = nullptr; // just for test get_current_caller
struct userinfo
{
std::string name;
int age;
std::map<int, std::string> purview;
// User defined object types require serialized the members like this:
template <class Archive>
void serialize(Archive & ar)
{
ar(name);
ar(age);
ar(purview);
}
};
// -- serialize the third party object
namespace nlohmann
{
template<class Archive>
void save(Archive& ar, nlohmann::json const& j)
{
ar << j.dump();
}
template<class Archive>
void load(Archive& ar, nlohmann::json& j)
{
std::string v;
ar >> v;
j = nlohmann::json::parse(v);
}
}
// Asynchronous rpc function
rpc::future<int> async_add(int a, int b)
{
ASIO2_ASSERT(pclient == asio2::get_current_caller<asio2::rpc_client*>());
rpc::promise<int> promise;
rpc::future<int> f = promise.get_future();
std::thread([a, b, promise = std::move(promise)]() mutable
{
promise.set_value(a + b);
}).detach();
return f;
}
// set the first parameter to client reference to know which client was called
void test(asio2::rpc_client& client, std::string str)
{
asio2::rpc_client& rc = asio2::get_current_caller<asio2::rpc_client&>();
asio2::ignore_unused(rc);
ASIO2_ASSERT(&client == &rc);
ASIO2_ASSERT(&client == pclient);
std::cout << client.get_user_data<int>() << " - test : " << str << std::endl;
}
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8010";
asio2::rpc_client client;
pclient = &client;
// set default rpc call timeout
client.set_default_timeout(std::chrono::seconds(3));
client.bind_connect([&]()
{
if (asio2::get_last_error())
return;
//------------------------------------------------------------------
// this thread is a commucation thread. like bind_recv,bind_connect,
// bind_disconnect..... is commucation thread.
// important : synchronous call rpc function in the commucation thread,
// then the call will degenerates into async_call and the return value is empty.
//------------------------------------------------------------------
client.call<double>("mul", 16.5, 26.5);
if (client.is_started())
{
ASIO2_ASSERT(asio2::get_last_error() == rpc::error::in_progress);
}
else
{
ASIO2_ASSERT(asio2::get_last_error() == rpc::error::not_connected);
}
// param 1 : user callback function(this param can be empty)
// param 2 : timeout (this param can be empty, if this param is empty, use the default timeout)
// param 3 : function name
// param 4 : function params
client.async_call([](int v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 12 + 11);
}
printf("sum1 : %d err : %d %s\n",
v, asio2::last_error_val(), asio2::last_error_msg().c_str());
}, std::chrono::seconds(13), "add", 12, 11);
// call the rpc function which has no param
client.async_call([]()
{
printf("heartbeat err : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, std::chrono::seconds(3), "heartbeat");
nlohmann::json j = nlohmann::json::object();
j["name"] = "lilei";
j["age"] = 30;
// Chain calls
client.async_call("test_json", j).response([](nlohmann::json js)
{
std::string s = js.dump();
if (!asio2::get_last_error())
{
ASIO2_ASSERT(js["age"].get<int>() == 30);
ASIO2_ASSERT(js["name"].get<std::string>() == "lilei");
}
asio2::ignore_unused(js, s);
});
// param 2 is empty, use the default timeout
client.async_call([](int v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 12 + 21);
}
printf("sum2 : %d err : %d %s\n", v,
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "add", 12, 21);
// call asynchronous rpc function, server's async_add is a asynchronous rpc function
client.async_call([](int v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 1 + 11);
}
printf("async_add : %d err : %d %s\n", v,
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, std::chrono::seconds(3), "async_add", 1, 11);
// param 1 is empty, the result of the rpc call is not returned
client.async_call("mul0", 2.5, 2.5);
// Chain calls :
client.set_timeout(std::chrono::seconds(5)).async_call("mul", 2.5, 2.5).response([](double v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 2.5 * 2.5);
}
std::cout << "mul1 " << v << std::endl;
});
client.async_call([]()
{
printf("async_test err : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, std::chrono::seconds(3), "async_test", "abc", "def");
});
// bind a rpc function in client, the server will call this client's rpc function
client.bind("sub", [](int a, int b) { return a - b; });
client.bind("async_add", async_add);
client.bind("test", test);
client.start(host, port);
// synchronous call
// param 1 : timeout (this param can be empty, if this param is empty, use the default timeout)
// param 2 : rpc function name
// param 3 : rpc function params
double mul = client.call<double>(std::chrono::seconds(3), "mul", 6.5, 6.5);
printf("mul5 : %lf err : %d %s\n", mul, asio2::last_error_val(), asio2::last_error_msg().c_str());
if (!asio2::get_last_error())
{
ASIO2_ASSERT(mul == 6.5 * 6.5);
}
nlohmann::json j = nlohmann::json::object();
j["name"] = "hanmeimei";
j["age"] = 20;
nlohmann::json j2 = client.call<nlohmann::json>(std::chrono::minutes(1), "test_json", j);
if (!asio2::get_last_error())
{
ASIO2_ASSERT(j2["age"].get<int>() == 20);
ASIO2_ASSERT(j2["name"].get<std::string>() == "hanmeimei");
}
userinfo u;
u = client.call<userinfo>("get_user");
if (!asio2::get_last_error())
{
ASIO2_ASSERT(u.name == "lilei" && u.purview.size() == 2);
}
u.name = "hanmeimei";
u.age = ((int)time(nullptr)) % 100;
u.purview = { {10,"get"},{20,"set"} };
client.async_call([]()
{
if (asio2::get_last_error())
printf("del_user : failed : %s\n\n", asio2::last_error_msg().c_str());
else
printf("del_user : successed\n\n");
}, "del_user", u);
// just call rpc function, don't need the rpc result
client.async_call("del_user", std::move(u));
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", "hanmeimei").response([](userinfo)
{
ASIO2_ASSERT(bool(asio2::get_last_error()));
std::cout << "del_user hanmeimei failed : " << asio2::last_error_msg() << std::endl;
});
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", 10, std::string("lilei"), 1).response([](userinfo)
{
ASIO2_ASSERT(bool(asio2::get_last_error()));
std::cout << "del_user lilei failed : " << asio2::last_error_msg() << std::endl;
});
// Chain calls :
int sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 12);
printf("sum5 : %d err : %d %s\n", sum, asio2::last_error_val(), asio2::last_error_msg().c_str());
if (!asio2::get_last_error())
{
ASIO2_ASSERT(sum == 11 + 12);
}
// Chain calls :
std::string str = client.call<std::string>("cat", "abc", "123");
printf("cat : %s err : %d %s\n", str.data(), asio2::last_error_val(), asio2::last_error_msg().c_str());
if (!asio2::get_last_error())
{
ASIO2_ASSERT(str == "abc123");
}
// Call a non-existent rpc function
client.async_call([](int v)
{
printf("test call no_exists_fn : %d err : %d %s\n",
v, asio2::last_error_val(), asio2::last_error_msg().c_str());
ASIO2_ASSERT(bool(asio2::get_last_error()));
}, "no_exists_fn", 10);
client.start_timer("timer_id1", std::chrono::milliseconds(500), [&]()
{
std::string s1;
s1 += '<';
for (int i = 100 + std::rand() % (100); i > 0; i--)
{
s1 += (char)((std::rand() % 26) + 'a');
}
std::string s2;
for (int i = 100 + std::rand() % (100); i > 0; i--)
{
s2 += (char)((std::rand() % 26) + 'a');
}
s2 += '>';
client.async_call([s1, s2](std::string v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == s1 + s2);
}
printf("cat : %s - %d %s\n", v.c_str(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "cat", s1, s2);
});
while (std::getchar() != '\n');
return 0;
}
<file_sep>#ifndef ASIO2_ENABLE_SSL
#define ASIO2_ENABLE_SSL
#endif
#include <asio2/rpc/rpcs_server.hpp>
#include <iostream>
int add(int a, int b)
{
return a + b;
}
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8011";
asio2::rpcs_server server;
// use file for cert
server.set_cert_file(
"../../cert/ca.crt",
"../../cert/server.crt",
"../../cert/server.key",
"123456");
if (asio2::get_last_error())
std::cout << "load cert files failed: " << asio2::last_error_msg() << std::endl;
server.bind_connect([&](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
session_ptr->async_call([](int v)
{
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == 15 - 6);
}
printf("sub : %d - %d %s\n", v,
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, std::chrono::seconds(10), "sub", 15, 6);
}).bind_start([&]()
{
printf("start rpcs server : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.bind("add", add);
server.bind("cat", [&](std::shared_ptr<asio2::rpcs_session>& session_ptr,
const std::string& a, const std::string& b)
{
int x = std::rand(), y = std::rand();
// Nested call rpc function in business function is ok.
session_ptr->async_call([x, y](int v)
{
asio2::ignore_unused(x, y);
if (!asio2::get_last_error())
{
ASIO2_ASSERT(v == x - y);
}
printf("sub : %d - %d %s\n", v,
asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "sub", x, y);
return a + b;
});
server.start(host, port);
while (std::getchar() != '\n');
server.stop();
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_EXTERNAL_ASSERT_HPP__
#define __ASIO2_EXTERNAL_ASSERT_HPP__
#include <asio2/config.hpp>
#if !defined(ASIO2_HEADER_ONLY) && __has_include(<boost/assert.hpp>)
#include <boost/assert.hpp>
#ifndef ASIO2_ASSERT
#define ASIO2_ASSERT BOOST_ASSERT
#endif
#else
#include <asio2/bho/assert.hpp>
#ifndef ASIO2_ASSERT
#define ASIO2_ASSERT BHO_ASSERT
#endif
#endif
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_EDG_H
#define BHO_PREDEF_COMPILER_EDG_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_EDG`
http://en.wikipedia.org/wiki/Edison_Design_Group[EDG {CPP} Frontend] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__EDG__+` | {predef_detection}
| `+__EDG_VERSION__+` | V.R.0
|===
*/ // end::reference[]
#define BHO_COMP_EDG BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__EDG__)
# define BHO_COMP_EDG_DETECTION BHO_PREDEF_MAKE_10_VRR(__EDG_VERSION__)
#endif
#ifdef BHO_COMP_EDG_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_EDG_EMULATED BHO_COMP_EDG_DETECTION
# else
# undef BHO_COMP_EDG
# define BHO_COMP_EDG BHO_COMP_EDG_DETECTION
# endif
# define BHO_COMP_EDG_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_EDG_NAME "EDG C++ Frontend"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_EDG,BHO_COMP_EDG_NAME)
#ifdef BHO_COMP_EDG_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_EDG_EMULATED,BHO_COMP_EDG_NAME)
#endif
<file_sep>/*
Copyright <NAME> 2011-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LANGUAGE_OBJC_H
#define BHO_PREDEF_LANGUAGE_OBJC_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LANG_OBJC`
http://en.wikipedia.org/wiki/Objective-C[Objective-C] language.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__OBJC__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_LANG_OBJC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__OBJC__)
# undef BHO_LANG_OBJC
# define BHO_LANG_OBJC BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_LANG_OBJC
# define BHO_LANG_OBJC_AVAILABLE
#endif
#define BHO_LANG_OBJC_NAME "Objective-C"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LANG_OBJC,BHO_LANG_OBJC_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_TCPS_SERVER_HPP__
#define __ASIO2_TCPS_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/tcp/tcps_session.hpp>
namespace asio2::detail
{
struct template_args_tcps_server
{
static constexpr bool is_session = false;
static constexpr bool is_client = false;
static constexpr bool is_server = true;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
template<class derived_t, class session_t>
class tcps_server_impl_t
: public ssl_context_cp <derived_t, template_args_tcps_server>
, public tcp_server_impl_t<derived_t, session_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
public:
using super = tcp_server_impl_t <derived_t, session_t>;
using self = tcps_server_impl_t<derived_t, session_t>;
using session_type = session_t;
public:
/**
* @brief constructor
*/
template<class... Args>
explicit tcps_server_impl_t(
asio::ssl::context::method method = asio::ssl::context::sslv23,
Args&&... args
)
: ssl_context_cp<derived_t, template_args_tcps_server>(method)
, super(std::forward<Args>(args)...)
{
}
/**
* @brief destructor
*/
~tcps_server_impl_t()
{
this->stop();
}
public:
/**
* @brief bind ssl handshake listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void(std::shared_ptr<asio2::tcps_session>& session_ptr)
*/
template<class F, class ...C>
inline derived_t & bind_handshake(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::handshake,
observer_t<std::shared_ptr<session_t>&>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<typename... Args>
inline std::shared_ptr<session_t> _make_session(Args&&... args)
{
return super::_make_session(std::forward<Args>(args)..., *this);
}
};
}
namespace asio2
{
template<class derived_t, class session_t>
using tcps_server_impl_t = detail::tcps_server_impl_t<derived_t, session_t>;
/**
* @brief ssl tcp server
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
template<class session_t>
class tcps_server_t : public detail::tcps_server_impl_t<tcps_server_t<session_t>, session_t>
{
public:
using detail::tcps_server_impl_t<tcps_server_t<session_t>, session_t>::tcps_server_impl_t;
};
/**
* @brief ssl tcp server
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
using tcps_server = tcps_server_t<tcps_session>;
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
template<class session_t>
class tcps_rate_server_t : public asio2::tcps_server_impl_t<tcps_rate_server_t<session_t>, session_t>
{
public:
using asio2::tcps_server_impl_t<tcps_rate_server_t<session_t>, session_t>::tcps_server_impl_t;
};
using tcps_rate_server = tcps_rate_server_t<tcps_rate_session>;
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_TCPS_SERVER_HPP__
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_REQUEST_IMPL_HPP__
#define __ASIO2_HTTP_REQUEST_IMPL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/impl/user_data_cp.hpp>
#include <asio2/http/detail/http_util.hpp>
#include <asio2/http/detail/http_url.hpp>
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::websocket
#else
namespace boost::beast::websocket
#endif
{
template <class> class listener;
}
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class Body, class Fields = http::fields>
class http_request_impl_t
: public http::message<true, Body, Fields>
#ifdef ASIO2_ENABLE_HTTP_REQUEST_USER_DATA
, public user_data_cp<http_request_impl_t<Body, Fields>>
#endif
{
template <class> friend class beast::websocket::listener;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
public:
using self = http_request_impl_t<Body, Fields>;
using super = http::message<true, Body, Fields>;
using header_type = typename super::header_type;
using body_type = typename super::body_type;
public:
/**
* @brief constructor
*/
template<typename... Args>
explicit http_request_impl_t(Args&&... args)
: super(std::forward<Args>(args)...)
#ifdef ASIO2_ENABLE_HTTP_REQUEST_USER_DATA
, user_data_cp<http_request_impl_t<Body, Fields>>()
#endif
{
}
http_request_impl_t(const http_request_impl_t& o)
: super()
#ifdef ASIO2_ENABLE_HTTP_REQUEST_USER_DATA
, user_data_cp<http_request_impl_t<Body, Fields>>()
#endif
{
this->base() = o.base();
this->url_ = o.url_;
this->ws_frame_type_ = o.ws_frame_type_;
this->ws_frame_data_ = o.ws_frame_data_;
}
http_request_impl_t(http_request_impl_t&& o)
: super()
#ifdef ASIO2_ENABLE_HTTP_REQUEST_USER_DATA
, user_data_cp<http_request_impl_t<Body, Fields>>()
#endif
{
this->base() = std::move(o.base());
this->url_ = std::move(o.url_);
this->ws_frame_type_ = o.ws_frame_type_;
this->ws_frame_data_ = o.ws_frame_data_;
}
self& operator=(const http_request_impl_t& o)
{
this->base() = o.base();
this->url_ = o.url_;
this->ws_frame_type_ = o.ws_frame_type_;
this->ws_frame_data_ = o.ws_frame_data_;
return *this;
}
self& operator=(http_request_impl_t&& o)
{
this->base() = std::move(o.base());
this->url_ = std::move(o.url_);
this->ws_frame_type_ = o.ws_frame_type_;
this->ws_frame_data_ = o.ws_frame_data_;
return *this;
}
http_request_impl_t(const http::message<true, Body, Fields>& req)
: super()
#ifdef ASIO2_ENABLE_HTTP_REQUEST_USER_DATA
, user_data_cp<http_request_impl_t<Body, Fields>>()
#endif
{
this->base() = req;
}
http_request_impl_t(http::message<true, Body, Fields>&& req)
: super()
#ifdef ASIO2_ENABLE_HTTP_REQUEST_USER_DATA
, user_data_cp<http_request_impl_t<Body, Fields>>()
#endif
{
this->base() = std::move(req);
}
self& operator=(const http::message<true, Body, Fields>& req)
{
this->base() = req;
return *this;
}
self& operator=(http::message<true, Body, Fields>&& req)
{
this->base() = std::move(req);
return *this;
}
/**
* @brief destructor
*/
~http_request_impl_t()
{
}
/// Returns the base portion of the message
inline super const& base() const noexcept
{
return *this;
}
/// Returns the base portion of the message
inline super& base() noexcept
{
return *this;
}
inline void reset()
{
static_cast<super&>(*this) = {};
}
public:
/**
* @brief Returns `true` if this HTTP request is a WebSocket Upgrade.
*/
inline bool is_upgrade() noexcept { return websocket::is_upgrade(*this); }
/**
* @brief Gets the content of the "schema" section, maybe empty
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
*/
inline std::string_view get_schema() noexcept
{
return this->url_.schema();
}
/**
* @brief Gets the content of the "schema" section, maybe empty
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
* same as get_schema
*/
inline std::string_view schema() noexcept
{
return this->get_schema();
}
/**
* @brief Gets the content of the "host" section, maybe empty
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
*/
inline std::string_view get_host() noexcept
{
return this->url_.host();
}
/**
* @brief Gets the content of the "host" section, maybe empty
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
* same as get_host
*/
inline std::string_view host() noexcept
{
return this->get_host();
}
/**
* @brief Gets the content of the "port" section, maybe empty
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
*/
inline std::string_view get_port() noexcept
{
return this->url_.port();
}
/**
* @brief Gets the content of the "port" section, maybe empty
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
* same as get_port
*/
inline std::string_view port() noexcept
{
return this->get_port();
}
/**
* @brief Gets the content of the "path" section of the target
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
*/
inline std::string_view get_path()
{
if (!this->url_.string().empty())
return this->url_.path();
if (!(this->url_.parser().field_set & (1 << (int)http::parses::url_fields::UF_PATH)))
return std::string_view{ "/" };
std::string_view target = this->target();
return std::string_view{ &target[
this->url_.parser().field_data[(int)http::parses::url_fields::UF_PATH].off],
this->url_.parser().field_data[(int)http::parses::url_fields::UF_PATH].len };
}
/**
* @brief Gets the content of the "path" section of the target
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
* same as get_path
*/
inline std::string_view path()
{
return this->get_path();
}
/**
* @brief Gets the content of the "query" section of the target
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
*/
inline std::string_view get_query()
{
if (!this->url_.string().empty())
return this->url_.query();
if (!(this->url_.parser().field_set & (1 << (int)http::parses::url_fields::UF_QUERY)))
return std::string_view{};
std::string_view target = this->target();
return std::string_view{ &target[
this->url_.parser().field_data[(int)http::parses::url_fields::UF_QUERY].off],
this->url_.parser().field_data[(int)http::parses::url_fields::UF_QUERY].len };
}
/**
* @brief Gets the content of the "query" section of the target
* <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<fragment>
* same as get_query
*/
inline std::string_view query()
{
return this->get_query();
}
/**
* @brief Returns `true` if this HTTP request's Content-Type is "multipart/form-data";
*/
inline bool has_multipart() noexcept
{
return http::has_multipart(*this);
}
/**
* @brief Get the "multipart/form-data" body content.
*/
inline decltype(auto) get_multipart()
{
return http::multipart(*this);
}
/**
* @brief Get the "multipart/form-data" body content. same as get_multipart
*/
inline decltype(auto) multipart()
{
return this->get_multipart();
}
/**
* @brief Get the url object reference. same as get_url
*/
inline http::url& url() { return this->url_; }
/**
* @brief Get the url object reference.
*/
inline http::url& get_url() { return this->url_; }
protected:
http::url url_{ "" };
websocket::frame ws_frame_type_ = websocket::frame::unknown;
std::string_view ws_frame_data_;
};
struct http_request_convert_helper
{
template<class Body, class Fields>
void from(http::request<Body, Fields>) {}
template<class Body, class Fields>
void from(detail::http_request_impl_t<Body, Fields>) {}
};
template<typename T, typename = void>
struct can_convert_to_http_request : std::false_type {};
template<typename T>
struct can_convert_to_http_request<T, std::void_t<decltype(std::declval<
http_request_convert_helper>().from(std::declval<T>()))>> : std::true_type {};
template<class T>
inline constexpr bool can_convert_to_http_request_v =
can_convert_to_http_request<detail::remove_cvref_t<T>>::value;
}
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::http
#else
namespace boost::beast::http
#endif
{
using web_request = asio2::detail::http_request_impl_t<http::string_body>;
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTP_REQUEST_IMPL_HPP__
<file_sep>// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2001.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// Metrowerks standard library:
#ifndef __MSL_CPP__
# include <asio2/bho/config/no_tr1/utility.hpp>
# ifndef __MSL_CPP__
# error This is not the MSL standard library!
# endif
#endif
#if __MSL_CPP__ >= 0x6000 // Pro 6
# define BHO_HAS_HASH
# define BHO_STD_EXTENSION_NAMESPACE Metrowerks
#endif
#define BHO_HAS_SLIST
#if __MSL_CPP__ < 0x6209
# define BHO_NO_STD_MESSAGES
#endif
// check C lib version for <stdint.h>
#include <cstddef>
#if defined(__MSL__) && (__MSL__ >= 0x5000)
# define BHO_HAS_STDINT_H
# if !defined(__PALMOS_TRAPS__)
# define BHO_HAS_UNISTD_H
# endif
// boilerplate code:
# include <asio2/bho/config/detail/posix_features.hpp>
#endif
#if defined(_MWMT) || _MSL_THREADSAFE
# define BHO_HAS_THREADS
#endif
#ifdef _MSL_NO_EXPLICIT_FUNC_TEMPLATE_ARG
# define BHO_NO_STD_USE_FACET
# define BHO_HAS_TWO_ARG_USE_FACET
#endif
// C++0x headers not yet implemented
//
# define BHO_NO_CXX11_HDR_ARRAY
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_HDR_CODECVT
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_FORWARD_LIST
# define BHO_NO_CXX11_HDR_FUTURE
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_RANDOM
# define BHO_NO_CXX11_HDR_RATIO
# define BHO_NO_CXX11_HDR_REGEX
# define BHO_NO_CXX11_HDR_SYSTEM_ERROR
# define BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_HDR_TUPLE
# define BHO_NO_CXX11_HDR_TYPE_TRAITS
# define BHO_NO_CXX11_HDR_TYPEINDEX
# define BHO_NO_CXX11_HDR_UNORDERED_MAP
# define BHO_NO_CXX11_HDR_UNORDERED_SET
# define BHO_NO_CXX11_NUMERIC_LIMITS
# define BHO_NO_CXX11_ALLOCATOR
# define BHO_NO_CXX11_POINTER_TRAITS
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
# define BHO_NO_CXX11_SMART_PTR
# define BHO_NO_CXX11_HDR_FUNCTIONAL
# define BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_STD_ALIGN
# define BHO_NO_CXX11_ADDRESSOF
# define BHO_NO_CXX11_HDR_EXCEPTION
#if defined(__has_include)
#if !__has_include(<shared_mutex>)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#elif __cplusplus < 201402
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#else
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
// C++14 features
# define BHO_NO_CXX14_STD_EXCHANGE
// C++17 features
# define BHO_NO_CXX17_STD_APPLY
# define BHO_NO_CXX17_STD_INVOKE
# define BHO_NO_CXX17_ITERATOR_TRAITS
#define BHO_STDLIB "Metrowerks Standard Library version " BHO_STRINGIZE(__MSL_CPP__)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_HP_ACC_H
#define BHO_PREDEF_COMPILER_HP_ACC_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_HPACC`
HP a{CPP} compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__HP_aCC+` | {predef_detection}
| `+__HP_aCC+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_HPACC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__HP_aCC)
# if !defined(BHO_COMP_HPACC_DETECTION) && (__HP_aCC > 1)
# define BHO_COMP_HPACC_DETECTION BHO_PREDEF_MAKE_10_VVRRPP(__HP_aCC)
# endif
# if !defined(BHO_COMP_HPACC_DETECTION)
# define BHO_COMP_HPACC_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_COMP_HPACC_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_HPACC_EMULATED BHO_COMP_HPACC_DETECTION
# else
# undef BHO_COMP_HPACC
# define BHO_COMP_HPACC BHO_COMP_HPACC_DETECTION
# endif
# define BHO_COMP_HPACC_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_HPACC_NAME "HP aC++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_HPACC,BHO_COMP_HPACC_NAME)
#ifdef BHO_COMP_HPACC_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_HPACC_EMULATED,BHO_COMP_HPACC_NAME)
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_PARISC_H
#define BHO_PREDEF_ARCHITECTURE_PARISC_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_PARISC`
http://en.wikipedia.org/wiki/PA-RISC_family[HP/PA RISC] architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__hppa__+` | {predef_detection}
| `+__hppa+` | {predef_detection}
| `+__HPPA__+` | {predef_detection}
| `+_PA_RISC1_0+` | 1.0.0
| `+_PA_RISC1_1+` | 1.1.0
| `+__HPPA11__+` | 1.1.0
| `+__PA7100__+` | 1.1.0
| `+_PA_RISC2_0+` | 2.0.0
| `+__RISC2_0__+` | 2.0.0
| `+__HPPA20__+` | 2.0.0
| `+__PA8000__+` | 2.0.0
|===
*/ // end::reference[]
#define BHO_ARCH_PARISC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__hppa__) || defined(__hppa) || defined(__HPPA__)
# undef BHO_ARCH_PARISC
# if !defined(BHO_ARCH_PARISC) && (defined(_PA_RISC1_0))
# define BHO_ARCH_PARISC BHO_VERSION_NUMBER(1,0,0)
# endif
# if !defined(BHO_ARCH_PARISC) && (defined(_PA_RISC1_1) || defined(__HPPA11__) || defined(__PA7100__))
# define BHO_ARCH_PARISC BHO_VERSION_NUMBER(1,1,0)
# endif
# if !defined(BHO_ARCH_PARISC) && (defined(_PA_RISC2_0) || defined(__RISC2_0__) || defined(__HPPA20__) || defined(__PA8000__))
# define BHO_ARCH_PARISC BHO_VERSION_NUMBER(2,0,0)
# endif
# if !defined(BHO_ARCH_PARISC)
# define BHO_ARCH_PARISC BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BHO_ARCH_PARISC
# define BHO_ARCH_PARISC_AVAILABLE
#endif
#if BHO_ARCH_PARISC
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_PARISC_NAME "HP/PA RISC"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_PARISC,BHO_ARCH_PARISC_NAME)
<file_sep>// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2002 - 2003.
// (C) Copyright <NAME> 2002.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// CodeGear C++ compiler setup:
//
// versions check:
// last known and checked version is 0x740
#if (__CODEGEARC__ > 0x740)
# if defined(BHO_ASSERT_CONFIG)
# error "boost: Unknown compiler version - please run the configure tests and report the results"
# else
# pragma message( "boost: Unknown compiler version - please run the configure tests and report the results")
# endif
#endif
#ifdef __clang__ // Clang enhanced Windows compiler
# include "clang.hpp"
# define BHO_NO_CXX11_THREAD_LOCAL
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
// This bug has been reported to Embarcadero
#if defined(BHO_HAS_INT128)
#undef BHO_HAS_INT128
#endif
#if defined(BHO_HAS_FLOAT128)
#undef BHO_HAS_FLOAT128
#endif
// The clang-based compilers can not do 128 atomic exchanges
#define BHO_ATOMIC_NO_CMPXCHG16B
// 32 functions are missing from the current RTL in cwchar, so it really can not be used even if it exists
# define BHO_NO_CWCHAR
# ifndef __MT__ /* If compiling in single-threaded mode, assume there is no CXX11_HDR_ATOMIC */
# define BHO_NO_CXX11_HDR_ATOMIC
# endif
/* temporarily disable this until we can link against fegetround fesetround feholdexcept */
#define BHO_NO_FENV_H
/* Reported this bug to Embarcadero with the latest C++ Builder Rio release */
#define BHO_NO_CXX11_HDR_EXCEPTION
//
// check for exception handling support:
//
#if !defined(_CPPUNWIND) && !defined(__EXCEPTIONS) && !defined(BHO_NO_EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
#endif
/*
// On non-Win32 platforms let the platform config figure this out:
#ifdef _WIN32
# define BHO_HAS_STDINT_H
#endif
//
// __int64:
//
#if !defined(__STRICT_ANSI__)
# define BHO_HAS_MS_INT64
#endif
//
// all versions have a <dirent.h>:
//
#if !defined(__STRICT_ANSI__)
# define BHO_HAS_DIRENT_H
#endif
//
// Disable Win32 support in ANSI mode:
//
# pragma defineonoption BHO_DISABLE_WIN32 -A
//
// MSVC compatibility mode does some nasty things:
// TODO: look up if this doesn't apply to the whole 12xx range
//
#if defined(_MSC_VER) && (_MSC_VER <= 1200)
# define BHO_NO_ARGUMENT_DEPENDENT_LOOKUP
# define BHO_NO_VOID_RETURNS
#endif
//
*/
// Specific settings for Embarcadero drivers
# define BHO_EMBTC __CODEGEARC__
# define BHO_EMBTC_FULL_VER ((__clang_major__ << 16) | \
(__clang_minor__ << 8) | \
__clang_patchlevel__ )
// Detecting which Embarcadero driver is being used
#if defined(BHO_EMBTC)
# if defined(_WIN64)
# define BHO_EMBTC_WIN64 1
# define BHO_EMBTC_WINDOWS 1
# ifndef BHO_USE_WINDOWS_H
# define BHO_USE_WINDOWS_H
# endif
# elif defined(_WIN32)
# define BHO_EMBTC_WIN32C 1
# define BHO_EMBTC_WINDOWS 1
# ifndef BHO_USE_WINDOWS_H
# define BHO_USE_WINDOWS_H
# endif
# elif defined(__APPLE__) && defined(__arm__)
# define BHO_EMBTC_IOSARM 1
# define BHO_EMBTC_IOS 1
# elif defined(__APPLE__) && defined(__aarch64__)
# define BHO_EMBTC_IOSARM64 1
# define BHO_EMBTC_IOS 1
# elif defined(__ANDROID__) && defined(__arm__)
# define BHO_EMBTC_AARM 1
# define BHO_EMBTC_ANDROID 1
# elif
# if defined(BHO_ASSERT_CONFIG)
# error "Unknown Embarcadero driver"
# else
# warning "Unknown Embarcadero driver"
# endif /* defined(BHO_ASSERT_CONFIG) */
# endif
#endif /* defined(BHO_EMBTC) */
#if defined(BHO_EMBTC_WINDOWS)
#if !defined(_chdir)
#define _chdir(x) chdir(x)
#endif
#if !defined(_dup2)
#define _dup2(x,y) dup2(x,y)
#endif
#endif
# undef BHO_COMPILER
# define BHO_COMPILER "Embarcadero-Clang C++ version " BHO_STRINGIZE(__CODEGEARC__) " clang: " __clang_version__
// # define __CODEGEARC_CLANG__ __CODEGEARC__
// # define __EMBARCADERO_CLANG__ __CODEGEARC__
// # define __BORLANDC_CLANG__ __BORLANDC__
#else // #if !defined(__clang__)
# define BHO_CODEGEARC __CODEGEARC__
# define BHO_BORLANDC __BORLANDC__
#if !defined( BHO_WITH_CODEGEAR_WARNINGS )
// these warnings occur frequently in optimized template code
# pragma warn -8004 // var assigned value, but never used
# pragma warn -8008 // condition always true/false
# pragma warn -8066 // dead code can never execute
# pragma warn -8104 // static members with ctors not threadsafe
# pragma warn -8105 // reference member in class without ctors
#endif
// CodeGear C++ Builder 2009
#if (__CODEGEARC__ <= 0x613)
# define BHO_NO_INTEGRAL_INT64_T
# define BHO_NO_DEPENDENT_NESTED_DERIVATIONS
# define BHO_NO_PRIVATE_IN_AGGREGATE
# define BHO_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE
// we shouldn't really need this - but too many things choke
// without it, this needs more investigation:
# define BHO_NO_LIMITS_COMPILE_TIME_CONSTANTS
# define BHO_SP_NO_SP_CONVERTIBLE
#endif
// CodeGear C++ Builder 2010
#if (__CODEGEARC__ <= 0x621)
# define BHO_NO_TYPENAME_WITH_CTOR // Cannot use typename keyword when making temporaries of a dependant type
# define BHO_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL
# define BHO_NO_MEMBER_TEMPLATE_FRIENDS
# define BHO_NO_NESTED_FRIENDSHIP // TC1 gives nested classes access rights as any other member
# define BHO_NO_USING_TEMPLATE
# define BHO_NO_TWO_PHASE_NAME_LOOKUP
// Temporary hack, until specific MPL preprocessed headers are generated
# define BHO_MPL_CFG_NO_PREPROCESSED_HEADERS
// CodeGear has not yet completely implemented value-initialization, for
// example for array types, as I reported in 2010: Embarcadero Report 83751,
// "Value-initialization: arrays should have each element value-initialized",
// http://qc.embarcadero.com/wc/qcmain.aspx?d=83751
// Last checked version: Embarcadero C++ 6.21
// See also: http://www.boost.org/libs/utility/value_init.htm#compiler_issues
// (<NAME>, LKEB, April 2010)
# define BHO_NO_COMPLETE_VALUE_INITIALIZATION
# if defined(NDEBUG) && defined(__cplusplus)
// fix broken <cstring> so that Boost.test works:
# include <cstring>
# undef strcmp
# endif
// fix broken errno declaration:
# include <errno.h>
# ifndef errno
# define errno errno
# endif
#endif
// Reportedly, #pragma once is supported since C++ Builder 2010
#if (__CODEGEARC__ >= 0x620)
# define BHO_HAS_PRAGMA_ONCE
#endif
#define BHO_NO_FENV_H
//
// C++0x macros:
//
#if (__CODEGEARC__ <= 0x620)
#define BHO_NO_CXX11_STATIC_ASSERT
#else
#define BHO_HAS_STATIC_ASSERT
#endif
#define BHO_HAS_CHAR16_T
#define BHO_HAS_CHAR32_T
#define BHO_HAS_LONG_LONG
// #define BHO_HAS_ALIGNOF
#define BHO_HAS_DECLTYPE
#define BHO_HAS_EXPLICIT_CONVERSION_OPS
// #define BHO_HAS_RVALUE_REFS
#define BHO_HAS_SCOPED_ENUM
// #define BHO_HAS_STATIC_ASSERT
#define BHO_HAS_STD_TYPE_TRAITS
#define BHO_NO_CXX11_AUTO_DECLARATIONS
#define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#define BHO_NO_CXX11_CONSTEXPR
#define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#define BHO_NO_CXX11_DELETED_FUNCTIONS
#define BHO_NO_CXX11_EXTERN_TEMPLATE
#define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define BHO_NO_CXX11_LAMBDAS
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RANGE_BASED_FOR
#define BHO_NO_CXX11_RAW_LITERALS
#define BHO_NO_CXX11_RVALUE_REFERENCES
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_CXX11_SFINAE_EXPR
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_UNICODE_LITERALS
#define BHO_NO_CXX11_VARIADIC_TEMPLATES
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#define BHO_NO_CXX11_USER_DEFINED_LITERALS
#define BHO_NO_CXX11_ALIGNAS
#define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#define BHO_NO_CXX11_INLINE_NAMESPACES
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_FINAL
#define BHO_NO_CXX11_OVERRIDE
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_DECLTYPE_N3276
#define BHO_NO_CXX11_UNRESTRICTED_UNION
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
//
// TR1 macros:
//
#define BHO_HAS_TR1_HASH
#define BHO_HAS_TR1_TYPE_TRAITS
#define BHO_HAS_TR1_UNORDERED_MAP
#define BHO_HAS_TR1_UNORDERED_SET
#define BHO_HAS_MACRO_USE_FACET
#define BHO_NO_CXX11_HDR_INITIALIZER_LIST
// On non-Win32 platforms let the platform config figure this out:
#ifdef _WIN32
# define BHO_HAS_STDINT_H
#endif
//
// __int64:
//
#if !defined(__STRICT_ANSI__)
# define BHO_HAS_MS_INT64
#endif
//
// check for exception handling support:
//
#if !defined(_CPPUNWIND) && !defined(BHO_CPPUNWIND) && !defined(__EXCEPTIONS) && !defined(BHO_NO_EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
#endif
//
// all versions have a <dirent.h>:
//
#if !defined(__STRICT_ANSI__)
# define BHO_HAS_DIRENT_H
#endif
//
// all versions support __declspec:
//
#if defined(__STRICT_ANSI__)
// config/platform/win32.hpp will define BHO_SYMBOL_EXPORT, etc., unless already defined
# define BHO_SYMBOL_EXPORT
#endif
//
// ABI fixing headers:
//
#ifndef BHO_ABI_PREFIX
# define BHO_ABI_PREFIX "asio2/bho/config/abi/borland_prefix.hpp"
#endif
#ifndef BHO_ABI_SUFFIX
# define BHO_ABI_SUFFIX "asio2/bho/config/abi/borland_suffix.hpp"
#endif
//
// Disable Win32 support in ANSI mode:
//
# pragma defineonoption BHO_DISABLE_WIN32 -A
//
// MSVC compatibility mode does some nasty things:
// TODO: look up if this doesn't apply to the whole 12xx range
//
#if defined(_MSC_VER) && (_MSC_VER <= 1200)
# define BHO_NO_ARGUMENT_DEPENDENT_LOOKUP
# define BHO_NO_VOID_RETURNS
#endif
#define BHO_COMPILER "CodeGear C++ version " BHO_STRINGIZE(__CODEGEARC__)
#endif // #if !defined(__clang__)
<file_sep>#include "unit_test.hpp"
#define ASIO2_ENABLE_RPC_INVOKER_THREAD_SAFE
#include <asio2/config.hpp>
#undef ASIO2_USE_WEBSOCKET_RPC
#include <asio2/rpc/rpc_server.hpp>
#include <asio2/rpc/rpc_client.hpp>
#include <asio2/external/json.hpp>
struct userinfo
{
std::string name;
int age;
std::map<int, std::string> purview;
// User defined object types require serialized the members like this:
template <class Archive>
void serialize(Archive & ar)
{
ar(name);
ar(age);
ar(purview);
}
};
namespace nlohmann
{
void operator<<(asio2::rpc::oarchive& sr, const nlohmann::json& j)
{
sr << j.dump();
}
void operator>>(asio2::rpc::iarchive& dr, nlohmann::json& j)
{
std::string v;
dr >> v;
j = nlohmann::json::parse(v);
}
}
std::string echo(std::string s)
{
return s;
}
int add(int a, int b)
{
return a + b;
}
rpc::future<int> async_add(int a, int b)
{
rpc::promise<int> promise;
rpc::future<int> f = promise.get_future();
std::thread([a, b, promise = std::move(promise)]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
promise.set_value(a + b);
}).detach();
return f;
}
rpc::future<void> async_test(std::shared_ptr<asio2::rpc_session>& session_ptr, std::string a, std::string b)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
rpc::promise<void> promise;
rpc::future<void> f = promise.get_future();
ASIO2_CHECK(a == "abc" && b == "def");
std::thread([a, b, promise]() mutable
{
asio2::ignore_unused(a, b);
promise.set_value();
}).detach();
return f;
}
nlohmann::json test_json(nlohmann::json j)
{
std::string s = j.dump();
return nlohmann::json::parse(s);
}
class usercrud
{
public:
double mul(double a, double b)
{
return a * b;
}
// If you want to know which client called this function, set the first parameter
// to std::shared_ptr<asio2::rpc_session>& session_ptr
userinfo get_user(std::shared_ptr<asio2::rpc_session>& session_ptr)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
userinfo u;
u.name = "lilei";
u.age = 32;
u.purview = { {1,"read"},{2,"write"} };
return u;
}
// If you want to know which client called this function, set the first parameter
// to std::shared_ptr<asio2::rpc_session>& session_ptr
void del_user(std::shared_ptr<asio2::rpc_session>& session_ptr, const userinfo& u)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(u.name == "hanmeimei");
ASIO2_CHECK(u.age == 33);
ASIO2_CHECK(u.purview.size() == 2);
for (auto&[k, v] : u.purview)
{
ASIO2_CHECK(k == 10 || k == 20);
if (k == 10) ASIO2_CHECK(v == "get");
if (k == 20) ASIO2_CHECK(v == "set");
}
}
};
void heartbeat(std::shared_ptr<asio2::rpc_session>& session_ptr)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
}
// set the first parameter to client reference to know which client was called
void client_fn_test(asio2::rpc_client& client, std::string str)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(str == "i love you");
}
class my_rpc_client_tcp : public asio2::rpc_client_use<asio2::net_protocol::tcp>
{
public:
using rpc_client_use<asio2::net_protocol::tcp>::rpc_client_use;
using super::send;
using super::async_send;
};
void rpc_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
// test max buffer size
{
asio2::rpc_server server(512, 1024, 4);
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
server.bind("echo", echo);
server.unbind("test_guard_by");
ASIO2_CHECK(server.find("echo") != nullptr);
bool server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::rpc_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
std::atomic<int> client_start_failed_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::rpc_client>());
asio2::rpc_client& client = *iter;
// set default rpc call timeout
client.set_default_timeout(std::chrono::seconds(3));
ASIO2_CHECK(client.get_default_timeout() == std::chrono::seconds(3));
client.set_auto_reconnect(false);
ASIO2_CHECK(!client.is_auto_reconnect());
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18010);
client_connect_counter++;
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
bool client_start_ret = client.start("127.0.0.1", 18010);
if (!client_start_ret)
client_start_failed_counter++;
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
}
while (server.get_session_count() < std::size_t(test_client_count - client_start_failed_counter))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
while (client_connect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
std::string msg;
msg.resize(1500);
for (int i = 0; i < test_client_count; i++)
{
auto& clt = clients[i];
clients[i]->async_call("echo", msg).response([&clt](std::string s)
{
ASIO2_CHECK(s.empty());
// when send data failed, the error is not rpc::error::operation_aborted,
ASIO2_CHECK(asio2::get_last_error() == rpc::error::operation_aborted);
if (asio2::get_last_error() != rpc::error::operation_aborted)
{
// close the socket, this will trigger the auto reconnect
clt->socket().close();
}
});
}
while (client_disconnect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count- client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
client_start_failed_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18010);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count - client_start_failed_counter))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
while (client_connect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
auto& clt = clients[i];
clients[i]->async_call("echo", msg).response([&clt](std::string s)
{
ASIO2_CHECK(s.empty());
// when send data failed, the error is not rpc::error::operation_aborted,
ASIO2_CHECK(asio2::get_last_error() == rpc::error::operation_aborted);
if (asio2::get_last_error() != rpc::error::operation_aborted)
{
// close the socket, this will trigger the auto reconnect
clt->socket().close();
}
});
}
while (client_disconnect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test illegal data
{
asio2::rpc_server server;
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
server.bind("echo", echo);
bool server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<my_rpc_client_tcp>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
std::atomic<int> client_start_failed_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<my_rpc_client_tcp>());
my_rpc_client_tcp& client = *iter;
// set default rpc call timeout
client.set_default_timeout(std::chrono::seconds(3));
ASIO2_CHECK(client.get_default_timeout() == std::chrono::seconds(3));
client.set_auto_reconnect(false);
ASIO2_CHECK(!client.is_auto_reconnect());
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18010);
ASIO2_CHECK(client.is_started());
client_connect_counter++;
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
bool client_start_ret = client.start("127.0.0.1", 18010);
if (!client_start_ret)
client_start_failed_counter++;
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
}
while (server.get_session_count() < std::size_t(test_client_count - client_start_failed_counter))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
while (client_connect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
std::string msg;
while (client_disconnect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK(client_disconnect_counter, client_connect_counter, client_start_failed_counter);
msg.clear();
int len = 200 + (std::rand() % 200);
for (int i = 0; i < len; i++)
{
msg += (char)(std::rand() % 255);
}
// send random data to server for every client, if the data is invalid, the session will be closed
for (int i = 0; i < test_client_count; i++)
{
clients[i]->async_send(msg);
}
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK( clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
client_start_failed_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18010);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count - client_start_failed_counter))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
while (client_connect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
while (client_disconnect_counter < test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK(client_disconnect_counter, client_connect_counter, client_start_failed_counter);
msg.clear();
int len = 200 + (std::rand() % 200);
for (int i = 0; i < len; i++)
{
msg += (char)(std::rand() % 255);
}
// send random data to server for every client, if the data is invalid, the session will be closed
for (int i = 0; i < test_client_count; i++)
{
clients[i]->async_send(msg);
}
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK( clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
}
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count - client_start_failed_counter)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test max buffer size and auto reconnect
{
struct ext_data
{
int data_zie = 0;
int send_counter = 0;
int client_init_counter = 0;
int client_connect_counter = 0;
int client_disconnect_counter = 0;
std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now();
};
asio2::rpc_server server(512, 1024, 4);
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
server.bind("echo", echo);
bool server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::rpc_client>> clients;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::rpc_client>());
asio2::rpc_client& client = *iter;
// set default rpc call timeout
client.set_default_timeout(std::chrono::seconds(3));
ASIO2_CHECK(client.get_default_timeout() == std::chrono::seconds(3));
client.set_connect_timeout(std::chrono::milliseconds(100));
client.set_auto_reconnect(true, std::chrono::milliseconds(100));
ASIO2_CHECK(client.is_auto_reconnect());
ASIO2_CHECK(client.get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ASIO2_CHECK(client.get_connect_timeout() == std::chrono::milliseconds(100));
client.bind_init([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
if (asio2::get_last_error())
return;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18010);
ext_data& ex = client.get_user_data<ext_data&>();
std::string msg;
msg.resize(ex.data_zie);
client.async_call("echo", msg).response([&client](std::string s)
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.send_counter++;
if (ex.data_zie <= 1024)
{
ASIO2_CHECK(!s.empty());
ASIO2_CHECK_VALUE(asio2::last_error_msg(), !asio2::get_last_error());
}
else
{
ASIO2_CHECK(s.empty());
// when send data failed, the error is not rpc::error::operation_aborted,
// and the server can't recv the illage data, and the server will can't
// disconnect this client, this will cause client_connect_counter can't
// be equal to 3.
if (asio2::get_last_error() != rpc::error::operation_aborted)
{
// close the socket, this will trigger the auto reconnect
client.socket().close();
}
}
});
ex.client_connect_counter++;
if (ex.client_connect_counter == 1)
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - ex.start_time).count() - 100);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= test_timer_deviation);
}
else
{
auto elapse1 = std::abs(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - ex.start_time).count() - 200);
ASIO2_CHECK_VALUE(elapse1, elapse1 <= test_timer_deviation);
}
ex.start_time = std::chrono::high_resolution_clock::now();
if (ex.client_connect_counter == 3)
{
client.set_auto_reconnect(false);
ASIO2_CHECK(!client.is_auto_reconnect());
}
});
client.bind_disconnect([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
ext_data ex;
ex.data_zie = 1500;
client.set_user_data(std::move(ex));
bool client_start_ret = client.start("127.0.0.1", 18010);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter, ex.client_init_counter == 3);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 3);
}
while (server_connect_counter < test_client_count * 3)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count * 3);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count * 3);
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_disconnect_counter < 3)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_disconnect_counter, ex.client_disconnect_counter == 3);
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK( clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
ASIO2_CHECK(!clients[i]->user_data_any().has_value());
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
//while (server_disconnect_counter != test_client_count * 3)
while (server_disconnect_counter < test_client_count * 3)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count*3);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
for (int i = 0; i < test_client_count; i++)
{
asio2::rpc_client& client = *clients[i];
ASIO2_CHECK(client.get_default_timeout() == std::chrono::seconds(3));
client.set_auto_reconnect(true, std::chrono::milliseconds(100));
ASIO2_CHECK(client.is_auto_reconnect());
ASIO2_CHECK(client.get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ASIO2_CHECK(client.get_connect_timeout() == std::chrono::milliseconds(100));
ext_data ex;
ex.data_zie = 500;
client.set_user_data(std::move(ex));
bool client_start_ret = client.start("127.0.0.1", 18010);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter, ex.client_init_counter == 1);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 1);
}
while (server_connect_counter < test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count * 1);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count * 1);
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK( clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.send_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK( clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
ASIO2_CHECK(!clients[i]->user_data_any().has_value());
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count*1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test rpc function
{
struct ext_data
{
int async_call_counter = 0;
int sync_call_counter = 0;
int client_init_counter = 0;
int client_connect_counter = 0;
int client_disconnect_counter = 0;
};
asio2::rpc_server server;
std::atomic<int> server_accept_counter = 0;
std::atomic<int> server_async_call_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
session_ptr->async_call([&, session_ptr](int v)
{
server_async_call_counter++;
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 15 - 6);
}, std::chrono::seconds(10), "sub", 15, 6);
session_ptr->async_call("test", "i love you");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
server.bind("echo", echo);
usercrud crud;
server
.bind("add", add)
.bind("mul", &usercrud::mul, crud)
.bind("get_user", &usercrud::get_user, crud)
.bind("del_user", &usercrud::del_user, &crud);
server.bind("async_add", async_add);
server.bind("async_test", async_test);
server.bind("test_json", test_json);
server.bind("heartbeat", heartbeat);
server.bind("cat", [&](std::shared_ptr<asio2::rpc_session>& session_ptr,
const std::string& a, const std::string& b)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
// Nested call rpc function in business function is ok.
session_ptr->async_call([&, session_ptr](int v) mutable
{
server_async_call_counter++;
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 15 - 8);
// Nested call rpc function in business function is ok.
session_ptr->async_call([&, session_ptr](int v)
{
server_async_call_counter++;
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 15 + 18);
}, "async_add", 15, 18);
}, "sub", 15, 8);
return a + b;
});
bool server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::rpc_client>> clients;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::rpc_client>());
asio2::rpc_client& client = *iter;
// set default rpc call timeout
client.set_default_timeout(std::chrono::seconds(3));
ASIO2_CHECK(client.get_default_timeout() == std::chrono::seconds(3));
client.set_auto_reconnect(false);
ASIO2_CHECK(!client.is_auto_reconnect());
client.bind_init([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
if (asio2::get_last_error())
return;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18010);
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_connect_counter++;
//------------------------------------------------------------------
client.call<double>("mul", 16.5, 26.5);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::in_progress);
client.async_call([&](int v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 12 + 11);
ex.async_call_counter++;
}, std::chrono::seconds(13), "add", 12, 11);
client.async_call([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ex.async_call_counter++;
}, std::chrono::seconds(3), "heartbeat");
nlohmann::json j = nlohmann::json::object();
j["name"] = "lilei";
j["age"] = 30;
client.async_call("test_json", j).response([&](nlohmann::json js)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ex.async_call_counter++;
std::string s = js.dump();
ASIO2_CHECK(js["age"].get<int>() == 30);
ASIO2_CHECK(js["name"].get<std::string>() == "lilei");
asio2::ignore_unused(js, s);
});
// param 2 is empty, use the default_timeout
client.async_call([&](int v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 12 + 21);
ex.async_call_counter++;
}, "add", 12, 21);
// param 1 is empty, the result of the rpc call is not returned
client.async_call("mul0", 2.5, 2.5);
// Chain calls :
client.set_timeout(std::chrono::seconds(5)).async_call("mul", 2.5, 2.5).response([&](double v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 2.5 * 2.5);
ex.async_call_counter++;
});
// Chain calls :
client.timeout(std::chrono::seconds(13)).response([&](double v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 3.5 * 3.5);
ex.async_call_counter++;
}).async_call("mul", 3.5, 3.5);
// Chain calls :
client.response([&](double v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 4.5 * 4.5);
ex.async_call_counter++;
}).timeout(std::chrono::seconds(5)).async_call("mul", 4.5, 4.5);
// Chain calls :
client.async_call("mul", 5.5, 5.5).response([&](double v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 5.5 * 5.5);
ex.async_call_counter++;
}).timeout(std::chrono::seconds(10));
client.async_call([&](int v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 1 + 11);
ex.async_call_counter++;
}, std::chrono::seconds(3), "async_add", 1, 11);
client.async_call([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ex.async_call_counter++;
}, std::chrono::seconds(3), "async_test", "abc", "def");
});
client.bind_disconnect([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
// bind a rpc function in client, the server will call this client's rpc function
client.bind("sub", [](int a, int b) { return a - b; });
client.bind("async_add", async_add);
client.bind("test", client_fn_test);
ext_data ex;
client.set_user_data(std::move(ex));
bool client_start_ret = client.start("127.0.0.1", 18010);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
nlohmann::json j = nlohmann::json::object();
j["name"] = "hanmeimei";
j["age"] = 20;
nlohmann::json j2 = client.call<nlohmann::json>(std::chrono::minutes(1), "test_json", j);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(j2["age"].get<int>() == 20);
ASIO2_CHECK(j2["name"].get<std::string>() == "hanmeimei");
double mul = client.call<double>(std::chrono::seconds(3), "mul", 6.5, 6.5);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(mul == 6.5 * 6.5);
userinfo u;
u = client.call<userinfo>("get_user");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(u.name == "lilei" && u.age == 32 && u.purview.size() == 2);
for (auto &[k, v] : u.purview)
{
ASIO2_CHECK(k == 1 || k == 2);
if (k == 1) ASIO2_CHECK(v == "read");
if (k == 2) ASIO2_CHECK(v == "write");
}
u.name = "hanmeimei";
u.age = 33;
u.purview = { {10,"get"},{20,"set"} };
client.async_call([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
}, "del_user", u);
// just call rpc function, don't need the rpc result
client.async_call("del_user", u);
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", "hanmeimei").response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", 10, std::string("lilei"), 1).response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", u, std::string("lilei"), 1).response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// Chain calls :
int sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 12);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sum == 11 + 12);
// Chain calls :
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 32);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sum == 11 + 32);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", "11", 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
// Chain calls :
std::string str = client.call<std::string>("cat", "abc", "123");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(str == "abc123");
client.async_call([&](int)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::not_found);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
}, "no_exists_fn", 10);
sum = client.timeout(std::chrono::seconds(13)).call<int>("no_exists_fn", 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::not_found);
ASIO2_CHECK(sum == 0);
}
server.call<int>(std::chrono::milliseconds(100), "sub", 10, 2);
server.call<int>("sub", 10, 2);
server.async_call([](int v) mutable
{
if (!asio2::get_last_error())
ASIO2_CHECK(v == 7);
}, "sub", 15, 8);
server.async_call([](int v) mutable
{
if (!asio2::get_last_error())
ASIO2_CHECK(v == 7);
}, std::chrono::milliseconds(100), "sub", 15, 8);
server.async_call<int>([](auto v) mutable
{
if (!asio2::get_last_error())
ASIO2_CHECK(v == 7);
}, "sub", 15, 8);
server.async_call<int>([](auto v) mutable
{
if (!asio2::get_last_error())
ASIO2_CHECK(v == 7);
}, std::chrono::milliseconds(100), "sub", 15, 8);
server.async_call("sub", 15, 8);
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter, ex.client_init_counter == 1);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 1);
}
while (server_connect_counter < test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count * 1);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count * 1);
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK( clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.async_call_counter < 15)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.async_call_counter, ex.async_call_counter == 15);
}
while (server_async_call_counter < test_client_count * 3)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_async_call_counter.load(), server_async_call_counter == test_client_count * 3);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK( clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
ASIO2_CHECK(!clients[i]->user_data_any().has_value());
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count*1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_async_call_counter = 0;
server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
for (int i = 0; i < test_client_count; i++)
{
asio2::rpc_client& client = *clients[i];
ASIO2_CHECK(client.get_default_timeout() == std::chrono::seconds(3));
client.set_auto_reconnect(true, std::chrono::milliseconds(100));
ASIO2_CHECK(client.is_auto_reconnect());
ASIO2_CHECK(client.get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ext_data ex;
client.set_user_data(std::move(ex));
bool client_start_ret = client.async_start("127.0.0.1", 18010);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter, ex.client_init_counter == 1);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 1);
}
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK( clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
asio2::rpc_client& client = *clients[i];
nlohmann::json j = nlohmann::json::object();
j["name"] = "hanmeimei";
j["age"] = 20;
nlohmann::json j2 = client.call<nlohmann::json>(std::chrono::minutes(1), "test_json", j);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(j2["age"].get<int>() == 20);
ASIO2_CHECK(j2["name"].get<std::string>() == "hanmeimei");
double mul = client.call<double>(std::chrono::seconds(3), "mul", 6.5, 6.5);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(mul == 6.5 * 6.5);
userinfo u;
u = client.call<userinfo>("get_user");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(u.name == "lilei" && u.age == 32 && u.purview.size() == 2);
for (auto &[k, v] : u.purview)
{
ASIO2_CHECK(k == 1 || k == 2);
if (k == 1) ASIO2_CHECK(v == "read");
if (k == 2) ASIO2_CHECK(v == "write");
}
u.name = "hanmeimei";
u.age = 33;
u.purview = { {10,"get"},{20,"set"} };
client.async_call([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
}, "del_user", u);
// just call rpc function, don't need the rpc result
client.async_call("del_user", u);
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", "hanmeimei").response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", 10, std::string("lilei"), 1).response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", u, std::string("lilei"), 1).response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// Chain calls :
int sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 12);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sum == 11 + 12);
// Chain calls :
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 32);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sum == 11 + 32);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", "11", 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
// Chain calls :
std::string str = client.call<std::string>("cat", "abc", "123");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(str == "abc123");
client.async_call([&](int)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::not_found);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
}, "no_exists_fn", 10);
sum = client.timeout(std::chrono::seconds(13)).call<int>("no_exists_fn", 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::not_found);
ASIO2_CHECK(sum == 0);
}
while (server_connect_counter < test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count * 1);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count * 1);
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK( clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.async_call_counter < 15)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.async_call_counter, ex.async_call_counter == 15);
}
while (server_async_call_counter < test_client_count * 3)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_async_call_counter.load(), server_async_call_counter == test_client_count * 3);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK( clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
ASIO2_CHECK(!clients[i]->user_data_any().has_value());
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count*1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test websocket rpc function
{
struct ext_data
{
int async_call_counter = 0;
int sync_call_counter = 0;
int client_init_counter = 0;
int client_connect_counter = 0;
int client_disconnect_counter = 0;
};
asio2::rpc_server_use<asio2::net_protocol::ws> server;
std::atomic<int> server_accept_counter = 0;
std::atomic<int> server_async_call_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
session_ptr->async_call([&, session_ptr](int v)
{
server_async_call_counter++;
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 15 - 6);
}, std::chrono::seconds(10), "sub", 15, 6);
session_ptr->async_call("test", "i love you");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
asio2::ignore_unused(session_ptr);
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18010);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
server.bind("echo", echo);
usercrud crud;
server
.bind("add", add)
.bind("mul", &usercrud::mul, crud)
.bind("get_user", []
(std::shared_ptr<asio2::rpc_session_use<asio2::net_protocol::ws>>& session_ptr)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
userinfo u;
u.name = "lilei";
u.age = 32;
u.purview = { {1,"read"},{2,"write"} };
return u;
})
.bind("del_user", []
(std::shared_ptr<asio2::rpc_session_use<asio2::net_protocol::ws>>& session_ptr, const userinfo& u)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(u.name == "hanmeimei");
ASIO2_CHECK(u.age == 33);
ASIO2_CHECK(u.purview.size() == 2);
for (auto&[k, v] : u.purview)
{
ASIO2_CHECK(k == 10 || k == 20);
if (k == 10) ASIO2_CHECK(v == "get");
if (k == 20) ASIO2_CHECK(v == "set");
}
});
server.bind("async_add", async_add);
server.bind("async_test", []
(std::shared_ptr<asio2::rpc_session_use<asio2::net_protocol::ws>>& session_ptr, std::string a, std::string b)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
rpc::promise<void> promise;
rpc::future<void> f = promise.get_future();
ASIO2_CHECK(a == "abc" && b == "def");
std::thread([a, b, promise]() mutable
{
asio2::ignore_unused(a, b);
promise.set_value();
}).detach();
return f;
});
server.bind("test_json", test_json);
server.bind("heartbeat", []
(std::shared_ptr<asio2::rpc_session_use<asio2::net_protocol::ws>>& session_ptr)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
server.bind("cat", [&](std::shared_ptr<asio2::rpc_session_use<asio2::net_protocol::ws>>& session_ptr,
const std::string& a, const std::string& b)
{
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
// Nested call rpc function in business function is ok.
session_ptr->async_call([&, session_ptr](int v) mutable
{
server_async_call_counter++;
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 15 - 8);
// Nested call rpc function in business function is ok.
session_ptr->async_call([&, session_ptr](int v)
{
server_async_call_counter++;
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 15 + 18);
}, "async_add", 15, 18);
}, "sub", 15, 8);
return a + b;
});
bool server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::rpc_client_use<asio2::net_protocol::ws>>> clients;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::rpc_client_use<asio2::net_protocol::ws>>());
asio2::rpc_client_use<asio2::net_protocol::ws>& client = *iter;
// set default rpc call timeout
client.set_default_timeout(std::chrono::seconds(3));
ASIO2_CHECK(client.get_default_timeout() == std::chrono::seconds(3));
client.set_auto_reconnect(false);
ASIO2_CHECK(!client.is_auto_reconnect());
client.bind_init([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
if (asio2::get_last_error())
return;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18010);
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_connect_counter++;
//------------------------------------------------------------------
client.call<double>("mul", 16.5, 26.5);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::in_progress);
client.async_call([&](int v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 12 + 11);
ex.async_call_counter++;
}, std::chrono::seconds(13), "add", 12, 11);
client.async_call<int>([&](auto v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 112 + 11);
ex.async_call_counter++;
}, std::chrono::seconds(13), "add", 112, 11);
client.async_call<int>([&](int v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 1112 + 11);
ex.async_call_counter++;
}, std::chrono::seconds(13), "add", 1112, 11);
client.async_call<std::string>([&](auto v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ex.async_call_counter++;
ASIO2_CHECK(v == "abcdef0123456789xx");
}, "echo", "abcdef0123456789xx");
client.async_call<std::string>([&](std::string v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == "xxabcdef0123456789");
ex.async_call_counter++;
}, "echo", "xxabcdef0123456789");
client.async_call([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ex.async_call_counter++;
}, std::chrono::seconds(3), "heartbeat");
nlohmann::json j = nlohmann::json::object();
j["name"] = "lilei";
j["age"] = 30;
client.async_call("test_json", j).response([&](nlohmann::json js)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ex.async_call_counter++;
std::string s = js.dump();
ASIO2_CHECK(js["age"].get<int>() == 30);
ASIO2_CHECK(js["name"].get<std::string>() == "lilei");
asio2::ignore_unused(js, s);
});
// param 2 is empty, use the default_timeout
client.async_call([&](int v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 12 + 21);
ex.async_call_counter++;
}, "add", 12, 21);
// param 1 is empty, the result of the rpc call is not returned
client.async_call("mul0", 2.5, 2.5);
// Chain calls :
client.set_timeout(std::chrono::seconds(5)).async_call("mul", 2.5, 2.5).response([&](double v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 2.5 * 2.5);
ex.async_call_counter++;
});
// Chain calls :
client.timeout(std::chrono::seconds(13)).response([&](double v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 3.5 * 3.5);
ex.async_call_counter++;
}).async_call("mul", 3.5, 3.5);
// Chain calls :
client.response([&](double v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 4.5 * 4.5);
ex.async_call_counter++;
}).timeout(std::chrono::seconds(5)).async_call("mul", 4.5, 4.5);
// Chain calls :
client.async_call("mul", 5.5, 5.5).response([&](double v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 5.5 * 5.5);
ex.async_call_counter++;
}).timeout(std::chrono::seconds(10));
client.async_call([&](int v)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(v == 1 + 11);
ex.async_call_counter++;
}, std::chrono::seconds(3), "async_add", 1, 11);
client.async_call([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ex.async_call_counter++;
}, std::chrono::seconds(3), "async_test", "abc", "def");
});
client.bind_disconnect([&]()
{
ext_data& ex = client.get_user_data<ext_data&>();
ex.client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
});
// bind a rpc function in client, the server will call this client's rpc function
client.bind("sub", [](int a, int b) { return a - b; });
client.bind("async_add", async_add);
client.bind("test", [](asio2::rpc_client_use<asio2::net_protocol::ws>& client, std::string str)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(str == "i love you");
});
ext_data ex;
client.set_user_data(std::move(ex));
bool client_start_ret = client.start("127.0.0.1", 18010);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(!asio2::get_last_error());
nlohmann::json j = nlohmann::json::object();
j["name"] = "hanmeimei";
j["age"] = 20;
nlohmann::json j2 = client.call<nlohmann::json>(std::chrono::minutes(1), "test_json", j);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(j2["age"].get<int>() == 20);
ASIO2_CHECK(j2["name"].get<std::string>() == "hanmeimei");
double mul = client.call<double>(std::chrono::seconds(3), "mul", 6.5, 6.5);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(mul == 6.5 * 6.5);
userinfo u;
u = client.call<userinfo>("get_user");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(u.name == "lilei" && u.age == 32 && u.purview.size() == 2);
for (auto &[k, v] : u.purview)
{
ASIO2_CHECK(k == 1 || k == 2);
if (k == 1) ASIO2_CHECK(v == "read");
if (k == 2) ASIO2_CHECK(v == "write");
}
u.name = "hanmeimei";
u.age = 33;
u.purview = { {10,"get"},{20,"set"} };
client.async_call([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
}, "del_user", u);
// just call rpc function, don't need the rpc result
client.async_call("del_user", u);
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", "hanmeimei").response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", 10, std::string("lilei"), 1).response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", u, std::string("lilei"), 1).response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// Chain calls :
int sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 12);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sum == 11 + 12);
// Chain calls :
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 32);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sum == 11 + 32);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", "11", 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
// Chain calls :
std::string str = client.call<std::string>("cat", "abc", "123");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(str == "abc123");
client.async_call([&](int)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::not_found);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
}, "no_exists_fn", 10);
sum = client.timeout(std::chrono::seconds(13)).call<int>("no_exists_fn", 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::not_found);
ASIO2_CHECK(sum == 0);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter, ex.client_init_counter == 1);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 1);
}
while (server_connect_counter < test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count * 1);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count * 1);
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK( clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.async_call_counter < 19)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.async_call_counter, ex.async_call_counter == 19);
}
while (server_async_call_counter < test_client_count * 3)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_async_call_counter.load(), server_async_call_counter == test_client_count * 3);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK( clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
ASIO2_CHECK(!clients[i]->user_data_any().has_value());
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count*1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_async_call_counter = 0;
server_start_ret = server.start("127.0.0.1", 18010);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
for (int i = 0; i < test_client_count; i++)
{
asio2::rpc_client_use<asio2::net_protocol::ws>& client = *clients[i];
ASIO2_CHECK(client.get_default_timeout() == std::chrono::seconds(3));
client.set_auto_reconnect(true, std::chrono::milliseconds(100));
ASIO2_CHECK(client.is_auto_reconnect());
ASIO2_CHECK(client.get_auto_reconnect_delay() == std::chrono::milliseconds(100));
ext_data ex;
client.set_user_data(std::move(ex));
bool client_start_ret = client.async_start("127.0.0.1", 18010);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.client_connect_counter < 1)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.client_init_counter, ex.client_init_counter == 1);
ASIO2_CHECK_VALUE(ex.client_connect_counter, ex.client_connect_counter == 1);
}
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK( clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
asio2::rpc_client_use<asio2::net_protocol::ws>& client = *clients[i];
nlohmann::json j = nlohmann::json::object();
j["name"] = "hanmeimei";
j["age"] = 20;
nlohmann::json j2 = client.call<nlohmann::json>(std::chrono::minutes(1), "test_json", j);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(j2["age"].get<int>() == 20);
ASIO2_CHECK(j2["name"].get<std::string>() == "hanmeimei");
double mul = client.call<double>(std::chrono::seconds(3), "mul", 6.5, 6.5);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(mul == 6.5 * 6.5);
userinfo u;
u = client.call<userinfo>("get_user");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(u.name == "lilei" && u.age == 32 && u.purview.size() == 2);
for (auto &[k, v] : u.purview)
{
ASIO2_CHECK(k == 1 || k == 2);
if (k == 1) ASIO2_CHECK(v == "read");
if (k == 2) ASIO2_CHECK(v == "write");
}
u.name = "hanmeimei";
u.age = 33;
u.purview = { {10,"get"},{20,"set"} };
client.async_call([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
}, "del_user", u);
// just call rpc function, don't need the rpc result
client.async_call("del_user", u);
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", "hanmeimei").response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", 10, std::string("lilei"), 1).response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// this call will be failed, beacuse the param is incorrect.
client.async_call("del_user", u, std::string("lilei"), 1).response([&](userinfo)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
});
// Chain calls :
int sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 12);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sum == 11 + 12);
// Chain calls :
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 32);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(sum == 11 + 32);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", 11, 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
sum = client.timeout(std::chrono::seconds(13)).call<int>("add", "11", 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::invalid_argument);
ASIO2_CHECK(sum == 0);
// Chain calls :
std::string str = client.call<std::string>("cat", "abc", "123");
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(str == "abc123");
client.async_call([&](int)
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(asio2::get_last_error() == rpc::error::not_found);
ext_data& ex = client.get_user_data<ext_data&>();
ex.async_call_counter++;
}, "no_exists_fn", 10);
sum = client.timeout(std::chrono::seconds(13)).call<int>("no_exists_fn", 12, 13);
ASIO2_CHECK(asio2::get_last_error() == rpc::error::not_found);
ASIO2_CHECK(sum == 0);
}
while (server_connect_counter < test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count * 1);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count * 1);
for (int i = 0; i < test_client_count; i++)
{
ASIO2_CHECK(!clients[i]->is_stopped());
ASIO2_CHECK( clients[i]->is_started());
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
while (ex.async_call_counter < 19)
{
ASIO2_TEST_WAIT_CHECK();
}
}
for (int i = 0; i < test_client_count; i++)
{
ext_data& ex = clients[i]->get_user_data<ext_data&>();
ASIO2_CHECK_VALUE(ex.async_call_counter, ex.async_call_counter == 19);
}
while (server_async_call_counter < test_client_count * 3)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_async_call_counter.load(), server_async_call_counter == test_client_count * 3);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK( clients[i]->is_stopped());
ASIO2_CHECK(!clients[i]->is_started());
ASIO2_CHECK(!clients[i]->user_data_any().has_value());
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count * 1)
{
ASIO2_TEST_WAIT_CHECK();
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count*1);
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"rpc",
ASIO2_TEST_CASE(rpc_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_WSS_SESSION_HPP__
#define __ASIO2_WSS_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcps_session.hpp>
#include <asio2/http/ws_session.hpp>
namespace asio2::detail
{
struct template_args_wss_session : public template_args_ws_session
{
using stream_t = websocket::stream<asio::ssl::stream<typename template_args_ws_session::socket_t&>&>;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class derived_t, class args_t = template_args_wss_session>
class wss_session_impl_t
: public tcps_session_impl_t<derived_t, args_t>
, public ws_stream_cp <derived_t, args_t>
, public ws_send_op <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
public:
using super = tcps_session_impl_t<derived_t, args_t>;
using self = wss_session_impl_t <derived_t, args_t>;
using args_type = args_t;
using key_type = std::size_t;
using body_type = typename args_t::body_t;
using buffer_type = typename args_t::buffer_t;
using ws_stream_comp = ws_stream_cp<derived_t, args_t>;
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
explicit wss_session_impl_t(
asio::ssl::context & ctx,
session_mgr_t<derived_t> & sessions,
listener_t & listener,
io_t & rwio,
std::size_t init_buf_size,
std::size_t max_buf_size
)
: super(ctx, sessions, listener, rwio, init_buf_size, max_buf_size)
, ws_stream_cp<derived_t, args_t>()
, ws_send_op <derived_t, args_t>()
{
}
/**
* @brief destructor
*/
~wss_session_impl_t()
{
}
/**
* @brief return the websocket stream object refrence
*/
inline typename args_t::stream_t& stream() noexcept
{
return this->derived().ws_stream();
}
public:
/**
* @brief get this object hash key,used for session map
*/
inline key_type hash_key() const noexcept
{
return reinterpret_cast<key_type>(this);
}
/**
* @brief get the websocket upgraged request object
*/
inline const websocket::request_type& get_upgrade_request() noexcept { return this->upgrade_req_; }
protected:
inline typename super::ssl_stream_type& upgrade_stream() noexcept
{
return this->ssl_stream();
}
template<typename C>
inline void _do_init(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
super::_do_init(this_ptr, ecs);
this->derived()._ws_init(ecs, this->ssl_stream());
}
template<typename DeferEvent>
inline void _post_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_LOG_DEBUG("wss_session::_post_shutdown: {} {}", ec.value(), ec.message());
this->derived()._ws_stop(this_ptr, defer_event
{
[this, ec, this_ptr, e = chain.move_event()](event_queue_guard<derived_t> g) mutable
{
super::_post_shutdown(ec, std::move(this_ptr), defer_event(std::move(e), std::move(g)));
}, chain.move_guard()
});
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
detail::ignore_unused(ec);
ASIO2_ASSERT(!ec);
ASIO2_ASSERT(this->derived().sessions().io().running_in_this_thread());
asio::dispatch(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
this->derived()._ssl_start(this_ptr, ecs, this->socket_, this->ctx_);
this->derived()._ws_start(this_ptr, ecs, this->ssl_stream());
this->derived()._post_handshake(std::move(this_ptr), std::move(ecs), std::move(chain));
}));
}
template<typename C, typename DeferEvent>
inline void _handle_handshake(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
// Use "sessions().dispatch" to ensure that the _fire_accept function and the _fire_handshake
// function are fired in the same thread
this->sessions().dispatch(
[this, ec, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
ASIO2_ASSERT(this->derived().sessions().io().running_in_this_thread());
set_last_error(ec);
this->derived()._fire_handshake(this_ptr);
if (ec)
{
this->derived()._do_disconnect(ec, std::move(this_ptr), std::move(chain));
return;
}
asio::dispatch(this->io().context(), make_allocator(this->wallocator_,
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
this->derived()._post_read_upgrade_request(
std::move(this_ptr), std::move(ecs), std::move(chain));
}));
});
}
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
return this->derived()._ws_send(data, std::forward<Callback>(callback));
}
protected:
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._ws_post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._ws_handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}
inline void _fire_upgrade(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_upgrade must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
this->listener_.notify(event_type::upgrade, this_ptr);
}
protected:
websocket::request_type upgrade_req_;
};
}
namespace asio2
{
using wss_session_args = detail::template_args_wss_session;
template<class derived_t, class args_t>
using wss_session_impl_t = detail::wss_session_impl_t<derived_t, args_t>;
template<class derived_t>
class wss_session_t : public detail::wss_session_impl_t<derived_t, detail::template_args_wss_session>
{
public:
using detail::wss_session_impl_t<derived_t, detail::template_args_wss_session>::wss_session_impl_t;
};
class wss_session : public wss_session_t<wss_session>
{
public:
using wss_session_t<wss_session>::wss_session_t;
};
}
#include <asio2/base/detail/pop_options.hpp>
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct wss_rate_session_args : public wss_session_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
using stream_t = websocket::stream<asio::ssl::stream<socket_t&>&>;
};
template<class derived_t>
class wss_rate_session_t : public asio2::wss_session_impl_t<derived_t, wss_rate_session_args>
{
public:
using asio2::wss_session_impl_t<derived_t, wss_rate_session_args>::wss_session_impl_t;
};
class wss_rate_session : public asio2::wss_rate_session_t<wss_rate_session>
{
public:
using asio2::wss_rate_session_t<wss_rate_session>::wss_rate_session_t;
};
}
#endif
#endif // !__ASIO2_WSS_SESSION_HPP__
#endif
<file_sep>/*
Copyright <NAME> 2011-2012
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_DETAIL_TEST_H
#define BHO_PREDEF_DETAIL_TEST_H
#if !defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#define BHO_PREDEF_DECLARE_TEST(x,s)
#endif
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_IRIX_H
#define BHO_PREDEF_OS_IRIX_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_IRIX`
http://en.wikipedia.org/wiki/Irix[IRIX] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `sgi` | {predef_detection}
| `+__sgi+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_IRIX BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(sgi) || defined(__sgi) \
)
# undef BHO_OS_IRIX
# define BHO_OS_IRIX BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_IRIX
# define BHO_OS_IRIX_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_IRIX_NAME "IRIX"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_IRIX,BHO_OS_IRIX_NAME)
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> dot <EMAIL> at g<EMAIL> dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_DETAIL_VARIANT_HPP
#define BHO_BEAST_DETAIL_VARIANT_HPP
#include <asio2/bho/beast/core/detail/type_traits.hpp>
#include <asio2/bho/assert.hpp>
namespace bho {
namespace beast {
namespace detail {
// This simple variant gets the job done without
// causing too much trouble with template depth:
//
// * Always allows an empty state I==0
// * emplace() and get() support 1-based indexes only
// * Basic exception guarantee
// * Max 255 types
//
} // detail
} // beast
} // bho
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RDC_CALL_COMPONENT_HPP__
#define __ASIO2_RDC_CALL_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <queue>
#include <any>
#include <future>
#include <tuple>
#include <type_traits>
#include <asio2/base/error.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/impl/condition_event_cp.hpp>
#include <asio2/component/rdc/rdc_invoker.hpp>
#include <asio2/component/rdc/rdc_option.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
template<class derived_t, class args_t>
class rdc_call_cp_impl
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
public:
using send_data_t = typename args_t::send_data_t;
using recv_data_t = typename args_t::recv_data_t;
using callback_type = std::function<void(const error_code&, send_data_t, recv_data_t)>;
/**
* @brief constructor
*/
rdc_call_cp_impl() noexcept = default;
/**
* @brief destructor
*/
~rdc_call_cp_impl() noexcept = default;
protected:
template<class derive_t, class arg_t>
struct sync_call_op
{
using send_data_t = typename arg_t::send_data_t;
using recv_data_t = typename arg_t::recv_data_t;
template<class return_t>
inline static void convert_recv_data_to_result(std::shared_ptr<return_t>& result, recv_data_t data)
{
if constexpr (std::is_reference_v<recv_data_t> &&
has_equal_operator<return_t, std::remove_reference_t<recv_data_t>>::value)
{
*result = std::move(data);
}
else
{
if constexpr (has_stream_operator<return_t, recv_data_t>::value)
{
*result << data;
}
else if constexpr (has_equal_operator<return_t, recv_data_t>::value)
{
*result = data;
}
else
{
::new (result.get()) return_t(data);
}
}
}
template<class return_t, class Rep, class Period, class DataT>
inline static return_t exec(derive_t& derive, std::chrono::duration<Rep, Period> timeout, DataT&& data)
{
static_assert(!std::is_void_v<return_t>);
static_assert(!std::is_reference_v<return_t> && !std::is_pointer_v<return_t>);
static_assert(!is_template_instance_of_v<std::basic_string_view, return_t>);
// should't read the ecs in other thread which is not the io_context thread.
//if (!derive.ecs_->get_rdc())
//{
// ASIO2_ASSERT(false && "This function is only available in rdc mode");
//}
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
// [20210818] don't throw an error, you can use get_last_error() to check
// is there any exception.
return return_t{};
}
std::shared_ptr<return_t> result = std::make_shared<return_t>();
std::shared_ptr<std::promise<error_code>> promise = std::make_shared<std::promise<error_code>>();
std::future<error_code> future = promise->get_future();
auto invoker = [&derive, result, pm = std::move(promise)]
(const error_code& ec, send_data_t s, recv_data_t r) mutable
{
ASIO2_ASSERT(derive.io().running_in_this_thread());
detail::ignore_unused(derive, s);
if (!ec)
{
convert_recv_data_to_result(result, r);
}
pm->set_value(ec);
};
// All pending sending events will be cancelled after enter the callback below.
derive.post(
[&derive, p = derive.selfptr(), timeout,
invoker = std::move(invoker), data = std::forward<DataT>(data)]
() mutable
{
derive._rdc_send(std::move(p), std::move(data), std::move(timeout), std::move(invoker));
});
// Whether we run on the io_context thread
if (!derive.io().running_in_this_thread())
{
std::future_status status = future.wait_for(timeout);
if (status == std::future_status::ready)
{
set_last_error(future.get());
}
else
{
set_last_error(asio::error::timed_out);
}
}
else
{
// If invoke synchronization rdc call function in communication thread,
// it will degenerates into async_call and the return value is empty.
set_last_error(asio::error::in_progress);
}
return std::move(*result);
}
};
template<class derive_t, class arg_t>
struct async_call_op
{
using send_data_t = typename arg_t::send_data_t;
using recv_data_t = typename arg_t::recv_data_t;
template<class DataT, class Rep, class Period, class Invoker>
inline static void exec(derive_t& derive, DataT&& data,
std::chrono::duration<Rep, Period> timeout, Invoker&& invoker)
{
// should't read the ecs in other thread which is not the io_context thread.
//if (!derive.ecs_->get_rdc())
//{
// ASIO2_ASSERT(false && "This function is only available in rdc mode");
//}
if (!derive.is_started())
{
set_last_error(asio::error::not_connected);
// ensure the callback was called in the communication thread.
derive.post(
[&derive, invoker = std::forward<Invoker>(invoker),
data = derive._data_persistence(std::forward<DataT>(data))]
() mutable
{
set_last_error(asio::error::not_connected);
derive._rdc_invoke_with_send(asio::error::not_connected,
invoker, derive._rdc_convert_to_send_data(data));
});
return;
}
// All pending sending events will be cancelled after enter the callback below.
derive.post(
[&derive, p = derive.selfptr(), timeout,
invoker = std::forward<Invoker>(invoker), data = std::forward<DataT>(data)]
() mutable
{
derive._rdc_send(std::move(p), std::move(data), std::move(timeout), std::move(invoker));
});
}
};
template<class derive_t, class arg_t>
class sync_caller
{
template <class, class> friend class rdc_call_cp_impl;
using send_data_t = typename arg_t::send_data_t;
using recv_data_t = typename arg_t::recv_data_t;
protected:
sync_caller(derive_t& d) : derive(d), tm_(d.get_default_timeout()) {}
sync_caller(sync_caller&& o) : derive(o.derive), tm_(std::move(o.tm_)) {}
sync_caller(const sync_caller&) = delete;
sync_caller& operator=(sync_caller&&) = delete;
sync_caller& operator=(const sync_caller&) = delete;
public:
~sync_caller() = default;
/**
* @brief set the timeout for remote data call component (means rdc)
*/
template<class Rep, class Period>
inline sync_caller& set_timeout(std::chrono::duration<Rep, Period> timeout)
{
this->tm_ = std::move(timeout);
return (*this);
}
/**
* @brief set the timeout for remote data call component (means rdc), same as set_timeout
*/
template<class Rep, class Period>
inline sync_caller& timeout(std::chrono::duration<Rep, Period> timeout)
{
return this->set_timeout(std::move(timeout));
}
template<class return_t, class DataT>
inline return_t call(DataT&& data)
{
return sync_call_op<derive_t, arg_t>::template exec<return_t>(
derive, tm_, std::forward<DataT>(data));
}
protected:
derive_t& derive;
asio::steady_timer::duration tm_;
};
template<class derive_t, class arg_t>
class async_caller
{
template <class, class> friend class rdc_call_cp_impl;
using send_data_t = typename arg_t::send_data_t;
using recv_data_t = typename arg_t::recv_data_t;
protected:
async_caller(derive_t& d) : derive(d), tm_(d.get_default_timeout()) {}
async_caller(async_caller&& o) : derive(o.derive),
tm_(std::move(o.tm_)), cb_(std::move(o.cb_)), fn_(std::move(o.fn_)) {}
async_caller(const async_caller&) = delete;
async_caller& operator=(async_caller&&) = delete;
async_caller& operator=(const async_caller&) = delete;
using defer_fn = std::function<void(asio::steady_timer::duration, callback_type)>;
public:
~async_caller()
{
if (this->fn_)
{
(this->fn_)(std::move(this->tm_), std::move(this->cb_));
}
}
/**
* @brief set the timeout for remote data call component (means rdc)
*/
template<class Rep, class Period>
inline async_caller& set_timeout(std::chrono::duration<Rep, Period> timeout)
{
this->tm_ = timeout;
return (*this);
}
/**
* @brief set the timeout for remote data call component (means rdc), same as set_timeout
*/
template<class Rep, class Period>
inline async_caller& timeout(std::chrono::duration<Rep, Period> timeout)
{
return this->set_timeout(std::move(timeout));
}
template<class Callback>
inline async_caller& response(Callback&& cb)
{
this->cb_ = rdc_make_callback_t<send_data_t, recv_data_t>::bind(std::forward<Callback>(cb));
return (*this);
}
template<class DataT>
inline async_caller& async_call(DataT&& data)
{
derive_t& deriv = derive;
this->fn_ = [&deriv, data = std::forward<DataT>(data)]
(asio::steady_timer::duration timeout, callback_type cb) mutable
{
async_call_op<derive_t, arg_t>::exec(deriv, std::move(data), std::move(timeout), std::move(cb));
};
return (*this);
}
protected:
derive_t& derive;
asio::steady_timer::duration tm_;
callback_type cb_;
defer_fn fn_;
};
template<class derive_t, class arg_t>
class base_caller
{
template <class, class> friend class rdc_call_cp_impl;
using send_data_t = typename arg_t::send_data_t;
using recv_data_t = typename arg_t::recv_data_t;
protected:
base_caller(derive_t& d) : derive(d), tm_(d.get_default_timeout()) {}
base_caller(base_caller&& o) : derive(o.derive), tm_(std::move(o.tm_)) {}
base_caller& operator=(base_caller&&) = delete;
base_caller(const base_caller&) = delete;
base_caller& operator=(const base_caller&) = delete;
public:
~base_caller() = default;
/**
* @brief set the timeout for remote data call component (means rdc)
*/
template<class Rep, class Period>
inline base_caller& set_timeout(std::chrono::duration<Rep, Period> timeout)
{
this->tm_ = std::move(timeout);
return (*this);
}
/**
* @brief set the timeout for remote data call component (means rdc), same as set_timeout
*/
template<class Rep, class Period>
inline base_caller& timeout(std::chrono::duration<Rep, Period> timeout)
{
return this->set_timeout(std::move(timeout));
}
template<class Callback>
inline async_caller<derive_t, arg_t> response(Callback&& cb)
{
async_caller<derive_t, arg_t> caller{ derive };
caller.set_timeout(std::move(this->tm_));
caller.response(std::forward<Callback>(cb));
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
template<class return_t, class DataT>
inline return_t call(DataT&& data)
{
return sync_call_op<derive_t, arg_t>::template exec<return_t>(
derive, this->tm_, std::forward<DataT>(data));
}
template<class DataT>
inline async_caller<derive_t, arg_t> async_call(DataT&& data)
{
async_caller<derive_t, arg_t> caller{ derive };
caller.set_timeout(std::move(this->tm_));
caller.async_call(std::forward<DataT>(data));
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
protected:
derive_t& derive;
asio::steady_timer::duration tm_;
};
public:
/**
* @brief Send data and synchronize waiting for a response or until the timeout period is reached
*/
template<class return_t, class DataT>
inline return_t call(DataT&& data)
{
derived_t& derive = static_cast<derived_t&>(*this);
return sync_call_op<derived_t, args_t>::template exec<return_t>(
derive, derive.get_default_timeout(), std::forward<DataT>(data));
}
/**
* @brief Send data and synchronize waiting for a response or until the timeout period is reached
*/
template<class return_t, class DataT, class Rep, class Period>
inline return_t call(DataT&& data, std::chrono::duration<Rep, Period> timeout)
{
derived_t& derive = static_cast<derived_t&>(*this);
return sync_call_op<derived_t, args_t>::template exec<return_t>(
derive, timeout, std::forward<DataT>(data));
}
/**
* @brief Send data and asynchronous waiting for a response or until the timeout period is reached
* Callback signature : void(DataType data)
*/
template<class DataT, class Callback>
inline typename std::enable_if_t<is_callable_v<Callback>, void>
async_call(DataT&& data, Callback&& cb)
{
derived_t& derive = static_cast<derived_t&>(*this);
async_call_op<derived_t, args_t>::exec(derive, std::forward<DataT>(data), derive.get_default_timeout(),
rdc_make_callback_t<send_data_t, recv_data_t>::bind(std::forward<Callback>(cb)));
}
/**
* @brief Send data and asynchronous waiting for a response or until the timeout period is reached
* Callback signature : void(DataType data)
*/
template<class DataT, class Callback, class Rep, class Period>
inline typename std::enable_if_t<is_callable_v<Callback>, void>
async_call(DataT&& data, Callback&& cb, std::chrono::duration<Rep, Period> timeout)
{
derived_t& derive = static_cast<derived_t&>(*this);
async_call_op<derived_t, args_t>::exec(derive, std::forward<DataT>(data), timeout,
rdc_make_callback_t<send_data_t, recv_data_t>::bind(std::forward<Callback>(cb)));
}
/**
* @brief Send data and asynchronous waiting for a response or until the timeout period is reached
*/
template<class DataT>
inline async_caller<derived_t, args_t> async_call(DataT&& data)
{
async_caller<derived_t, args_t> caller{ static_cast<derived_t&>(*this) };
caller.async_call(std::forward<DataT>(data));
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
/**
* @brief set the timeout for remote data call component (means rdc)
*/
template<class Rep, class Period>
inline base_caller<derived_t, args_t> set_timeout(std::chrono::duration<Rep, Period> timeout)
{
base_caller<derived_t, args_t> caller{ static_cast<derived_t&>(*this) };
caller.set_timeout(timeout);
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
/**
* @brief set the timeout for remote data call component (means rdc), same as set_timeout
*/
template<class Rep, class Period>
inline base_caller<derived_t, args_t> timeout(std::chrono::duration<Rep, Period> timeout)
{
return this->set_timeout(std::move(timeout));
}
/**
* @brief bind a response callback function for remote data call component (means rdc)
*/
template<class Callback>
inline async_caller<derived_t, args_t> response(Callback&& cb)
{
async_caller<derived_t, args_t> caller{ static_cast<derived_t&>(*this) };
caller.response(std::forward<Callback>(cb));
return caller; // "caller" is local variable has RVO optimization, should't use std::move()
}
protected:
template<typename C>
inline void _rdc_init(std::shared_ptr<ecs_t<C>>& ecs)
{
detail::ignore_unused(ecs);
}
template<typename C>
inline void _rdc_start(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
detail::ignore_unused(this_ptr, ecs);
if constexpr (ecs_helper::has_rdc<C>())
{
ASIO2_ASSERT(ecs->get_component().rdc_option(std::in_place)->invoker().reqs().empty());
}
else
{
std::ignore = true;
}
}
inline void _rdc_stop()
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
// this callback maybe executed after the session stop, and the session
// stop will destroy the ecs, so we need check whether the ecs is valid.
if (!derive.ecs_)
return;
asio2::rdc::option_base* prdc = derive.ecs_->get_rdc();
// maybe not rdc mode, so must check whether the rdc is valid.
if (!prdc)
return;
// if stoped, execute all callbacks in the requests, otherwise if some
// call or async_call 's timeout is too long, then the application will
// can't exit before all timeout timer is reached.
prdc->foreach_and_clear([&derive](void*, void* val) mutable
{
std::tuple<std::shared_ptr<asio::steady_timer>, callback_type>& tp =
*((std::tuple<std::shared_ptr<asio::steady_timer>, callback_type>*)val);
auto& [timer, invoker] = tp;
detail::cancel_timer(*timer);
derive._rdc_invoke_with_none(asio::error::operation_aborted, invoker);
});
}
template<class DataT>
void _rdc_send(
std::shared_ptr<derived_t> this_ptr, DataT&& data,
std::chrono::steady_clock::duration timeout, callback_type invoker)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(derive.io().running_in_this_thread());
auto persisted_data = derive._data_persistence(std::forward<DataT>(data));
send_data_t sent_typed_data = derive._rdc_convert_to_send_data(persisted_data);
if (!derive.ecs_)
{
derive._rdc_invoke_with_send(asio::error::operation_aborted, invoker, sent_typed_data);
return;
}
// if ecs is valid, the rdc must be valid.
asio2::rdc::option_base* prdc = derive.ecs_->get_rdc();
// maybe not rdc mode, so must check whether the rdc is valid.
if (!prdc)
{
ASIO2_ASSERT(false && "This function is only available in rdc mode");
derive._rdc_invoke_with_send(asio::error::operation_not_supported, invoker, sent_typed_data);
return;
}
std::any id = prdc->call_parser(true, (void*)&sent_typed_data);
std::shared_ptr<asio::steady_timer> timer =
std::make_shared<asio::steady_timer>(derive.io().context());
std::tuple tp(timer, std::move(invoker));
prdc->emplace_request(id, (void*)&tp);
auto ex = [&derive, id = std::move(id), prdc]() mutable
{
ASIO2_ASSERT(derive.io().running_in_this_thread());
prdc->execute_and_erase(id, [&derive](void* val) mutable
{
std::tuple<std::shared_ptr<asio::steady_timer>, callback_type>& tp =
*((std::tuple<std::shared_ptr<asio::steady_timer>, callback_type>*)val);
auto& [tmer, cb] = tp;
detail::cancel_timer(*tmer);
derive._rdc_invoke_with_none(asio::error::timed_out, cb);
});
};
timer->expires_after(timeout);
timer->async_wait([this_ptr, ex](const error_code& ec) mutable
{
if (ec == asio::error::operation_aborted)
return;
ex();
});
derive.push_event(
[&derive, p = std::move(this_ptr), id = derive.life_id(), ex = std::move(ex), data = std::move(persisted_data)]
(event_queue_guard<derived_t> g) mutable
{
if (id != derive.life_id())
{
set_last_error(asio::error::operation_aborted);
ex();
return;
}
derive._do_send(data, [&ex, g = std::move(g)](const error_code& ec, std::size_t) mutable
{
detail::ignore_unused(g);
if (ec)
{
ex();
}
});
});
}
template<typename C>
inline void _do_rdc_handle_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, recv_data_t data)
{
detail::ignore_unused(this_ptr);
derived_t& derive = static_cast<derived_t&>(*this);
auto _rdc = ecs->get_component().rdc_option(std::in_place);
if (_rdc->invoker().reqs().empty())
return;
auto id = (_rdc->get_recv_parser())(data);
ASIO2_ASSERT(derive.io().running_in_this_thread());
auto iter = _rdc->invoker().find(id);
if (iter != _rdc->invoker().end())
{
auto&[timer, invoker] = iter->second;
detail::cancel_timer(*timer);
derive._rdc_invoke_with_recv(error_code{}, invoker, data);
_rdc->invoker().erase(iter);
}
}
template<typename C>
inline void _rdc_handle_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, recv_data_t data)
{
if constexpr (ecs_helper::has_rdc<C>())
{
derived_t& derive = static_cast<derived_t&>(*this);
derive._do_rdc_handle_recv(this_ptr, ecs, data);
}
else
{
detail::ignore_unused(this_ptr, ecs, data);
}
}
};
template<class args_t>
struct is_rdc_call_cp_enabled
{
template<class, class = void>
struct has_member_enabled : std::false_type {};
template<class T>
struct has_member_enabled<T, std::void_t<decltype(T::rdc_call_cp_enabled)>> : std::true_type {};
static constexpr bool value()
{
if constexpr (has_member_enabled<args_t>::value)
{
return args_t::rdc_call_cp_enabled;
}
else
{
return true;
}
}
};
template<class derived_t, class args_t, bool Enable = is_rdc_call_cp_enabled<args_t>::value()>
class rdc_call_cp_bridge;
template<class derived_t, class args_t>
class rdc_call_cp_bridge<derived_t, args_t, true> : public rdc_call_cp_impl<derived_t, args_t> {};
template<class derived_t, class args_t>
class rdc_call_cp_bridge<derived_t, args_t, false>
{
protected:
// just placeholders
template<typename... Args> inline void _rdc_init (Args const& ...) {}
template<typename... Args> inline void _rdc_start (Args const& ...) {}
template<typename... Args> inline void _rdc_stop (Args const& ...) {}
template<typename... Args> inline void _rdc_handle_recv(Args const& ...) {}
};
template<class derived_t, class args_t>
class rdc_call_cp : public rdc_call_cp_bridge<derived_t, args_t> {};
}
#endif // !__ASIO2_RDC_CALL_COMPONENT_HPP__
<file_sep>#include <asio2/base/detail/push_options.hpp>
#define ASIO_STANDALONE
// https://github.com/qicosmos/rest_rpc
// first : unzip the "asio2/test/bench/rpc/rest_rpc-master.zip"
// the unziped path is like this : "asio2/test/bench/rpc/rest_rpc-master/include"
#include <fstream>
#include <memory>
#include <chrono>
#include <thread>
#include <rpc_server.h>
using namespace rest_rpc;
using namespace rpc_service;
decltype(std::chrono::steady_clock::now()) time1 = std::chrono::steady_clock::now();
decltype(std::chrono::steady_clock::now()) time2 = std::chrono::steady_clock::now();
std::size_t qps = 0;
bool first = true;
std::string echo(rpc_conn conn, std::string a) {
if (first)
{
first = false;
time1 = std::chrono::steady_clock::now();
time2 = std::chrono::steady_clock::now();
}
qps++;
decltype(std::chrono::steady_clock::now()) time3 = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time2).count();
if (ms > 1)
{
time2 = time3;
ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time1).count();
double speed = (double)qps / (double)ms;
printf("%.1lf\n", speed);
}
return a;
}
int main() {
rpc_server server(8080, std::thread::hardware_concurrency());
server.register_handler("echo", echo);
server.run();
return 0;
}
#include <asio2/base/detail/pop_options.hpp>
<file_sep>
#include <asio2/base/detail/push_options.hpp>
#include <asio2/asio2.hpp>
using asio::ip::udp;
decltype(std::chrono::steady_clock::now()) time1 = std::chrono::steady_clock::now();
decltype(std::chrono::steady_clock::now()) time2 = std::chrono::steady_clock::now();
std::size_t recvd_bytes = 0;
bool first_flag = true;
class server
{
public:
server(asio::io_context& io_context, short port)
: socket_(io_context, udp::endpoint(udp::v4(), port))
{
socket_.async_receive_from(asio::buffer(data_, max_length), sender_endpoint_,
[this](const asio::error_code& error, size_t bytes_recvd)
{
handle_receive_from(error, bytes_recvd);
});
}
void handle_receive_from(const asio::error_code& error,
size_t bytes_recvd)
{
if (!error && bytes_recvd > 0)
{
if (first_flag)
{
first_flag = false;
time1 = std::chrono::steady_clock::now();
time2 = std::chrono::steady_clock::now();
}
recvd_bytes += bytes_recvd;
decltype(std::chrono::steady_clock::now()) time3 = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time2).count();
if (ms > 1)
{
time2 = time3;
ms = std::chrono::duration_cast<std::chrono::seconds>(time3 - time1).count();
double speed = (double)recvd_bytes / (double)ms / double(1024) / double(1024);
printf("%.1lf MByte/Sec\n", speed);
}
socket_.async_send_to(
asio::buffer(data_, bytes_recvd), sender_endpoint_,
[this](const asio::error_code& error, size_t bytes_recvd)
{
handle_send_to(error, bytes_recvd);
});
}
else
{
socket_.async_receive_from(asio::buffer(data_, max_length), sender_endpoint_,
[this](const asio::error_code& error, size_t bytes_recvd)
{
handle_receive_from(error, bytes_recvd);
});
}
}
void handle_send_to(const asio::error_code& /*error*/,
size_t /*bytes_sent*/)
{
socket_.async_receive_from(asio::buffer(data_, max_length), sender_endpoint_,
[this](const asio::error_code& error, size_t bytes_recvd)
{
handle_receive_from(error, bytes_recvd);
});
}
private:
udp::socket socket_;
udp::endpoint sender_endpoint_;
enum { max_length = 1500 };
char data_[max_length];
};
int main()
{
asio::io_context io_context;
server s(io_context, 8115);
io_context.run();
while (std::getchar() != '\n'); // press enter to exit this program
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* https://github.com/mcxiaoke/mqtt
* https://github.com/eclipse/paho.mqtt.c
* https://github.com/eclipse/paho.mqtt.cpp
*
* https://github.com/mqtt/mqtt.org/wiki/libraries
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_CORE_HPP__
#define __ASIO2_MQTT_CORE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <iosfwd>
#include <cstdint>
#include <cstddef>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <vector>
#include <optional>
#include <array>
#include <variant>
#include <tuple>
#include <type_traits>
#include <asio2/external/beast.hpp>
#include <asio2/external/predef.h>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
#include <asio2/mqtt/error.hpp>
/*
* Server Broker Port Websocket
* ------------------------------------------------------------------
* iot.eclipse.org Mosquitto 1883/8883 n/a
* broker.hivemq.com HiveMQ 1883 8000 **
* test.mosquitto.org Mosquitto 1883/8883/8884 8080/8081
* test.mosca.io mosca 1883 80
* broker.mqttdashboard.com HiveMQ 1883
*
*/
//namespace asio2::detail
//{
// template <class> class mqtt_handler_t;
// template <class> class mqtt_invoker_t;
// template <class> class mqtt_aop_connect;
// template <class> class mqtt_aop_publish;
//}
namespace asio2::mqtt
{
static constexpr unsigned int max_payload = 268435455u;
enum class version : std::uint8_t
{
// mqtt version 3.1 , The protocol version of the mqtt 3.1 CONNECT message is 0x03
v3 = 3,
// mqtt version 3.1.1, The protocol version of the mqtt 3.1.1 CONNECT message is 0x04
v4 = 4,
// mqtt version 5.0 , The protocol version of the mqtt 5.0 CONNECT message is 0x05
v5 = 5
};
/**
* MQTT Control Packet type
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718021
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901022
*/
enum class control_packet_type : std::uint8_t
{
// [Forbidden]
// Reserved
reserved = 0,
// [Client to Server]
// Client request to connect to Server
connect = 1,
// [Server to Client]
// Connect acknowledgment
connack = 2,
// [Client to Server] or [Server to Client]
// Publish message
publish = 3,
// [Client to Server] or [Server to Client]
// Publish acknowledgment
puback = 4,
// [Client to Server] or [Server to Client]
// Publish received (assured delivery part 1)
pubrec = 5,
// [Client to Server] or [Server to Client]
// Publish release (assured delivery part 2)
pubrel = 6,
// [Client to Server] or [Server to Client]
// Publish complete (assured delivery part 3)
pubcomp = 7,
// [Client to Server]
// Client subscribe request
subscribe = 8,
// [Server to Client]
// Subscribe acknowledgment
suback = 9,
// [Client to Server]
// Unsubscribe request
unsubscribe = 10,
// [Server to Client]
// Unsubscribe acknowledgment
unsuback = 11,
// [Client to Server]
// PING request
pingreq = 12,
// [Server to Client]
// PING response
pingresp = 13,
// [Client to Server]
// Client is disconnecting
disconnect = 14,
// [Client to Server] or [Server to Client]
// Authentication exchange
// Only valid in mqtt 5.0
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901256
auth = 15,
};
/**
* Data representation
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901006
*/
enum class representation_type : std::uint8_t
{
one_byte_integer,
two_byte_integer,
four_byte_integer,
variable_byte_integer,
binary_data,
utf8_string,
utf8_string_pair
};
/**
* This field indicates the level of assurance for delivery of an Application Message.
* The QoS levels are shown below.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901103
*/
enum class qos_type : std::uint8_t
{
at_most_once = 0, // At most once delivery
at_least_once = 1, // At least once delivery
exactly_once = 2, // Exactly once delivery
};
static constexpr std::uint8_t qos_min_value = static_cast<std::uint8_t>(qos_type::at_most_once);
static constexpr std::uint8_t qos_max_value = static_cast<std::uint8_t>(qos_type::exactly_once);
template<class QosOrInt>
typename std::enable_if_t<
std::is_same_v<asio2::detail::remove_cvref_t<QosOrInt>, mqtt::qos_type> ||
std::is_integral_v<asio2::detail::remove_cvref_t<QosOrInt>>, bool>
inline is_valid_qos(QosOrInt q)
{
return (static_cast<std::uint8_t>(q) >= qos_min_value && static_cast<std::uint8_t>(q) <= qos_max_value);
}
/**
* Bits 4 and 5 of the Subscription Options represent the Retain Handling option.
* This option specifies whether retained messages are sent when the subscription is established.
* This does not affect the sending of retained messages at any point after the subscribe.
* If there are no retained messages matching the Topic Filter, all of these values act the same.
* The values are:
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901169
*/
enum class retain_handling_type : std::uint8_t
{
// Send retained messages at the time of the subscribe
send = 0,
// Send retained messages at subscribe only if the subscription does not currently exist
send_only_new_subscription = 1,
// Do not send retained messages at the time of the subscribe
not_send = 2,
};
/*
* The algorithm for encoding a non-negative integer (X) into the Variable Byte Integer encoding scheme is as follows:
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901011
*/
template<class Integer>
std::array<std::uint8_t, 4> encode_variable_byte_integer(Integer X)
{
std::int32_t i = 0;
std::array<std::uint8_t, 4> value{};
if (static_cast<std::size_t>(X) > static_cast<std::size_t>(mqtt::max_payload))
{
asio2::set_last_error(asio::error::invalid_argument);
return value;
}
asio2::clear_last_error();
do
{
std::uint8_t encodedByte = X % 128;
X = X / 128;
// if there are more data to encode, set the top bit of this byte
if (X > 0)
{
encodedByte = encodedByte | 128;
}
// 'output' encodedByte
value[i] = encodedByte;
++i;
} while (X > 0);
return value;
}
template<class Integer>
inline bool check_size(Integer size)
{
return (std::size_t(size) <= std::size_t(65535));
}
template<class String>
inline bool check_utf8(String& str)
{
#if defined(ASIO2_CHECK_UTF8)
return beast::websocket::detail::check_utf8(str.data(), str.size());
#else
asio2::detail::ignore_unused(str);
return true;
#endif
}
/*
* @return pair.first - the integer value, pair.second - number of bytes
*
* The algorithm for decoding a Variable Byte Integer type is as follows:
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901011
*/
template<class BufferContainer>
std::pair<std::int32_t, std::int32_t> decode_variable_byte_integer(BufferContainer X)
{
std::int32_t i = 0;
std::int32_t multiplier = 1;
std::int32_t value = 0;
std::uint8_t encodedByte;
do
{
if (X.size() < std::size_t(i + 1))
{
i = 0;
value = 0;
asio2::set_last_error(asio::error::no_buffer_space);
return { value, i };
}
encodedByte = static_cast<std::uint8_t>(X[i]); // 'next byte from stream'
++i;
value += (encodedByte & 127) * multiplier;
if (multiplier > 128 * 128 * 128)
{
i = 0;
value = 0;
asio2::set_last_error(asio::error::invalid_argument);
return { value, i };
}
multiplier *= 128;
} while ((encodedByte & 128) != 0);
asio2::clear_last_error();
// When this algorithm terminates, value contains the Variable Byte Integer value.
return { value, i };
}
/**
* Bits in a byte are labelled 7 to 0. Bit number 7 is the most significant bit,
* the least significant bit is assigned bit number 0.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901007
*/
class one_byte_integer
{
public:
using value_type = std::uint8_t;
one_byte_integer() = default;
explicit one_byte_integer(std::uint8_t v) : value_(v)
{
}
inline std::uint8_t value() const noexcept
{
return value_;
}
inline operator std::uint8_t() const noexcept { return value(); }
inline one_byte_integer& operator=(std::uint8_t v)
{
value_ = v;
return (*this);
}
inline constexpr std::size_t required_size() const noexcept
{
return (sizeof(std::uint8_t));
}
inline constexpr std::size_t size() const noexcept
{
return (sizeof(std::uint8_t));
}
inline one_byte_integer& serialize(std::vector<asio::const_buffer>& buffers)
{
buffers.emplace_back(std::addressof(value_), required_size());
return (*this);
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline one_byte_integer& serialize(Container& buffer)
{
static_assert(sizeof(typename Container::value_type) == std::size_t(1));
auto* p = reinterpret_cast<typename Container::const_pointer>(std::addressof(value_));
buffer.insert(buffer.end(), p, p + required_size());
return (*this);
}
inline one_byte_integer& deserialize(std::string_view& data)
{
if (data.size() < required_size())
{
set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
return (*this);
}
asio2::clear_last_error();
value_ = data[0];
data.remove_prefix(required_size());
return (*this);
}
protected:
std::uint8_t value_{ 0 };
};
/**
* Two Byte Integer data values are 16-bit unsigned integers in big-endian order: the high order
* byte precedes the lower order byte. This means that a 16-bit word is presented on the network
* as Most Significant Byte (MSB), followed by Least Significant Byte (LSB).
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901008
*/
class two_byte_integer
{
public:
using value_type = std::uint16_t;
two_byte_integer() = default;
explicit two_byte_integer(std::uint16_t v)
{
*this = v;
}
inline std::uint16_t value() const noexcept
{
#if ASIO2_ENDIAN_BIG_BYTE
return value_;
#else
return (((value_ >> 8) & 0x00ff) | ((value_ << 8) & 0xff00));
#endif
}
inline operator std::uint16_t() const noexcept { return value(); }
inline two_byte_integer& operator=(std::uint16_t v)
{
#if ASIO2_ENDIAN_BIG_BYTE
value_ = v;
#else
value_ = ((v >> 8) & 0x00ff) | ((v << 8) & 0xff00);
#endif
return (*this);
}
inline constexpr std::size_t required_size() const noexcept
{
return (sizeof(std::uint16_t));
}
inline constexpr std::size_t size() const noexcept
{
return (sizeof(std::uint16_t));
}
inline two_byte_integer& serialize(std::vector<asio::const_buffer>& buffers)
{
buffers.emplace_back(std::addressof(value_), required_size());
return (*this);
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline two_byte_integer& serialize(Container& buffer)
{
static_assert(sizeof(typename Container::value_type) == std::size_t(1));
auto* p = reinterpret_cast<typename Container::const_pointer>(std::addressof(value_));
buffer.insert(buffer.end(), p, p + required_size());
return (*this);
}
inline two_byte_integer& deserialize(std::string_view& data)
{
if (data.size() < required_size())
{
set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
return (*this);
}
asio2::clear_last_error();
value_ = ((data[1] << 8) & 0xff00) | ((data[0] << 0) & 0x00ff);
data.remove_prefix(required_size());
return (*this);
}
protected:
std::uint16_t value_{ 0 };
};
/**
* Four Byte Integer data values are 32-bit unsigned integers in big-endian order: the high order
* byte precedes the successively lower order bytes. This means that a 32-bit word is presented on
* the network as Most Significant Byte (MSB), followed by the next most Significant Byte (MSB),
* followed by the next most Significant Byte (MSB), followed by Least Significant Byte (LSB).
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901009
*/
class four_byte_integer
{
public:
using value_type = std::uint32_t;
four_byte_integer() = default;
explicit four_byte_integer(std::uint32_t v)
{
*this = v;
}
inline std::uint32_t value() const noexcept
{
#if ASIO2_ENDIAN_BIG_BYTE
return value_;
#else
return (
((value_ >> 24) & 0x000000ff) |
((value_ << 24) & 0xff000000) |
((value_ >> 8) & 0x0000ff00) |
((value_ << 8) & 0x00ff0000));
#endif
}
inline operator std::uint32_t() const noexcept { return value(); }
inline four_byte_integer& operator=(std::uint32_t v)
{
#if ASIO2_ENDIAN_BIG_BYTE
value_ = v;
#else
value_ = ((v >> 24) & 0x000000ff) | ((v << 24) & 0xff000000) | ((v >> 8) & 0x0000ff00) | ((v << 8) & 0x00ff0000);
#endif
return (*this);
}
inline constexpr std::size_t required_size() const noexcept
{
return (sizeof(std::uint32_t));
}
inline constexpr std::size_t size() const noexcept
{
return (sizeof(std::uint32_t));
}
inline four_byte_integer& serialize(std::vector<asio::const_buffer>& buffers)
{
buffers.emplace_back(std::addressof(value_), required_size());
return (*this);
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline four_byte_integer& serialize(Container& buffer)
{
static_assert(sizeof(typename Container::value_type) == std::size_t(1));
auto* p = reinterpret_cast<typename Container::const_pointer>(std::addressof(value_));
buffer.insert(buffer.end(), p, p + required_size());
return (*this);
}
inline four_byte_integer& deserialize(std::string_view& data)
{
if (data.size() < required_size())
{
set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
return (*this);
}
asio2::clear_last_error();
value_ =
((data[3] << 24) & 0xff000000) |
((data[2] << 16) & 0x00ff0000) |
((data[1] << 8) & 0x0000ff00) |
((data[0] << 0) & 0x000000ff);
data.remove_prefix(required_size());
return (*this);
}
protected:
std::uint32_t value_{ 0 };
};
/**
* The Variable Byte Integer is encoded using an encoding scheme which uses a single byte for values up to 127.
* Larger values are handled as follows. The least significant seven bits of each byte encode the data, and
* the most significant bit is used to indicate whether there are bytes following in the representation.
* Thus, each byte encodes 128 values and a "continuation bit".
* The maximum number of bytes in the Variable Byte Integer field is four.
* The encoded value MUST use the minimum number of bytes necessary to represent the value [MQTT-1.5.5-1].
* This is shown in Table 1?1 Size of Variable Byte Integer.
*
* Table 1-1 Size of Variable Byte Integer
* +---------+-------------------------------------+---------------------------------------+
* | Digits | From | To |
* +---------+-------------------------------------+---------------------------------------+
* | 1 | 0 (0x00) | 127 (0x7F) |
* +---------+-------------------------------------+---------------------------------------+
* | 2 | 128 (0x80, 0x01) | 16,383 (0xFF, 0x7F) |
* +---------+-------------------------------------+---------------------------------------+
* | 3 | 16,384 (0x80, 0x80, 0x01) | 2,097,151 (0xFF, 0xFF, 0x7F) |
* +---------+-------------------------------------+---------------------------------------+
* | 4 | 2,097,152 (0x80, 0x80, 0x80, 0x01) | 268,435,455 (0xFF, 0xFF, 0xFF, 0x7F) |
* +---------+-------------------------------------+---------------------------------------+
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901011
*/
class variable_byte_integer
{
public:
using value_type = std::int32_t;
variable_byte_integer() = default;
explicit variable_byte_integer(std::int32_t v)
{
*this = v;
}
inline std::int32_t value()
{
return std::get<0>(decode_variable_byte_integer(value_));
}
inline operator std::int32_t() { return value(); }
inline variable_byte_integer& operator=(std::int32_t v)
{
value_ = encode_variable_byte_integer(v);
return (*this);
}
inline std::size_t required_size()
{
return std::get<1>(decode_variable_byte_integer(value_));
}
inline std::size_t size()
{
return std::get<1>(decode_variable_byte_integer(value_));
}
inline variable_byte_integer& serialize(std::vector<asio::const_buffer>& buffers)
{
buffers.emplace_back(value_.data(), required_size());
return (*this);
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline variable_byte_integer& serialize(Container& buffer)
{
static_assert(sizeof(typename Container::value_type) == std::size_t(1));
auto* p = reinterpret_cast<typename Container::const_pointer>(value_.data());
buffer.insert(buffer.end(), p, p + required_size());
return (*this);
}
inline variable_byte_integer& deserialize(std::string_view& data)
{
auto[value, bytes] = decode_variable_byte_integer(data);
if (asio2::get_last_error())
return (*this);
asio2::detail::ignore_unused(value);
std::memcpy((void*)value_.data(), (const void*)data.data(), bytes);
data.remove_prefix(bytes);
return (*this);
}
protected:
// The Variable Byte Integer is encoded using an encoding scheme which uses a single byte for values
// up to 127. Larger values are handled as follows. The least significant seven bits of each byte
// encode the data, and the most significant bit is used to indicate whether there are bytes following
// in the representation. Thus, each byte encodes 128 values and a "continuation bit". The maximum
// number of bytes in the Variable Byte Integer field is four. The encoded value MUST use the minimum
// number of bytes necessary to represent the value [MQTT-1.5.5-1].
std::array<std::uint8_t, 4> value_{};
};
/**
* UTF-8 Encoded String
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901010
*/
class utf8_string
{
public:
using value_type = std::string;
using view_type = std::string_view;
utf8_string() = default;
utf8_string(utf8_string const& o) : length_(o.length_), data_(o.data_)
{
//asio2::detail::disable_sso(data_);
}
utf8_string& operator=(utf8_string const& o)
{
length_ = o.length_;
data_ = o.data_;
//asio2::detail::disable_sso(data_);
return (*this);
}
explicit utf8_string(const char* const s)
{
*this = std::string{ s };
}
explicit utf8_string(std::string s)
{
*this = std::move(s);
}
explicit utf8_string(std::string_view s)
{
*this = std::move(s);
}
inline utf8_string& operator=(std::string s)
{
if (!check_size(s.size()))
{
asio2::set_last_error(asio::error::invalid_argument);
return (*this);
}
if (!check_utf8(s))
{
asio2::set_last_error(asio::error::invalid_argument);
return (*this);
}
asio2::clear_last_error();
data_ = std::move(s);
length_ = static_cast<std::uint16_t>(data_.size());
//asio2::detail::disable_sso(data_);
return (*this);
}
inline utf8_string& operator=(std::string_view s)
{
*this = std::string{ s };
return (*this);
}
inline utf8_string& operator=(const char* const s)
{
*this = std::string{ s };
return (*this);
}
inline bool operator==(const std::string & s) noexcept { return (data_ == s); }
inline bool operator==(const std::string_view & s) noexcept { return (data_ == s); }
inline bool operator!=(const std::string & s) noexcept { return (data_ != s); }
inline bool operator!=(const std::string_view & s) noexcept { return (data_ != s); }
inline utf8_string& operator+=(const std::string & s)
{
if (!check_size(data_.size() + s.size()))
{
asio2::set_last_error(asio::error::invalid_argument);
return (*this);
}
if (!check_utf8(s))
{
asio2::set_last_error(asio::error::invalid_argument);
return (*this);
}
asio2::clear_last_error();
data_ += s;
length_ = static_cast<std::uint16_t>(data_.size());
//asio2::detail::disable_sso(data_);
return (*this);
}
inline utf8_string& operator+=(const std::string_view & s)
{
if (!check_size(data_.size() + s.size()))
{
asio2::set_last_error(asio::error::invalid_argument);
return (*this);
}
if (!check_utf8(s))
{
asio2::set_last_error(asio::error::invalid_argument);
return (*this);
}
asio2::clear_last_error();
data_ += s;
length_ = static_cast<std::uint16_t>(data_.size());
//asio2::detail::disable_sso(data_);
return (*this);
}
inline utf8_string& operator+=(const char* const s)
{
this->operator+=(std::string_view{ s });
return (*this);
}
// https://stackoverflow.com/questions/56833000/c20-with-u8-char8-t-and-stdstring
#if defined(__cpp_lib_char8_t)
explicit utf8_string(const char8_t* const s)
{
*this = std::u8string_view{ s };
}
explicit utf8_string(const std::u8string& s)
{
*this = s;
}
explicit utf8_string(const std::u8string_view& s)
{
*this = s;
}
inline utf8_string& operator=(const std::u8string& s)
{
*this = std::string{ s.begin(), s.end() };
return (*this);
}
inline utf8_string& operator=(const std::u8string_view& s)
{
*this = std::string{ s.begin(), s.end() };
return (*this);
}
inline utf8_string& operator=(const char8_t* const s)
{
*this = std::u8string_view{ s };
return (*this);
}
inline bool operator==(const std::u8string & s) noexcept { return (data_ == std::string{s.begin(), s.end()}); }
inline bool operator==(const std::u8string_view & s) noexcept { return (data_ == std::string{s.begin(), s.end()}); }
inline bool operator!=(const std::u8string & s) noexcept { return (data_ != std::string{s.begin(), s.end()}); }
inline bool operator!=(const std::u8string_view & s) noexcept { return (data_ != std::string{s.begin(), s.end()}); }
inline utf8_string& operator+=(const std::u8string & s)
{
*this += std::string{ s.begin(), s.end() };
return (*this);
}
inline utf8_string& operator+=(const std::u8string_view & s)
{
*this += std::string{ s.begin(), s.end() };
return (*this);
}
inline utf8_string& operator+=(const char8_t* const s)
{
*this += std::u8string_view{ s };
return (*this);
}
#endif
inline std::size_t required_size() const noexcept
{
return (length_.required_size() + data_.size());
}
inline std::size_t size() const noexcept
{
return (data_.size());
}
inline bool empty() const noexcept { return data_.empty(); }
inline std::string data () { return data_; }
inline std::string_view data_view() { return data_; }
inline operator std::string () { return data_; }
inline operator std::string_view () { return data_; }
inline utf8_string& serialize(std::vector<asio::const_buffer>& buffers)
{
length_.serialize(buffers);
buffers.emplace_back(asio::buffer(data_));
return (*this);
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline utf8_string& serialize(Container& buffer)
{
length_.serialize(buffer);
buffer.insert(buffer.end(), data_.begin(), data_.end());
return (*this);
}
inline utf8_string& deserialize(std::string_view& data)
{
length_.deserialize(data);
if (asio2::get_last_error())
return (*this);
if (data.size() < length_.value())
{
set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
return (*this);
}
asio2::clear_last_error();
data_ = data.substr(0, length_.value());
data.remove_prefix(data_.size());
//asio2::detail::disable_sso(data_);
return (*this);
}
protected:
// Each of these strings is prefixed with a Two Byte Integer length field that gives the number of
// bytes in a UTF-8 encoded string itself, as illustrated in Figure 1.1 Structure of UTF-8 Encoded
// Strings below. Consequently, the maximum size of a UTF-8 Encoded String is 65,535 bytes.
two_byte_integer length_{};
// UTF-8 encoded character data, if length > 0.
std::string data_ {};
};
/**
* Binary Data
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901012
*/
class binary_data
{
public:
using value_type = std::string;
using view_type = std::string_view;
binary_data() = default;
binary_data(binary_data const& o) : length_(o.length_), data_(o.data_)
{
//asio2::detail::disable_sso(data_);
}
binary_data& operator=(binary_data const& o)
{
length_ = o.length_;
data_ = o.data_;
//asio2::detail::disable_sso(data_);
return (*this);
}
explicit binary_data(const char* const s)
{
*this = std::string{ s };
}
explicit binary_data(std::string s)
{
*this = std::move(s);
}
explicit binary_data(std::string_view s)
{
*this = std::move(s);
}
inline binary_data& operator=(std::string s)
{
if (!check_size(s.size()))
{
asio2::set_last_error(asio::error::invalid_argument);
return (*this);
}
asio2::clear_last_error();
data_ = std::move(s);
length_ = static_cast<std::uint16_t>(data_.size());
//asio2::detail::disable_sso(data_);
return (*this);
}
inline binary_data& operator=(std::string_view s)
{
*this = std::string{ s };
return (*this);
}
inline binary_data& operator=(const char* const s)
{
*this = std::string{ s };
return (*this);
}
inline bool operator==(const std::string & s) noexcept { return (data_ == s); }
inline bool operator==(const std::string_view & s) noexcept { return (data_ == s); }
inline bool operator!=(const std::string & s) noexcept { return (data_ != s); }
inline bool operator!=(const std::string_view & s) noexcept { return (data_ != s); }
inline binary_data& operator+=(const std::string & s)
{
if (!check_size(data_.size() + s.size()))
{
asio2::set_last_error(asio::error::invalid_argument);
return (*this);
}
asio2::clear_last_error();
data_ += s;
length_ = static_cast<std::uint16_t>(data_.size());
//asio2::detail::disable_sso(data_);
return (*this);
}
inline binary_data& operator+=(const std::string_view & s)
{
if (!check_size(data_.size() + s.size()))
{
asio2::set_last_error(asio::error::invalid_argument);
return (*this);
}
asio2::clear_last_error();
data_ += s;
length_ = static_cast<std::uint16_t>(data_.size());
//asio2::detail::disable_sso(data_);
return (*this);
}
inline binary_data& operator+=(const char* const s)
{
this->operator+=(std::string_view{ s });
return (*this);
}
#if defined(__cpp_lib_char8_t)
explicit binary_data(const char8_t* const s)
{
*this = std::u8string{ s };
}
explicit binary_data(const std::u8string& s)
{
*this = s;
}
explicit binary_data(const std::u8string_view& s)
{
*this = s;
}
inline binary_data& operator=(const std::u8string& s)
{
*this = std::string{ s.begin(), s.end() };
return (*this);
}
inline binary_data& operator=(const std::u8string_view& s)
{
*this = std::string{ s.begin(), s.end() };
return (*this);
}
inline binary_data& operator=(const char8_t* const s)
{
*this = std::u8string_view{ s };
return (*this);
}
inline bool operator==(const std::u8string & s) noexcept { return (data_ == std::string(s.begin(), s.end())); }
inline bool operator==(const std::u8string_view & s) noexcept { return (data_ == std::string(s.begin(), s.end())); }
inline bool operator!=(const std::u8string & s) noexcept { return (data_ != std::string(s.begin(), s.end())); }
inline bool operator!=(const std::u8string_view & s) noexcept { return (data_ != std::string(s.begin(), s.end())); }
inline binary_data& operator+=(const std::u8string & s)
{
*this += std::string{ s.begin(), s.end() };
return (*this);
}
inline binary_data& operator+=(const std::u8string_view & s)
{
*this += std::string{ s.begin(), s.end() };
return (*this);
}
inline binary_data& operator+=(const char8_t* const s)
{
*this += std::u8string_view{ s };
return (*this);
}
#endif
inline std::size_t required_size() const noexcept
{
return (length_.required_size() + data_.size());
}
inline std::size_t size() const noexcept
{
return (data_.size());
}
inline bool empty() const noexcept { return data_.empty(); }
inline std::string data () { return data_; }
inline std::string_view data_view() { return data_; }
inline operator std::string () { return data_; }
inline operator std::string_view () { return data_; }
inline binary_data& serialize(std::vector<asio::const_buffer>& buffers)
{
length_.serialize(buffers);
buffers.emplace_back(asio::buffer(data_));
return (*this);
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline binary_data& serialize(Container& buffer)
{
length_.serialize(buffer);
buffer.insert(buffer.end(), data_.begin(), data_.end());
return (*this);
}
inline binary_data& deserialize(std::string_view& data)
{
length_.deserialize(data);
if (asio2::get_last_error())
return (*this);
if (data.size() < length_.value())
{
set_last_error(mqtt::make_error_code(mqtt::error::malformed_packet));
return (*this);
}
asio2::clear_last_error();
data_ = data.substr(0, length_.value());
data.remove_prefix(data_.size());
//asio2::detail::disable_sso(data_);
return (*this);
}
protected:
// Binary Data is represented by a Two Byte Integer length which indicates the number of data bytes,
// followed by that number of bytes. Thus, the length of Binary Data is limited to the range of 0 to
// 65,535 Bytes.
two_byte_integer length_{};
// number of bytes
std::string data_ {};
};
/**
* A UTF-8 String Pair consists of two UTF-8 Encoded Strings.
* This data type is used to hold name-value pairs.
* The first string serves as the name, and the second string contains the value.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901013
*/
class utf8_string_pair
{
public:
using value_type = std::pair<std::string, std::string>;
using view_type = std::pair<std::string_view, std::string_view>;
utf8_string_pair() = default;
explicit utf8_string_pair(const char* const key, const char* const val)
: key_(std::move(key)), val_(std::move(val))
{
}
explicit utf8_string_pair(std::string key, std::string val)
: key_(std::move(key)), val_(std::move(val))
{
}
explicit utf8_string_pair(std::string_view key, std::string_view val)
: key_(std::move(key)), val_(std::move(val))
{
}
inline utf8_string_pair& operator=(std::tuple<std::string, std::string> kv)
{
key_ = std::move(std::get<0>(kv));
val_ = std::move(std::get<1>(kv));
return (*this);
}
inline utf8_string_pair& operator=(std::pair<std::string, std::string> kv)
{
key_ = std::move(std::get<0>(kv));
val_ = std::move(std::get<1>(kv));
return (*this);
}
inline utf8_string_pair& operator=(std::tuple<std::string_view, std::string_view> kv)
{
key_ = std::move(std::get<0>(kv));
val_ = std::move(std::get<1>(kv));
return (*this);
}
inline utf8_string_pair& operator=(std::pair<std::string_view, std::string_view> kv)
{
key_ = std::move(std::get<0>(kv));
val_ = std::move(std::get<1>(kv));
return (*this);
}
#if defined(__cpp_lib_char8_t)
explicit utf8_string_pair(const char8_t* const key, const char8_t* const val)
: key_(std::move(key)), val_(std::move(val))
{
}
explicit utf8_string_pair(const std::u8string& key, const std::u8string& val)
: key_(key), val_(val)
{
}
explicit utf8_string_pair(const std::u8string_view& key, const std::u8string_view& val)
: key_(key), val_(val)
{
}
inline utf8_string_pair& operator=(std::tuple<std::u8string, std::u8string> kv)
{
key_ = std::move(std::get<0>(kv));
val_ = std::move(std::get<1>(kv));
return (*this);
}
inline utf8_string_pair& operator=(std::pair<std::u8string, std::u8string> kv)
{
key_ = std::move(std::get<0>(kv));
val_ = std::move(std::get<1>(kv));
return (*this);
}
inline utf8_string_pair& operator=(std::tuple<std::u8string_view, std::u8string_view> kv)
{
key_ = std::move(std::get<0>(kv));
val_ = std::move(std::get<1>(kv));
return (*this);
}
inline utf8_string_pair& operator=(std::pair<std::u8string_view, std::u8string_view> kv)
{
key_ = std::move(std::get<0>(kv));
val_ = std::move(std::get<1>(kv));
return (*this);
}
#endif
inline std::size_t required_size() const noexcept
{
return (key_.required_size() + val_.required_size());
}
inline std::size_t size() const noexcept
{
return (key_.size() + val_.size());
}
inline std::string key() { return key_.data(); }
inline std::string val() { return val_.data(); }
inline std::string_view key_view() { return key_.data_view(); }
inline std::string_view val_view() { return val_.data_view(); }
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline utf8_string_pair& serialize(Container& buffer)
{
key_.serialize(buffer);
val_.serialize(buffer);
return (*this);
}
inline utf8_string_pair& deserialize(std::string_view& data)
{
key_.deserialize(data);
if (asio2::get_last_error())
return (*this);
val_.deserialize(data);
return (*this);
}
protected:
utf8_string key_{};
utf8_string val_{};
};
/**
* The Payload contains the Application Message that is being published.
* The content and format of the data is application specific.
* The length of the Payload can be calculated by subtracting the length of the Variable Header
* from the Remaining Length field that is in the Fixed Header.
* It is valid for a PUBLISH packet to contain a zero length Payload.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901119
*/
class application_message
{
public:
using value_type = std::string;
using view_type = std::string_view;
application_message() = default;
application_message(application_message const& o) : data_(o.data_)
{
//asio2::detail::disable_sso(data_);
}
application_message& operator=(application_message const& o)
{
data_ = o.data_;
//asio2::detail::disable_sso(data_);
return (*this);
}
explicit application_message(const char* const s)
{
*this = std::string{ s };
}
explicit application_message(std::string s)
{
*this = std::move(s);
}
explicit application_message(std::string_view s)
{
*this = std::move(s);
}
inline application_message& operator=(std::string s)
{
if (s.size() > std::size_t(max_payload))
{
set_last_error(asio::error::invalid_argument);
return (*this);
}
asio2::clear_last_error();
data_ = std::move(s);
//asio2::detail::disable_sso(data_);
return (*this);
}
inline application_message& operator=(std::string_view s)
{
*this = std::string{ s };
return (*this);
}
inline application_message& operator=(const char* const s)
{
*this = std::string{ s };
return (*this);
}
inline bool operator==(const std::string & s) noexcept { return (data_ == s); }
inline bool operator==(const std::string_view & s) noexcept { return (data_ == s); }
inline bool operator!=(const std::string & s) noexcept { return (data_ != s); }
inline bool operator!=(const std::string_view & s) noexcept { return (data_ != s); }
inline application_message& operator+=(const std::string & s)
{
if (data_.size() + s.size() > std::size_t(max_payload))
{
set_last_error(asio::error::invalid_argument);
return (*this);
}
asio2::clear_last_error();
data_ += s;
//asio2::detail::disable_sso(data_);
return (*this);
}
inline application_message& operator+=(const std::string_view & s)
{
if (data_.size() + s.size() > std::size_t(max_payload))
{
set_last_error(asio::error::invalid_argument);
return (*this);
}
asio2::clear_last_error();
data_ += s;
//asio2::detail::disable_sso(data_);
return (*this);
}
inline application_message& operator+=(const char* const s)
{
this->operator+=(std::string_view{ s });
return (*this);
}
#if defined(__cpp_lib_char8_t)
explicit application_message(const char8_t* const s)
{
*this = std::u8string{ s };
}
explicit application_message(const std::u8string& s)
{
*this = s;
}
explicit application_message(const std::u8string_view& s)
{
*this = s;
}
inline application_message& operator=(const std::u8string& s)
{
*this = std::string(s.begin(), s.end());
return (*this);
}
inline application_message& operator=(const std::u8string_view& s)
{
*this = std::string(s.begin(), s.end());
return (*this);
}
inline application_message& operator=(const char8_t* const s)
{
*this = std::u8string_view{ s };
return (*this);
}
inline bool operator==(const std::u8string & s) noexcept { return (data_ == std::string(s.begin(), s.end())); }
inline bool operator==(const std::u8string_view & s) noexcept { return (data_ == std::string(s.begin(), s.end())); }
inline bool operator!=(const std::u8string & s) noexcept { return (data_ != std::string(s.begin(), s.end())); }
inline bool operator!=(const std::u8string_view & s) noexcept { return (data_ != std::string(s.begin(), s.end())); }
inline application_message& operator+=(const std::u8string & s)
{
*this += std::string{ s.begin(), s.end() };
return (*this);
}
inline application_message& operator+=(const std::u8string_view & s)
{
*this += std::string{ s.begin(), s.end() };
return (*this);
}
inline application_message& operator+=(const char8_t* const s)
{
*this += std::u8string_view{ s };
return (*this);
}
#endif
inline std::size_t required_size() const noexcept
{
return (data_.size());
}
inline std::size_t size() const noexcept
{
return (data_.size());
}
inline bool empty() const noexcept { return data_.empty(); }
inline std::string data () { return data_; }
inline std::string_view data_view() { return data_; }
inline operator std::string () { return data_; }
inline operator std::string_view () { return data_; }
inline application_message& serialize(std::vector<asio::const_buffer>& buffers)
{
buffers.emplace_back(asio::buffer(data_));
return (*this);
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline application_message& serialize(Container& buffer)
{
buffer.insert(buffer.end(), data_.begin(), data_.end());
return (*this);
}
inline application_message& deserialize(std::string_view& data)
{
data_ = data;
data.remove_prefix(data_.size());
//asio2::detail::disable_sso(data_);
return (*this);
}
protected:
std::string data_{};
};
/**
* this class is just used for user application, it is not the part of mqtt protocol.
*/
template<class derived_t>
class user_message_attr
{
//template <class> friend class asio2::detail::mqtt_handler_t;
//template <class> friend class asio2::detail::mqtt_invoker_t;
//template <class> friend class asio2::detail::mqtt_aop_connect;
//template <class> friend class asio2::detail::mqtt_aop_publish;
public:
user_message_attr() = default;
~user_message_attr() = default;
//protected:
inline derived_t& set_send_flag(bool v) { send_flag_ = v; return (static_cast<derived_t&>(*this)); }
inline bool get_send_flag( ) { return send_flag_; }
protected:
bool send_flag_ = true;
};
/**
* Fixed header format
* Each MQTT Control Packet contains a Fixed Header as shown below.
*
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718020
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901021
*/
template<std::uint8_t Version>
class fixed_header : public user_message_attr<fixed_header<Version>>
{
public:
union type_and_flags
{
one_byte_integer byte{ 0 }; // the whole byte
#if ASIO2_ENDIAN_BIG_BYTE
struct
{
std::uint8_t type : 4; // MQTT Control Packet type
bool dup : 1; // Duplicate delivery of a PUBLISH Control Packet
std::uint8_t qos : 2; // PUBLISH Quality of Service, 0, 1 or 2
bool retain : 1; // PUBLISH Retain flag
} bits;
struct
{
std::uint8_t type : 4; // MQTT Control Packet type
std::uint8_t bit3 : 1;
std::uint8_t bit2 : 1;
std::uint8_t bit1 : 1;
std::uint8_t bit0 : 1;
} reserved;
#else
struct
{
bool retain : 1; // PUBLISH Retain flag
std::uint8_t qos : 2; // PUBLISH Quality of Service, 0, 1 or 2
bool dup : 1; // Duplicate delivery of a PUBLISH Control Packet
std::uint8_t type : 4; // MQTT Control Packet type
} bits;
struct
{
std::uint8_t bit0 : 1;
std::uint8_t bit1 : 1;
std::uint8_t bit2 : 1;
std::uint8_t bit3 : 1;
std::uint8_t type : 4; // MQTT Control Packet type
} reserved;
#endif
};
public:
fixed_header()
{
}
explicit fixed_header(control_packet_type type)
{
type_and_flags_.bits.type = asio2::detail::to_underlying(type);
}
constexpr std::uint8_t version() const noexcept { return Version; }
inline std::size_t required_size()
{
return (type_and_flags_.byte.required_size() + remain_length_.required_size());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline fixed_header& serialize(Container& buffer)
{
type_and_flags_.byte.serialize(buffer);
remain_length_ .serialize(buffer);
return (*this);
}
inline fixed_header& deserialize(std::string_view& data)
{
type_and_flags_.byte.deserialize(data);
if (asio2::get_last_error())
return (*this);
remain_length_ .deserialize(data);
return (*this);
}
inline control_packet_type packet_type () { return static_cast<control_packet_type>(type_and_flags_.bits.type ); }
inline control_packet_type message_type () { return packet_type(); }
inline std::int32_t remain_length() { return remain_length_.value(); }
protected:
type_and_flags type_and_flags_{ };
// The Remaining Length is a Variable Byte Integer that represents the number of bytes remaining
// within the current Control Packet, including data in the Variable Header and the Payload.
// The Remaining Length does not include the bytes used to encode the Remaining Length.
// The packet size is the total number of bytes in an MQTT Control Packet, this is equal to the
// length of the Fixed Header plus the Remaining Length.
variable_byte_integer remain_length_ { 0 };
};
/**
* Used to init a variant mqtt::message to empty.
*/
class nullmsg : public fixed_header<asio2::detail::to_underlying(mqtt::version::v4)>
{
public:
nullmsg() : fixed_header(control_packet_type::reserved) {}
inline nullmsg& update_remain_length() { return (*this); }
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901168
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901248
*/
class subscription
{
public:
subscription() = default;
/*
* the "no_local,rap,retain_handling" are only valid in mqtt 5.0
*/
template<class String, class QosOrInt>
explicit subscription(String&& topic_filter,
QosOrInt qos, bool no_local = false, bool rap = false,
retain_handling_type retain_handling = retain_handling_type::send
)
: topic_filter_(std::forward<String>(topic_filter))
{
option_.bits.qos = static_cast<std::uint8_t>(qos);
option_.bits.nl = no_local;
option_.bits.rap = rap;
option_.bits.retain_handling = asio2::detail::to_underlying(retain_handling);
}
inline std::size_t required_size()
{
return (topic_filter_.required_size() + option_.byte.required_size());
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline subscription& serialize(Container& buffer)
{
topic_filter_.serialize(buffer);
option_.byte .serialize(buffer);
return (*this);
}
inline subscription& deserialize(std::string_view& data)
{
topic_filter_.deserialize(data);
if (asio2::get_last_error())
return (*this);
option_.byte .deserialize(data);
return (*this);
}
inline qos_type qos () { return static_cast<qos_type>(option_.bits.qos); }
inline bool no_local () { return option_.bits.nl ; }
inline bool rap () { return option_.bits.rap ; }
inline retain_handling_type retain_handling() { return static_cast<retain_handling_type>(option_.bits.retain_handling); }
inline std::string_view share_name ()
{
auto[name, filter] = parse_topic_filter(topic_filter_.data_view());
std::ignore = filter;
return name;
}
inline std::string_view topic_filter ()
{
auto[name, filter] = parse_topic_filter(topic_filter_.data_view());
std::ignore = name;
return filter;
}
template<class QosOrInt>
inline subscription& qos (QosOrInt v) { option_.bits.qos = static_cast<std::uint8_t>(v); return (*this); }
inline subscription& no_local (bool v) { option_.bits.nl = v; return (*this); }
inline subscription& rap (bool v) { option_.bits.rap = v; return (*this); }
inline subscription& retain_handling(std::uint8_t v) { option_.bits.retain_handling = v; return (*this); }
template<class String>
inline subscription& topic_filter (String&& v) { topic_filter_ = std::forward<String>(v) ; return (*this); }
inline subscription& retain_handling(retain_handling_type v) { option_.bits.retain_handling = asio2::detail::to_underlying(v); return (*this); }
protected:
// The Payload of a SUBSCRIBE packet contains a list of Topic Filters indicating the Topics to
// which the Client wants to subscribe. The Topic Filters MUST be a UTF-8 Encoded String
utf8_string topic_filter_{};
// Each Topic Filter is followed by a Subscription Options byte.
union
{
one_byte_integer byte{ 0 }; // the whole byte
#if ASIO2_ENDIAN_BIG_BYTE
struct
{
std::uint8_t reserved : 2; // reserved for future use
std::uint8_t retain_handling : 2; // Retain Handling option, [Only valid for mqtt 5.0]
bool rap : 1; // Retain As Published option, [Only valid for mqtt 5.0]
bool nl : 1; // No Local option, [Only valid for mqtt 5.0]
std::uint8_t qos : 2; // PUBLISH Quality of Service, 0, 1 or 2
} bits;
#else
struct
{
std::uint8_t qos : 2; // PUBLISH Quality of Service, 0, 1 or 2
bool nl : 1; // No Local option, [Only valid for mqtt 5.0]
bool rap : 1; // Retain As Published option, [Only valid for mqtt 5.0]
std::uint8_t retain_handling : 2; // Retain Handling option, [Only valid for mqtt 5.0]
std::uint8_t reserved : 2; // reserved for future use
} bits;
#endif
} option_{ };
};
/**
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901168
*/
class subscriptions_set
{
protected:
template<class... Args>
static constexpr bool _is_subscription() noexcept
{
if constexpr (sizeof...(Args) == std::size_t(0))
return true;
else
return ((std::is_same_v<asio2::detail::remove_cvref_t<Args>, mqtt::subscription>) && ...);
}
public:
subscriptions_set()
{
}
template<class... Subscriptions, std::enable_if_t<_is_subscription<Subscriptions...>(), int> = 0>
explicit subscriptions_set(Subscriptions&&... Subscripts)
{
set(std::forward<Subscriptions>(Subscripts)...);
}
subscriptions_set(subscriptions_set&&) noexcept = default;
subscriptions_set(subscriptions_set const&) = default;
subscriptions_set& operator=(subscriptions_set&&) noexcept = default;
subscriptions_set& operator=(subscriptions_set const&) = default;
template<class... Subscriptions, std::enable_if_t<_is_subscription<Subscriptions...>(), int> = 0>
inline subscriptions_set& set(Subscriptions&&... Subscripts)
{
data_.clear();
(data_.emplace_back(std::forward<Subscriptions>(Subscripts)), ...);
return (*this);
}
template<class... Subscriptions, std::enable_if_t<_is_subscription<Subscriptions...>(), int> = 0>
inline subscriptions_set& add(Subscriptions&&... Subscripts)
{
(data_.emplace_back(std::forward<Subscriptions>(Subscripts)), ...);
return (*this);
}
inline subscriptions_set& erase(std::string_view topic_filter)
{
for (auto it = data_.begin(); it != data_.end();)
{
if (it->topic_filter() == topic_filter)
it = data_.erase(it);
else
++it;
}
return (*this);
}
inline subscriptions_set& clear()
{
data_.clear();
return (*this);
}
inline std::size_t required_size()
{
std::size_t r = 0;
for (auto& v : data_)
{
r += v.required_size();
}
return r;
}
inline std::size_t count() const noexcept
{
return data_.size();
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline subscriptions_set& serialize(Container& buffer)
{
for (auto& v : data_)
{
v.serialize(buffer);
}
return (*this);
}
inline subscriptions_set& deserialize(std::string_view& data)
{
while (!data.empty())
{
subscription s{};
s.deserialize(data);
if (asio2::get_last_error())
return (*this);
data_.emplace_back(std::move(s));
}
return (*this);
}
inline std::vector<subscription>& data() { return data_; }
protected:
std::vector<subscription> data_{};
};
class one_byte_integer_set
{
protected:
template<class... Args>
static constexpr bool _is_integral() noexcept
{
if constexpr (sizeof...(Args) == std::size_t(0))
return true;
else
return ((std::is_integral_v<asio2::detail::remove_cvref_t<Args>>) && ...);
}
public:
one_byte_integer_set()
{
}
template<class... Integers, std::enable_if_t<_is_integral<Integers...>(), int> = 0>
explicit one_byte_integer_set(Integers... Ints)
{
set(Ints...);
}
one_byte_integer_set(one_byte_integer_set&&) noexcept = default;
one_byte_integer_set(one_byte_integer_set const&) = default;
one_byte_integer_set& operator=(one_byte_integer_set&&) noexcept = default;
one_byte_integer_set& operator=(one_byte_integer_set const&) = default;
template<class... Integers, std::enable_if_t<_is_integral<Integers...>(), int> = 0>
inline one_byte_integer_set& set(Integers... Ints)
{
data_.clear();
(data_.emplace_back(static_cast<one_byte_integer::value_type>(Ints)), ...);
return (*this);
}
template<class... Integers, std::enable_if_t<_is_integral<Integers...>(), int> = 0>
inline one_byte_integer_set& add(Integers... Ints)
{
(data_.emplace_back(static_cast<one_byte_integer::value_type>(Ints)), ...);
return (*this);
}
inline one_byte_integer_set& erase(std::size_t index)
{
if (index < data_.size())
data_.erase(std::next(data_.begin(), index));
return (*this);
}
inline one_byte_integer_set& clear()
{
data_.clear();
return (*this);
}
inline std::size_t required_size()
{
return (data_.empty() ? 0 : data_.size() * data_.front().required_size());
}
inline std::size_t count() const noexcept
{
return data_.size();
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline one_byte_integer_set& serialize(Container& buffer)
{
for (auto& v : data_)
{
v.serialize(buffer);
}
return (*this);
}
inline one_byte_integer_set& deserialize(std::string_view& data)
{
while (!data.empty())
{
one_byte_integer v{};
v.deserialize(data);
if (asio2::get_last_error())
return (*this);
data_.emplace_back(std::move(v));
}
return (*this);
}
inline std::vector<one_byte_integer>& data() { return data_; }
inline one_byte_integer::value_type at(std::size_t i)
{
return static_cast<one_byte_integer::value_type>(data_.size() > i ? data_[i].value() : -1);
}
protected:
std::vector<one_byte_integer> data_{};
};
class utf8_string_set
{
public:
utf8_string_set()
{
}
template<class... Strings>
explicit utf8_string_set(Strings&&... Strs)
{
set(std::forward<Strings>(Strs)...);
}
utf8_string_set(utf8_string_set&&) noexcept = default;
utf8_string_set(utf8_string_set const&) = default;
utf8_string_set& operator=(utf8_string_set&&) noexcept = default;
utf8_string_set& operator=(utf8_string_set const&) = default;
template<class... Strings>
inline utf8_string_set& set(Strings&&... Strs)
{
data_.clear();
(data_.emplace_back(std::forward<Strings>(Strs)), ...);
return (*this);
}
template<class... Strings>
inline utf8_string_set& add(Strings... Strs)
{
(data_.emplace_back(std::forward<Strings>(Strs)), ...);
return (*this);
}
inline utf8_string_set& erase(std::string_view s)
{
for (auto it = data_.begin(); it != data_.end();)
{
if (it->data_view() == s)
it = data_.erase(it);
else
++it;
}
return (*this);
}
inline utf8_string_set& clear()
{
data_.clear();
return (*this);
}
inline std::size_t required_size()
{
std::size_t r = 0;
for (auto& v : data_)
{
r += v.required_size();
}
return r;
}
inline std::size_t count() const noexcept
{
return data_.size();
}
/*
* The Container is usually a std::string, std::vector<char>, ...
*/
template<class Container>
inline utf8_string_set& serialize(Container& buffer)
{
for (auto& v : data_)
{
v.serialize(buffer);
}
return (*this);
}
inline utf8_string_set& deserialize(std::string_view& data)
{
while (!data.empty())
{
utf8_string s{};
s.deserialize(data);
if (asio2::get_last_error())
return (*this);
data_.emplace_back(std::move(s));
}
return (*this);
}
inline std::vector<utf8_string>& data() { return data_; }
/**
* function signature : void(mqtt::utf8_string& str)
*/
template<class Function>
inline utf8_string_set& for_each(Function&& f)
{
for (auto& v : data_)
{
f(v);
}
return (*this);
}
protected:
std::vector<utf8_string> data_{};
};
namespace
{
using iterator = asio::buffers_iterator<asio::streambuf::const_buffers_type>;
using diff_type = typename iterator::difference_type;
std::pair<iterator, bool> mqtt_match_role(iterator begin, iterator end)
{
for (iterator p = begin; p < end;)
{
// Fixed header : at least 2 bytes
if (end - p < static_cast<diff_type>(2))
break;
p += 1;
// Remaining Length
std::int32_t remain_length = 0, remain_bytes = 0;
auto[value, bytes] = decode_variable_byte_integer(std::string_view{ reinterpret_cast<
std::string_view::const_pointer>(p.operator->()), static_cast<std::size_t>(end - p) });
if (error_code ec = asio2::get_last_error(); ec)
{
// need more data
if (ec == asio::error::no_buffer_space)
{
return std::pair(begin, false);
}
// illegal packet
else
{
return std::pair(begin, true);
}
}
remain_length = value;
remain_bytes = bytes;
p += remain_bytes;
// Variable Header, Payload
if (end - p < static_cast<diff_type>(remain_length))
break;
return std::pair(p + static_cast<diff_type>(remain_length), true);
}
return std::pair(begin, false);
}
}
// Write the text for a one_byte_integer variable to an output stream.
inline std::ostream& operator<<(std::ostream& os, one_byte_integer v)
{
std::string s;
v.serialize(s);
return os << std::move(s);
}
// Write the text for a two_byte_integer variable to an output stream.
inline std::ostream& operator<<(std::ostream& os, two_byte_integer v)
{
std::string s;
v.serialize(s);
return os << std::move(s);
}
// Write the text for a four_byte_integer variable to an output stream.
inline std::ostream& operator<<(std::ostream& os, four_byte_integer v)
{
std::string s;
v.serialize(s);
return os << std::move(s);
}
// Write the text for a variable_byte_integer variable to an output stream.
inline std::ostream& operator<<(std::ostream& os, variable_byte_integer v)
{
std::string s;
v.serialize(s);
return os << std::move(s);
}
// Write the text for a utf8_string variable to an output stream.
inline std::ostream& operator<<(std::ostream& os, utf8_string& v)
{
std::string s;
v.serialize(s);
return os << std::move(s);
}
// Write the text for a binary_data variable to an output stream.
inline std::ostream& operator<<(std::ostream& os, binary_data& v)
{
std::string s;
v.serialize(s);
return os << std::move(s);
}
// Write the text for a utf8_string_pair variable to an output stream.
inline std::ostream& operator<<(std::ostream& os, utf8_string_pair& v)
{
std::string s;
v.serialize(s);
return os << std::move(s);
}
// Write the text for a application_message variable to an output stream.
inline std::ostream& operator<<(std::ostream& os, application_message& v)
{
return os << v.data_view();
}
}
#endif // !__ASIO2_MQTT_CORE_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#if !defined(BHO_PREDEF_ARCHITECTURE_H) || defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BHO_PREDEF_ARCHITECTURE_H
#define BHO_PREDEF_ARCHITECTURE_H
#endif
#include <asio2/bho/predef/architecture/alpha.h>
#include <asio2/bho/predef/architecture/arm.h>
#include <asio2/bho/predef/architecture/blackfin.h>
#include <asio2/bho/predef/architecture/convex.h>
#include <asio2/bho/predef/architecture/e2k.h>
#include <asio2/bho/predef/architecture/ia64.h>
#include <asio2/bho/predef/architecture/m68k.h>
#include <asio2/bho/predef/architecture/mips.h>
#include <asio2/bho/predef/architecture/parisc.h>
#include <asio2/bho/predef/architecture/ppc.h>
#include <asio2/bho/predef/architecture/ptx.h>
#include <asio2/bho/predef/architecture/pyramid.h>
#include <asio2/bho/predef/architecture/riscv.h>
#include <asio2/bho/predef/architecture/rs6k.h>
#include <asio2/bho/predef/architecture/sparc.h>
#include <asio2/bho/predef/architecture/superh.h>
#include <asio2/bho/predef/architecture/sys370.h>
#include <asio2/bho/predef/architecture/sys390.h>
#include <asio2/bho/predef/architecture/x86.h>
#include <asio2/bho/predef/architecture/z.h>
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_LOG_HPP__
#define __ASIO2_LOG_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cassert>
#include <string>
#include <asio2/external/predef.h>
#include <asio2/external/assert.hpp>
#include <asio2/base/detail/filesystem.hpp>
#if defined(ASIO2_ENABLE_LOG)
#if __has_include(<spdlog/spdlog.h>)
#if ASIO2_OS_LINUX || ASIO2_OS_UNIX
#if __has_include(<unistd.h>)
#include <unistd.h>
#endif
#if __has_include(<dirent.h>)
#include <dirent.h>
#endif
#elif ASIO2_OS_WINDOWS
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#if __has_include(<Windows.h>)
#include <Windows.h>
#endif
#elif ASIO2_OS_MACOS
#if __has_include(<mach-o/dyld.h>)
#include <mach-o/dyld.h>
#endif
#endif
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/fmt/bundled/chrono.h>
#else
#undef ASIO2_ENABLE_LOG
#endif
#endif
namespace asio2::detail
{
#if defined(ASIO2_ENABLE_LOG)
static std::shared_ptr<spdlog::logger>& get_logger()
{
static std::shared_ptr<spdlog::logger> logger;
static std::mutex mtx;
if (!logger)
{
std::lock_guard guard(mtx);
if (!logger)
{
std::string filepath;
std::shared_ptr<spdlog::logger> loger;
try
{
#if ASIO2_OS_LINUX || ASIO2_OS_UNIX
filepath.resize(PATH_MAX);
auto r = readlink("/proc/self/exe", (char *)filepath.data(), PATH_MAX);
std::ignore = r; // gcc 7 warning: ignoring return value of ... [-Wunused-result]
#elif ASIO2_OS_WINDOWS
filepath.resize(MAX_PATH);
filepath.resize(::GetModuleFileNameA(NULL, (LPSTR)filepath.data(), MAX_PATH));
#elif ASIO2_OS_MACOS
filepath.resize(PATH_MAX);
std::uint32_t bufsize = std::uint32_t(PATH_MAX);
_NSGetExecutablePath(filepath.data(), std::addressof(bufsize));
#endif
if (std::string::size_type pos = filepath.find('\0'); pos != std::string::npos)
filepath.resize(pos);
ASIO2_ASSERT(!filepath.empty());
std::filesystem::path path{ filepath };
std::string name = path.filename().string();
std::string ext = path.extension().string();
name.resize(name.size() - ext.size());
filepath = path.parent_path().append(name).string() + ".asio2.log";
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filepath, true);
file_sink->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%l] %v");
loger = std::make_shared<spdlog::logger>("ASIO2_LOG", std::move(file_sink));
loger->set_level(spdlog::level::debug);
loger->flush_on(spdlog::level::err);
}
catch (const std::exception&)
{
loger.reset();
}
logger = std::move(loger);
}
}
return logger;
}
template<typename... Args>
inline void log(spdlog::level::level_enum lvl, fmt::format_string<Args...> fmtstr, Args&&...args)
{
std::shared_ptr<spdlog::logger>& loger = get_logger();
if (loger)
{
loger->log(lvl, fmtstr, std::forward<Args>(args)...);
}
}
#else
template <typename... Ts>
inline constexpr void log(Ts const& ...) noexcept {}
#endif
class [[maybe_unused]] external_linkaged_log
{
public:
[[maybe_unused]] static bool& has_unexpected_behavior() noexcept
{
static bool flag = false;
return flag;
}
};
namespace internal_linkaged_log
{
[[maybe_unused]] static bool& has_unexpected_behavior() noexcept
{
static bool flag = false;
return flag;
}
}
// just for : debug, find bug ...
[[maybe_unused]] static bool& has_unexpected_behavior() noexcept
{
return external_linkaged_log::has_unexpected_behavior();
}
}
#ifdef ASIO2_LOG
static_assert(false, "Unknown ASIO2_LOG definition will affect the relevant functions of this program.");
#endif
#if defined(ASIO2_ENABLE_LOG)
#define ASIO2_LOG(...) asio2::detail::log(__VA_ARGS__)
#define ASIO2_LOG_TRACE(...) asio2::detail::log(spdlog::level::trace , __VA_ARGS__)
#define ASIO2_LOG_DEBUG(...) asio2::detail::log(spdlog::level::debug , __VA_ARGS__)
#define ASIO2_LOG_INFOR(...) asio2::detail::log(spdlog::level::info , __VA_ARGS__)
#define ASIO2_LOG_WARNS(...) asio2::detail::log(spdlog::level::warn , __VA_ARGS__)
#define ASIO2_LOG_ERROR(...) asio2::detail::log(spdlog::level::err , __VA_ARGS__)
#define ASIO2_LOG_FATAL(...) asio2::detail::log(spdlog::level::critical, __VA_ARGS__)
#else
#define ASIO2_LOG(...) ((void)0)
#define ASIO2_LOG_TRACE(...) ((void)0)
#define ASIO2_LOG_DEBUG(...) ((void)0)
#define ASIO2_LOG_INFOR(...) ((void)0)
#define ASIO2_LOG_WARNS(...) ((void)0)
#define ASIO2_LOG_ERROR(...) ((void)0)
#define ASIO2_LOG_FATAL(...) ((void)0)
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_LOG_HPP__
<file_sep>/*
Copyright <NAME>, 2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_PLAT_WINDOWS_SYSTEM_H
#define BHO_PREDEF_PLAT_WINDOWS_SYSTEM_H
#include <asio2/bho/predef/make.h>
#include <asio2/bho/predef/os/windows.h>
#include <asio2/bho/predef/platform/windows_uwp.h>
#include <asio2/bho/predef/version_number.h>
/* tag::reference[]
= `BHO_PLAT_WINDOWS_SYSTEM`
https://docs.microsoft.com/en-us/windows/uwp/get-started/universal-application-platform-guide[UWP]
for Windows System development.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `WINAPI_FAMILY == WINAPI_FAMILY_SYSTEM` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_PLAT_WINDOWS_SYSTEM BHO_VERSION_NUMBER_NOT_AVAILABLE
#if BHO_OS_WINDOWS && \
defined(WINAPI_FAMILY_SYSTEM) && WINAPI_FAMILY == WINAPI_FAMILY_SYSTEM
# undef BHO_PLAT_WINDOWS_SYSTEM
# define BHO_PLAT_WINDOWS_SYSTEM BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_PLAT_WINDOWS_SYSTEM
# define BHO_PLAT_WINDOWS_SYSTEM_AVAILABLE
# include <asio2/bho/predef/detail/platform_detected.h>
#endif
#define BHO_PLAT_WINDOWS_SYSTEM_NAME "Windows Drivers and Tools"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_WINDOWS_SYSTEM,BHO_PLAT_WINDOWS_SYSTEM_NAME)
<file_sep>
// (C) Copyright <NAME> 1999.
// (C) <NAME> 2002. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// use this header as a workaround for missing <limits>
// See http://www.boost.org/libs/compatibility/index.html for documentation.
#ifndef BHO_LIMITS
#define BHO_LIMITS
#include <asio2/bho/config.hpp>
#ifdef BHO_NO_LIMITS
# error "There is no std::numeric_limits suppport available."
#else
# include <limits>
#endif
#if (!defined(BOOST_LLT)) && (!defined(BOOST_ULLT)) \
&& ((defined(BHO_HAS_LONG_LONG) && defined(BHO_NO_LONG_LONG_NUMERIC_LIMITS)) \
|| (defined(BHO_HAS_MS_INT64 ) && defined(BHO_NO_MS_INT64_NUMERIC_LIMITS )))
// Add missing specializations for numeric_limits:
#ifdef BHO_HAS_MS_INT64
# define BHO_LLT __int64
# define BHO_ULLT unsigned __int64
#else
# define BHO_LLT ::bho::long_long_type
# define BHO_ULLT ::bho::ulong_long_type
#endif
#include <climits> // for CHAR_BIT
namespace std
{
template<>
class numeric_limits<BHO_LLT>
{
public:
BHO_STATIC_CONSTANT(bool, is_specialized = true);
#ifdef BHO_HAS_MS_INT64
static BHO_LLT min BHO_PREVENT_MACRO_SUBSTITUTION (){ return 0x8000000000000000i64; }
static BHO_LLT max BHO_PREVENT_MACRO_SUBSTITUTION (){ return 0x7FFFFFFFFFFFFFFFi64; }
#elif defined(LLONG_MAX)
static BHO_LLT min BHO_PREVENT_MACRO_SUBSTITUTION (){ return LLONG_MIN; }
static BHO_LLT max BHO_PREVENT_MACRO_SUBSTITUTION (){ return LLONG_MAX; }
#elif defined(LONGLONG_MAX)
static BHO_LLT min BHO_PREVENT_MACRO_SUBSTITUTION (){ return LONGLONG_MIN; }
static BHO_LLT max BHO_PREVENT_MACRO_SUBSTITUTION (){ return LONGLONG_MAX; }
#else
static BHO_LLT min BHO_PREVENT_MACRO_SUBSTITUTION (){ return 1LL << (sizeof(BHO_LLT) * CHAR_BIT - 1); }
static BHO_LLT max BHO_PREVENT_MACRO_SUBSTITUTION (){ return ~(min)(); }
#endif
BHO_STATIC_CONSTANT(int, digits = sizeof(BHO_LLT) * CHAR_BIT -1);
BHO_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BHO_LLT) - 1) * 301L / 1000);
BHO_STATIC_CONSTANT(bool, is_signed = true);
BHO_STATIC_CONSTANT(bool, is_integer = true);
BHO_STATIC_CONSTANT(bool, is_exact = true);
BHO_STATIC_CONSTANT(int, radix = 2);
static BHO_LLT epsilon() throw() { return 0; };
static BHO_LLT round_error() throw() { return 0; };
BHO_STATIC_CONSTANT(int, min_exponent = 0);
BHO_STATIC_CONSTANT(int, min_exponent10 = 0);
BHO_STATIC_CONSTANT(int, max_exponent = 0);
BHO_STATIC_CONSTANT(int, max_exponent10 = 0);
BHO_STATIC_CONSTANT(bool, has_infinity = false);
BHO_STATIC_CONSTANT(bool, has_quiet_NaN = false);
BHO_STATIC_CONSTANT(bool, has_signaling_NaN = false);
BHO_STATIC_CONSTANT(bool, has_denorm = false);
BHO_STATIC_CONSTANT(bool, has_denorm_loss = false);
static BHO_LLT infinity() throw() { return 0; };
static BHO_LLT quiet_NaN() throw() { return 0; };
static BHO_LLT signaling_NaN() throw() { return 0; };
static BHO_LLT denorm_min() throw() { return 0; };
BHO_STATIC_CONSTANT(bool, is_iec559 = false);
BHO_STATIC_CONSTANT(bool, is_bounded = true);
BHO_STATIC_CONSTANT(bool, is_modulo = true);
BHO_STATIC_CONSTANT(bool, traps = false);
BHO_STATIC_CONSTANT(bool, tinyness_before = false);
BHO_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero);
};
template<>
class numeric_limits<BHO_ULLT>
{
public:
BHO_STATIC_CONSTANT(bool, is_specialized = true);
#ifdef BHO_HAS_MS_INT64
static BHO_ULLT min BHO_PREVENT_MACRO_SUBSTITUTION (){ return 0ui64; }
static BHO_ULLT max BHO_PREVENT_MACRO_SUBSTITUTION (){ return 0xFFFFFFFFFFFFFFFFui64; }
#elif defined(ULLONG_MAX) && defined(ULLONG_MIN)
static BHO_ULLT min BHO_PREVENT_MACRO_SUBSTITUTION (){ return ULLONG_MIN; }
static BHO_ULLT max BHO_PREVENT_MACRO_SUBSTITUTION (){ return ULLONG_MAX; }
#elif defined(ULONGLONG_MAX) && defined(ULONGLONG_MIN)
static BHO_ULLT min BHO_PREVENT_MACRO_SUBSTITUTION (){ return ULONGLONG_MIN; }
static BHO_ULLT max BHO_PREVENT_MACRO_SUBSTITUTION (){ return ULONGLONG_MAX; }
#else
static BHO_ULLT min BHO_PREVENT_MACRO_SUBSTITUTION (){ return 0uLL; }
static BHO_ULLT max BHO_PREVENT_MACRO_SUBSTITUTION (){ return ~0uLL; }
#endif
BHO_STATIC_CONSTANT(int, digits = sizeof(BHO_LLT) * CHAR_BIT);
BHO_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BHO_LLT)) * 301L / 1000);
BHO_STATIC_CONSTANT(bool, is_signed = false);
BHO_STATIC_CONSTANT(bool, is_integer = true);
BHO_STATIC_CONSTANT(bool, is_exact = true);
BHO_STATIC_CONSTANT(int, radix = 2);
static BHO_ULLT epsilon() throw() { return 0; };
static BHO_ULLT round_error() throw() { return 0; };
BHO_STATIC_CONSTANT(int, min_exponent = 0);
BHO_STATIC_CONSTANT(int, min_exponent10 = 0);
BHO_STATIC_CONSTANT(int, max_exponent = 0);
BHO_STATIC_CONSTANT(int, max_exponent10 = 0);
BHO_STATIC_CONSTANT(bool, has_infinity = false);
BHO_STATIC_CONSTANT(bool, has_quiet_NaN = false);
BHO_STATIC_CONSTANT(bool, has_signaling_NaN = false);
BHO_STATIC_CONSTANT(bool, has_denorm = false);
BHO_STATIC_CONSTANT(bool, has_denorm_loss = false);
static BHO_ULLT infinity() throw() { return 0; };
static BHO_ULLT quiet_NaN() throw() { return 0; };
static BHO_ULLT signaling_NaN() throw() { return 0; };
static BHO_ULLT denorm_min() throw() { return 0; };
BHO_STATIC_CONSTANT(bool, is_iec559 = false);
BHO_STATIC_CONSTANT(bool, is_bounded = true);
BHO_STATIC_CONSTANT(bool, is_modulo = true);
BHO_STATIC_CONSTANT(bool, traps = false);
BHO_STATIC_CONSTANT(bool, tinyness_before = false);
BHO_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero);
};
}
#endif
#endif
<file_sep>#ifndef BHO_THROW_EXCEPTION_HPP_INCLUDED
#define BHO_THROW_EXCEPTION_HPP_INCLUDED
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
//
// bho/throw_exception.hpp
//
// Copyright (c) 2002, 2018, 2019 <NAME>
// Copyright (c) 2008-2009 <NAME> and Reverge Studios, Inc.
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// http://www.boost.org/libs/throw_exception
//
#include <asio2/bho/assert/source_location.hpp>
#include <asio2/bho/config.hpp>
#include <asio2/bho/config/workaround.hpp>
#include <exception>
#include <cstddef>
#if !defined( BHO_EXCEPTION_DISABLE ) && defined( BHO_BORLANDC ) && BHO_WORKAROUND( BHO_BORLANDC, BHO_TESTED_AT(0x593) )
# define BHO_EXCEPTION_DISABLE
#endif
namespace bho
{
#if defined( BHO_NO_EXCEPTIONS )
BHO_NORETURN void throw_exception( std::exception const & e ); // user defined
BHO_NORETURN void throw_exception( std::exception const & e, bho::source_location const & loc ); // user defined
#endif
// All boost exceptions are required to derive from std::exception,
// to ensure compatibility with BHO_NO_EXCEPTIONS.
inline void throw_exception_assert_compatibility( std::exception const & ) {}
// bho::throw_exception
#if !defined( BHO_NO_EXCEPTIONS )
#if defined( BHO_EXCEPTION_DISABLE )
template<class E> BHO_NORETURN void throw_exception( E const & e )
{
throw_exception_assert_compatibility( e );
throw e;
}
template<class E> BHO_NORETURN void throw_exception( E const & e, bho::source_location const & )
{
throw_exception_assert_compatibility( e );
throw e;
}
#else // defined( BHO_EXCEPTION_DISABLE )
template<class E> BHO_NORETURN void throw_exception( E const & e )
{
throw_exception_assert_compatibility( e );
throw e;
}
template<class E> BHO_NORETURN void throw_exception( E const & e, bho::source_location const & loc )
{
throw_exception_assert_compatibility( e );
((void)loc);
throw e;
}
#endif // defined( BHO_EXCEPTION_DISABLE )
#endif // !defined( BHO_NO_EXCEPTIONS )
} // namespace bho
// BHO_THROW_EXCEPTION
#define BHO_THROW_EXCEPTION(x) ::bho::throw_exception(x, BHO_CURRENT_LOCATION)
#endif // #ifndef BHO_THROW_EXCEPTION_HPP_INCLUDED
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_TCP_KEEPALIVE_COMPONENT_HPP__
#define __ASIO2_TCP_KEEPALIVE_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <tuple>
#include <asio2/external/predef.h>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/util.hpp>
#if ASIO2_OS_WINDOWS
# if __has_include(<Mstcpip.h>)
# include <Mstcpip.h> // tcp_keepalive struct
# endif
#endif
namespace asio2::detail
{
template<class derived_t, class args_t>
class tcp_keepalive_cp
{
public:
tcp_keepalive_cp() noexcept {}
~tcp_keepalive_cp() noexcept {}
/**
* @brief set tcp socket keep alive options
* @param onoff - Turn keepalive on or off.
* @param idle - How many seconds after the connection is idle, start sending keepalives.
* @param interval - How many seconds later to send again when no reply is received.
* @param count - How many times to resend when no reply is received.
* @li on macOS Catalina 10.15.5 (19F101), the default value is:
* onoff - false, idle - 7200, interval - 75, count - 8
*/
bool set_keep_alive_options(
bool onoff = true,
unsigned int idle = 60,
unsigned int interval = 3,
unsigned int count = 3
) noexcept
{
derived_t& derive = static_cast<derived_t&>(*this);
auto & socket = derive.socket();
if (!socket.is_open())
{
set_last_error(asio::error::not_connected);
return false;
}
error_code ec;
asio::socket_base::keep_alive option(onoff);
socket.set_option(option, ec);
if (ec)
{
set_last_error(ec);
return false;
}
auto native_fd = socket.native_handle();
detail::ignore_unused(onoff, idle, interval, count, native_fd);
#if ASIO2_OS_LINUX
// For *n*x systems
int ret_keepidle = setsockopt(native_fd, SOL_TCP, TCP_KEEPIDLE , (void*)&idle , sizeof(unsigned int));
if (ret_keepidle)
{
set_last_error(errno, asio::error::get_system_category());
return false;
}
int ret_keepintvl = setsockopt(native_fd, SOL_TCP, TCP_KEEPINTVL, (void*)&interval, sizeof(unsigned int));
if (ret_keepintvl)
{
set_last_error(errno, asio::error::get_system_category());
return false;
}
int ret_keepcount = setsockopt(native_fd, SOL_TCP, TCP_KEEPCNT , (void*)&count , sizeof(unsigned int));
if (ret_keepcount)
{
set_last_error(errno, asio::error::get_system_category());
return false;
}
#elif ASIO2_OS_UNIX
// be pending
#elif ASIO2_OS_MACOS
int ret_keepalive = setsockopt(native_fd, IPPROTO_TCP, TCP_KEEPALIVE, (void*)&idle , sizeof(unsigned int));
if (ret_keepalive)
{
set_last_error(errno, asio::error::get_system_category());
return false;
}
int ret_keepintvl = setsockopt(native_fd, IPPROTO_TCP, TCP_KEEPINTVL, (void*)&interval, sizeof(unsigned int));
if (ret_keepintvl)
{
set_last_error(errno, asio::error::get_system_category());
return false;
}
int ret_keepcount = setsockopt(native_fd, IPPROTO_TCP, TCP_KEEPCNT , (void*)&count , sizeof(unsigned int));
if (ret_keepcount)
{
set_last_error(errno, asio::error::get_system_category());
return false;
}
#elif ASIO2_OS_IOS
// be pending
#elif ASIO2_OS_WINDOWS
// on WSL ubuntu, the ASIO2_OS_WINDOWS is true, but can't find the <Mstcpip.h> file.
#if __has_include(<Mstcpip.h>)
// Partially supported on windows
tcp_keepalive keepalive_options;
keepalive_options.onoff = onoff;
keepalive_options.keepalivetime = idle * 1000; // Keep Alive in milliseconds.
keepalive_options.keepaliveinterval = interval * 1000; // Resend if No-Reply
DWORD bytes_returned = 0;
if (SOCKET_ERROR == ::WSAIoctl(native_fd, SIO_KEEPALIVE_VALS, (LPVOID)&keepalive_options,
(DWORD)sizeof(keepalive_options), nullptr, 0, (LPDWORD)&bytes_returned, nullptr, nullptr))
{
if (::WSAGetLastError() != WSAEWOULDBLOCK)
{
set_last_error(::WSAGetLastError(), asio::error::get_system_category());
return false;
}
}
#endif
#endif
return true;
}
private:
};
}
#endif // !__ASIO2_TCP_KEEPALIVE_COMPONENT_HPP__
<file_sep>#ifndef ASIO2_USE_SSL
#define ASIO2_USE_SSL
#endif
#include "unit_test.hpp"
#include <asio2/asio2.hpp>
#include <asio2/external/fmt.hpp>
static std::string_view chars = "<KEY>";
std::string_view server_key = R"(
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,32DBC28981A12AF1
<KEY>
)";
std::string_view server_crt = R"(
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 1 (0x1)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=AU, ST=HENAN, L=ZHENGZHOU, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=<EMAIL>
Validity
Not Before: Nov 26 08:21:41 2021 GMT
Not After : Nov 24 08:21:41 2031 GMT
Subject: C=AU, ST=HENAN, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=<EMAIL>
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (1024 bit)
Modulus:
00:c4:ba:4e:5f:22:45:ac:74:8f:5a:c3:06:4b:b4:
a6:22:be:68:7b:99:bf:44:02:66:69:09:ec:2c:7a:
68:c9:a9:0a:b2:f4:ed:69:6b:ad:29:59:b7:a6:ff:
69:df:f6:e5:45:44:d7:70:a7:40:84:d6:19:dd:c4:
36:27:86:1d:6d:79:e0:91:e5:77:79:49:28:4f:06:
7f:31:70:8b:ec:c2:58:9c:f4:14:1d:29:bb:2c:5a:
82:c2:b5:ca:de:eb:cb:a8:34:fc:7b:eb:48:76:44:
ed:29:a1:7d:99:3c:ad:a9:3d:8c:8d:ef:12:ef:d5:
ad:bf:40:34:b4:fd:e4:f2:a9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
9B:D5:B6:0E:47:C3:A7:B6:DA:84:3B:F0:CE:D1:50:D3:8F:4F:0A:8A
X509v3 Authority Key Identifier:
keyid:61:74:1F:7E:B1:0E:0D:F9:46:DD:6A:97:85:72:DE:1A:7D:A2:34:65
Signature Algorithm: sha256WithRSAEncryption
b6:1e:bb:f7:fa:c5:9f:07:6e:36:9d:2e:7d:39:8e:a1:ed:f1:
65:a0:0c:e4:bb:6d:bc:eb:58:d5:1d:c2:03:57:8a:41:0a:f1:
81:0f:87:38:c4:56:83:c3:9d:dc:f3:47:88:c8:a7:ba:69:f9:
bb:45:1f:73:48:96:f9:d7:fc:da:73:f9:17:5f:2f:94:19:83:
27:4b:b0:3e:19:29:71:a2:fc:db:d2:5f:6e:4f:e5:f1:d8:35:
55:f8:d9:db:75:dc:fe:11:e0:9f:70:6e:a8:26:2a:ca:7e:25:
08:e1:d5:d8:e3:0b:10:48:c6:ae:c5:b4:7b:15:20:87:97:20:
fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:2a:22:b0:36:16:1d:7a:70:bc:1b:
d3:89:94:ae:33:66:0c:cd:39:95:9e:69:30:37:05:bb:62:cd:
3f:dd:2b:bb:72:16:48:75:91:33:33:ae:b7:d7:2d:bd:ce:66:
f3:6b:69:81:fa:0d:aa:0e:5a:09:9d:24:54:ac:21:9b:14:43:
44:12:56:8b:cc:13:b5:3b:5a:ba:4e:7b:81:42:1e:38:61:ff:
a0:a7:01:2f:0b:67:77:90:48:bb:8a:52:62:69:76:3c:a8:a1:
d6:13:1e:27:f6:02:58:ae:91:4b:9d:37:4e:31:55:73:18:4e:
d0:61:54:3b
-----BEGIN CERTIFICATE-----
<KEY>BA<KEY>
-----END CERTIFICATE-----
)";
std::string_view ca_crt = R"(
-----<KEY>
-----END CERTIFICATE-----
)";
std::string_view dh = R"(
-----BEGIN DH PARAMETERS-----
M<KEY>9lL96seMYoER32zw6y2tXgUeksVrjOkGuheTAgEC
-----END DH PARAMETERS-----
)";
std::string_view client_key = R"(
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,967AA0B1DF77C592
<KEY>
)";
std::string_view client_crt = R"(
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 2 (0x2)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=AU, ST=HENAN, L=ZHENGZHOU, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=3<EMAIL>@qq.com
Validity
Not Before: Nov 26 09:04:13 2021 GMT
Not After : Nov 24 09:04:13 2031 GMT
Subject: C=AU, ST=HENAN, O=WJ, OU=WJSOFT, CN=ZHL/emailAddress=37792738@qq.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (1024 bit)
Modulus:
00:be:94:6f:5b:ae:20:a8:73:25:3f:a8:4d:92:5a:
5b:8b:64:4d:7b:53:2c:fb:10:e9:ad:e5:06:41:5a:
f6:eb:58:9a:22:6b:5c:ac:04:03:c5:09:2a:3d:84:
d9:34:25:42:76:f8:e6:c7:64:cd:5d:ce:ee:03:54:
da:af:dd:da:f2:b4:93:72:3f:26:d6:57:ea:18:ec:
9c:c8:20:bc:1a:a1:f9:e0:f5:64:67:9d:61:b8:f6:
87:a4:d3:36:01:24:b4:e7:00:c3:54:82:bd:7f:22:
48:40:df:43:8c:26:83:aa:b3:68:5d:e9:a1:fe:7c:
6f:a6:5d:a4:bd:f4:1f:e3:25
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
50:C7:26:F5:62:F6:B7:24:3C:1C:5C:58:96:08:59:94:A5:7A:A1:22
X509v3 Authority Key Identifier:
keyid:61:74:1F:7E:B1:0E:0D:F9:46:DD:6A:97:85:72:DE:1A:7D:A2:34:65
Signature Algorithm: sha256WithRSAEncryption
39:c1:66:e0:1a:68:2a:bc:6e:56:a0:a4:18:53:ac:2e:49:03:
d3:df:e0:7d:4e:51:4c:0b:fb:f9:1d:ae:a5:b8:16:b1:b6:23:
db:62:33:25:72:14:99:e1:3a:1a:52:d2:f4:51:74:ef:df:04:
fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:60:05:d5:65:09:6c:44:14:e6:29:
b8:51:03:e0:bd:33:c3:9d:da:99:24:eb:a8:76:18:88:14:84:
83:ee:33:a3:5c:05:9a:3c:e3:f0:35:e3:52:a2:4e:aa:39:07:
41:43:10:3f:cb:03:a2:48:a9:90:ef:5a:53:3b:5b:c7:4d:bb:
76:05:70:eb:a7:15:22:ad:b5:ed:3b:74:58:71:c0:53:90:44:
fc00:e968:6179::de52:7100:66:ee:18:53:d4:4c:5e:d6:29:f4:
4c:18:2c:7a:79:96:38:d7:cf:51:e4:3b:72:9f:9c:be:7f:2e:
fc00:db20:35b:7399::5:cc:31:a7:4c:d9:94:bd:d3:b4:22:
b8:42:d2:6f:99:7a:72:43:b3:a9:03:e2:36:6d:6b:28:4f:f8:
c5:b5:1b:2b:1d:e9:34:8f:66:0a:13:58:d5:28:38:03:22:bc:
37:27:ed:c7:b3:c7:80:63:25:d7:fc:38:ad:ac:f9:aa:5b:07:
15:df:56:17
-----BEGIN CERTIFICATE-----
<KEY>
-----END CERTIFICATE-----
)";
void rdc_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
// tcp dgram rdc
{
struct ext_data
{
int num = 1;
};
asio2::rdc::option server_rdc_option
{
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
},
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num) - 1;
}
};
asio2::rdc::option client_rdc_option
{
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
},
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
}
};
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_call(msg, [msg](std::string_view data) mutable
{
asio::error_code ec = asio2::get_last_error();
if (!ec)
{
std::string s1 = msg.substr(0, msg.find(','));
std::string s2{ data.substr(0, data.find(',')) };
ASIO2_CHECK(std::stoi(s1) + 1 == std::stoi(s2));
}
else
{
ASIO2_CHECK(ec == asio::error::operation_aborted || ec == asio::error::timed_out);
}
});
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18037, asio2::use_dgram, server_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18037);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 20)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
client.async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
});
bool client_start_ret = client.async_start("127.0.0.1", 18037, asio2::use_dgram, client_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18037, asio2::use_dgram, server_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18037, asio2::use_dgram, client_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
std::string rep = clients[i]->call<std::string>(msg);
ASIO2_CHECK(msg == rep);
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test udp rdc
{
struct ext_data
{
int num = 1;
};
asio2::rdc::option udp_rdc_option
{
[](std::string_view)
{
return 0;
}
};
asio2::udp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::udp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_call(msg, [msg](std::string_view data) mutable
{
asio::error_code ec = asio2::get_last_error();
if (!ec)
{
std::string s1 = msg.substr(0, msg.find(','));
std::string s2{ data.substr(0, data.find(',')) };
ASIO2_CHECK(std::stoi(s1) + 1 == std::stoi(s2));
}
else
{
ASIO2_CHECK(ec == asio::error::operation_aborted || ec == asio::error::timed_out);
}
});
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18037, udp_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::udp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::udp_client>());
asio2::udp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_reuse_address());
client.set_no_delay(true);
ASIO2_CHECK(asio2::get_last_error());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18037);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 10)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
client.async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
});
bool client_start_ret = client.async_start("127.0.0.1", 18037, udp_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(server_connect_counter.load(), server_connect_counter == test_client_count);
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 11 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18037, udp_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18037, udp_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
std::string rep = clients[i]->call<std::string>(msg);
ASIO2_CHECK(msg == rep);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
ASIO2_CHECK_VALUE(server_connect_counter.load(), server_connect_counter == test_client_count);
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 11 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test udp kcp rdc
{
struct ext_data
{
int num = 1;
};
asio2::rdc::option udp_rdc_option
{
[](std::string_view)
{
return 0;
}
};
asio2::udp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::udp_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_call(msg, [msg](std::string_view data) mutable
{
asio::error_code ec = asio2::get_last_error();
if (!ec)
{
std::string s1 = msg.substr(0, msg.find(','));
std::string s2{ data.substr(0, data.find(',')) };
ASIO2_CHECK(std::stoi(s1) + 1 == std::stoi(s2));
}
else
{
ASIO2_CHECK(ec == asio::error::operation_aborted || ec == asio::error::timed_out);
}
});
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18037, asio2::use_kcp, udp_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::udp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::udp_client>());
asio2::udp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_reuse_address());
client.set_no_delay(true);
ASIO2_CHECK(asio2::get_last_error());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18037);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 10)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
client.async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
});
bool client_start_ret = client.async_start("127.0.0.1", 18037, asio2::use_kcp, udp_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 11 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18037, asio2::use_kcp, udp_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18037, asio2::use_kcp, udp_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
std::string rep = clients[i]->call<std::string>(msg);
ASIO2_CHECK(msg == rep);
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 11 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
{
asio2::tcp_client client;
std::shared_ptr<asio2::socks5::option<asio2::socks5::method::anonymous>>
sock5_option = std::make_shared<asio2::socks5::option<asio2::socks5::method::anonymous>>("127.0.0.1", 10808);
asio2::rdc::option client_rdc_option
{
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
},
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
}
};
// here, can't use the port 18037 again, otherwise the server_accept_counter and server_disconnect_counter
// maybe not equal the client_connect_counter of the 18037 server, this is because this client
// uses a socks5 proxy, even if this client was destroyed already, the proxy software will
// still connect to the 18037 server.
client.start("127.0.0.1", 18038, asio2::use_dgram, sock5_option, client_rdc_option);
}
{
//std::shared_ptr<asio2::socks5::option<asio2::socks5::method::anonymous>>
// sock5_option = std::make_shared<asio2::socks5::option<asio2::socks5::method::anonymous>>("127.0.0.1", 10808);
//asio2::socks5::option<asio2::socks5::method::anonymous, asio2::socks5::method::password>
// sock5_option{ "s5.doudouip.cn",1088,"zjww-1","aaa123" };
//asio2::rdc::option rdc_option{ [](http::web_request&) { return 0; },[](http::web_response&) { return 0; } };
//std::shared_ptr<asio2::rdc::option<int, http::web_request&, http::web_response&>> rdc_option =
// std::make_shared<asio2::rdc::option<int, http::web_request&, http::web_response&>>(
// [](http::web_request&) { return 0; }, [](http::web_response&) { return 0; });
//client.start(host, port, sock5_option, rdc_option);
}
// test websocket rdc
{
struct ext_data
{
int num = 1;
};
asio2::rdc::option server_rdc_option
{
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
},
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num) - 1;
}
};
asio2::rdc::option client_rdc_option
{
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
},
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
}
};
asio2::ws_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::ws_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_call(msg, [msg](std::string_view data) mutable
{
asio::error_code ec = asio2::get_last_error();
if (!ec)
{
std::string s1 = msg.substr(0, msg.find(','));
std::string s2{ data.substr(0, data.find(',')) };
ASIO2_CHECK(std::stoi(s1) + 1 == std::stoi(s2));
}
else
{
ASIO2_CHECK(ec == asio::error::operation_aborted || ec == asio::error::timed_out);
}
});
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
//ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
//ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18037, server_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::ws_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::ws_client>());
asio2::ws_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18037);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 20)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
client.async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
});
bool client_start_ret = client.async_start("127.0.0.1", 18037, client_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18037, server_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18037, client_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
std::string rep = clients[i]->call<std::string>(msg);
ASIO2_CHECK(msg == rep);
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test http rdc
{
asio2::rdc::option client_rdc_option
{
[](http::web_request&)
{
return 0;
},
[](http::web_response&)
{
return 0;
}
};
asio2::http_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv(
[&](std::shared_ptr<asio2::http_session> & session_ptr, http::web_request& req, http::web_response& rep)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
asio2::ignore_unused(req, rep);
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
//ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
//ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
server.bind("*", [&](http::web_request& req, http::web_response& rep)
{
ASIO2_CHECK(!asio2::get_last_error());
asio2::ignore_unused(req, rep);
std::string target(req.target());
ASIO2_CHECK(target == req.body());
target += ":response";
rep.fill_text(target);
});
bool server_start_ret = server.start("127.0.0.1", 18037);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::http_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::http_client>());
asio2::http_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18037);
client_connect_counter++;
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&](http::web_request& req, http::web_response& rep)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(client.is_started());
asio2::ignore_unused(req, rep);
client.stop();
});
bool client_start_ret = client.async_start("127.0.0.1", 18037, client_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string str = std::to_string(std::rand());
str.insert(0, "/");
http::web_request req;
req.version(11);
req.method(http::verb::get);
req.target(str);
req.body() = str;
req.prepare_payload();
clients[i]->async_call(req, [str](http::web_response& rep) mutable
{
str += ":response";
ASIO2_CHECK(rep.body().text() == str);
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 1 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18037);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18037);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string str = std::to_string(std::rand());
str.insert(0, "/");
http::web_request req;
req.version(11);
req.method(http::verb::get);
req.target(str);
req.body() = str;
req.prepare_payload();
str += ":response";
http::web_response rep = clients[i]->call<http::web_response>(req);
ASIO2_CHECK(rep.body().text() == str);
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 1 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test ssl tcp dgram rdc
{
struct ext_data
{
int num = 1;
};
asio2::rdc::option server_rdc_option
{
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
},
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num) - 1;
}
};
asio2::rdc::option client_rdc_option
{
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
},
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
}
};
asio2::tcps_server server;
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcps_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_call(msg, [msg](std::string_view data) mutable
{
asio::error_code ec = asio2::get_last_error();
if (!ec)
{
std::string s1 = msg.substr(0, msg.find(','));
std::string s2{ data.substr(0, data.find(',')) };
ASIO2_CHECK(std::stoi(s1) + 1 == std::stoi(s2));
}
else
{
ASIO2_CHECK(ec == asio::error::operation_aborted || ec == asio::error::timed_out);
}
});
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18037, asio2::use_dgram, server_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcps_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcps_client>());
asio2::tcps_client& client = *iter;
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18037);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 20)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
client.async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
});
bool client_start_ret = client.async_start("127.0.0.1", 18037, asio2::use_dgram, client_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18037, asio2::use_dgram, server_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18037, asio2::use_dgram, client_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
std::string rep = clients[i]->call<std::string>(msg);
ASIO2_CHECK(msg == rep);
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test ssl websocket rdc
{
struct ext_data
{
int num = 1;
};
asio2::rdc::option server_rdc_option
{
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
},
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num) - 1;
}
};
asio2::rdc::option client_rdc_option
{
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
},
[](std::string_view data)
{
std::string num { data.substr(0,data.find(','))};
return std::stoi(num);
}
};
asio2::wss_server server;
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
// use memory string for cert
server.set_cert_buffer(ca_crt, server_crt, server_key, "123456");
server.set_dh_buffer(dh);
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::wss_session> & session_ptr, std::string_view data)
{
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
ext_data& ex = session_ptr->get_user_data<ext_data&>();
std::string msg = fmt::format("{:05d},", ex.num);
for (int i = 0; i < ex.num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex.num++;
session_ptr->async_call(msg, [msg](std::string_view data) mutable
{
asio::error_code ec = asio2::get_last_error();
if (!ec)
{
std::string s1 = msg.substr(0, msg.find(','));
std::string s2{ data.substr(0, data.find(',')) };
ASIO2_CHECK(std::stoi(s1) + 1 == std::stoi(s2));
}
else
{
ASIO2_CHECK(ec == asio::error::operation_aborted || ec == asio::error::timed_out);
}
});
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ext_data ex;
ex.num = 1;
session_ptr->set_user_data(ex);
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
//ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
//ASIO2_CHECK(session_ptr->local_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18037);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18037, server_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::wss_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::wss_client>());
asio2::wss_client& client = *iter;
// use memory string for cert
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_buffer(ca_crt, client_crt, client_key, "123456");
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18037);
client_connect_counter++;
ext_data ex;
ex.num = 1;
client.set_user_data(ex);
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
ext_data* ex = client.get_user_data<ext_data*>();
if (ex->num > 20)
{
client.stop();
return;
}
std::string msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
ASIO2_CHECK(msg == data);
ex->num++;
msg = fmt::format("{:05d},", ex->num);
for (int i = 0; i < ex->num; i++)
{
msg += chars;
}
client.async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
});
bool client_start_ret = client.async_start("127.0.0.1", 18037, client_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
clients[i]->async_call(msg, [msg](std::string_view data) mutable
{
ASIO2_CHECK(msg == data);
});
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
server_init_counter = 0;
server_start_counter = 0;
server_disconnect_counter = 0;
server_stop_counter = 0;
server_accept_counter = 0;
server_connect_counter = 0;
server_recv_counter = 0;
server_start_ret = server.start("127.0.0.1", 18037, server_rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
client_init_counter = 0;
client_connect_counter = 0;
client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
bool client_start_ret = clients[i]->async_start("127.0.0.1", 18037, client_rdc_option);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
std::string msg = fmt::format("{:05d},", 1);
msg += chars;
std::string rep = clients[i]->call<std::string>(msg);
ASIO2_CHECK(msg == rep);
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
while (server_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 21 * test_client_count);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"rdc",
ASIO2_TEST_CASE(rdc_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_AOP_UNSUBSCRIBE_HPP__
#define __ASIO2_MQTT_AOP_UNSUBSCRIBE_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::detail
{
template<class caller_t, class args_t>
class mqtt_aop_unsubscribe
{
friend caller_t;
protected:
// must be server
template<class Message, class Response, bool IsClient = args_t::is_client>
inline std::enable_if_t<!IsClient, void>
_before_unsubscribe_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
rep.packet_id(msg.packet_id());
mqtt::utf8_string_set& topic_filters = msg.topic_filters();
topic_filters.for_each([&](/*mqtt::utf8_string*/auto& str)
{
auto[share_name, topic_filter] = mqtt::parse_topic_filter(str.data_view());
if (!share_name.empty())
{
caller->shared_targets().erase(caller_ptr, share_name, topic_filter);
}
std::size_t removed = caller->subs_map().erase(topic_filter, caller->client_id());
// The Payload contains a list of Reason Codes.
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901194
if constexpr (std::is_same_v<response_type, mqtt::v5::unsuback>)
{
if /**/ (topic_filter.empty())
rep.add_reason_codes(detail::to_underlying(mqtt::error::topic_filter_invalid));
else if (removed == 0)
rep.add_reason_codes(detail::to_underlying(mqtt::error::no_subscription_existed));
else
rep.add_reason_codes(detail::to_underlying(mqtt::error::success));
}
else
{
std::ignore = removed;
}
});
}
template<class Message, class Response, bool IsClient = args_t::is_client>
inline std::enable_if_t<IsClient, void>
_before_unsubscribe_callback(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
Message& msg, Response& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
ASIO2_ASSERT(false && "client should't recv the unsubscribe message");
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::unsubscribe& msg, mqtt::v3::unsuback& rep)
{
if (_before_unsubscribe_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::unsubscribe& msg, mqtt::v4::unsuback& rep)
{
if (_before_unsubscribe_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
// must be server
inline void _before_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::unsubscribe& msg, mqtt::v5::unsuback& rep)
{
if (_before_unsubscribe_callback(ec, caller_ptr, caller, om, msg, rep); ec)
return;
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v3::unsubscribe& msg, mqtt::v3::unsuback& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v4::unsubscribe& msg, mqtt::v4::unsuback& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
inline void _after_user_callback_impl(
error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
mqtt::v5::unsubscribe& msg, mqtt::v5::unsuback& rep)
{
detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
}
};
}
#endif // !__ASIO2_MQTT_AOP_UNSUBSCRIBE_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_COMEAU_H
#define BHO_PREDEF_COMPILER_COMEAU_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
#define BHO_COMP_COMO BHO_VERSION_NUMBER_NOT_AVAILABLE
/* tag::reference[]
= `BHO_COMP_COMO`
http://en.wikipedia.org/wiki/Comeau_C/C%2B%2B[Comeau {CPP}] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__COMO__+` | {predef_detection}
| `+__COMO_VERSION__+` | V.R.P
|===
*/ // end::reference[]
#if defined(__COMO__)
# if !defined(BHO_COMP_COMO_DETECTION) && defined(__COMO_VERSION__)
# define BHO_COMP_COMO_DETECTION BHO_PREDEF_MAKE_0X_VRP(__COMO_VERSION__)
# endif
# if !defined(BHO_COMP_COMO_DETECTION)
# define BHO_COMP_COMO_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_COMP_COMO_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_COMO_EMULATED BHO_COMP_COMO_DETECTION
# else
# undef BHO_COMP_COMO
# define BHO_COMP_COMO BHO_COMP_COMO_DETECTION
# endif
# define BHO_COMP_COMO_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_COMO_NAME "Comeau C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_COMO,BHO_COMP_COMO_NAME)
#ifdef BHO_COMP_COMO_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_COMO_EMULATED,BHO_COMP_COMO_NAME)
#endif
<file_sep>/*
Copyright <NAME> 2015-2016
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_VERSION_H
#define BHO_PREDEF_VERSION_H
#include <asio2/bho/predef/version_number.h>
#define BHO_PREDEF_VERSION BHO_VERSION_NUMBER(1,13,1)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HPP__
#define __ASIO2_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/version.hpp>
#include <asio2/config.hpp>
#include <asio2/base/timer.hpp>
#include <asio2/tcp/tcp_client.hpp>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/udp/udp_client.hpp>
#include <asio2/udp/udp_server.hpp>
#include <asio2/udp/udp_cast.hpp>
#include <asio2/http/http_client.hpp>
#include <asio2/http/http_server.hpp>
#include <asio2/websocket/ws_client.hpp>
#include <asio2/websocket/ws_server.hpp>
#include <asio2/rpc/rpc_client.hpp>
#include <asio2/rpc/rpc_server.hpp>
#include <asio2/icmp/ping.hpp>
#include <asio2/serial_port/serial_port.hpp>
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
# include <asio2/tcp/tcps_client.hpp>
# include <asio2/tcp/tcps_server.hpp>
# include <asio2/http/https_client.hpp>
# include <asio2/http/https_server.hpp>
# include <asio2/websocket/wss_client.hpp>
# include <asio2/websocket/wss_server.hpp>
# include <asio2/rpc/rpcs_client.hpp>
# include <asio2/rpc/rpcs_server.hpp>
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HPP__
<file_sep>// Copyright (c) 2017 Dynatrace
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// See http://www.boost.org for most recent version.
// Standard library setup for IBM z/OS XL C/C++ compiler.
// Oldest library version currently supported is 2.1 (V2R1)
#if __TARGET_LIB__ < 0x42010000
# error "Library version not supported or configured - please reconfigure"
#endif
#if __TARGET_LIB__ > 0x42010000
# if defined(BHO_ASSERT_CONFIG)
# error "Unknown library version - please run the configure tests and report the results"
# endif
#endif
#define BHO_STDLIB "IBM z/OS XL C/C++ standard library"
#define BHO_HAS_MACRO_USE_FACET
#define BHO_NO_CXX11_HDR_TYPE_TRAITS
#define BHO_NO_CXX11_HDR_INITIALIZER_LIST
#define BHO_NO_CXX11_ADDRESSOF
#define BHO_NO_CXX11_SMART_PTR
#define BHO_NO_CXX11_ATOMIC_SMART_PTR
#define BHO_NO_CXX11_NUMERIC_LIMITS
#define BHO_NO_CXX11_ALLOCATOR
#define BHO_NO_CXX11_POINTER_TRAITS
#define BHO_NO_CXX11_HDR_FUNCTIONAL
#define BHO_NO_CXX11_HDR_UNORDERED_SET
#define BHO_NO_CXX11_HDR_UNORDERED_MAP
#define BHO_NO_CXX11_HDR_TYPEINDEX
#define BHO_NO_CXX11_HDR_TUPLE
#define BHO_NO_CXX11_HDR_THREAD
#define BHO_NO_CXX11_HDR_SYSTEM_ERROR
#define BHO_NO_CXX11_HDR_REGEX
#define BHO_NO_CXX11_HDR_RATIO
#define BHO_NO_CXX11_HDR_RANDOM
#define BHO_NO_CXX11_HDR_MUTEX
#define BHO_NO_CXX11_HDR_FUTURE
#define BHO_NO_CXX11_HDR_FORWARD_LIST
#define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
#define BHO_NO_CXX11_HDR_CODECVT
#define BHO_NO_CXX11_HDR_CHRONO
#define BHO_NO_CXX11_HDR_ATOMIC
#define BHO_NO_CXX11_HDR_ARRAY
#define BHO_NO_CXX11_HDR_EXCEPTION
#define BHO_NO_CXX11_STD_ALIGN
#define BHO_NO_CXX14_STD_EXCHANGE
#define BHO_NO_CXX14_HDR_SHARED_MUTEX
#define BHO_NO_CXX17_STD_INVOKE
#define BHO_NO_CXX17_STD_APPLY
#define BHO_NO_CXX17_ITERATOR_TRAITS
<file_sep># 基于c++和asio的网络编程框架asio2教程基础篇:4、使用tcp客户端发送数据时,如何同步获取服务端返回结果
## 问题描述
我们先看使用异步框架遇见的一个问题:
```cpp
// 我们调用send函数向服务端发送数据
client.send("abc");
```
假定服务端收到abc之后,回复123,问题是:我们在哪里接收这个123呢?如下:
```cpp
client.bind_recv([&](std::string_view data)
{
// 会在这个回调函数里收到 123
});
```
这有个问题就是我们没有办法在发送数据的地方,直接得到远程回复的结果。
```cpp
// 比如我想这样:发送完abc之后,等待服务端回复,回复的结果直接存储到我的变量里。
// (注意这里只是举例,实际使用方法和这里不同)
std::string res = client.send("abc");
```
好的,框架已经支持这种功能,我给这个功能取了个名字叫rdc,即remote data call,即远程数据调用。
最简单的例子:
```cpp
asio2::tcp_client client;
// 数据解析函数
asio2::rdc::option rdc_option
{
[](std::string_view data) { return 0; }
};
// 启动,把rdc_option传进去
client.start("127.0.0.1", 8080, rdc_option);
// 同步远程调用
std::string res = client.call<std::string>("abc"); // res == "123"
```
上面这个例子只是作为最简单的演示代码,没有处理tcp拆包,实际使用过程中会有问题。这个问题先放一边,看完后面复杂的协议处理部分自然就明白了。
我们先思考一下,我们如何实现这个功能?
简单的思路就是,发送数据时,将发送的数据取一个id,将id保存到一个map中,当收到回复时,从回复数据中也取一个id,然后到map中查找有没有这个id,如果找到了,就把回复的数据给那个id即可。(id怎么取?把回复的数据给那个id:怎么给?这个问题放一边,只要知道,我们实现这个功能基本上就是这个思路,就行了)
我们再看上面的例子:
```cpp
std::string res = client.call<std::string>("abc"); // res == "123"
```
发abc得123,这只是最简单的情况,实际情况下服务端可能会发送很多数据,如果服务端发了123,又发了567,上面的res这个变量内容到底是123还是567呢?
这就需要我们思考一个问题:怎么把发送的数据和接收的数据对应起来?我发送abc之后,res变量的内容一定要是123,而不能是567。
怎么办呢?对,就是取id?
上面的数据abc,有id吗?能取id吗?不能。所以上面的数据解析函数里是 return 0; 因为没法取id
```cpp
// 数据解析函数
asio2::rdc::option rdc_option
{
[](std::string_view data) { return 0; /* 所以这里用了return 0;*/ }
};
```
为什么用 return 0; 其实return 0;的流程是这样的:
使用call函数发送数据时,调用数据解析函数(即上面的rdc_option),把数据传过去(即传到std::string_view data这里了),返回一个id(即return 0),把这个id 0存到map中,当收到回复123时,也调用数据解析函数,也把数据传过去(这次传的数据时接收的数据),也返回一个id(仍然是return 0),到map中查找这个id 0,找到了,于是把123这个数据赋给了res那个变量。
所以,如果先收到了567,也会把567赋给res变量。这是因为这里没有取id,id永远是0,id是0的意思就是:不管收到什么数据,都会认为是这次call函数的回复。
所以,如果想用这个功能,那你的协议必须要有id对应关系,否则,虽然能用,但是数据可能是错的,对不上号。
那么下面假定你的协议是个字符串,格式是这样的:id,内容
也就是说开头是id,id是个字符串,后面是内容,内容也是字符串,id和内容之间用一个逗号分隔。
下面开始说这种情况怎么使用该功能:
##### 客户端代码
```cpp
asio2::tcp_client client;
// 数据解析函数,当你发送数据时,框架内部会自动调用这个函数来从发送的数据中解析出
// 唯一id,asio2的tcp在发送数据时,数据最终都会变为std::string_view格式,所以这个
// 解析函数的参数是(std::string_view data)这个参数就表示你真正发送出去的数据
asio2::rdc::option rdc_option
{
[](std::string_view data)
{
// 把逗号之前的id取出来,转换为整数(其实转不转为整数都行,直接返回字符串形式的id也支持)
std::string strid = data.substr(0, data.find(','));
int id = std::stoi(strid);
return id;
}
};
// 启动,第3个参数表示用\n做数据边界
// 另外,如果你要是不用“远程数据调用”这个功能的话,下面的第4个参数你是不需要传的,就传前
// 3个参数就行了,也就是说,想用“远程数据调用”这个功能,就传rdc_option,不想用就不传,如果
// 没有传rdc_option这个参数,那么框架在编译期就会把该功能禁用掉,所以用不用“远程数据调用”
// 这个功能,对运行时的性能基本没有任何损失。
client.start("127.0.0.1", 8080, '\n', rdc_option);
// 要发送的数据:id是1,接着是逗号,接着是内容abc,接着是\n,为什么要用\n
// \n是做tcp拆包用的,注意看上面的client.start的第3个参数\n,就表示按照\n
// 进行拆包(关于tcp数据拆包的知识,如果不熟悉的先网络搜索了解一下)
std::string msg = "1,abc\n";
// 调用call函数发送数据,并等待服务端回复结果
std::string res = client.call<std::string>(msg); // res == "1,123\n"
// 这里res的值一定是1,123\n 而不会是其它数据
// 注意call<std::string>这里的这个模板参数,表示返回的数据类型,因为我们的协议用的
// 是字符串,所以这里我们就用std::string来接收返回的数据,注意不能用std::string_view
// 因为一旦client.call这个同步远程调用结束返回后,client对象的socket接收缓冲区的
// 内容可能就被销毁无效了,也就意味着std::string_view的内容也会无效。
```
##### 服务端代码
```cpp
asio2::tcp_server server;
server.bind_recv([&](auto & session_ptr, std::string_view data)
{
// 这里就简单的判断一下,如果收到1,abc\n就回复1,123\n
// 实际情况肯定要复杂很多,按照实际要求去处理即可。
if (data == "1,abc\n")
session_ptr->async_send("1,123\n");
});
server.start("0.0.0.0", 8080, '\n'); // 服务端同样也按\n拆包
```
##### 异步远程调用
```cpp
// 第1个参数是要发送的数据 这个参数和调用async_send函数发送数据时第1个参数的性质完全一样
// 第2个参数表示回调函数,当服务端返回数据时,或者超时了,这个回调函数就会被调用
// 第3个参数表示超时时间,这个参数可以为空,为空时会使用默认超时,默认超时可用
// client.set_default_timeout(...)来设置
client.async_call(msg, [](std::string_view data)
{
// 使用asio2::get_last_error()来判断本次调用是成功还是失败,
// 比如超时了,那么错误码就是asio::error::timed_out
if (!asio2::get_last_error())
{
// 如果没有错误 可以处理数据了
// data 就是服务端返回的数据 这里就不演示怎么处理数据了
// data的内容是服务端返回的"1,123\n"
std::cout << data;
}
}, std::chrono::seconds(3));
```
## 深入功能1:使用自定义类型的返回数据
问:上面的async_call回调函数的参数是(std::string_view data),其中data表示接收到的数据内容,那么有人可能会问,我能用自定义的数据类型来存储接收到的数据内容吗?
答:可以的。
```cpp
// 首先定义一个用户自定义的类型 然后就是如何把接收到的数据内容转换为自定义类型的问题了
struct userinfo
{
std::string content;
// 必须实现一个无参数的构造函数
userinfo() = default;
// 如何将接收到的数据转换为userinfo类型呢?
// 方法1:提供一个(std::string_view s)的构造函数
userinfo(std::string_view s)
{
// s就是接收到到的数据内容,这里就是简单的把s的内容保存到成员变量content中了
content = s.substr(s.find(',') + 1);
}
// 方法2:提供一个operator=(std::string_view s)的等于操作符函数
void operator=(std::string_view s)
{
content = s.substr(s.find(',') + 1);
}
// 方法3:提供一个operator<<(std::string_view s)的输入操作符函数
//void operator<<(std::string_view s)
//{
// content = s.substr(s.find(',') + 1);
//}
};
// 方法4:提供一个全局的operator<<(...)的输入操作符函数
// 注意方法3和4同时只能有一个 方法1到4只提供一个即可
void operator<<(userinfo& u, std::string_view s)
{
u.content = s.substr(s.find(',') + 1);
}
```
然后直接按自定义类型进行调用:
```cpp
// 异步远程调用
client.async_call(s, [](userinfo u)
{
// 注意回调函数的参数是userinfo u
});
// 同步远程调用
userinfo info = client.call<userinfo>(s, std::chrono::seconds(3));
```
## 深入功能2:使用自定义类型的唯一id
问:上面的发送数据的解析函数(即上面代码中声明的变量rdc_option)返回的唯一id的类型是int型的,我能用自定义的数据类型作为唯一id返回吗?
答:可以的。
除了用基本int类型作为唯一id,用字符串std::string等各种c++标准库自带的类型都是可以的。只要这个c++标准库自带的类型能用作multimap的key就行(框架内部是用multimap来存储id的)。
比如,最常见的,你可以用uuid作为唯一id,这时就需要用字符串std::string类型来作为唯一id了。
除此之外,你也可以用你自己的自定义的类型作为id的类型,如下:
```cpp
// 首先定义一个自定义的唯一id类型
struct custom_id
{
std::string country;
std::string name;
// 由于框架内部使用的是multimap来存储id的,所以自定义的类型,必须提供一个比较函数
// 方法1:提供一个小于的比较操作符成员函数重载
//bool operator<(const custom_id &p) const
//{
// return (this->country + this->name < p.country + p.name);
//}
};
// 方法2:提供一个std标准库的std::less的全局函数重载
template <>
struct std::less<custom_id>
{
public:
bool operator()(const custom_id &p1, const custom_id &p2) const
{
return (p1.country + p1.name < p2.country + p2.name);
}
};
```
然后在发送数据的解析函数中去转换即可,如下:
```cpp
asio2::rdc::option rdc_option
{
[](std::string_view data)
{
// 然后按照你的实际需求将发送数据里面的id相关的信息取出来,转化为
// 自定义类型变量并返回即可
// 至于怎么转换,下面只是简单的举例,你完全可以按照你自己的协议去做
custom_id id;
id.name = data.substr(0, data.find(','));
return id;
}
};
```
## 深入功能3:链式调用
问:上面的异步远程调用函数async_call和同步远程调用函数call里面的参数比较多,容易忘记参数顺序,有没有好的办法处理呢?
答:使用链式调用。
```cpp
// 异步链式调用 timeout async_call response的顺序完全随意
client.timeout(std::chrono::seconds(5)).async_call(s).response([](userinfo info)
{
});
// 同步链式调用 .call函数必须是最后一个调用节点
client.timeout(std::chrono::seconds(3)).call<std::string>(s);
```
## 深入功能4:服务端和客户端互相调用
问:上面演示的都是客户端远程调用服务端的,服务端能不能远程调用客户端呢?
答:可以。使用方法和前面的说明基本完全相同。
```cpp
// 服务端启动时必须也要传rdc_option
server.start("0.0.0.0", 8080, "\r\n", std::move(rdc_option));
// 然后有了session_ptr后,就可以用它来调用了
session_ptr->async_call(str, [](std::string_view data)
{
}, std::chrono::seconds(3));
```
## 深入功能5:发送数据和接收数据使用不同的解析函数
问:上面的演示代码中只使用了“发送数据的解析函数”,如果发送数据所使用的协议,和接收数据所使用的协议不同,无法用同一个解析函数解析出唯一id,该怎么办呢?
答:同时提供发送数据的解析函数,和接收数据的解析函数即可。
实际上框架内部有两个解析函数,一个发送数据时的解析函数,一个接收数据时的解析函数。如果你的rdc_option中只包含了一个解析函数,那么这个解析函数既用来解析发送数据,也用来解析接收数据。
```cpp
asio2::rdc::option rdc_option
{
[](std::string_view data) // 第1个是send数据的解析函数
{
// 然后按照你的实际需求将发送数据里面的id相关的信息取出来,转化为
// 自定义类型变量并返回即可
// 至于怎么转换,下面只是简单的举例,你完全可以按照你自己的协议去做
custom_id id;
id.name = data.substr(0, data.find(','));
return id;
},
[](std::string_view data) // 第2个是recv数据的解析函数
{
// 注意:虽然可以同时提供发送数据的解析函数,和接收数据的解析函数
// 但是返回的id的类型必须相同,因为框架内部是根据id来查找回调函数的
// 如果id类型不一样,就没法处理了。
// 还有,这里只是示意怎么使用,并没有按照协议的不同做不同的解析,这个
// 用户根据自己的实际需求去做就行了。
custom_id id;
id.country = data.substr(0, data.find(','));
return id;
}
};
server.start(host, port, "\r\n", std::move(rdc_option));
```
## 深入功能6:两次发送的数据的唯一id相同可以吗?
答:可以的。
```cpp
asio2::rdc::option rdc_option
{
[](std::string_view data)
{
// 实际上,你可以在这里直接返回0 (返回其它的数字或字符串,等等,都可以)
// 只要每次返回的id都相同,这就表示所有发送出去的的数据,对方在返回结果
// 数据后,会按照发送时的顺序,依次调用你的回调函数。
return 0;
}
};
client.start(host, port, "\r\n", std::move(rdc_option));
```
```cpp
asio2::rdc::option rdc_option
{
[](std::string_view data)
{
// 如果协议中没有包含有效的id,那么就返回0,这样也是可以的
// 当接收到数据时,会按照发送时的顺序,依次调用id是0的回调函数
// 当然,发送数据解析出的id如果是0,那么接收数据解析出的id也
// 一定要是0,只不过可以有多个数据都返回了0这个id
if (data.find(',') == std::string_view::npos)
return 0;
// 如果协议中包含了有效的id 那么就返回该id作为唯一id
// 返回了id的,当接收到数据时,就会按照接收数据解析出来的id
// 来调用你对应的回调函数
return std::stoi(std::string{ data.substr(0, data.find(',')) });
}
};
client.start(host, port, "\r\n", std::move(rdc_option));
```
但是:如果两次发送的数据的id相同的话,一旦网络不稳定,是会出现问题的。我用下面的流程举例:
1、client调用call或async_call,发送数据,假如id是0,超时是3秒,框架会把0存到multimap中;
2、server在3秒内一直不回复;
3、client的超时到了,你的回调函数被调用,同时框架内部会把multimap中id是0的元素删掉(实际只删第1个id是0的元素,假如有多个id是0的话)
4、client再次调用call或async_call,发送数据,id还是0,框架会把0再存到multimap中;
5、此时server回复了,但回复的信息是针对第1步中那个id为0的消息进行回复的;
6、client中,你的回调函数被调用,但在这个回调函数中接收的数据实际上是第1次call(或async_call)的结果,而不是第2次call的结果,因为两次id都是0,框架是无法识别哪个回复对应哪个请求的,只能按照顺序取出multimap中保存的回调函数进行调用。
但是如果每个数据的id都是不同的,那就不会存在上面的问题。
所以如果你的协议中,有id相同的情况的话,而且对数据的正确性要求非常严格,那就不能这样用了,网络的延迟和波动等等问题很难说,长时间运行的话,是一定会出问题的。当然如果对数据的正确性要求不那么严格,那id相同也没什么问题。
## 深入功能7:服务端是别人写的不能改,只有客户端是我写的能用这个功能吗?
答:可以的。
实际上这个功能只和你的协议以及响应模式有关(就是说你发送一条,对方就给你回一条,而不是给你回多条,也就是只要是一发一收,一对一的关系就能用)
## 深入功能8:call,async_call 和 send,async_send可以混用吗?
答:可以的。
如果你想在发送数据的代码的地方直接取得对方返回的结果数据,那就用call或async_call。
如果只是想发送数据,并不想立即取得结果,那就用send或async_send即可。
不管是send或async_send还是call或async_call,都会发送数据,区别在于,send或async_send发送数据时,框架内部没有从你发送的数据中解析出id,当然也就没有存储该id了。send或async_send函数把数据发出去之后就不管了。但call或async_call把数据发出去之后,如果收到对方回复的数据了,框架内部还会解析接收到数据,然后调用你提供的回调函数等。
但是如果你在启动某组件时没有传入rdc数据解析器(比如这样client.start(host, port, "\r\n");没有第4个参数,也就是说没有传rdc_option),那么call和async_call是用不了。
还有一点是用来发送数据的async_send函数有个重载版本,也可以传入一个回调函数,如
client.async_send("abc",[](std::size_t bytes_sent)
{
});
这个回调函数只是用来通知你,这次发送的数据,是发送成功了还是发送失败了。并不是收到了远端给你的回复数据的通知。所以这点不要搞混淆了,只有call和async_call的回调函数才是“收到了远端的回复数据的通知”。
## 实现流程简要说明
流程是这样的:
1、客户端调用call或async_call发送数据
2、asio2框架内部调用rdc_option中的解析函数解析发送的数据,得到id 存起来(存到一个multimap中了)
3、服务端返回数据,框架内部调用rdc_option中的解析函数解析接收的数据,得到id ,到multimap中找前面存起来的那个id,找到了,就调用该id对应的回调函数
服务端远程调用客户端流程是一样的。
**上面是用tcp通信来举例的,实际上asio2框架里的所有组件tcp udp http websocket ssl 串口,全部支持远程数据调用功能。**
其中udp websocket组件中的使用方式和tcp中的使用方式完全一样,因为这几个协议的形为一致,而且内部都是用std::string_view来传递数据的。这里就不再为udp websocket列举代码来介绍怎么用了。
但http的使用方式是不一样的,下面用代码说明:
## http下远程数据调用步骤
```cpp
asio2::http_client client;
// http client 的远程数据调用必须同时提供发送数据的解析函数和接收数据的解析函数
// 因为http client在发送数据时,框架底层的数据格式是web_request类型
// 而http client在接收数据时,框架底层的数据格式是web_response类型
// 发送和接收数据的类型不一样,所以必须提供两个解析函数
// 为什么都是return 0;呢?这是由http 1.1协议的特性决定的,http client先发送请求,
// 然后http server再回复请求,而且http协议通常是一对一的,即一次请求对应
// 一次回复,所以再用id就没有多大意义了,但又必须得返回个id,所以就return 0了
asio2::rdc::option rdc_option
{
[](http::web_request &) { return 0; },
[](http::web_response&) { return 0; }
};
if (client.start(host, port, rdc_option))
{
http::web_request req(http::verb::get, "/", 11);
// 同步调用
http::web_response rep = client.call<http::web_response>(req);
// 异步调用
// 注意有个细节:上面的同步调用时返回的是http::web_response对象,而这里的异步
// 调用的回调函数的参数http::web_response&是个引用类型,因为同步调用函数如果
// 返回引用会不安全,这个和上面介绍的tcp下同步调用不能返回std::string_view
// 是相同的原因。
client.async_call(std::move(req), [](http::web_response& rep)
{
std::ignore = rep;
});
}
```
上面是http client使用远程数据调用的方法,那http server能远程调用http client吗?
不能的,这还是由http协议的特性决定的,只能由http client主动向http server发送请求,然后http server回复,而不能由http server发送请求,http client来回复。(目前asio2框架里只支持到http 1.1,http 2.0协议上的不同暂不考虑)
但是,http session如果升级到websocket之后,是支持向websocket client主动发出远程数据调用的。
###### 现在http client已经内置了rdc option,如果你没传rdc option就用内置的rdc option,所以现在http client可以这样使用:
```cpp
asio2::http_client client;
client.start("127.0.0.1", "8080");
http::web_request req1(http::verb::get, "/index.html", 11);
http::web_response res1 = client.call<http::web_response>(req1);
http::web_request req2(http::verb::get, "/login.html", 11);
http::web_response res2 = client.call<http::web_response>(req2);
```
上面这个用法相比 http_client::execute 的好处是:http_client::execute每次都创建一个新连接,用完之后连接就关掉了,而上面这个用法,不会关闭连接,而是一直使用同一个连接,这样就不存在每次建立连接时的tcp三次握手这个问题,效率要好一些,而且http client有自动重连功能,即使由于超时或其它原因,断开之后也会再次连接上服务端。
### 最后编辑于2022-12-18
<file_sep>/*
Copyright 2018 <NAME>
(<EMAIL>)
Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_CORE_EMPTY_VALUE_HPP
#define BHO_CORE_EMPTY_VALUE_HPP
#include <asio2/bho/config.hpp>
#if !defined(BHO_NO_CXX11_RVALUE_REFERENCES)
#include <utility>
#endif
#if defined(BHO_GCC_VERSION) && (BHO_GCC_VERSION >= 40700)
#define BHO_DETAIL_EMPTY_VALUE_BASE
#elif defined(BHO_INTEL) && defined(_MSC_VER) && (_MSC_VER >= 1800)
#define BHO_DETAIL_EMPTY_VALUE_BASE
#elif defined(BHO_MSVC) && (BHO_MSVC >= 1800)
#define BHO_DETAIL_EMPTY_VALUE_BASE
#elif defined(BHO_CLANG) && !defined(__CUDACC__)
#if __has_feature(is_empty) && __has_feature(is_final)
#define BHO_DETAIL_EMPTY_VALUE_BASE
#endif
#endif
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4510)
#endif
namespace bho {
template<class T>
struct use_empty_value_base {
enum {
#if defined(BHO_DETAIL_EMPTY_VALUE_BASE)
value = __is_empty(T) && !__is_final(T)
#else
value = false
#endif
};
};
struct empty_init_t { };
namespace empty_ {
template<class T, unsigned N = 0,
bool E = bho::use_empty_value_base<T>::value>
class empty_value {
public:
typedef T type;
#if !defined(BHO_NO_CXX11_DEFAULTED_FUNCTIONS)
empty_value() = default;
#else
empty_value() { }
#endif
empty_value(bho::empty_init_t)
: value_() { }
#if !defined(BHO_NO_CXX11_RVALUE_REFERENCES)
#if !defined(BHO_NO_CXX11_VARIADIC_TEMPLATES)
template<class U, class... Args>
empty_value(bho::empty_init_t, U&& value, Args&&... args)
: value_(std::forward<U>(value), std::forward<Args>(args)...) { }
#else
template<class U>
empty_value(bho::empty_init_t, U&& value)
: value_(std::forward<U>(value)) { }
#endif
#else
template<class U>
empty_value(bho::empty_init_t, const U& value)
: value_(value) { }
template<class U>
empty_value(bho::empty_init_t, U& value)
: value_(value) { }
#endif
const T& get() const BHO_NOEXCEPT {
return value_;
}
T& get() BHO_NOEXCEPT {
return value_;
}
private:
T value_;
};
#if !defined(BHO_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template<class T, unsigned N>
class empty_value<T, N, true>
: T {
public:
typedef T type;
#if !defined(BHO_NO_CXX11_DEFAULTED_FUNCTIONS)
empty_value() = default;
#else
empty_value() { }
#endif
empty_value(bho::empty_init_t)
: T() { }
#if !defined(BHO_NO_CXX11_RVALUE_REFERENCES)
#if !defined(BHO_NO_CXX11_VARIADIC_TEMPLATES)
template<class U, class... Args>
empty_value(bho::empty_init_t, U&& value, Args&&... args)
: T(std::forward<U>(value), std::forward<Args>(args)...) { }
#else
template<class U>
empty_value(bho::empty_init_t, U&& value)
: T(std::forward<U>(value)) { }
#endif
#else
template<class U>
empty_value(bho::empty_init_t, const U& value)
: T(value) { }
template<class U>
empty_value(bho::empty_init_t, U& value)
: T(value) { }
#endif
const T& get() const BHO_NOEXCEPT {
return *this;
}
T& get() BHO_NOEXCEPT {
return *this;
}
};
#endif
} /* empty_ */
using empty_::empty_value;
BHO_INLINE_CONSTEXPR empty_init_t empty_init = empty_init_t();
} /* boost */
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#endif
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> dot <EMAIL> at g<EMAIL> dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_WRITE_OSTREAM_HPP
#define BHO_BEAST_WRITE_OSTREAM_HPP
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/beast/core/detail/ostream.hpp>
#include <type_traits>
#include <streambuf>
#include <utility>
#ifdef BHO_BEAST_ALLOW_DEPRECATED
#include <asio2/bho/beast/core/make_printable.hpp>
#endif
namespace bho {
namespace beast {
/** Return an output stream that formats values into a <em>DynamicBuffer</em>.
This function wraps the caller provided <em>DynamicBuffer</em> into
a `std::ostream` derived class, to allow `operator<<` stream style
formatting operations.
@par Example
@code
ostream(buffer) << "Hello, world!" << std::endl;
@endcode
@note Calling members of the underlying buffer before the output
stream is destroyed results in undefined behavior.
@param buffer An object meeting the requirements of <em>DynamicBuffer</em>
into which the formatted output will be placed.
@return An object derived from `std::ostream` which redirects output
The wrapped dynamic buffer is not modified, a copy is made instead.
Ownership of the underlying memory is not transferred, the application
is still responsible for managing its lifetime. The caller is
responsible for ensuring the dynamic buffer is not destroyed for the
lifetime of the output stream.
*/
template<class DynamicBuffer>
#if BHO_BEAST_DOXYGEN
__implementation_defined__
#else
detail::ostream_helper<
DynamicBuffer, char, std::char_traits<char>,
detail::basic_streambuf_movable::value>
#endif
ostream(DynamicBuffer& buffer)
{
static_assert(
net::is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer type requirements not met");
return detail::ostream_helper<
DynamicBuffer, char, std::char_traits<char>,
detail::basic_streambuf_movable::value>{buffer};
}
//------------------------------------------------------------------------------
#ifdef BHO_BEAST_ALLOW_DEPRECATED
template<class T>
detail::make_printable_adaptor<T>
buffers(T const& t)
{
return make_printable(t);
}
#else
template<class T>
void buffers(T const&)
{
static_assert(sizeof(T) == 0,
"The function buffers() is deprecated, use make_printable() instead, "
"or define BHO_BEAST_ALLOW_DEPRECATED to silence this error.");
}
#endif
} // beast
} // bho
#endif
<file_sep>rm -rf *.vcxproj
rm -rf *.vcxproj.filters
rm -rf *.vcxproj.user
rm -rf *.sln
rm -rf cmake_install.cmake
rm -rf CMakeCache.txt
rm -rf .vs
rm -rf asio2_example_project
rm -rf CMakeFiles
rm -rf bin
rm -rf x64
rm -rf x86
rm -rf Win32
rm -rf ARM64
rm -rf ARM
rm -rf Debug
rm -rf Release
rm -rf out
rm -rf client/.vs
rm -rf client/asio2_client_example_project
rm -rf client/CMakeFiles
rm -rf client/bin
rm -rf client/x64
rm -rf client/x86
rm -rf client/Win32
rm -rf client/ARM64
rm -rf client/ARM
rm -rf client/Debug
rm -rf client/Release
rm -rf client/out
rm -rf server/.vs
rm -rf server/asio2_server_example_project
rm -rf server/CMakeFiles
rm -rf server/bin
rm -rf server/x64
rm -rf server/x86
rm -rf server/Win32
rm -rf server/ARM64
rm -rf server/ARM
rm -rf server/Debug
rm -rf server/Release
rm -rf server/out
rm -rf ndk/libs
rm -rf ndk/obj
rm -rf Makefile
<file_sep>#include "unit_test.hpp"
#include <fmt/format.h>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/tcp/tcp_client.hpp>
static std::string_view chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// the byte 1 head (1 bytes) : #
// the byte 2 length (1 bytes) : the body length
// the byte 3... body (n bytes) : the body content
class match_role
{
public:
explicit match_role(char c) : c_(c) {}
template <typename Iterator>
std::pair<Iterator, bool> operator()(Iterator begin, Iterator end) const
{
Iterator p = begin;
while (p != end)
{
// how to convert the Iterator to char*
[[maybe_unused]] const char * buf = &(*p);
ASIO2_CHECK(remote_addr_ == session_ptr_->get_remote_address());
ASIO2_CHECK(remote_port_ == session_ptr_->get_remote_port());
// eg : How to close illegal clients
if (*p != c_)
{
if (std::rand() % 2)
{
// method 1:
// call the session stop function directly.
session_ptr_->stop();
break;
}
else
{
// method 2:
// return the matching success here and then determine the number of bytes received
// in the on_recv callback function, if it is 0, we close the connection in on_recv.
return std::pair(begin, true); // head character is not #, return and kill the client
}
}
p++;
if (p == end) break;
int length = std::uint8_t(*p); // get content length
p++;
if (p == end) break;
if (end - p >= length)
return std::pair(p + length, true);
break;
}
return std::pair(begin, false);
}
// the asio2 framework will call this function immediately after the session is created,
// you can save the session pointer into a member variable, or do something else.
void init(std::shared_ptr<asio2::tcp_session>& session_ptr)
{
ASIO2_CHECK(remote_addr_.empty());
ASIO2_CHECK(remote_port_ == 0);
ASIO2_CHECK(session_ptr_ == nullptr);
session_ptr_ = session_ptr;
remote_addr_ = session_ptr_->get_remote_address();
remote_port_ = session_ptr_->get_remote_port();
}
private:
char c_;
std::string remote_addr_;
std::uint16_t remote_port_ = 0;
// note : use a shared_ptr to save the session does not cause circular reference.
std::shared_ptr<asio2::tcp_session> session_ptr_;
};
using buffer_iterator = asio::buffers_iterator<asio::streambuf::const_buffers_type>;
std::pair<buffer_iterator, bool> match_role_func(buffer_iterator begin, buffer_iterator end)
{
buffer_iterator p = begin;
while (p != end)
{
// how to convert the Iterator to char*
[[maybe_unused]] const char* buf = &(*p);
if (*p != '#')
return std::pair(begin, true); // head character is not #, return and kill the client
p++;
if (p == end) break;
int length = std::uint8_t(*p); // get content length
p++;
if (p == end) break;
if (end - p >= length)
return std::pair(p + length, true);
break;
}
return std::pair(begin, false);
}
#ifdef ASIO_STANDALONE
namespace asio
#else
namespace boost::asio
#endif
{
template <> struct is_match_condition<match_role> : public std::true_type {};
}
void tcp_custom_test()
{
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
//
{
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
if (data.size() == 0)
{
session_ptr->stop();
return;
}
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18026);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
bool server_start_ret = server.start("127.0.0.1", 18026, match_role('#'));
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
std::atomic<int> client_recv_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18026);
client_connect_counter++;
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
client_recv_counter++;
std::vector<std::uint8_t> msg;
for (int n = 20 + std::rand() % 100; n > 0; n--)
msg.emplace_back(chars.at(std::rand() % chars.size()));
msg.insert(msg.begin(), std::uint8_t(msg.size()));
msg.insert(msg.begin(), '#');
if (client_recv_counter > test_client_count * 20)
msg.insert(msg.begin(), '0');
client.async_send(std::move(msg));
});
bool client_start_ret = client.async_start("127.0.0.1", 18026, match_role_func);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter.load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter.load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter.load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter.load(), server_connect_counter == test_client_count);
std::vector<std::shared_ptr<asio2::tcp_client>> illegal_clients;
std::atomic<int> illegal_client_init_counter = 0;
std::atomic<int> illegal_client_connect_counter = 0;
std::atomic<int> illegal_client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = illegal_clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& illegal_client = *iter;
// disable auto reconnect, default reconnect option is "enable"
illegal_client.set_auto_reconnect(true, std::chrono::milliseconds(100));
illegal_client.bind_init([&]()
{
illegal_client_init_counter++;
illegal_client.set_no_delay(true);
ASIO2_CHECK(illegal_client.io().running_in_this_thread());
ASIO2_CHECK(illegal_client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(illegal_client.is_keep_alive());
ASIO2_CHECK(illegal_client.is_reuse_address());
ASIO2_CHECK(illegal_client.is_no_delay());
});
illegal_client.bind_connect([&]()
{
ASIO2_CHECK(illegal_client.io().running_in_this_thread());
ASIO2_CHECK(illegal_client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(illegal_client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(illegal_client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(illegal_client.get_remote_port() == 18026);
illegal_client_connect_counter++;
std::vector<std::uint8_t> msg;
for (int n = 20 + std::rand() % 100; n > 0; n--)
msg.emplace_back(chars.at(std::rand() % chars.size()));
illegal_client.async_send(std::move(msg));
});
illegal_client.bind_disconnect([&]()
{
illegal_client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(illegal_client.io().running_in_this_thread());
ASIO2_CHECK(illegal_client.iopool().get(0).running_in_this_thread());
});
illegal_client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(illegal_client.io().running_in_this_thread());
ASIO2_CHECK(illegal_client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(illegal_client.is_started());
//illegal_client.async_send(data);
});
bool illegal_client_start_ret = illegal_client.async_start("127.0.0.1", 18026);
ASIO2_CHECK(illegal_client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
for (int i = 0; i < test_client_count; i++)
{
auto& clt = clients[i];
std::vector<std::uint8_t> msg;
for (int n = 20 + std::rand() % 100; n > 0; n--)
msg.emplace_back(chars.at(std::rand() % chars.size()));
msg.insert(msg.begin(), std::uint8_t(msg.size()));
msg.insert(msg.begin(), '#');
clt->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
//// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
//while (server_disconnect_counter != test_client_count)
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
//ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == test_client_count * 20);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
for (int i = 0; i < test_client_count; i++)
{
illegal_clients[i]->stop();
ASIO2_CHECK(illegal_clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
//ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
//server_init_counter = 0;
//server_start_counter = 0;
//server_disconnect_counter = 0;
//server_stop_counter = 0;
//server_accept_counter = 0;
//server_connect_counter = 0;
//server_start_ret = server.start("127.0.0.1", 18026, match_role('#'));
//ASIO2_CHECK(server_start_ret);
//ASIO2_CHECK(server.is_started());
//ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
//ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
//client_init_counter = 0;
//client_connect_counter = 0;
//client_disconnect_counter = 0;
//for (int i = 0; i < test_client_count; i++)
//{
// bool client_start_ret = clients[i]->async_start("127.0.0.1", 18026, match_role_func);
// ASIO2_CHECK(client_start_ret);
// ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
//}
//while (server.get_session_count() < std::size_t(test_client_count))
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
//while (client_connect_counter < test_client_count)
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
//ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
//ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
//ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
//for (int i = 0; i < test_client_count; i++)
//{
// auto& clt = clients[i];
// clients[i]->post([&clt]()
// {
// std::vector<std::uint8_t> msg;
// int len = 200 + (std::rand() % 200);
// msg.resize(len);
// for (int i = 0; i < len; i++)
// {
// msg[i] = std::uint8_t(std::rand() % 0xff);
// }
// msg[0] = std::uint8_t(254);
// if (asio2::detail::is_little_endian())
// {
// msg[1] = std::uint8_t(253);
// msg[2] = std::uint8_t(0);
// }
// else
// {
// msg[1] = std::uint8_t(0);
// msg[2] = std::uint8_t(253);
// }
// msg[3] = std::uint8_t(0);
// msg[4] = std::uint8_t(0);
// msg[5] = std::uint8_t(0);
// msg[6] = std::uint8_t(0);
// msg[7] = std::uint8_t(0);
// msg[8] = std::uint8_t(0);
// asio::write(clt->socket(), asio::buffer(msg));
// });
//}
//while (client_disconnect_counter != test_client_count)
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
//while (server_disconnect_counter != test_client_count)
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
//ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 0);
//ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
//for (int i = 0; i < test_client_count; i++)
//{
// clients[i]->stop();
// ASIO2_CHECK(clients[i]->is_stopped());
//}
//server.stop();
//ASIO2_CHECK(server.is_stopped());
//ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
// test match role init function with ecs
{
asio2::tcp_server server;
std::atomic<int> server_recv_counter = 0;
server.bind_recv([&](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view data)
{
if (data.size() == 0)
{
session_ptr->stop();
return;
}
if (server.iopool().size() > 1)
{
ASIO2_CHECK(std::addressof(session_ptr->io()) != std::addressof(server.io()));
}
server_recv_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(session_ptr->is_started());
session_ptr->async_send(data);
ASIO2_CHECK(session_ptr->io().running_in_this_thread());
});
std::atomic<int> server_accept_counter = 0;
server.bind_accept([&](auto & session_ptr)
{
if (!asio2::get_last_error())
{
session_ptr->no_delay(true);
server_accept_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18026);
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
//// You can close the connection directly here.
//if (session_ptr->remote_address() == "192.168.0.254")
// session_ptr->stop();
}
});
std::atomic<int> server_connect_counter = 0;
server.bind_connect([&](auto & session_ptr)
{
server_connect_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(session_ptr->is_keep_alive());
ASIO2_CHECK(session_ptr->is_no_delay());
});
std::atomic<int> server_disconnect_counter = 0;
server.bind_disconnect([&](auto & session_ptr)
{
server_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(!server.find_session(session_ptr->hash_key()));
ASIO2_CHECK(session_ptr->socket().is_open());
ASIO2_CHECK(session_ptr->remote_address() == "127.0.0.1");
ASIO2_CHECK(session_ptr->local_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_init_counter = 0;
server.bind_init([&]()
{
server_init_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
asio::socket_base::reuse_address option;
server.acceptor().get_option(option);
ASIO2_CHECK(option.value());
});
std::atomic<int> server_start_counter = 0;
server.bind_start([&]()
{
server_start_counter++;
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
std::atomic<int> server_stop_counter = 0;
server.bind_stop([&]()
{
server_stop_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(server.get_listen_address() == "127.0.0.1");
ASIO2_CHECK(server.get_listen_port() == 18026);
ASIO2_CHECK(server.io().running_in_this_thread());
ASIO2_CHECK(server.iopool().get(0).running_in_this_thread());
});
asio2::rdc::option rdc_option
{
[](std::string_view)
{
return 0;
}
};
bool server_start_ret = server.start("127.0.0.1", 18026, match_role('#'), rdc_option);
ASIO2_CHECK(server_start_ret);
ASIO2_CHECK(server.is_started());
ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
std::atomic<int> client_init_counter = 0;
std::atomic<int> client_connect_counter = 0;
std::atomic<int> client_disconnect_counter = 0;
std::atomic<int> client_recv_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& client = *iter;
// disable auto reconnect, default reconnect option is "enable"
client.set_auto_reconnect(false);
client.bind_init([&]()
{
client_init_counter++;
client.set_no_delay(true);
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.is_keep_alive());
ASIO2_CHECK(client.is_reuse_address());
ASIO2_CHECK(client.is_no_delay());
});
client.bind_connect([&]()
{
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(client.get_remote_port() == 18026);
client_connect_counter++;
});
client.bind_disconnect([&]()
{
client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
});
client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(client.io().running_in_this_thread());
ASIO2_CHECK(client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(client.is_started());
//client.async_send(data);
client_recv_counter++;
std::vector<std::uint8_t> msg;
for (int n = 20 + std::rand() % 100; n > 0; n--)
msg.emplace_back(chars.at(std::rand() % chars.size()));
msg.insert(msg.begin(), std::uint8_t(msg.size()));
msg.insert(msg.begin(), '#');
if (client_recv_counter > test_client_count * 20)
msg.insert(msg.begin(), '0');
client.async_send(std::move(msg));
});
bool client_start_ret = client.async_start("127.0.0.1", 18026, match_role_func);
ASIO2_CHECK(client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
while (server.get_session_count() < std::size_t(test_client_count))
{
ASIO2_TEST_WAIT_CHECK();
}
auto session_count = server.get_session_count();
ASIO2_CHECK_VALUE(session_count, session_count == std::size_t(test_client_count));
while (client_connect_counter < test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
ASIO2_CHECK_VALUE(client_init_counter.load(), client_init_counter == test_client_count);
ASIO2_CHECK_VALUE(client_connect_counter.load(), client_connect_counter == test_client_count);
ASIO2_CHECK_VALUE(server_accept_counter.load(), server_accept_counter == test_client_count);
ASIO2_CHECK_VALUE(server_connect_counter.load(), server_connect_counter == test_client_count);
std::vector<std::shared_ptr<asio2::tcp_client>> illegal_clients;
std::atomic<int> illegal_client_init_counter = 0;
std::atomic<int> illegal_client_connect_counter = 0;
std::atomic<int> illegal_client_disconnect_counter = 0;
for (int i = 0; i < test_client_count; i++)
{
auto iter = illegal_clients.emplace_back(std::make_shared<asio2::tcp_client>());
asio2::tcp_client& illegal_client = *iter;
// disable auto reconnect, default reconnect option is "enable"
illegal_client.set_auto_reconnect(true, std::chrono::milliseconds(100));
illegal_client.bind_init([&]()
{
illegal_client_init_counter++;
illegal_client.set_no_delay(true);
ASIO2_CHECK(illegal_client.io().running_in_this_thread());
ASIO2_CHECK(illegal_client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(illegal_client.is_keep_alive());
ASIO2_CHECK(illegal_client.is_reuse_address());
ASIO2_CHECK(illegal_client.is_no_delay());
});
illegal_client.bind_connect([&]()
{
ASIO2_CHECK(illegal_client.io().running_in_this_thread());
ASIO2_CHECK(illegal_client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(illegal_client.get_local_address() == "127.0.0.1");
ASIO2_CHECK(illegal_client.get_remote_address() == "127.0.0.1");
ASIO2_CHECK(illegal_client.get_remote_port() == 18026);
illegal_client_connect_counter++;
std::vector<std::uint8_t> msg;
for (int n = 20 + std::rand() % 100; n > 0; n--)
msg.emplace_back(chars.at(std::rand() % chars.size()));
illegal_client.async_send(std::move(msg));
});
illegal_client.bind_disconnect([&]()
{
illegal_client_disconnect_counter++;
ASIO2_CHECK(asio2::get_last_error());
ASIO2_CHECK(illegal_client.io().running_in_this_thread());
ASIO2_CHECK(illegal_client.iopool().get(0).running_in_this_thread());
});
illegal_client.bind_recv([&]([[maybe_unused]] std::string_view data)
{
ASIO2_CHECK(!asio2::get_last_error());
ASIO2_CHECK(illegal_client.io().running_in_this_thread());
ASIO2_CHECK(illegal_client.iopool().get(0).running_in_this_thread());
ASIO2_CHECK(!data.empty());
ASIO2_CHECK(illegal_client.is_started());
//illegal_client.async_send(data);
});
bool illegal_client_start_ret = illegal_client.async_start("127.0.0.1", 18026);
ASIO2_CHECK(illegal_client_start_ret);
ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
}
for (int i = 0; i < test_client_count; i++)
{
auto& clt = clients[i];
std::vector<std::uint8_t> msg;
for (int n = 20 + std::rand() % 100; n > 0; n--)
msg.emplace_back(chars.at(std::rand() % chars.size()));
msg.insert(msg.begin(), std::uint8_t(msg.size()));
msg.insert(msg.begin(), '#');
clt->async_send(std::move(msg));
}
while (client_disconnect_counter != test_client_count)
{
ASIO2_TEST_WAIT_CHECK();
}
//// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
//while (server_disconnect_counter != test_client_count)
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
//ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == test_client_count * 20);
ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
for (int i = 0; i < test_client_count; i++)
{
clients[i]->stop();
ASIO2_CHECK(clients[i]->is_stopped());
}
for (int i = 0; i < test_client_count; i++)
{
illegal_clients[i]->stop();
ASIO2_CHECK(illegal_clients[i]->is_stopped());
}
server.stop();
ASIO2_CHECK(server.is_stopped());
ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
//-----------------------------------------------------------------------------------------
//ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(0));
//server_init_counter = 0;
//server_start_counter = 0;
//server_disconnect_counter = 0;
//server_stop_counter = 0;
//server_accept_counter = 0;
//server_connect_counter = 0;
//server_start_ret = server.start("127.0.0.1", 18026, match_role('#'));
//ASIO2_CHECK(server_start_ret);
//ASIO2_CHECK(server.is_started());
//ASIO2_CHECK_VALUE(server_init_counter .load(), server_init_counter == 1);
//ASIO2_CHECK_VALUE(server_start_counter .load(), server_start_counter == 1);
//client_init_counter = 0;
//client_connect_counter = 0;
//client_disconnect_counter = 0;
//for (int i = 0; i < test_client_count; i++)
//{
// bool client_start_ret = clients[i]->async_start("127.0.0.1", 18026, match_role_func);
// ASIO2_CHECK(client_start_ret);
// ASIO2_CHECK(asio2::get_last_error() == asio::error::in_progress);
//}
//while (server.get_session_count() < std::size_t(test_client_count))
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//ASIO2_CHECK_VALUE(server.get_session_count(), server.get_session_count() == std::size_t(test_client_count));
//while (client_connect_counter < test_client_count)
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//ASIO2_CHECK_VALUE(client_init_counter .load(), client_init_counter == test_client_count);
//ASIO2_CHECK_VALUE(client_connect_counter .load(), client_connect_counter == test_client_count);
//ASIO2_CHECK_VALUE(server_accept_counter .load(), server_accept_counter == test_client_count);
//ASIO2_CHECK_VALUE(server_connect_counter .load(), server_connect_counter == test_client_count);
//for (int i = 0; i < test_client_count; i++)
//{
// auto& clt = clients[i];
// clients[i]->post([&clt]()
// {
// std::vector<std::uint8_t> msg;
// int len = 200 + (std::rand() % 200);
// msg.resize(len);
// for (int i = 0; i < len; i++)
// {
// msg[i] = std::uint8_t(std::rand() % 0xff);
// }
// msg[0] = std::uint8_t(254);
// if (asio2::detail::is_little_endian())
// {
// msg[1] = std::uint8_t(253);
// msg[2] = std::uint8_t(0);
// }
// else
// {
// msg[1] = std::uint8_t(0);
// msg[2] = std::uint8_t(253);
// }
// msg[3] = std::uint8_t(0);
// msg[4] = std::uint8_t(0);
// msg[5] = std::uint8_t(0);
// msg[6] = std::uint8_t(0);
// msg[7] = std::uint8_t(0);
// msg[8] = std::uint8_t(0);
// asio::write(clt->socket(), asio::buffer(msg));
// });
//}
//while (client_disconnect_counter != test_client_count)
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//// use this to ensure the ASIO2_CHECK(session_ptr->is_started());
//while (server_disconnect_counter != test_client_count)
//{
// ASIO2_TEST_WAIT_CHECK();
//}
//ASIO2_CHECK_VALUE(server_disconnect_counter.load(), server_disconnect_counter == test_client_count);
//ASIO2_CHECK_VALUE(server_recv_counter.load(), server_recv_counter == 0);
//ASIO2_CHECK_VALUE(client_disconnect_counter.load(), client_disconnect_counter == test_client_count);
//for (int i = 0; i < test_client_count; i++)
//{
// clients[i]->stop();
// ASIO2_CHECK(clients[i]->is_stopped());
//}
//server.stop();
//ASIO2_CHECK(server.is_stopped());
//ASIO2_CHECK_VALUE(server_stop_counter .load(), server_stop_counter == 1);
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"tcp_custom",
ASIO2_TEST_CASE(tcp_custom_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RPC_SERIALIZATION_HPP__
#define __ASIO2_RPC_SERIALIZATION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <istream>
#include <ostream>
#include <streambuf>
#include <string>
#include <string_view>
#include <asio2/external/cereal.hpp>
#include <asio2/base/error.hpp>
#include <asio2/rpc/detail/rpc_portable_binary.hpp>
#include <asio2/rpc/error.hpp>
namespace asio2::detail
{
class ostrbuf : public std::streambuf
{
public:
using string_type = std::basic_string<char_type, traits_type>;
using size_type = typename string_type::size_type;
ostrbuf() {}
virtual ~ostrbuf() noexcept {}
inline const string_type& str() const noexcept
{
return this->str_;
}
inline void clear() noexcept
{
this->str_.clear();
this->setp(this->str_.data(), this->str_.data() + this->str_.size());
}
protected:
virtual std::streamsize xsputn(const char_type* s, std::streamsize count) override
{
this->str_.append(s, size_type(count));
this->setp(this->str_.data(), this->str_.data() + this->str_.size());
return count;
}
protected:
string_type str_;
};
class istrbuf : public std::streambuf
{
public:
using string_type = std::basic_string<char_type, traits_type>;
using size_type = typename string_type::size_type;
istrbuf() {}
virtual ~istrbuf() noexcept {}
inline void setbuf(std::string_view s) noexcept
{
this->setbuf(const_cast<char_type*>(s.data()), std::streamsize(s.size()));
}
virtual std::streambuf* setbuf(char_type* s, std::streamsize n) override
{
this->setg(s, s, s + n);
return this;
}
protected:
virtual std::streamsize xsgetn(char_type* s, std::streamsize count) override
{
if (this->in_avail() < count)
return std::streamsize(0);
std::memcpy((void*)s, (const void*)(this->gptr()), size_type(count));
this->setg(this->eback(), this->gptr() + count, this->egptr());
return count;
}
};
class rpc_serializer
{
public:
using oarchive = cereal::RPCPortableBinaryOutputArchive;
rpc_serializer()
: obuffer_()
, ostream_(std::addressof(obuffer_))
, oarchive_(ostream_)
{}
~rpc_serializer() = default;
template<typename T>
inline rpc_serializer& operator<<(const T& v)
{
this->oarchive_ << v;
return (*this);
}
inline rpc_serializer& operator<<(const error_code& ec)
{
this->oarchive_ << ec.value();
return (*this);
}
template<class ...Args>
inline rpc_serializer& save(const Args&... args)
{
((this->oarchive_ << args), ...);
return (*this);
}
inline rpc_serializer& reset()
{
this->obuffer_.clear();
this->oarchive_.save_endian();
return (*this);
}
inline const auto& str() const noexcept
{
return this->obuffer_.str();
}
inline ostrbuf& buffer() noexcept { return this->obuffer_; }
protected:
ostrbuf obuffer_;
std::ostream ostream_;
oarchive oarchive_;
};
class rpc_deserializer
{
public:
using iarchive = cereal::RPCPortableBinaryInputArchive;
rpc_deserializer()
: ibuffer_()
, istream_(std::addressof(ibuffer_))
, iarchive_(istream_)
{}
~rpc_deserializer() = default;
template<typename T>
inline rpc_deserializer& operator>>(T& v)
{
this->iarchive_ >> v;
return (*this);
}
inline rpc_deserializer& operator>>(error_code& ec)
{
decltype(ec.value()) v;
this->iarchive_ >> v;
ec.assign(v, ec.category());
return (*this);
}
template<class ...Args>
inline rpc_deserializer& load(Args&... args)
{
((this->iarchive_ >> args), ...);
return (*this);
}
inline rpc_deserializer& reset(std::string_view s)
{
this->ibuffer_.setbuf(s);
this->iarchive_.load_endian();
return (*this);
}
inline istrbuf& buffer() noexcept { return this->ibuffer_; }
protected:
istrbuf ibuffer_;
std::istream istream_;
iarchive iarchive_;
};
}
namespace asio2::rpc
{
// for serializer
using oarchive = cereal::RPCPortableBinaryOutputArchive;
// for deserializer
using iarchive = cereal::RPCPortableBinaryInputArchive;
}
#endif // !__ASIO2_RPC_SERIALIZATION_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_ERROR_HPP__
#define __ASIO2_MQTT_ERROR_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/error.hpp>
namespace asio2::mqtt
{
///// The type of error category used by the library
//using error_category = asio::error_category;
///// The type of error condition used by the library
//using error_condition = std::error_condition;
//enum class error
//{
// success = 0,
// failure,
// persistence_error,
// disconnected,
// max_messages_inflight,
// bad_utf8_string,
// null_parameter,
// topicname_truncated,
// bad_structure,
// bad_qos,
// no_more_msgids,
// operation_incomplete,
// max_buffered_messages,
// ssl_not_supported,
// bad_mqtt_version,
// bad_protocol,
// bad_mqtt_option,
// wrong_mqtt_version,
// zero_len_will_topic,
//};
//enum class condition
//{
// success = 0,
// failure,
// persistence_error, // unspecified_error
// disconnected, // disconnect_with_will_message
// max_messages_inflight, // message_rate_too_high
// bad_utf8_string, // topic_filter_invalid topic_name_invalid topic_alias_invalid
// null_parameter, // malformed_packet
// topicname_truncated, // topic_name_invalid
// bad_structure, // protocol_error implementation_specific_error
// bad_qos, // qos_not_supported
// no_more_msgids, // packet_identifier_not_found no_matching_subscribers no_subscription_existed
// operation_incomplete, // server_busy
// max_buffered_messages, // packet_too_large
// ssl_not_supported, // unsupported_protocol_version server_unavailable
// bad_mqtt_version, // unsupported_protocol_version
// bad_protocol, // protocol_error
// bad_mqtt_option, // payload_format_invalid protocol_error malformed_packet
// wrong_mqtt_version, // unsupported_protocol_version
// zero_len_will_topic, // topic_filter_invalid topic_name_invalid topic_alias_invalid
//};
//class mqtt_error_category : public error_category
//{
//public:
// const char* name() const noexcept override
// {
// return "asio2.mqtt";
// }
// inline std::string message(int ev) const override
// {
// switch (static_cast<error>(ev))
// {
// case error::success : return "Success";
// case error::failure : return "Failure";
// case error::persistence_error : return "Persistence error";
// case error::disconnected : return "Disconnected";
// case error::max_messages_inflight : return "Maximum in-flight messages amount reached";
// case error::bad_utf8_string : return "Invalid UTF8 string";
// case error::null_parameter : return "Invalid (NULL) parameter";
// case error::topicname_truncated : return "Topic containing NULL characters has been truncated";
// case error::bad_structure : return "Bad structure";
// case error::bad_qos : return "Invalid QoS value";
// case error::no_more_msgids : return "Too many pending commands";
// case error::operation_incomplete : return "Operation discarded before completion";
// case error::max_buffered_messages : return "No more messages can be buffered";
// case error::ssl_not_supported : return "SSL is not supported";
// case error::bad_mqtt_version : return "Unrecognized MQTT version";
// case error::bad_protocol : return "Invalid protocol scheme";
// case error::bad_mqtt_option : return "Options for wrong MQTT version";
// case error::wrong_mqtt_version : return "Client created for another version of MQTT";
// case error::zero_len_will_topic : return "Zero length will topic on connect";
// default : return "Unknown";
// }
// }
// inline error_condition default_error_condition(int ev) const noexcept override
// {
// //switch (static_cast<error>(ev))
// //{
// //default:
// //case error::disconnected : return condition::disconnected ;
// //case error::max_messages_inflight : return condition::max_messages_inflight ;
// //case error::bad_utf8_string : return condition::bad_utf8_string ;
// //case error::null_parameter : return condition::null_parameter ;
// //case error::topicname_truncated : return condition::topicname_truncated ;
// //case error::bad_structure : return condition::bad_structure ;
// //case error::bad_qos : return condition::bad_qos ;
// //case error::ssl_not_supported : return condition::ssl_not_supported ;
// //case error::bad_mqtt_version : return condition::bad_mqtt_version ;
// //case error::bad_protocol : return condition::bad_protocol ;
// //case error::bad_mqtt_option : return condition::bad_mqtt_option ;
// //case error::wrong_mqtt_version : return condition::wrong_mqtt_version ;
// //}
// return error_condition{ ev, *this };
// }
//};
//inline const mqtt_error_category& mqtt_category() noexcept
//{
// static mqtt_error_category const cat{};
// return cat;
//}
//inline error_code make_error_code(error e)
//{
// return error_code{ static_cast<std::underlying_type<error>::type>(e), mqtt_category() };
//}
//inline error_condition make_error_condition(condition c)
//{
// return error_condition{ static_cast<std::underlying_type<condition>::type>(c), mqtt_category() };
//}
/**
* Reason Code
*
* A Reason Code is a one byte unsigned value that indicates the result of an operation. Reason Codes
* less than 0x80 indicate successful completion of an operation. The normal Reason Code for success
* is 0. Reason Code values of 0x80 or greater indicate failure.
*
* The Reason Codes share a common set of values as shown below.
*
* https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901031
*/
enum class error : std::uint8_t
{
// The operation completed successfully.
success = 0,
// Close the connection normally. Do not send the Will Message.
normal_disconnection = 0,
// Granted the PUBLISH Quality of Service is 0
granted_qos_0 = 0,
// Granted the PUBLISH Quality of Service is 1
granted_qos_1 = 1,
// Granted the PUBLISH Quality of Service is 2
granted_qos_2 = 2,
// The Client wishes to disconnect but requires that the Server also publishes its Will Message.
disconnect_with_will_message = 4,
// The message is accepted but there are no subscribers. This is sent only by the Server. If the Server knows that there are no matching subscribers, it MAY use this Reason Code instead of 0x00 (Success).
no_matching_subscribers = 16,
// No subscription existed
no_subscription_existed = 17,
// Continue the authentication with another step
continue_authentication = 24,
// Initiate a re-authentication
reauthenticate = 25,
// The Server or Client does not wish to reveal the reason for the failure, or none of the other Reason Codes apply.
unspecified_error = 128,
// The received packet does not conform to this specification.
malformed_packet = 129,
// An unexpected or out of order packet was received.
protocol_error = 130,
// The packet received is valid but cannot be processed by this implementation.
implementation_specific_error = 131,
// The Server does not support the version of the MQTT protocol requested by the Client.
unsupported_protocol_version = 132,
// The Client Identifier is a valid string but is not allowed by the Server.
client_identifier_not_valid = 133,
// The Server does not accept the User Name or Password specified by the Client
bad_user_name_or_password = 134,
// The request is not authorized.
not_authorized = 135,
// The MQTT Server is not available.
server_unavailable = 136,
// The Server is busy and cannot continue processing requests from this Client.
server_busy = 137,
// This Client has been banned by administrative action. Contact the server administrator.
banned = 138,
// The Server is shutting down.
server_shutting_down = 139,
// The authentication method is not supported or does not match the authentication method currently in use.
bad_authentication_method = 140,
// The Connection is closed because no packet has been received for 1.5 times the Keepalive time.
keep_alive_timeout = 141,
// Another Connection using the same ClientID has connected causing this Connection to be closed.
session_taken_over = 142,
// The Topic Filter is correctly formed, but is not accepted by this Sever.
topic_filter_invalid = 143,
// The Topic Name is not malformed, but is not accepted by this Client or Server.
topic_name_invalid = 144,
// The Packet Identifier is already in use. This might indicate a mismatch in the Session State between the Client and Server.
packet_identifier_in_use = 145,
// The Packet Identifier is not known. This is not an error during recovery, but at other times indicates a mismatch between the Session State on the Client and Server.
packet_identifier_not_found = 146,
// The Client or Server has received more than Receive Maximum publication for which it has not sent PUBACK or PUBCOMP.
receive_maximum_exceeded = 147,
// The Client or Server has received a PUBLISH packet containing a Topic Alias which is greater than the Maximum Topic Alias it sent in the CONNECT or CONNACK packet.
topic_alias_invalid = 148,
// The packet size is greater than Maximum Packet Size for this Client or Server.
packet_too_large = 149,
// The received data rate is too high.
message_rate_too_high = 150,
// An implementation or administrative imposed limit has been exceeded.
quota_exceeded = 151,
// The Connection is closed due to an administrative action.
administrative_action = 152,
// The payload format does not match the specified Payload Format Indicator.
payload_format_invalid = 153,
// The Server has does not support retained messages.
retain_not_supported = 154,
// The Server does not support the QoS set in Will QoS.
qos_not_supported = 155,
// The Client should temporarily use another server.
use_another_server = 156,
// The Server is moved and the Client should permanently use another server.
server_moved = 157,
// The Server does not support Shared Subscriptions.
shared_subscriptions_not_supported = 158,
// The connection rate limit has been exceeded.
connection_rate_exceeded = 159,
// The maximum connection time authorized for this connection has been exceeded.
maximum_connect_time = 160,
// The Server does not support Subscription Identifiers; the subscription is not accepted.
subscription_identifiers_not_supported = 161,
// The Server does not support Wildcard Subscriptions; the subscription is not accepted.
wildcard_subscriptions_not_supported = 162,
};
enum class condition : std::uint8_t
{
// The operation completed successfully.
success = 0,
// Close the connection normally. Do not send the Will Message.
normal_disconnection = 0,
// Granted the PUBLISH Quality of Service is 0
granted_qos_0 = 0,
// Granted the PUBLISH Quality of Service is 1
granted_qos_1 = 1,
// Granted the PUBLISH Quality of Service is 2
granted_qos_2 = 2,
// The Client wishes to disconnect but requires that the Server also publishes its Will Message.
disconnect_with_will_message = 4,
// The message is accepted but there are no subscribers. This is sent only by the Server. If the Server knows that there are no matching subscribers, it MAY use this Reason Code instead of 0x00 (Success).
no_matching_subscribers = 16,
// No subscription existed
no_subscription_existed = 17,
// Continue the authentication with another step
continue_authentication = 24,
// Initiate a re-authentication
reauthenticate = 25,
// The Server or Client does not wish to reveal the reason for the failure, or none of the other Reason Codes apply.
unspecified_error = 128,
// The received packet does not conform to this specification.
malformed_packet = 129,
// An unexpected or out of order packet was received.
protocol_error = 130,
// The packet received is valid but cannot be processed by this implementation.
implementation_specific_error = 131,
// The Server does not support the version of the MQTT protocol requested by the Client.
unsupported_protocol_version = 132,
// The Client Identifier is a valid string but is not allowed by the Server.
client_identifier_not_valid = 133,
// The Server does not accept the User Name or Password specified by the Client
bad_user_name_or_password = 134,
// The request is not authorized.
not_authorized = 135,
// The MQTT Server is not available.
server_unavailable = 136,
// The Server is busy and cannot continue processing requests from this Client.
server_busy = 137,
// This Client has been banned by administrative action. Contact the server administrator.
banned = 138,
// The Server is shutting down.
server_shutting_down = 139,
// The authentication method is not supported or does not match the authentication method currently in use.
bad_authentication_method = 140,
// The Connection is closed because no packet has been received for 1.5 times the Keepalive time.
keep_alive_timeout = 141,
// Another Connection using the same ClientID has connected causing this Connection to be closed.
session_taken_over = 142,
// The Topic Filter is correctly formed, but is not accepted by this Sever.
topic_filter_invalid = 143,
// The Topic Name is not malformed, but is not accepted by this Client or Server.
topic_name_invalid = 144,
// The Packet Identifier is already in use. This might indicate a mismatch in the Session State between the Client and Server.
packet_identifier_in_use = 145,
// The Packet Identifier is not known. This is not an error during recovery, but at other times indicates a mismatch between the Session State on the Client and Server.
packet_identifier_not_found = 146,
// The Client or Server has received more than Receive Maximum publication for which it has not sent PUBACK or PUBCOMP.
receive_maximum_exceeded = 147,
// The Client or Server has received a PUBLISH packet containing a Topic Alias which is greater than the Maximum Topic Alias it sent in the CONNECT or CONNACK packet.
topic_alias_invalid = 148,
// The packet size is greater than Maximum Packet Size for this Client or Server.
packet_too_large = 149,
// The received data rate is too high.
message_rate_too_high = 150,
// An implementation or administrative imposed limit has been exceeded.
quota_exceeded = 151,
// The Connection is closed due to an administrative action.
administrative_action = 152,
// The payload format does not match the specified Payload Format Indicator.
payload_format_invalid = 153,
// The Server has does not support retained messages.
retain_not_supported = 154,
// The Server does not support the QoS set in Will QoS.
qos_not_supported = 155,
// The Client should temporarily use another server.
use_another_server = 156,
// The Server is moved and the Client should permanently use another server.
server_moved = 157,
// The Server does not support Shared Subscriptions.
shared_subscriptions_not_supported = 158,
// The connection rate limit has been exceeded.
connection_rate_exceeded = 159,
// The maximum connection time authorized for this connection has been exceeded.
maximum_connect_time = 160,
// The Server does not support Subscription Identifiers; the subscription is not accepted.
subscription_identifiers_not_supported = 161,
// The Server does not support Wildcard Subscriptions; the subscription is not accepted.
wildcard_subscriptions_not_supported = 162,
};
/// The type of error category used by the library
using error_category = asio::error_category;
/// The type of error condition used by the library
using error_condition = asio::error_condition;
class mqtt_error_category : public error_category
{
public:
const char* name() const noexcept override
{
return "asio2.mqtt";
}
inline std::string message(int ev) const override
{
switch (static_cast<error>(ev))
{
case error::success : return "The operation completed successfully.";
//case error::normal_disconnection : return "Close the connection normally. Do not send the Will Message.";
//case error::granted_qos_0 : return "Granted the PUBLISH Quality of Service is 0";
case error::granted_qos_1 : return "Granted the PUBLISH Quality of Service is 1";
case error::granted_qos_2 : return "Granted the PUBLISH Quality of Service is 2";
case error::disconnect_with_will_message : return "The Client wishes to disconnect but requires that the Server also publishes its Will Message.";
case error::no_matching_subscribers : return "The message is accepted but there are no subscribers. This is sent only by the Server. If the Server knows that there are no matching subscribers, it MAY use this Reason Code instead of 0x00 (Success).";
case error::no_subscription_existed : return "No subscription existed";
case error::continue_authentication : return "Continue the authentication with another step";
case error::reauthenticate : return "Initiate a re-authentication";
case error::unspecified_error : return "The Server or Client does not wish to reveal the reason for the failure, or none of the other Reason Codes apply.";
case error::malformed_packet : return "The received packet does not conform to this specification.";
case error::protocol_error : return "An unexpected or out of order packet was received.";
case error::implementation_specific_error : return "The packet received is valid but cannot be processed by this implementation.";
case error::unsupported_protocol_version : return "The Server does not support the version of the MQTT protocol requested by the Client.";
case error::client_identifier_not_valid : return "The Client Identifier is a valid string but is not allowed by the Server.";
case error::bad_user_name_or_password : return "The Server does not accept the User Name or Password specified by the Client";
case error::not_authorized : return "The request is not authorized.";
case error::server_unavailable : return "The MQTT Server is not available.";
case error::server_busy : return "The Server is busy and cannot continue processing requests from this Client.";
case error::banned : return "This Client has been banned by administrative action. Contact the server administrator.";
case error::server_shutting_down : return "The Server is shutting down.";
case error::bad_authentication_method : return "The authentication method is not supported or does not match the authentication method currently in use.";
case error::keep_alive_timeout : return "The Connection is closed because no packet has been received for 1.5 times the Keepalive time.";
case error::session_taken_over : return "Another Connection using the same ClientID has connected causing this Connection to be closed.";
case error::topic_filter_invalid : return "The Topic Filter is correctly formed, but is not accepted by this Sever.";
case error::topic_name_invalid : return "The Topic Name is not malformed, but is not accepted by this Client or Server.";
case error::packet_identifier_in_use : return "The Packet Identifier is already in use. This might indicate a mismatch in the Session State between the Client and Server.";
case error::packet_identifier_not_found : return "The Packet Identifier is not known. This is not an error during recovery, but at other times indicates a mismatch between the Session State on the Client and Server.";
case error::receive_maximum_exceeded : return "The Client or Server has received more than Receive Maximum publication for which it has not sent PUBACK or PUBCOMP.";
case error::topic_alias_invalid : return "The Client or Server has received a PUBLISH packet containing a Topic Alias which is greater than the Maximum Topic Alias it sent in the CONNECT or CONNACK packet.";
case error::packet_too_large : return "The packet size is greater than Maximum Packet Size for this Client or Server.";
case error::message_rate_too_high : return "The received data rate is too high.";
case error::quota_exceeded : return "An implementation or administrative imposed limit has been exceeded.";
case error::administrative_action : return "The Connection is closed due to an administrative action.";
case error::payload_format_invalid : return "The payload format does not match the specified Payload Format Indicator.";
case error::retain_not_supported : return "The Server has does not support retained messages.";
case error::qos_not_supported : return "The Server does not support the QoS set in Will QoS.";
case error::use_another_server : return "The Client should temporarily use another server.";
case error::server_moved : return "The Server is moved and the Client should permanently use another server.";
case error::shared_subscriptions_not_supported : return "The Server does not support Shared Subscriptions.";
case error::connection_rate_exceeded : return "The connection rate limit has been exceeded.";
case error::maximum_connect_time : return "The maximum connection time authorized for this connection has been exceeded.";
case error::subscription_identifiers_not_supported: return "The Server does not support Subscription Identifiers; the subscription is not accepted.";
case error::wildcard_subscriptions_not_supported : return "The Server does not support Wildcard Subscriptions; the subscription is not accepted.";
default : return "Unknown error";
}
}
inline error_condition default_error_condition(int ev) const noexcept override
{
return error_condition{ ev, *this };
}
};
inline const mqtt_error_category& mqtt_category() noexcept
{
static mqtt_error_category const cat{};
return cat;
}
inline asio::error_code make_error_code(error e)
{
return asio::error_code{ static_cast<std::underlying_type<error>::type>(e), mqtt_category() };
}
inline error_condition make_error_condition(condition c)
{
return error_condition{ static_cast<std::underlying_type<condition>::type>(c), mqtt_category() };
}
template<typename = void>
inline constexpr std::string_view to_string(error e)
{
using namespace std::string_view_literals;
switch (e)
{
case error::success : return "The operation completed successfully.";
//case error::normal_disconnection : return "Close the connection normally. Do not send the Will Message.";
//case error::granted_qos_0 : return "Granted the PUBLISH Quality of Service is 0";
case error::granted_qos_1 : return "Granted the PUBLISH Quality of Service is 1";
case error::granted_qos_2 : return "Granted the PUBLISH Quality of Service is 2";
case error::disconnect_with_will_message : return "The Client wishes to disconnect but requires that the Server also publishes its Will Message.";
case error::no_matching_subscribers : return "The message is accepted but there are no subscribers. This is sent only by the Server. If the Server knows that there are no matching subscribers, it MAY use this Reason Code instead of 0x00 (Success).";
case error::no_subscription_existed : return "No subscription existed";
case error::continue_authentication : return "Continue the authentication with another step";
case error::reauthenticate : return "Initiate a re-authentication";
case error::unspecified_error : return "The Server or Client does not wish to reveal the reason for the failure, or none of the other Reason Codes apply.";
case error::malformed_packet : return "The received packet does not conform to this specification.";
case error::protocol_error : return "An unexpected or out of order packet was received.";
case error::implementation_specific_error : return "The packet received is valid but cannot be processed by this implementation.";
case error::unsupported_protocol_version : return "The Server does not support the version of the MQTT protocol requested by the Client.";
case error::client_identifier_not_valid : return "The Client Identifier is a valid string but is not allowed by the Server.";
case error::bad_user_name_or_password : return "The Server does not accept the User Name or Password specified by the Client";
case error::not_authorized : return "The request is not authorized.";
case error::server_unavailable : return "The MQTT Server is not available.";
case error::server_busy : return "The Server is busy and cannot continue processing requests from this Client.";
case error::banned : return "This Client has been banned by administrative action. Contact the server administrator.";
case error::server_shutting_down : return "The Server is shutting down.";
case error::bad_authentication_method : return "The authentication method is not supported or does not match the authentication method currently in use.";
case error::keep_alive_timeout : return "The Connection is closed because no packet has been received for 1.5 times the Keepalive time.";
case error::session_taken_over : return "Another Connection using the same ClientID has connected causing this Connection to be closed.";
case error::topic_filter_invalid : return "The Topic Filter is correctly formed, but is not accepted by this Sever.";
case error::topic_name_invalid : return "The Topic Name is not malformed, but is not accepted by this Client or Server.";
case error::packet_identifier_in_use : return "The Packet Identifier is already in use. This might indicate a mismatch in the Session State between the Client and Server.";
case error::packet_identifier_not_found : return "The Packet Identifier is not known. This is not an error during recovery, but at other times indicates a mismatch between the Session State on the Client and Server.";
case error::receive_maximum_exceeded : return "The Client or Server has received more than Receive Maximum publication for which it has not sent PUBACK or PUBCOMP.";
case error::topic_alias_invalid : return "The Client or Server has received a PUBLISH packet containing a Topic Alias which is greater than the Maximum Topic Alias it sent in the CONNECT or CONNACK packet.";
case error::packet_too_large : return "The packet size is greater than Maximum Packet Size for this Client or Server.";
case error::message_rate_too_high : return "The received data rate is too high.";
case error::quota_exceeded : return "An implementation or administrative imposed limit has been exceeded.";
case error::administrative_action : return "The Connection is closed due to an administrative action.";
case error::payload_format_invalid : return "The payload format does not match the specified Payload Format Indicator.";
case error::retain_not_supported : return "The Server has does not support retained messages.";
case error::qos_not_supported : return "The Server does not support the QoS set in Will QoS.";
case error::use_another_server : return "The Client should temporarily use another server.";
case error::server_moved : return "The Server is moved and the Client should permanently use another server.";
case error::shared_subscriptions_not_supported : return "The Server does not support Shared Subscriptions.";
case error::connection_rate_exceeded : return "The connection rate limit has been exceeded.";
case error::maximum_connect_time : return "The maximum connection time authorized for this connection has been exceeded.";
case error::subscription_identifiers_not_supported: return "The Server does not support Subscription Identifiers; the subscription is not accepted.";
case error::wildcard_subscriptions_not_supported : return "The Server does not support Wildcard Subscriptions; the subscription is not accepted.";
default : return "Unknown error";
}
return "Unknown error";
};
}
namespace mqtt = ::asio2::mqtt;
namespace std
{
template<>
struct is_error_code_enum<::asio2::mqtt::error>
{
static bool const value = true;
};
template<>
struct is_error_condition_enum<::asio2::mqtt::condition>
{
static bool const value = true;
};
}
#endif // !__ASIO2_MQTT_ERROR_HPP__
<file_sep>//
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2021 <NAME> (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <asio2/base/detail/push_options.hpp>
#define ASIO_STANDALONE
#include "asio.hpp"
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
#include "handler_allocator.hpp"
class stats
{
public:
stats()
: mutex_(),
total_bytes_written_(0),
total_bytes_read_(0)
{
}
void add(size_t bytes_written, size_t bytes_read)
{
asio::detail::mutex::scoped_lock lock(mutex_);
total_bytes_written_ += bytes_written;
total_bytes_read_ += bytes_read;
}
void print()
{
asio::detail::mutex::scoped_lock lock(mutex_);
std::cout << total_bytes_written_ << " total bytes written\n";
std::cout << total_bytes_read_ << " total bytes read\n";
}
private:
asio::detail::mutex mutex_;
size_t total_bytes_written_;
size_t total_bytes_read_;
};
class session
{
public:
session(asio::io_context& ioc, size_t block_size, stats& s)
: strand_(ioc.get_executor()),
socket_(ioc),
block_size_(block_size),
read_data_(new char[block_size]),
read_data_length_(0),
write_data_(new char[block_size]),
unwritten_count_(0),
bytes_written_(0),
bytes_read_(0),
stats_(s)
{
for (size_t i = 0; i < block_size_; ++i)
write_data_[i] = static_cast<char>(i % 128);
}
~session()
{
stats_.add(bytes_written_, bytes_read_);
delete[] read_data_;
delete[] write_data_;
}
void start(asio::ip::tcp::resolver::results_type endpoints)
{
asio::async_connect(socket_, endpoints,
asio::bind_executor(strand_,
std::bind(&session::handle_connect, this,
std::placeholders::_1)));
}
void stop()
{
asio::post(strand_, std::bind(&session::close_socket, this));
}
private:
void handle_connect(const asio::error_code& err)
{
if (!err)
{
asio::error_code set_option_err;
asio::ip::tcp::no_delay no_delay(true);
socket_.set_option(no_delay, set_option_err);
if (!set_option_err)
{
++unwritten_count_;
async_write(socket_, asio::buffer(write_data_, block_size_),
asio::bind_executor(strand_,
make_custom_alloc_handler(write_allocator_,
std::bind(&session::handle_write, this,
std::placeholders::_1,
std::placeholders::_2))));
socket_.async_read_some(asio::buffer(read_data_, block_size_),
asio::bind_executor(strand_,
make_custom_alloc_handler(read_allocator_,
std::bind(&session::handle_read, this,
std::placeholders::_1,
std::placeholders::_2))));
}
}
}
void handle_read(const asio::error_code& err, size_t length)
{
if (!err)
{
bytes_read_ += length;
read_data_length_ = length;
++unwritten_count_;
if (unwritten_count_ == 1)
{
std::swap(read_data_, write_data_);
async_write(socket_, asio::buffer(write_data_, read_data_length_),
asio::bind_executor(strand_,
make_custom_alloc_handler(write_allocator_,
std::bind(&session::handle_write, this,
std::placeholders::_1,
std::placeholders::_2))));
socket_.async_read_some(asio::buffer(read_data_, block_size_),
asio::bind_executor(strand_,
make_custom_alloc_handler(read_allocator_,
std::bind(&session::handle_read, this,
std::placeholders::_1,
std::placeholders::_2))));
}
}
}
void handle_write(const asio::error_code& err, size_t length)
{
if (!err && length > 0)
{
bytes_written_ += length;
--unwritten_count_;
if (unwritten_count_ == 1)
{
std::swap(read_data_, write_data_);
async_write(socket_, asio::buffer(write_data_, read_data_length_),
asio::bind_executor(strand_,
make_custom_alloc_handler(write_allocator_,
std::bind(&session::handle_write, this,
std::placeholders::_1,
std::placeholders::_2))));
socket_.async_read_some(asio::buffer(read_data_, block_size_),
asio::bind_executor(strand_,
make_custom_alloc_handler(read_allocator_,
std::bind(&session::handle_read, this,
std::placeholders::_1,
std::placeholders::_2))));
}
}
}
void close_socket()
{
socket_.close();
}
private:
asio::strand<asio::io_context::executor_type> strand_;
asio::ip::tcp::socket socket_;
size_t block_size_;
char* read_data_;
size_t read_data_length_;
char* write_data_;
int unwritten_count_;
size_t bytes_written_;
size_t bytes_read_;
stats& stats_;
handler_allocator read_allocator_;
handler_allocator write_allocator_;
};
class client
{
public:
client(asio::io_context& ioc,
const asio::ip::tcp::resolver::results_type endpoints,
size_t block_size, size_t session_count, int timeout)
: io_context_(ioc),
stop_timer_(ioc),
sessions_(),
stats_()
{
stop_timer_.expires_after(asio::chrono::seconds(timeout));
stop_timer_.async_wait(std::bind(&client::handle_timeout, this));
for (size_t i = 0; i < session_count; ++i)
{
session* new_session = new session(io_context_, block_size, stats_);
new_session->start(endpoints);
sessions_.push_back(new_session);
}
}
~client()
{
while (!sessions_.empty())
{
delete sessions_.front();
sessions_.pop_front();
}
stats_.print();
}
void handle_timeout()
{
std::for_each(sessions_.begin(), sessions_.end(),
std::mem_fn(&session::stop));
}
private:
asio::io_context& io_context_;
asio::steady_timer stop_timer_;
std::list<session*> sessions_;
stats stats_;
};
int main(int argc, char* argv[])
{
(void)argc;
(void)argv;
try
{
using namespace std; // For atoi.
const char* host = "127.0.0.1";
const char* port = "8080";
int thread_count = 1;
size_t block_size = 1024;
size_t session_count = 1;
int timeout = 1000;
asio::io_context ioc;
asio::ip::tcp::resolver r(ioc);
asio::ip::tcp::resolver::results_type endpoints =
r.resolve(host, port);
client c(ioc, endpoints, block_size, session_count, timeout);
std::list<asio::thread*> threads;
while (--thread_count > 0)
{
asio::thread* new_thread = new asio::thread([&ioc]()
{
ioc.run();
}
/*std::bind(&asio::io_context::run, &ioc)*/);
threads.push_back(new_thread);
}
ioc.run();
while (!threads.empty())
{
threads.front()->join();
delete threads.front();
threads.pop_front();
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
#include <asio2/base/detail/pop_options.hpp>
<file_sep>#ifndef ASIO2_INCLUDE_RATE_LIMIT
#define ASIO2_INCLUDE_RATE_LIMIT
#endif
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/tcp/tcp_client.hpp>
#include <iostream>
int main()
{
asio2::tcp_rate_server tcp_server;
tcp_server.bind_connect([](std::shared_ptr<asio2::tcp_rate_session>& session_ptr)
{
// set the send rate
session_ptr->socket().rate_policy().write_limit(256);
// set the recv rate
session_ptr->socket().rate_policy().read_limit(256);
}).bind_recv([](auto& session_ptr, std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
});
tcp_server.start("0.0.0.0", 8102);
asio2::tcp_rate_client tcp_client;
tcp_client.bind_connect([&tcp_client]()
{
// set the send rate
tcp_client.socket().rate_policy().write_limit(512);
if (!asio2::get_last_error())
{
std::string str;
for (int i = 0; i < 1024; i++)
{
str += '0' + std::rand() % 64;
}
tcp_client.async_send(str);
}
}).bind_recv([&tcp_client](std::string_view data)
{
tcp_client.async_send(data);
});
tcp_client.start("127.0.0.1", 8102);
std::thread([&tcp_client]()
{
// note: if you set the rate in the other thread which is not the io_context
// thread, you should use post function to make the operation is executed in
// the io_context thread, otherwise it is not thread safety.
tcp_client.post([&tcp_client]()
{
// set the recv rate
tcp_client.socket().rate_policy().read_limit(512);
});
}).detach();
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#ifndef __ASIO2_WSS_SERVER_HPP__
#define __ASIO2_WSS_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcps_server.hpp>
#include <asio2/http/wss_session.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
template<class derived_t, class session_t>
class wss_server_impl_t : public tcps_server_impl_t<derived_t, session_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
public:
using super = tcps_server_impl_t<derived_t, session_t>;
using self = wss_server_impl_t <derived_t, session_t>;
using session_type = session_t;
public:
/**
* @brief constructor
*/
template<class... Args>
explicit wss_server_impl_t(
asio::ssl::context::method method = asio::ssl::context::sslv23,
Args&&... args
)
: super(method, std::forward<Args>(args)...)
{
}
/**
* @brief destructor
*/
~wss_server_impl_t()
{
this->stop();
}
/**
* @brief start the server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param service - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
bool start(String&& host, StrOrInt&& service, Args&&... args)
{
return this->derived()._do_start(
std::forward<String>(host), std::forward<StrOrInt>(service),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
public:
/**
* @brief bind websocket upgrade listener
* @param fun - a user defined callback function.
* Function signature : void(std::shared_ptr<asio2::wss_session>& session_ptr)
*/
template<class F, class ...C>
inline derived_t & bind_upgrade(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::upgrade, observer_t<std::shared_ptr<session_t>&>
(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
};
}
namespace asio2
{
template<class derived_t, class session_t>
using wss_server_impl_t = detail::wss_server_impl_t<derived_t, session_t>;
template<class session_t>
class wss_server_t : public detail::wss_server_impl_t<wss_server_t<session_t>, session_t>
{
public:
using detail::wss_server_impl_t<wss_server_t<session_t>, session_t>::wss_server_impl_t;
};
using wss_server = wss_server_t<wss_session>;
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
template<class session_t>
class wss_rate_server_t : public asio2::wss_server_impl_t<wss_rate_server_t<session_t>, session_t>
{
public:
using asio2::wss_server_impl_t<wss_rate_server_t<session_t>, session_t>::wss_server_impl_t;
};
using wss_rate_server = wss_rate_server_t<wss_rate_session>;
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_WSS_SERVER_HPP__
#endif
<file_sep>// Copyright <NAME> 2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BHO_CONFIG_WORKAROUND_HPP
#define BHO_CONFIG_WORKAROUND_HPP
// Compiler/library version workaround macro
//
// Usage:
//
// #if BHO_WORKAROUND(BHO_MSVC, < 1300)
// // workaround for eVC4 and VC6
// ... // workaround code here
// #endif
//
// When BHO_STRICT_CONFIG is defined, expands to 0. Otherwise, the
// first argument must be undefined or expand to a numeric
// value. The above expands to:
//
// (BHO_MSVC) != 0 && (BHO_MSVC) < 1300
//
// When used for workarounds that apply to the latest known version
// and all earlier versions of a compiler, the following convention
// should be observed:
//
// #if BHO_WORKAROUND(BHO_MSVC, BHO_TESTED_AT(1301))
//
// The version number in this case corresponds to the last version in
// which the workaround was known to have been required. When
// BHO_DETECT_OUTDATED_WORKAROUNDS is not the defined, the macro
// BHO_TESTED_AT(x) expands to "!= 0", which effectively activates
// the workaround for any version of the compiler. When
// BHO_DETECT_OUTDATED_WORKAROUNDS is defined, a compiler warning or
// error will be issued if the compiler version exceeds the argument
// to BHO_TESTED_AT(). This can be used to locate workarounds which
// may be obsoleted by newer versions.
#ifndef BHO_STRICT_CONFIG
#include <asio2/bho/config.hpp>
#ifndef __BORLANDC__
#define __BORLANDC___WORKAROUND_GUARD 1
#else
#define __BORLANDC___WORKAROUND_GUARD 0
#endif
#ifndef __CODEGEARC__
#define __CODEGEARC___WORKAROUND_GUARD 1
#else
#define __CODEGEARC___WORKAROUND_GUARD 0
#endif
#ifndef BHO_BORLANDC
#define BHO_BORLANDC_WORKAROUND_GUARD 1
#else
#define BHO_BORLANDC_WORKAROUND_GUARD 0
#endif
#ifndef BHO_CODEGEARC
#define BHO_CODEGEARC_WORKAROUND_GUARD 1
#else
#define BHO_CODEGEARC_WORKAROUND_GUARD 0
#endif
#ifndef BHO_EMBTC
#define BHO_EMBTC_WORKAROUND_GUARD 1
#else
#define BHO_EMBTC_WORKAROUND_GUARD 0
#endif
#ifndef _MSC_VER
#define _MSC_VER_WORKAROUND_GUARD 1
#else
#define _MSC_VER_WORKAROUND_GUARD 0
#endif
#ifndef _MSC_FULL_VER
#define _MSC_FULL_VER_WORKAROUND_GUARD 1
#else
#define _MSC_FULL_VER_WORKAROUND_GUARD 0
#endif
#ifndef BHO_MSVC
#define BHO_MSVC_WORKAROUND_GUARD 1
#else
#define BHO_MSVC_WORKAROUND_GUARD 0
#endif
#ifndef BHO_MSVC_FULL_VER
#define BHO_MSVC_FULL_VER_WORKAROUND_GUARD 1
#else
#define BHO_MSVC_FULL_VER_WORKAROUND_GUARD 0
#endif
#ifndef __GNUC__
#define __GNUC___WORKAROUND_GUARD 1
#else
#define __GNUC___WORKAROUND_GUARD 0
#endif
#ifndef __GNUC_MINOR__
#define __GNUC_MINOR___WORKAROUND_GUARD 1
#else
#define __GNUC_MINOR___WORKAROUND_GUARD 0
#endif
#ifndef __GNUC_PATCHLEVEL__
#define __GNUC_PATCHLEVEL___WORKAROUND_GUARD 1
#else
#define __GNUC_PATCHLEVEL___WORKAROUND_GUARD 0
#endif
#ifndef BHO_GCC
#define BHO_GCC_WORKAROUND_GUARD 1
#define BHO_GCC_VERSION_WORKAROUND_GUARD 1
#else
#define BHO_GCC_WORKAROUND_GUARD 0
#define BHO_GCC_VERSION_WORKAROUND_GUARD 0
#endif
#ifndef BHO_XLCPP_ZOS
#define BHO_XLCPP_ZOS_WORKAROUND_GUARD 1
#else
#define BHO_XLCPP_ZOS_WORKAROUND_GUARD 0
#endif
#ifndef __IBMCPP__
#define __IBMCPP___WORKAROUND_GUARD 1
#else
#define __IBMCPP___WORKAROUND_GUARD 0
#endif
#ifndef __SUNPRO_CC
#define __SUNPRO_CC_WORKAROUND_GUARD 1
#else
#define __SUNPRO_CC_WORKAROUND_GUARD 0
#endif
#ifndef __DECCXX_VER
#define __DECCXX_VER_WORKAROUND_GUARD 1
#else
#define __DECCXX_VER_WORKAROUND_GUARD 0
#endif
#ifndef __MWERKS__
#define __MWERKS___WORKAROUND_GUARD 1
#else
#define __MWERKS___WORKAROUND_GUARD 0
#endif
#ifndef __EDG__
#define __EDG___WORKAROUND_GUARD 1
#else
#define __EDG___WORKAROUND_GUARD 0
#endif
#ifndef __EDG_VERSION__
#define __EDG_VERSION___WORKAROUND_GUARD 1
#else
#define __EDG_VERSION___WORKAROUND_GUARD 0
#endif
#ifndef __HP_aCC
#define __HP_aCC_WORKAROUND_GUARD 1
#else
#define __HP_aCC_WORKAROUND_GUARD 0
#endif
#ifndef __hpxstd98
#define __hpxstd98_WORKAROUND_GUARD 1
#else
#define __hpxstd98_WORKAROUND_GUARD 0
#endif
#ifndef _CRAYC
#define _CRAYC_WORKAROUND_GUARD 1
#else
#define _CRAYC_WORKAROUND_GUARD 0
#endif
#ifndef __DMC__
#define __DMC___WORKAROUND_GUARD 1
#else
#define __DMC___WORKAROUND_GUARD 0
#endif
#ifndef MPW_CPLUS
#define MPW_CPLUS_WORKAROUND_GUARD 1
#else
#define MPW_CPLUS_WORKAROUND_GUARD 0
#endif
#ifndef __COMO__
#define __COMO___WORKAROUND_GUARD 1
#else
#define __COMO___WORKAROUND_GUARD 0
#endif
#ifndef __COMO_VERSION__
#define __COMO_VERSION___WORKAROUND_GUARD 1
#else
#define __COMO_VERSION___WORKAROUND_GUARD 0
#endif
#ifndef __INTEL_COMPILER
#define __INTEL_COMPILER_WORKAROUND_GUARD 1
#else
#define __INTEL_COMPILER_WORKAROUND_GUARD 0
#endif
#ifndef __ICL
#define __ICL_WORKAROUND_GUARD 1
#else
#define __ICL_WORKAROUND_GUARD 0
#endif
#ifndef _COMPILER_VERSION
#define _COMPILER_VERSION_WORKAROUND_GUARD 1
#else
#define _COMPILER_VERSION_WORKAROUND_GUARD 0
#endif
#ifndef __clang_major__
#define __clang_major___WORKAROUND_GUARD 1
#else
#define __clang_major___WORKAROUND_GUARD 0
#endif
#ifndef _RWSTD_VER
#define _RWSTD_VER_WORKAROUND_GUARD 1
#else
#define _RWSTD_VER_WORKAROUND_GUARD 0
#endif
#ifndef BHO_RWSTD_VER
#define BHO_RWSTD_VER_WORKAROUND_GUARD 1
#else
#define BHO_RWSTD_VER_WORKAROUND_GUARD 0
#endif
#ifndef __GLIBCPP__
#define __GLIBCPP___WORKAROUND_GUARD 1
#else
#define __GLIBCPP___WORKAROUND_GUARD 0
#endif
#ifndef _GLIBCXX_USE_C99_FP_MACROS_DYNAMIC
#define _GLIBCXX_USE_C99_FP_MACROS_DYNAMIC_WORKAROUND_GUARD 1
#else
#define _GLIBCXX_USE_C99_FP_MACROS_DYNAMIC_WORKAROUND_GUARD 0
#endif
#ifndef __SGI_STL_PORT
#define __SGI_STL_PORT_WORKAROUND_GUARD 1
#else
#define __SGI_STL_PORT_WORKAROUND_GUARD 0
#endif
#ifndef _STLPORT_VERSION
#define _STLPORT_VERSION_WORKAROUND_GUARD 1
#else
#define _STLPORT_VERSION_WORKAROUND_GUARD 0
#endif
#ifndef __LIBCOMO_VERSION__
#define __LIBCOMO_VERSION___WORKAROUND_GUARD 1
#else
#define __LIBCOMO_VERSION___WORKAROUND_GUARD 0
#endif
#ifndef _CPPLIB_VER
#define _CPPLIB_VER_WORKAROUND_GUARD 1
#else
#define _CPPLIB_VER_WORKAROUND_GUARD 0
#endif
#ifndef BHO_INTEL_CXX_VERSION
#define BHO_INTEL_CXX_VERSION_WORKAROUND_GUARD 1
#else
#define BHO_INTEL_CXX_VERSION_WORKAROUND_GUARD 0
#endif
#ifndef BHO_INTEL_WIN
#define BHO_INTEL_WIN_WORKAROUND_GUARD 1
#else
#define BHO_INTEL_WIN_WORKAROUND_GUARD 0
#endif
#ifndef BHO_DINKUMWARE_STDLIB
#define BHO_DINKUMWARE_STDLIB_WORKAROUND_GUARD 1
#else
#define BHO_DINKUMWARE_STDLIB_WORKAROUND_GUARD 0
#endif
#ifndef BHO_INTEL
#define BHO_INTEL_WORKAROUND_GUARD 1
#else
#define BHO_INTEL_WORKAROUND_GUARD 0
#endif
#ifndef BHO_CLANG_VERSION
#define BHO_CLANG_VERSION_WORKAROUND_GUARD 1
#else
#define BHO_CLANG_VERSION_WORKAROUND_GUARD 0
#endif
// Always define to zero, if it's used it'll be defined my MPL:
#define BHO_MPL_CFG_GCC_WORKAROUND_GUARD 0
#define BHO_WORKAROUND(symbol, test) \
((symbol ## _WORKAROUND_GUARD + 0 == 0) && \
(symbol != 0) && (1 % (( (symbol test) ) + 1)))
// ^ ^ ^ ^
// The extra level of parenthesis nesting above, along with the
// BHO_OPEN_PAREN indirection below, is required to satisfy the
// broken preprocessor in MWCW 8.3 and earlier.
//
// The basic mechanism works as follows:
// (symbol test) + 1 => if (symbol test) then 2 else 1
// 1 % ((symbol test) + 1) => if (symbol test) then 1 else 0
//
// The complication with % is for cooperation with BHO_TESTED_AT().
// When "test" is BHO_TESTED_AT(x) and
// BHO_DETECT_OUTDATED_WORKAROUNDS is #defined,
//
// symbol test => if (symbol <= x) then 1 else -1
// (symbol test) + 1 => if (symbol <= x) then 2 else 0
// 1 % ((symbol test) + 1) => if (symbol <= x) then 1 else divide-by-zero
//
#ifdef BHO_DETECT_OUTDATED_WORKAROUNDS
# define BHO_OPEN_PAREN (
# define BHO_TESTED_AT(value) > value) ?(-1): BHO_OPEN_PAREN 1
#else
# define BHO_TESTED_AT(value) != ((value)-(value))
#endif
#else
#define BHO_WORKAROUND(symbol, test) 0
#endif
#endif // BHO_CONFIG_WORKAROUND_HPP
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_DIGITALMARS_H
#define BHO_PREDEF_COMPILER_DIGITALMARS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_DMC`
http://en.wikipedia.org/wiki/Digital_Mars[Digital Mars] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__DMC__+` | {predef_detection}
| `+__DMC__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_DMC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__DMC__)
# define BHO_COMP_DMC_DETECTION BHO_PREDEF_MAKE_0X_VRP(__DMC__)
#endif
#ifdef BHO_COMP_DMC_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_DMC_EMULATED BHO_COMP_DMC_DETECTION
# else
# undef BHO_COMP_DMC
# define BHO_COMP_DMC BHO_COMP_DMC_DETECTION
# endif
# define BHO_COMP_DMC_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_DMC_NAME "Digital Mars"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_DMC,BHO_COMP_DMC_NAME)
#ifdef BHO_COMP_DMC_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_DMC_EMULATED,BHO_COMP_DMC_NAME)
#endif
<file_sep>
LOCAL_PATH := $(call my-dir)
ASIO2_ROOT_DIR := $(LOCAL_PATH)/../../../
ASIO2_EXAMPLE_DIR := $(ASIO2_ROOT_DIR)/example
ASIO2_TEST_DIR := $(ASIO2_ROOT_DIR)/test
ASIO2_INCLUDE := $(ASIO2_ROOT_DIR)/3rd
ASIO2_INCLUDE += $(ASIO2_ROOT_DIR)/3rd/openssl/include
ASIO2_INCLUDE += $(ASIO2_ROOT_DIR)/include
# $(info "TARGET_ARCH_ABI = $(TARGET_ARCH_ABI)")
# $(info "ASIO2_ROOT_DIR = $(ASIO2_ROOT_DIR)")
ifeq ($(TARGET_ARCH_ABI), arm64-v8a)
else ifeq ($(TARGET_ARCH_ABI), armeabi-v7a)
else ifeq ($(TARGET_ARCH_ABI), x86)
else ifeq ($(TARGET_ARCH_ABI), x86_64)
else
$(error "Not supported TARGET_ARCH_ABI: $(TARGET_ARCH_ABI)")
endif
###############################################################################
## ssl librarys link
include $(CLEAR_VARS)
LOCAL_MODULE := libssl
LOCAL_SRC_FILES := $(ASIO2_ROOT_DIR)/3rd/openssl/prebuilt/android/$(TARGET_ARCH_ABI)/libssl.a
include $(PREBUILT_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := libcrypto
LOCAL_SRC_FILES := $(ASIO2_ROOT_DIR)/3rd/openssl/prebuilt/android/$(TARGET_ARCH_ABI)/libcrypto.a
include $(PREBUILT_STATIC_LIBRARY)
###############################################################################
## projects
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := http_client.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/http/client/http_client.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := http_server.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/http/server/http_server.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := icmp_ping.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/icmp/icmp_ping.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := inherit.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/inherit/inherit.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := mqtt_client.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/mqtt/client/mqtt_client.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := mqtt_server.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/mqtt/server/mqtt_server.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := rate_limit.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/rate_limit/rate_limit.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := rpc_client.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/rpc/client/rpc_client.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := rpc_server.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/rpc/server/rpc_server.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := serial_port.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/serial_port/serial_port.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := shared_iopool.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/shared_iopool/shared_iopool.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_client_character.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/tcp/client/character/tcp_client_character.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_client_custom.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/tcp/client/custom/tcp_client_custom.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_client_datagram.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/tcp/client/datagram/tcp_client_datagram.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_client_general.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/tcp/client/general/tcp_client_general.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_server_character.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/tcp/server/character/tcp_server_character.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_server_custom.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/tcp/server/custom/tcp_server_custom.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_server_datagram.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/tcp/server/datagram/tcp_server_datagram.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_server_general.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/tcp/server/general/tcp_server_general.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := timer.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/timer/timer.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := udp_cast.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/udp/cast/udp_cast.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := udp_client.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/udp/client/general/udp_client.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := udp_client_kcp.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/udp/client/kcp/udp_client_kcp.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := udp_server.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/udp/server/general/udp_server.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := udp_server_kcp.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/udp/server/kcp/udp_server_kcp.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := websocket_client.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/websocket/client/websocket_client.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := websocket_server.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/websocket/server/websocket_server.cpp
include $(BUILD_EXECUTABLE)
###############################################################################
## ssl projects
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := ssl_http_client.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/ssl/http/client/ssl_http_client.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := ssl_http_server.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/ssl/http/server/ssl_http_server.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := ssl_rpc_client.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/ssl/rpc/client/ssl_rpc_client.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := ssl_rpc_server.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/ssl/rpc/server/ssl_rpc_server.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := ssl_tcp_client_general.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/ssl/tcp/client/general/ssl_tcp_client_general.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := ssl_tcp_server_general.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/ssl/tcp/server/general/ssl_tcp_server_general.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := ssl_websocket_client.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/ssl/websocket/client/ssl_websocket_client.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := ssl_websocket_server.out
LOCAL_SRC_FILES := $(ASIO2_EXAMPLE_DIR)/ssl/websocket/server/ssl_websocket_server.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_LINEAR_BUFFER_HPP__
#define __ASIO2_LINEAR_BUFFER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <limits>
#include <memory>
#include <vector>
#include <asio2/external/asio.hpp>
namespace asio2
{
template<class Container>
class basic_linear_buffer : protected Container
{
public:
/// The type of allocator used.
using allocator_type = typename Container::allocator_type;
using size_type = typename Container::size_type;
/// The type used to represent the input sequence as a list of buffers.
using const_buffers_type = asio::const_buffer;
/// The type used to represent the output sequence as a list of buffers.
using mutable_buffers_type = asio::mutable_buffer;
/// Destructor
~basic_linear_buffer() = default;
basic_linear_buffer() = default;
explicit basic_linear_buffer(size_type max) noexcept : Container(), max_(max) {}
basic_linear_buffer(basic_linear_buffer&& other) = default;
basic_linear_buffer(basic_linear_buffer const& other) = default;
basic_linear_buffer& operator=(basic_linear_buffer&& other) = default;
basic_linear_buffer& operator=(basic_linear_buffer const& other) = default;
/// Returns the size of the input sequence.
inline size_type size() const noexcept
{
return (wpos_ - rpos_);
}
/// Return the maximum sum of the input and output sequence sizes.
inline size_type max_size() const noexcept
{
return max_;
}
/// Return the maximum sum of input and output sizes that can be held without an allocation.
inline size_type capacity() const noexcept
{
return Container::capacity();
}
/// Get a list of buffers that represent the input sequence.
inline const_buffers_type data() const noexcept
{
return { Container::data() + rpos_, wpos_ - rpos_ };
}
/** Get a list of buffers that represent the output sequence, with the given size.
@throws std::length_error if `size() + n` exceeds `max_size()`.
@note All previous buffers sequences obtained from
calls to @ref data or @ref prepare are invalidated.
*/
inline mutable_buffers_type prepare(size_type n)
{
size_type const cap = Container::capacity();
if (n <= cap - wpos_)
{
Container::resize(wpos_ + n);
// existing capacity is sufficient
return{ Container::data() + wpos_, n };
}
size_type const size = this->size();
if (n <= cap - size)
{
// after a memmove,
// existing capacity is sufficient
if (size > 0)
std::memmove(Container::data(), Container::data() + rpos_, size);
rpos_ = 0;
wpos_ = size;
Container::resize(wpos_ + n);
return { Container::data() + wpos_, n };
}
// enforce maximum capacity
if (n > max_ - size)
asio::detail::throw_exception(std::length_error{ "basic_linear_buffer overflow" });
// allocate a new buffer
size_type const new_size = (std::max<size_type>)((std::min<size_type>)(
max_,
(std::max<size_type>)(2 * cap, wpos_ + n)), min_size);
Container::resize(new_size);
Container::resize(wpos_ + n);
return { Container::data() + wpos_, n };
}
/** Move bytes from the output sequence to the input sequence.
@param n The number of bytes to move. If this is larger than
the number of bytes in the output sequences, then the entire
output sequences is moved.
@note All previous buffers sequences obtained from
calls to @ref data or @ref prepare are invalidated.
*/
inline void commit(size_type n) noexcept
{
wpos_ += (std::min<size_type>)(n, Container::size() - wpos_);
}
/** Remove bytes from the input sequence.
If `n` is greater than the number of bytes in the input
sequence, all bytes in the input sequence are removed.
@note All previous buffers sequences obtained from
calls to @ref data or @ref prepare are invalidated.
*/
inline void consume(size_type n) noexcept
{
if (n >= wpos_ - rpos_)
{
wpos_ = 0;
rpos_ = 0;
Container::resize(0);
return;
}
rpos_ += n;
}
inline void shrink_to_fit()
{
Container::shrink_to_fit();
}
protected:
size_type rpos_ = 0;
size_type wpos_ = 0;
size_type max_ = (std::numeric_limits<size_type>::max)();
static size_type constexpr min_size = 512;
};
using linear_buffer = basic_linear_buffer<std::vector<char>>;
}
#endif // !__ASIO2_LINEAR_BUFFER_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_STD_LIBCOMO_H
#define BHO_PREDEF_LIBRARY_STD_LIBCOMO_H
#include <asio2/bho/predef/library/std/_prefix.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_LIB_STD_COMO`
http://www.comeaucomputing.com/libcomo/[Comeau Computing] Standard {CPP} Library.
Version number available as major.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__LIBCOMO__+` | {predef_detection}
| `+__LIBCOMO_VERSION__+` | V.0.0
|===
*/ // end::reference[]
#define BHO_LIB_STD_COMO BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__LIBCOMO__)
# undef BHO_LIB_STD_COMO
# define BHO_LIB_STD_COMO BHO_VERSION_NUMBER(__LIBCOMO_VERSION__,0,0)
#endif
#if BHO_LIB_STD_COMO
# define BHO_LIB_STD_COMO_AVAILABLE
#endif
#define BHO_LIB_STD_COMO_NAME "Comeau Computing"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_STD_COMO,BHO_LIB_STD_COMO_NAME)
<file_sep>/*
* Copyright <NAME> 2007 - 2013.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file explicit_operator_bool.hpp
* \author <NAME>
* \date 08.03.2009
*
* This header defines a compatibility macro that implements an unspecified
* \c bool operator idiom, which is superseded with explicit conversion operators in
* C++11.
*/
#ifndef BHO_CORE_EXPLICIT_OPERATOR_BOOL_HPP
#define BHO_CORE_EXPLICIT_OPERATOR_BOOL_HPP
#include <asio2/bho/config.hpp>
#include <asio2/bho/config/workaround.hpp>
#ifdef BHO_HAS_PRAGMA_ONCE
#pragma once
#endif
#if !defined(BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS)
/*!
* \brief The macro defines an explicit operator of conversion to \c bool
*
* The macro should be used inside the definition of a class that has to
* support the conversion. The class should also implement <tt>operator!</tt>,
* in terms of which the conversion operator will be implemented.
*/
#define BHO_EXPLICIT_OPERATOR_BOOL()\
BHO_FORCEINLINE explicit operator bool () const\
{\
return !this->operator! ();\
}
/*!
* \brief The macro defines a noexcept explicit operator of conversion to \c bool
*
* The macro should be used inside the definition of a class that has to
* support the conversion. The class should also implement <tt>operator!</tt>,
* in terms of which the conversion operator will be implemented.
*/
#define BHO_EXPLICIT_OPERATOR_BOOL_NOEXCEPT()\
BHO_FORCEINLINE explicit operator bool () const BHO_NOEXCEPT\
{\
return !this->operator! ();\
}
#if !BHO_WORKAROUND(BHO_GCC, < 40700)
/*!
* \brief The macro defines a constexpr explicit operator of conversion to \c bool
*
* The macro should be used inside the definition of a class that has to
* support the conversion. The class should also implement <tt>operator!</tt>,
* in terms of which the conversion operator will be implemented.
*/
#define BHO_CONSTEXPR_EXPLICIT_OPERATOR_BOOL()\
BHO_FORCEINLINE BHO_CONSTEXPR explicit operator bool () const BHO_NOEXCEPT\
{\
return !this->operator! ();\
}
#else
#define BHO_CONSTEXPR_EXPLICIT_OPERATOR_BOOL() BHO_EXPLICIT_OPERATOR_BOOL_NOEXCEPT()
#endif
#else // !defined(BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS)
#if (defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x530)) && !defined(BHO_NO_COMPILER_CONFIG)
// Sun C++ 5.3 can't handle the safe_bool idiom, so don't use it
#define BHO_NO_UNSPECIFIED_BOOL
#endif // (defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x530)) && !defined(BHO_NO_COMPILER_CONFIG)
#if !defined(BHO_NO_UNSPECIFIED_BOOL)
namespace bho {
namespace detail {
#if !defined(_MSC_VER) && !defined(__IBMCPP__)
struct unspecified_bool
{
// NOTE TO THE USER: If you see this in error messages then you tried
// to apply an unsupported operator on the object that supports
// explicit conversion to bool.
struct OPERATORS_NOT_ALLOWED;
static void true_value(OPERATORS_NOT_ALLOWED*) {}
};
typedef void (*unspecified_bool_type)(unspecified_bool::OPERATORS_NOT_ALLOWED*);
#else
// MSVC and VACPP are too eager to convert pointer to function to void* even though they shouldn't
struct unspecified_bool
{
// NOTE TO THE USER: If you see this in error messages then you tried
// to apply an unsupported operator on the object that supports
// explicit conversion to bool.
struct OPERATORS_NOT_ALLOWED;
void true_value(OPERATORS_NOT_ALLOWED*) {}
};
typedef void (unspecified_bool::*unspecified_bool_type)(unspecified_bool::OPERATORS_NOT_ALLOWED*);
#endif
} // namespace detail
} // namespace bho
#define BHO_EXPLICIT_OPERATOR_BOOL()\
BHO_FORCEINLINE operator bho::detail::unspecified_bool_type () const\
{\
return (!this->operator! () ? &bho::detail::unspecified_bool::true_value : (bho::detail::unspecified_bool_type)0);\
}
#define BHO_EXPLICIT_OPERATOR_BOOL_NOEXCEPT()\
BHO_FORCEINLINE operator bho::detail::unspecified_bool_type () const BHO_NOEXCEPT\
{\
return (!this->operator! () ? &bho::detail::unspecified_bool::true_value : (bho::detail::unspecified_bool_type)0);\
}
#define BHO_CONSTEXPR_EXPLICIT_OPERATOR_BOOL()\
BHO_FORCEINLINE BHO_CONSTEXPR operator bho::detail::unspecified_bool_type () const BHO_NOEXCEPT\
{\
return (!this->operator! () ? &bho::detail::unspecified_bool::true_value : (bho::detail::unspecified_bool_type)0);\
}
#else // !defined(BHO_NO_UNSPECIFIED_BOOL)
#define BHO_EXPLICIT_OPERATOR_BOOL()\
BHO_FORCEINLINE operator bool () const\
{\
return !this->operator! ();\
}
#define BHO_EXPLICIT_OPERATOR_BOOL_NOEXCEPT()\
BHO_FORCEINLINE operator bool () const BHO_NOEXCEPT\
{\
return !this->operator! ();\
}
#define BHO_CONSTEXPR_EXPLICIT_OPERATOR_BOOL()\
BHO_FORCEINLINE BHO_CONSTEXPR operator bool () const BHO_NOEXCEPT\
{\
return !this->operator! ();\
}
#endif // !defined(BHO_NO_UNSPECIFIED_BOOL)
#endif // !defined(BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS)
#endif // BHO_CORE_EXPLICIT_OPERATOR_BOOL_HPP
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RPC_ERROR_HPP__
#define __ASIO2_RPC_ERROR_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/error.hpp>
namespace asio2::rpc
{
/**
*/
enum class error
{
// The operation completed successfully.
success = 0,
// Operation aborted.
operation_aborted,
// Invalid argument.
invalid_argument,
// Illegal data.
illegal_data,
// The operation timed out.
timed_out,
// Does not have associated data.
no_data,
// Operation now in progress.
in_progress,
// Transport endpoint is not connected.
not_connected,
// Element not found.
not_found,
// Unspecified error.
unspecified_error,
};
enum class condition
{
// The operation completed successfully.
success = 0,
// Operation aborted.
operation_aborted,
// Invalid argument.
invalid_argument,
// Illegal data.
illegal_data,
// The operation timed out.
timed_out,
// Does not have associated data.
no_data,
// Operation now in progress.
in_progress,
// Transport endpoint is not connected.
not_connected,
// Element not found.
not_found,
// Unknown error.
unspecified_error,
};
/// The type of error category used by the library
using error_category = asio::error_category;
/// The type of error condition used by the library
using error_condition = asio::error_condition;
class rpc_error_category : public error_category
{
public:
const char* name() const noexcept override
{
return "asio2.rpc";
}
inline std::string message(int ev) const override
{
switch (static_cast<error>(ev))
{
case error::success : return "The operation completed successfully.";
case error::operation_aborted : return "Operation aborted.";
case error::invalid_argument : return "Invalid argument.";
case error::illegal_data : return "Illegal data.";
case error::timed_out : return "The operation timed out.";
case error::no_data : return "Does not have associated data.";
case error::in_progress : return "Operation now in progress.";
case error::not_connected : return "Transport endpoint is not connected.";
case error::not_found : return "Element not found.";
case error::unspecified_error : return "Unspecified error.";
default : return "Unknown error";
}
}
inline error_condition default_error_condition(int ev) const noexcept override
{
return error_condition{ ev, *this };
}
};
inline const rpc_error_category& rpc_category() noexcept
{
static rpc_error_category const cat{};
return cat;
}
inline asio::error_code make_error_code(error e)
{
return asio::error_code{ static_cast<std::underlying_type<error>::type>(e), rpc_category() };
}
inline error_condition make_error_condition(condition c)
{
return error_condition{ static_cast<std::underlying_type<condition>::type>(c), rpc_category() };
}
template<typename = void>
inline constexpr std::string_view to_string(error e)
{
using namespace std::string_view_literals;
switch (e)
{
case error::success : return "The operation completed successfully.";
case error::operation_aborted : return "Operation aborted.";
case error::invalid_argument : return "Invalid argument.";
case error::illegal_data : return "Illegal data.";
case error::timed_out : return "The operation timed out.";
case error::no_data : return "Does not have associated data.";
case error::in_progress : return "Operation now in progress.";
case error::not_connected : return "Transport endpoint is not connected.";
case error::not_found : return "Element not found.";
case error::unspecified_error : return "Unspecified error.";
default : return "Unknown error";
}
return "Unknown error";
};
}
namespace rpc = ::asio2::rpc;
namespace std
{
template<>
struct is_error_code_enum<::asio2::rpc::error>
{
static bool const value = true;
};
template<>
struct is_error_condition_enum<::asio2::rpc::condition>
{
static bool const value = true;
};
}
#endif // !__ASIO2_RPC_ERROR_HPP__
<file_sep>#include <asio2/asio2.hpp>
#include <iostream>
int main()
{
// 4 threads
asio2::iopool iopool(4);
// iopool must start first, othwise the server.start will blocked forever.
iopool.start();
std::vector<std::future<void>> futures;
auto future1 = iopool.post([]()
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "task 1:" << std::this_thread::get_id() << std::endl;
});
auto future2 = iopool.post([]()
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "task 2:" << std::this_thread::get_id() << std::endl;
});
auto future3 = iopool.post(2, [&iopool]()
{
std::cout << "task 3:" << std::this_thread::get_id() << std::endl;
ASIO2_ASSERT(iopool.get_thread_id(2) == std::this_thread::get_id());
ASIO2_ASSERT(iopool.get(2).get_thread_id() == std::this_thread::get_id());
asio2::ignore_unused(iopool);
});
futures.emplace_back(std::move(future1));
futures.emplace_back(std::move(future2));
futures.emplace_back(std::move(future3));
for (auto& future : futures)
{
future.wait();
}
//// --------------------------------------------------------------------------------
asio2::timer timer(iopool.get(std::rand() % iopool.size()));
timer.start_timer(1, std::chrono::milliseconds(1000), [&]()
{
printf("timer 1, loop infinite\n");
});
//-----------------------------------------------------------------------------------
// 256 - init recv buffer size, 2048 - max recv buffer size, see the constructor of tcp_server
asio2::tcp_server server(256, 2048, std::vector<asio2::io_t*>{ &iopool.get(0), & iopool.get(1) });
server.bind_recv([&](std::shared_ptr<asio2::tcp_session>& session_ptr, std::string_view data)
{
ASIO2_ASSERT(session_ptr->io().running_in_this_thread());
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
// delay 3 seconds, then send the response
session_ptr->post([session_ptr, s = std::string{ data }]() mutable
{
session_ptr->async_send(std::move(s));
}, std::chrono::milliseconds(3000));
}).bind_connect([&](auto& session_ptr)
{
ASIO2_ASSERT(iopool.running_in_thread(0));
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([&](auto & session_ptr)
{
ASIO2_ASSERT(iopool.running_in_thread(0));
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
}).bind_start([&]()
{
ASIO2_ASSERT(iopool.running_in_thread(0));
printf("start tcp server : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
ASIO2_ASSERT(iopool.running_in_thread(0));
printf("stop : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.start("127.0.0.1", 4567);
//-----------------------------------------------------------------------------------
// if you create a object and it will destroyed before iopool.stop(), you must create
// the object as shared_ptr<asio2::tcp_client>, can't be asio2::tcp_client.
{
std::shared_ptr<asio2::tcp_client> client = std::make_shared<asio2::tcp_client>(iopool.get(0));
client->start("127.0.0.1", 4567);
client->async_send("i love you");
std::this_thread::sleep_for(std::chrono::seconds(2));
}
//-----------------------------------------------------------------------------------
std::vector<std::shared_ptr<asio2::tcp_client>> clients;
for (int i = 0; i < 10; i++)
{
std::shared_ptr<asio2::tcp_client>& client_ptr = clients.emplace_back(
std::make_shared<asio2::tcp_client>(iopool.get(i % iopool.size())));
client_ptr->bind_recv([client_ptr](std::string_view data)
{
client_ptr->async_send(data);
}).bind_connect([client_ptr]()
{
client_ptr->async_send("<0123456789abcdefg>");
});
client_ptr->async_start("127.0.0.1", 4567);
}
while (std::getchar() != '\n'); // press enter to exit this program
/* call the server.stop and client.stop, or not call the server.stop and client.stop, is OK.*/
//server.stop();
//for (auto& client_ptr : clients)
//{
// client_ptr->stop();
//}
// must call iopool.stop() before exit.
iopool.stop();
return 0;
}
<file_sep>// Copyright (c) 2014 <NAME>, <NAME>.
//
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BHO_CORE_IGNORE_UNUSED_HPP
#define BHO_CORE_IGNORE_UNUSED_HPP
#include <asio2/bho/config.hpp>
namespace bho {
#if !defined(BHO_NO_CXX11_VARIADIC_TEMPLATES)
#if !defined(BHO_NO_CXX11_RVALUE_REFERENCES)
template <typename... Ts>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(Ts&& ...)
{}
#else
template <typename... Ts>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(Ts const& ...)
{}
#endif
template <typename... Ts>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused()
{}
#else // !defined(BHO_NO_CXX11_VARIADIC_TEMPLATES)
template <typename T1>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1&)
{}
template <typename T1>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1 const&)
{}
template <typename T1, typename T2>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1&, T2&)
{}
template <typename T1, typename T2>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1 const&, T2 const&)
{}
template <typename T1, typename T2, typename T3>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1&, T2&, T3&)
{}
template <typename T1, typename T2, typename T3>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1 const&, T2 const&, T3 const&)
{}
template <typename T1, typename T2, typename T3, typename T4>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1&, T2&, T3&, T4&)
{}
template <typename T1, typename T2, typename T3, typename T4>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1 const&, T2 const&, T3 const&, T4 const&)
{}
template <typename T1, typename T2, typename T3, typename T4, typename T5>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1&, T2&, T3&, T4&, T5&)
{}
template <typename T1, typename T2, typename T3, typename T4, typename T5>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused(T1 const&, T2 const&, T3 const&, T4 const&, T5 const&)
{}
template <typename T1>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused()
{}
template <typename T1, typename T2>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused()
{}
template <typename T1, typename T2, typename T3>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused()
{}
template <typename T1, typename T2, typename T3, typename T4>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused()
{}
template <typename T1, typename T2, typename T3, typename T4, typename T5>
BHO_FORCEINLINE BHO_CXX14_CONSTEXPR void ignore_unused()
{}
#endif
} // namespace bho
#endif // BHO_CORE_IGNORE_UNUSED_HPP
<file_sep>// (C) Copyright <NAME> 2011.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// config for libc++
// Might need more in here later.
#if !defined(_LIBCPP_VERSION)
# include <ciso646>
# if !defined(_LIBCPP_VERSION)
# error "This is not libc++!"
# endif
#endif
#define BHO_STDLIB "libc++ version " BHO_STRINGIZE(_LIBCPP_VERSION)
#define BHO_HAS_THREADS
#ifdef _LIBCPP_HAS_NO_VARIADICS
# define BHO_NO_CXX11_HDR_TUPLE
#endif
// BHO_NO_CXX11_ALLOCATOR should imply no support for the C++11
// allocator model. The C++11 allocator model requires a conforming
// std::allocator_traits which is only possible with C++11 template
// aliases since members rebind_alloc and rebind_traits require it.
#if defined(_LIBCPP_HAS_NO_TEMPLATE_ALIASES)
# define BHO_NO_CXX11_ALLOCATOR
# define BHO_NO_CXX11_POINTER_TRAITS
#endif
#if __cplusplus < 201103
//
// These two appear to be somewhat useable in C++03 mode, there may be others...
//
//# define BHO_NO_CXX11_HDR_ARRAY
//# define BHO_NO_CXX11_HDR_FORWARD_LIST
# define BHO_NO_CXX11_HDR_CODECVT
# define BHO_NO_CXX11_HDR_CONDITION_VARIABLE
# define BHO_NO_CXX11_HDR_EXCEPTION
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
# define BHO_NO_CXX11_HDR_MUTEX
# define BHO_NO_CXX11_HDR_RANDOM
# define BHO_NO_CXX11_HDR_RATIO
# define BHO_NO_CXX11_HDR_REGEX
# define BHO_NO_CXX11_HDR_SYSTEM_ERROR
# define BHO_NO_CXX11_HDR_THREAD
# define BHO_NO_CXX11_HDR_TUPLE
# define BHO_NO_CXX11_HDR_TYPEINDEX
# define BHO_NO_CXX11_HDR_UNORDERED_MAP
# define BHO_NO_CXX11_HDR_UNORDERED_SET
# define BHO_NO_CXX11_NUMERIC_LIMITS
# define BHO_NO_CXX11_ALLOCATOR
# define BHO_NO_CXX11_POINTER_TRAITS
# define BHO_NO_CXX11_SMART_PTR
# define BHO_NO_CXX11_HDR_FUNCTIONAL
# define BHO_NO_CXX11_STD_ALIGN
# define BHO_NO_CXX11_ADDRESSOF
# define BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_HDR_TYPE_TRAITS
# define BHO_NO_CXX11_HDR_FUTURE
#elif _LIBCPP_VERSION < 3700
//
// These appear to be unusable/incomplete so far:
//
# define BHO_NO_CXX11_HDR_ATOMIC
# define BHO_NO_CXX11_ATOMIC_SMART_PTR
# define BHO_NO_CXX11_HDR_CHRONO
# define BHO_NO_CXX11_HDR_TYPE_TRAITS
# define BHO_NO_CXX11_HDR_FUTURE
#endif
#if _LIBCPP_VERSION < 3700
// libc++ uses a non-standard messages_base
#define BHO_NO_STD_MESSAGES
#endif
// C++14 features
#if (_LIBCPP_VERSION < 3700) || (__cplusplus <= 201402L)
# define BHO_NO_CXX14_STD_EXCHANGE
#endif
// C++17 features
#if (_LIBCPP_VERSION < 4000) || (__cplusplus <= 201402L)
# define BHO_NO_CXX17_STD_APPLY
# define BHO_NO_CXX17_HDR_OPTIONAL
# define BHO_NO_CXX17_HDR_STRING_VIEW
# define BHO_NO_CXX17_HDR_VARIANT
#endif
#if (_LIBCPP_VERSION > 4000) && (__cplusplus > 201402L) && !defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
# define BHO_NO_AUTO_PTR
#endif
#if (_LIBCPP_VERSION > 4000) && (__cplusplus > 201402L) && !defined(_LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE)
# define BHO_NO_CXX98_RANDOM_SHUFFLE
#endif
#if (_LIBCPP_VERSION > 4000) && (__cplusplus > 201402L) && !defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
# define BHO_NO_CXX98_BINDERS
#endif
#ifdef __has_include
#if __has_include(<version>)
#include <version>
#if !defined(__cpp_lib_execution) || (__cpp_lib_execution < 201603L)
# define BHO_NO_CXX17_HDR_EXECUTION
#endif
#if !defined(__cpp_lib_invoke) || (__cpp_lib_invoke < 201411L)
#define BHO_NO_CXX17_STD_INVOKE
#endif
#if !defined(__cpp_lib_bit_cast) || (__cpp_lib_bit_cast < 201806L) || !defined(__cpp_lib_bitops) || (__cpp_lib_bitops < 201907L) || !defined(__cpp_lib_endian) || (__cpp_lib_endian < 201907L)
# define BHO_NO_CXX20_HDR_BIT
#endif
#if !defined(__cpp_lib_three_way_comparison) || (__cpp_lib_three_way_comparison < 201907L)
# define BHO_NO_CXX20_HDR_COMPARE
#endif
#if !defined(__cpp_lib_ranges) || (__cpp_lib_ranges < 201911L)
# define BHO_NO_CXX20_HDR_RANGES
#endif
#if !defined(__cpp_lib_barrier) || (__cpp_lib_barrier < 201907L)
# define BHO_NO_CXX20_HDR_BARRIER
#endif
#if !defined(__cpp_lib_format) || (__cpp_lib_format < 201907L)
# define BHO_NO_CXX20_HDR_FORMAT
#endif
#if !defined(__cpp_lib_source_location) || (__cpp_lib_source_location < 201907L)
# define BHO_NO_CXX20_HDR_SOURCE_LOCATION
#endif
#if !defined(__cpp_lib_latch) || (__cpp_lib_latch < 201907L)
# define BHO_NO_CXX20_HDR_SOURCE_LATCH
#endif
#if !defined(__cpp_lib_span) || (__cpp_lib_span < 202002L)
# define BHO_NO_CXX20_HDR_SOURCE_SPAN
#endif
#if !defined(__cpp_lib_math_constants) || (__cpp_lib_math_constants < 201907L)
# define BHO_NO_CXX20_HDR_SOURCE_NUMBERS
#endif
#if !defined(__cpp_lib_jthread) || (__cpp_lib_jthread < 201911L)
# define BHO_NO_CXX20_HDR_SOURCE_STOP_TOKEN
#endif
#if !defined(__cpp_lib_concepts) || (__cpp_lib_concepts < 202002L)
# define BHO_NO_CXX20_HDR_SOURCE_STOP_CONCEPTS
#endif
#if !defined(__cpp_lib_syncbuf) || (__cpp_lib_syncbuf < 201803L)
# define BHO_NO_CXX20_HDR_SYNCSTREAM
#endif
#if !defined(__cpp_lib_coroutine) || (__cpp_lib_coroutine < 201902L)
# define BHO_NO_CXX20_HDR_COROUTINE
#endif
#if !defined(__cpp_lib_semaphore) || (__cpp_lib_semaphore < 201907L)
# define BHO_NO_CXX20_HDR_SEMAPHORE
#endif
#if !defined(__cpp_lib_concepts) || (__cpp_lib_concepts < 202002L)
# define BHO_NO_CXX20_HDR_CONCEPTS
#endif
#if(_LIBCPP_VERSION < 9000) && !defined(BHO_NO_CXX20_HDR_SPAN)
// as_writable_bytes is missing.
# define BHO_NO_CXX20_HDR_SPAN
#endif
#else
#define BHO_NO_CXX17_STD_INVOKE // Invoke support is incomplete (no invoke_result)
#define BHO_NO_CXX17_HDR_EXECUTION
#endif
#else
#define BHO_NO_CXX17_STD_INVOKE // Invoke support is incomplete (no invoke_result)
#define BHO_NO_CXX17_HDR_EXECUTION
#endif
#if _LIBCPP_VERSION < 10000 // What's the correct version check here?
#define BHO_NO_CXX17_ITERATOR_TRAITS
#endif
#if (_LIBCPP_VERSION <= 1101) && !defined(BHO_NO_CXX11_THREAD_LOCAL)
// This is a bit of a sledgehammer, because really it's just libc++abi that has no
// support for thread_local, leading to linker errors such as
// "undefined reference to `__cxa_thread_atexit'". It is fixed in the
// most recent releases of libc++abi though...
# define BHO_NO_CXX11_THREAD_LOCAL
#endif
#if defined(__linux__) && (_LIBCPP_VERSION < 6000) && !defined(BHO_NO_CXX11_THREAD_LOCAL)
// After libc++-dev is installed on Trusty, clang++-libc++ almost works,
// except uses of `thread_local` fail with undefined reference to
// `__cxa_thread_atexit`.
//
// clang's libc++abi provides an implementation by deferring to the glibc
// implementation, which may or may not be available (it is not on Trusty).
// clang 4's libc++abi will provide an implementation if one is not in glibc
// though, so thread local support should work with clang 4 and above as long
// as libc++abi is linked in.
# define BHO_NO_CXX11_THREAD_LOCAL
#endif
#if defined(__has_include)
#if !__has_include(<shared_mutex>)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#elif __cplusplus <= 201103
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#elif __cplusplus < 201402
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
#if !defined(BHO_NO_CXX14_HDR_SHARED_MUTEX) && (_LIBCPP_VERSION < 5000)
# define BHO_NO_CXX14_HDR_SHARED_MUTEX
#endif
// --- end ---
<file_sep>
LOCAL_PATH := $(call my-dir)
ASIO2_ROOT_DIR := $(LOCAL_PATH)/../../../
ASIO2_EXAMPLE_DIR := $(ASIO2_ROOT_DIR)/example
ASIO2_TEST_DIR := $(ASIO2_ROOT_DIR)/test
ASIO2_INCLUDE := $(ASIO2_ROOT_DIR)/3rd
ASIO2_INCLUDE += $(ASIO2_ROOT_DIR)/3rd/openssl/include
ASIO2_INCLUDE += $(ASIO2_ROOT_DIR)/include
# $(info "TARGET_ARCH_ABI = $(TARGET_ARCH_ABI)")
# $(info "ASIO2_ROOT_DIR = $(ASIO2_ROOT_DIR)")
ifeq ($(TARGET_ARCH_ABI), arm64-v8a)
else ifeq ($(TARGET_ARCH_ABI), armeabi-v7a)
else ifeq ($(TARGET_ARCH_ABI), x86)
else ifeq ($(TARGET_ARCH_ABI), x86_64)
else
$(error "Not supported TARGET_ARCH_ABI: $(TARGET_ARCH_ABI)")
endif
###############################################################################
## ssl librarys link
include $(CLEAR_VARS)
LOCAL_MODULE := libssl
LOCAL_SRC_FILES := $(ASIO2_ROOT_DIR)/3rd/openssl/prebuilt/android/$(TARGET_ARCH_ABI)/libssl.a
include $(PREBUILT_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := libcrypto
LOCAL_SRC_FILES := $(ASIO2_ROOT_DIR)/3rd/openssl/prebuilt/android/$(TARGET_ARCH_ABI)/libcrypto.a
include $(PREBUILT_STATIC_LIBRARY)
###############################################################################
## projects
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := asio2_rpc_qps_client.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/bench/rpc/asio2_rpc_qps_client/asio2_rpc_qps_client.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := asio2_rpc_qps_server.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/bench/rpc/asio2_rpc_qps_server/asio2_rpc_qps_server.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := asio_tcp_tps_client.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/bench/tcp/asio_tcp_tps_client/asio_tcp_tps_client.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := asio_tcp_tps_server.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/bench/tcp/asio_tcp_tps_server/asio_tcp_tps_server.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := asio2_tcp_tps_client.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/bench/tcp/asio2_tcp_tps_client/asio2_tcp_tps_client.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := asio2_tcp_tps_server.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/bench/tcp/asio2_tcp_tps_server/asio2_tcp_tps_server.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := aes.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/aes.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := base64.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/base64.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := codecvt.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/codecvt.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := des.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/des.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := event_dispatcher.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/event_dispatcher.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := http.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/http.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := https.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/https.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := ini.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/ini.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := md5.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/md5.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := mqtt.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/mqtt.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := rate_limit.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/rate_limit.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := rdc.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/rdc.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := reflection.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/reflection.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := rpc.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/rpc.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := sha1.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/sha1.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := shared_iopool.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/shared_iopool.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := start_stop.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/start_stop.cpp
LOCAL_STATIC_LIBRARIES += libssl
LOCAL_STATIC_LIBRARIES += libcrypto
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := strutil.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/strutil.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_custom.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/tcp_custom.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_dgram.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/tcp_dgram.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := tcp_general.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/tcp_general.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := thread_pool.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/thread_pool.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := timer.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/timer.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := timer_enable_error.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/timer_enable_error.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := udp.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/udp.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := uuid.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/uuid.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := websocket.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/websocket.cpp
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(ASIO2_INCLUDE)
LOCAL_MODULE := zlib.out
LOCAL_SRC_FILES := $(ASIO2_TEST_DIR)/unit/zlib.cpp
include $(BUILD_EXECUTABLE)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_METROWERKS_H
#define BHO_PREDEF_COMPILER_METROWERKS_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_MWERKS`
http://en.wikipedia.org/wiki/CodeWarrior[Metrowerks CodeWarrior] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__MWERKS__+` | {predef_detection}
| `+__CWCC__+` | {predef_detection}
| `+__CWCC__+` | V.R.P
| `+__MWERKS__+` | V.R.P >= 4.2.0
| `+__MWERKS__+` | 9.R.0
| `+__MWERKS__+` | 8.R.0
|===
*/ // end::reference[]
#define BHO_COMP_MWERKS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__MWERKS__) || defined(__CWCC__)
# if !defined(BHO_COMP_MWERKS_DETECTION) && defined(__CWCC__)
# define BHO_COMP_MWERKS_DETECTION BHO_PREDEF_MAKE_0X_VRPP(__CWCC__)
# endif
# if !defined(BHO_COMP_MWERKS_DETECTION) && (__MWERKS__ >= 0x4200)
# define BHO_COMP_MWERKS_DETECTION BHO_PREDEF_MAKE_0X_VRPP(__MWERKS__)
# endif
# if !defined(BHO_COMP_MWERKS_DETECTION) && (__MWERKS__ >= 0x3204) // note the "skip": 04->9.3
# define BHO_COMP_MWERKS_DETECTION BHO_VERSION_NUMBER(9,(__MWERKS__)%100-1,0)
# endif
# if !defined(BHO_COMP_MWERKS_DETECTION) && (__MWERKS__ >= 0x3200)
# define BHO_COMP_MWERKS_DETECTION BHO_VERSION_NUMBER(9,(__MWERKS__)%100,0)
# endif
# if !defined(BHO_COMP_MWERKS_DETECTION) && (__MWERKS__ >= 0x3000)
# define BHO_COMP_MWERKS_DETECTION BHO_VERSION_NUMBER(8,(__MWERKS__)%100,0)
# endif
# if !defined(BHO_COMP_MWERKS_DETECTION)
# define BHO_COMP_MWERKS_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_COMP_MWERKS_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_MWERKS_EMULATED BHO_COMP_MWERKS_DETECTION
# else
# undef BHO_COMP_MWERKS
# define BHO_COMP_MWERKS BHO_COMP_MWERKS_DETECTION
# endif
# define BHO_COMP_MWERKS_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_MWERKS_NAME "Metrowerks CodeWarrior"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_MWERKS,BHO_COMP_MWERKS_NAME)
#ifdef BHO_COMP_MWERKS_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_MWERKS_EMULATED,BHO_COMP_MWERKS_NAME)
#endif
<file_sep># asio2
### [中文](README.md) | English
Header only c++ network library, based on asio,support tcp,udp,http,websocket,rpc,ssl,icmp,serial_port.
* header only, do not rely on the Boost library;
* Support tcp, udp, http, websocket, rpc, ssl, icmp, serial_port;
* Support reliable udp (based on KCP), support SSL;
* TCP supports data unpacking (character or string or user defined protocol);
* Support windows,linux,macos,arm,android, 32 bits, 64 bits;Compiled under msvc gcc clang ndk mingw;
* Dependence on C++ 17,dependence on asio (standalone asio or boost::asio).
* The example directory contains a large number of sample code, and a variety of use methods refer to the sample code.
## TCP:
##### server:
```c++
asio2::tcp_server server;
server.bind_recv([&server](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view s)
{
session_ptr->no_delay(true);
printf("recv : %zu %.*s\n", s.size(), (int)s.size(), s.data());
session_ptr->async_send(s);
}).bind_connect([&server](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([&server](auto & session_ptr)
{
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
});
server.start("0.0.0.0", 8080);
// Automatic unpacking by \n (arbitrary characters can be specified)
//server.start("0.0.0.0", 8080, '\n');
// Automatic unpacking by \r\n (arbitrary string can be specified)
//server.start("0.0.0.0", 8080, "\r\n");
// Automatic unpacking according to the rules specified by match_role
// (see demo code for match_role) (for user-defined protocol unpacking)
//server.start("0.0.0.0", 8080, match_role('#'));
// Receive a fixed 100 bytes at a time
//server.start("0.0.0.0", 8080, asio::transfer_exactly(100));
// TCP in datagram mode, no matter how long the data is sent, the whole
// package data of the corresponding length must be received by both sides.
//server.start("0.0.0.0", 8080, asio2::use_dgram);
```
##### client:
```c++
asio2::tcp_client client;
// The client will automatically reconnect when it disconnects
// [ default reconnect option is "enable" ]
// disable auto reconnect
//client.auto_reconnect(false);
// enable auto reconnect and use the default delay
//client.auto_reconnect(true);
// enable auto reconnect and use custom delay
client.auto_reconnect(true, std::chrono::seconds(3));
client.bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n", client.local_address().c_str(), client.local_port());
client.async_send("<abcdefghijklmnopqrstovuxyz0123456789>");
}).bind_disconnect([]()
{
printf("disconnect : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_recv([&](std::string_view sv)
{
printf("recv : %zu %.*s\n", sv.size(), (int)sv.size(), sv.data());
client.async_send(sv);
})
//// Binding global functions
//.bind_recv(on_recv)
//// Binding member functions (see demo code for details)
//.bind_recv(std::bind(&listener::on_recv, &lis, std::placeholders::_1))
//// Bind member functions by reference to lis object (see demo code for details)
//.bind_recv(&listener::on_recv, lis)
//// Bind member functions by pointers to lis object (see demo code for details)
//.bind_recv(&listener::on_recv, &lis)
;
// Asynchronous connection to server
client.async_start("0.0.0.0", 8080);
// Synchronized connection to server
//client.start("0.0.0.0", 8080);
//client.async_start("0.0.0.0", 8080, '\n');
//client.async_start("0.0.0.0", 8080, "\r\n");
//client.async_start("0.0.0.0", 8080, match_role);
//client.async_start("0.0.0.0", 8080, asio::transfer_exactly(100));
//client.start("0.0.0.0", 8080, asio2::use_dgram);
```
## UDP:
##### server:
```c++
asio2::udp_server server;
// ... Binding listener (see demo code)
server.start("0.0.0.0", 8080); // general UDP
//server.start("0.0.0.0", 8080, asio2::use_kcp); // Reliable UDP
```
##### client:
```c++
asio2::udp_client client;
// ... Binding listener (see demo code)
client.start("0.0.0.0", 8080);
//client.async_start("0.0.0.0", 8080, asio2::use_kcp); // Reliable UDP
```
## RPC:
##### server:
```c++
// If you want to know which client called this function, set the first parameter
// to std::shared_ptr<asio2::rpc_session>& session_ptr, If you don't want to,keep
// it empty is ok.
int add(std::shared_ptr<asio2::rpc_session>& session_ptr, int a, int b)
{
return a + b;
}
// Specify the "max recv buffer size" to avoid malicious packets, if some client
// sent data packets size is too long to the "max recv buffer size", then the
// client will be disconnect automatic .
asio2::rpc_server server(
512, // the initialize recv buffer size :
1024, // the max recv buffer size :
4 // the thread count :
);
// ... Binding listener (see demo code)
A a; // For the definition of A, see the demo code
// Binding RPC global functions
server.bind("add", add);
// Binding RPC member functions
server.bind("mul", &A::mul, a);
// Binding lambda
server.bind("cat", [&](const std::string& a, const std::string& b) { return a + b; });
// Binding member functions (by reference)
server.bind("get_user", &A::get_user, a);
// Binding member functions (by pointer)
server.bind("del_user", &A::del_user, &a);
server.start("0.0.0.0", 8080);
```
##### client:
```c++
asio2::rpc_client client;
// ... Binding listener (see demo code)
client.start("0.0.0.0", 8080);
// Synchronized invoke RPC functions
int sum = client.call<int>(std::chrono::seconds(3), "add", 11, 2);
printf("sum : %d err : %d %s\n", sum, asio2::last_error_val(), asio2::last_error_msg().c_str());
// Asynchronous invocation of RPC function, the first parameter is the callback function,
// when the call is completed or timeout, the callback function automatically called.
client.async_call([](int v)
{
// if timeout or other errors, you can get the error info by asio2::get_last_error.
printf("sum : %d err : %d %s\n", v, asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "add", 10, 20);
// Result value is user-defined data type (see demo code for the definition of user type)
user u = client.call<user>("get_user");
printf("%s %d ", u.name.c_str(), u.age);
for (auto &[k, v] : u.purview)
{
printf("%d %s ", k, v.c_str());
}
printf("\n");
u.name = "hanmeimei";
u.age = ((int)time(nullptr)) % 100;
u.purview = { {10,"get"},{20,"set"} };
// If the result value of the RPC function is void, then the user callback
// function has only one parameter.
client.async_call([]()
{
}, "del_user", std::move(u));
// just call rpc function, don't need result
client.async_call("del_user", std::move(u));
```
## HTTP and WEBSOCKET:
##### server:
```c++
struct aop_log
{
bool before(http::request& req, http::response& rep)
{
asio2::detail::ignore_unused(rep);
printf("aop_log before %s\n", req.method_string().data());
return true;
}
bool after(std::shared_ptr<asio2::http_session>& session_ptr,
http::request& req, http::response& rep)
{
asio2::detail::ignore_unused(session_ptr, req, rep);
printf("aop_log after\n");
return true;
}
};
struct aop_check
{
bool before(std::shared_ptr<asio2::http_session>& session_ptr,
http::request& req, http::response& rep)
{
asio2::detail::ignore_unused(session_ptr, req, rep);
printf("aop_check before\n");
return true;
}
bool after(http::request& req, http::response& rep)
{
asio2::detail::ignore_unused(req, rep);
printf("aop_check after\n");
return true;
}
};
asio2::http_server server;
server.bind_recv([&](http::request& req, http::response& rep)
{
std::cout << req.path() << std::endl;
std::cout << req.query() << std::endl;
}).bind_connect([](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([](auto & session_ptr)
{
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
}).bind_start([&]()
{
printf("start http server : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
printf("stop : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.bind<http::verb::get, http::verb::post>("/index.*",
[](http::request& req, http::response& rep)
{
rep.fill_file("../../../index.html");
rep.chunked(true);
}, aop_log{});
server.bind<http::verb::get>("/del_user",
[](std::shared_ptr<asio2::http_session>& session_ptr,
http::request& req, http::response& rep)
{
printf("del_user ip : %s\n", session_ptr->remote_address().data());
rep.fill_page(http::status::ok, "del_user successed.");
}, aop_check{});
server.bind<http::verb::get>("/api/user/*", [](http::request& req, http::response& rep)
{
rep.fill_text("the user name is hanmeimei, .....");
}, aop_log{}, aop_check{});
server.bind<http::verb::get>("/defer", [](http::request& req, http::response& rep)
{
// use defer to make the reponse not send immediately, util the derfer shared_ptr
// is destroyed, then the response will be sent.
std::shared_ptr<http::response_defer> rep_defer = rep.defer();
std::thread([rep_defer, &rep]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
auto newrep = asio2::http_client::execute("http://www.baidu.com");
rep = std::move(newrep);
}).detach();
}, aop_log{}, aop_check{});
server.bind("/ws", websocket::listener<asio2::http_session>{}.
on("message", [](std::shared_ptr<asio2::http_session>& session_ptr, std::string_view data)
{
printf("ws msg : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}).on("open", [](std::shared_ptr<asio2::http_session>& session_ptr)
{
printf("ws open\n");
// print the websocket request header.
std::cout << session_ptr->request() << std::endl;
// how to set custom websocket response data :
session_ptr->ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::response_type& rep)
{
rep.set(http::field::authorization, " http-server-coro");
}));
}).on("close", [](std::shared_ptr<asio2::http_session>& session_ptr)
{
printf("ws close\n");
}));
server.bind_not_found([](http::request& req, http::response& rep)
{
rep.fill_page(http::status::not_found);
});
server.start(host, port);
```
##### client:
```c++
// 1. download and save the file directly.
// The file is in this directory: /asio2/example/bin/x64/QQ9.6.7.28807.exe
asio2::https_client::download(
"https://dldir1.qq.com/qqfile/qq/PCQQ9.6.7/QQ9.6.7.28807.exe",
"QQ9.6.7.28807.exe");
// 2. you can save the file content by youself.
std::fstream hugefile("CentOS-7-x86_64-DVD-2009.iso", std::ios::out | std::ios::binary | std::ios::trunc);
asio2::https_client::download(asio::ssl::context{ asio::ssl::context::tlsv13 },
"https://mirrors.tuna.tsinghua.edu.cn/centos/7.9.2009/isos/x86_64/CentOS-7-x86_64-DVD-2009.iso",
//[](auto& header) // http header callback. this param is optional. the body callback is required.
//{
// std::cout << header << std::endl;
//},
[&hugefile](std::string_view chunk) // http body callback.
{
hugefile.write(chunk.data(), chunk.size());
}
);
hugefile.close();
auto req1 = http::make_request("http://www.baidu.com/get_user?name=abc");
auto rep1 = asio2::http_client::execute("http://www.baidu.com/get_user?name=abc");
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep1 << std::endl;
auto req2 = http::make_request("GET / HTTP/1.1\r\nHost: 192.168.0.1\r\n\r\n");
auto rep2 = asio2::http_client::execute("www.baidu.com", "80", req2, std::chrono::seconds(3));
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep2 << std::endl;
auto path = asio2::http::url_to_path("/get_user?name=abc");
std::cout << path << std::endl;
auto query = asio2::http::url_to_query("/get_user?name=abc");
std::cout << query << std::endl;
std::cout << std::endl;
auto rep3 = asio2::http_client::execute("www.baidu.com", "80", "/api/get_user?name=abc");
if (asio2::get_last_error())
std::cout << asio2::last_error_msg() << std::endl;
else
std::cout << rep3 << std::endl;
std::string en = http::url_encode(R"(http://www.baidu.com/json={"qeury":"name like '%abc%'","id":1})");
std::cout << en << std::endl;
std::string de = http::url_decode(en);
std::cout << de << std::endl;
```
## ICMP:
```c++
asio2::ping ping;
ping.timeout(std::chrono::seconds(3))
.interval(std::chrono::seconds(1))
.body("abc")
.bind_recv([](asio2::icmp_rep& rep)
{
if (rep.is_timeout())
std::cout << "request timed out" << std::endl;
else
std::cout << rep.total_length() - rep.header_length()
<< " bytes from " << rep.source_address()
<< ": icmp_seq=" << rep.sequence_number()
<< ", ttl=" << rep.time_to_live()
<< ", time=" << rep.milliseconds() << "ms"
<< std::endl;
}).start("172.16.58.3");
```
```c++
std::cout << asio2::ping::execute("www.google.com").milliseconds() << std::endl;
```
## SSL:
##### TCP/HTTP/WEBSOCKET all support SSL(config.hpp uncomment #define ASIO2_USE_SSL)
```c++
asio2::tcps_server server;
// server set_verify_mode :
// "verify_peer", ca_cert_buffer can be empty.
// Whether the client has a certificate or not is ok.
// "verify_fail_if_no_peer_cert", ca_cert_buffer can be empty.
// Whether the client has a certificate or not is ok.
// "verify_peer | verify_fail_if_no_peer_cert", ca_cert_buffer cannot be empty.
// Client must use certificate, otherwise handshake will be failed.
// client set_verify_mode :
// "verify_peer", ca_cert_buffer cannot be empty.
// "verify_none", ca_cert_buffer can be empty.
server.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
//
server.set_cert_buffer(ca_crt, server_crt, server_key, "server"); // use memory string for cert
server.set_dh_buffer(dh);
//
server.set_cert_file("ca.crt", "server.crt", "server.key", "server"); // use file for cert
server.set_dh_file("dh1024.pem");
// >> openssl create your certificates and sign them
// ------------------------------------------------------------------------------------------------
// // 1. Generate Server private key
// openssl genrsa -des3 -out server.key 1024
// // 2. Generate Server Certificate Signing Request(CSR)
// openssl req -new -key server.key -out server.csr -config openssl.cnf
// // 3. Generate Client private key
// openssl genrsa -des3 -out client.key 1024
// // 4. Generate Client Certificate Signing Request(CSR)
// openssl req -new -key client.key -out client.csr -config openssl.cnf
// // 5. Generate CA private key
// openssl genrsa -des3 -out ca.key 2048
// // 6. Generate CA Certificate file
// openssl req -new -x509 -key ca.key -out ca.crt -days 3650 -config openssl.cnf
// // 7. Generate Server Certificate file
// openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key -config openssl.cnf
// // 8. Generate Client Certificate file
// openssl ca -in client.csr -out client.crt -cert ca.crt -keyfile ca.key -config openssl.cnf
// // 9. Generate dhparam file
// openssl dhparam -out dh1024.pem 1024
```
## serial port:
```c++
std::string_view device = "COM1"; // for windows
//std::string_view device = "/dev/ttyS0"; // for linux
std::string_view baud_rate = "9600";
asio2::serial_port sp;
sp.bind_init([&]()
{
// Set other serial port parameters at here
sp.socket().set_option(asio::serial_port::flow_control(asio::serial_port::flow_control::type::none));
sp.socket().set_option(asio::serial_port::parity(asio::serial_port::parity::type::none));
sp.socket().set_option(asio::serial_port::stop_bits(asio::serial_port::stop_bits::type::one));
sp.socket().set_option(asio::serial_port::character_size(8));
}).bind_recv([&](std::string_view sv)
{
printf("recv : %zu %.*s\n", sv.size(), (int)sv.size(), sv.data());
std::string s;
uint8_t len = uint8_t(10 + (std::rand() % 20));
s += '<';
for (uint8_t i = 0; i < len; i++)
{
s += (char)((std::rand() % 26) + 'a');
}
s += '>';
sp.async_send(std::move(s));
});
//sp.start(device, baud_rate);
sp.start(device, baud_rate, '>');
//sp.start(device, baud_rate, "\r\n");
//sp.start(device, baud_rate, match_role);
//sp.start(device, baud_rate, asio::transfer_at_least(1));
//sp.start(device, baud_rate, asio::transfer_exactly(10));
```
##### timer
```c++
asio2::timer timer;
timer.start_timer(1, std::chrono::seconds(1), [&]()
{
printf("timer 1\n");
if (true)
timer.stop_timer(1);
});
timer.start_timer("id2", 2000, 5, []()
{
printf("timer id2, loop 5 times\n");
});
timer.start_timer(5, std::chrono::milliseconds(1000), std::chrono::milliseconds(5000), []()
{
printf("timer 5, loop infinite, delay 5 seconds\n");
});
```
##### Manually triggered events
```c++
asio2::tcp_client client;
// Post an asynchronous condition event that is never executed unless it is manually triggered
std::shared_ptr<asio2::condition_event> event_ptr = client.post_condition_event([]()
{
// do something.
});
client.bind_recv([&](std::string_view data)
{
// For example, to achieve a certain condition
if (data == "some_condition")
{
// Trigger the event to start execution
event_ptr->notify();
}
});
```
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_BEAST_HPP__
#define __ASIO2_BEAST_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/config.hpp>
#include <asio2/base/detail/push_options.hpp>
#ifdef ASIO2_HEADER_ONLY
#ifndef BEAST_HEADER_ONLY
#define BEAST_HEADER_ONLY 1
#endif
#endif
#ifdef ASIO2_HEADER_ONLY
#include <asio2/bho/beast.hpp>
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
// boost 1.72(107200) BOOST_BEAST_VERSION 277
#if defined(BEAST_VERSION) && (BEAST_VERSION >= 277)
#include <asio2/bho/beast/ssl.hpp>
#endif
#include <asio2/bho/beast/websocket/ssl.hpp>
#endif
#else
#ifndef BOOST_BEAST_USE_STD_STRING_VIEW
#define BOOST_BEAST_USE_STD_STRING_VIEW
#endif
#include <boost/beast.hpp>
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
// boost 1.72(107200) BOOST_BEAST_VERSION 277
#if defined(BOOST_BEAST_VERSION) && (BOOST_BEAST_VERSION >= 277)
#include <boost/beast/ssl.hpp>
#endif
#include <boost/beast/websocket/ssl.hpp>
#endif
#ifndef BEAST_VERSION
#define BEAST_VERSION BOOST_BEAST_VERSION
#endif
#ifndef BEAST_VERSION_STRING
#define BEAST_VERSION_STRING BOOST_BEAST_VERSION_STRING
#endif
#ifndef BHO_BEAST_VERSION
#define BHO_BEAST_VERSION BOOST_BEAST_VERSION
#endif
#ifndef BHO_BEAST_VERSION_STRING
#define BHO_BEAST_VERSION_STRING BOOST_BEAST_VERSION_STRING
#endif
#endif
#ifdef ASIO2_HEADER_ONLY
namespace bho::beast::http
{
template<class Body, class Fields = fields>
using request_t = request<Body, Fields>;
template<class Body, class Fields = fields>
using response_t = response<Body, Fields>;
}
namespace beast = ::bho::beast;
#else
namespace boost::beast::http
{
template<class Body, class Fields = fields>
using request_t = request<Body, Fields>;
template<class Body, class Fields = fields>
using response_t = response<Body, Fields>;
}
namespace beast = ::boost::beast;
namespace asio = ::boost::asio;
namespace bho = ::boost; // bho means boost header only
#endif
namespace http = ::beast::http;
namespace websocket = ::beast::websocket;
namespace asio2
{
namespace http = ::beast::http;
namespace websocket = ::beast::websocket;
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_BEAST_HPP__
<file_sep>#include <iostream>
#include <asio2/asio2.hpp>
struct aop_log
{
bool before(http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(rep);
printf("aop_log before %s\n", req.method_string().data());
return true;
}
bool after(std::shared_ptr<asio2::http_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
ASIO2_ASSERT(asio2::get_current_caller<std::shared_ptr<asio2::http_session>>().get() == session_ptr.get());
asio2::ignore_unused(session_ptr, req, rep);
printf("aop_log after\n");
return true;
}
};
struct aop_check
{
bool before(std::shared_ptr<asio2::http_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
ASIO2_ASSERT(asio2::get_current_caller<std::shared_ptr<asio2::http_session>>().get() == session_ptr.get());
asio2::ignore_unused(session_ptr, req, rep);
printf("aop_check before\n");
return true;
}
bool after(http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
printf("aop_check after\n");
return true;
}
};
int main()
{
// try open http://localhost:8080 in your browser
std::string_view host = "0.0.0.0";
std::string_view port = "8080";
asio2::http_server server;
server.support_websocket(true);
// set the root directory, here is: /asio2/example/wwwroot
std::filesystem::path root = std::filesystem::current_path().parent_path().parent_path().append("wwwroot");
server.set_root_directory(std::move(root));
server.bind_recv([&](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
// all http and websocket request will goto here first.
std::cout << req.path() << req.query() << std::endl;
}).bind_connect([](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
//session_ptr->set_response_mode(asio2::response_mode::manual);
}).bind_disconnect([](auto & session_ptr)
{
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
}).bind_start([&]()
{
printf("start http server : %s %u %d %s\n",
server.listen_address().c_str(), server.listen_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_stop([&]()
{
printf("stop http server : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
server.bind<http::verb::get, http::verb::post>("/", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
rep.fill_file("index.html");
}, aop_log{}, http::enable_cache);
// If no method is specified, GET and POST are both enabled by default.
server.bind("*", [](http::web_request& req, http::web_response& rep)
{
rep.fill_file(req.target());
}, aop_check{}, http::enable_cache);
// Test http multipart
server.bind<http::verb::get, http::verb::post>("/multipart_test", [](http::web_request& req, http::web_response& rep)
{
auto& body = req.body();
auto target = req.target();
std::stringstream ss;
ss << req;
auto str_req = ss.str();
asio2::ignore_unused(body, target, str_req);
for (auto it = req.begin(); it != req.end(); ++it)
{
std::cout << it->name_string() << ": " << it->value() << std::endl;
}
auto mpbody = req.multipart();
for (auto it = mpbody.begin(); it != mpbody.end(); ++it)
{
std::cout
<< "filename:" << it->filename() << " name:" << it->name()
<< " content_type:" << it->content_type() << std::endl;
}
if (req.has_multipart())
{
http::multipart_fields multipart_body = req.multipart();
auto& field_username = multipart_body["username"];
auto username = field_username.value();
auto& field_password = multipart_body["password"];
auto password = field_password.value();
std::string str = http::to_string(multipart_body);
std::string type = "multipart/form-data; boundary="; type += multipart_body.boundary();
rep.fill_text(str, http::status::ok, type);
http::web_request req_copy;
req_copy.method(http::verb::post);
req_copy.set(http::field::content_type, type);
req_copy.keep_alive(true);
req_copy.target("/api/user/");
req_copy.body() = str;
req_copy.prepare_payload();
std::stringstream ress;
ress << req_copy;
auto restr = ress.str();
asio2::ignore_unused(username, password, restr);
}
else
{
rep.fill_page(http::status::ok);
}
}, aop_log{});
server.bind<http::verb::get>("/del_user",
[](std::shared_ptr<asio2::http_session>& session_ptr, http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
printf("del_user ip : %s\n", session_ptr->remote_address().data());
rep.fill_page(http::status::ok, "del_user successed.");
}, aop_check{});
server.bind<http::verb::get, http::verb::post>("/api/user/*", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
// if the url is :
// /api/user/add_user?name=hanmeimei&age=20&height=168
[[maybe_unused]] std::string_view t = req.target(); // t == /api/user/add_user?name=hanmeimei&age=20&height=168
[[maybe_unused]] std::string_view p = req.get_path(); // p == /api/user/add_user
[[maybe_unused]] std::string_view q = req.get_query(); // q == name=hanmeimei&age=20&height=168
std::vector<std::string_view> kvs = asio2::split(q, '&');
for (std::string_view kv : kvs)
{
[[maybe_unused]] std::string_view k = kv.substr(0, kv.find('='));
[[maybe_unused]] std::string_view v = kv.substr(kv.find('=') + 1);
}
//rep.fill_text("the user name is hanmeimei, .....");
}, aop_log{}, aop_check{});
server.bind<http::verb::get>("/defer", [](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req, rep);
// use defer to make the reponse not send immediately, util the derfer shared_ptr
// is destroyed, then the response will be sent.
std::shared_ptr<http::response_defer> rep_defer = rep.defer();
std::thread([rep_defer, &rep]() mutable
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
rep = asio2::http_client::execute("http://www.baidu.com");
}).detach();
}, aop_log{}, aop_check{});
// the /ws is the websocket upgraged target
server.bind("/ws", websocket::listener<asio2::http_session>{}.
on("message", [](std::shared_ptr<asio2::http_session>& session_ptr, std::string_view data)
{
printf("ws msg : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}).on("open", [](std::shared_ptr<asio2::http_session>& session_ptr)
{
printf("ws open\n");
// print the websocket request header.
std::cout << session_ptr->request() << std::endl;
// Set the binary message write option.
session_ptr->ws_stream().binary(true);
// Set the text message write option.
//session_ptr->ws_stream().text(true);
// how to set custom websocket response data :
session_ptr->ws_stream().set_option(websocket::stream_base::decorator(
[](websocket::response_type& rep)
{
rep.set(http::field::authorization, " http-server-coro");
}));
}).on("close", [](std::shared_ptr<asio2::http_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
printf("ws close\n");
}).on_ping([](std::shared_ptr<asio2::http_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
printf("ws ping\n");
}).on_pong([](std::shared_ptr<asio2::http_session>& session_ptr)
{
asio2::ignore_unused(session_ptr);
printf("ws pong\n");
}));
server.bind_not_found([](http::web_request& req, http::web_response& rep)
{
asio2::ignore_unused(req);
rep.fill_page(http::status::not_found);
});
server.start(host, port);
while (std::getchar() != '\n'); // press enter to exit this program
return 0;
}
//-------------------------------------------------------------------
// http request protocol sample
//-------------------------------------------------------------------
//GET / HTTP/1.1
//Host: 127.0.0.1:8443
//Connection: keep-alive
//Cache-Control: max-age=0
//User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
//Upgrade-Insecure-Requests: 1
//Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
//Accept-Encoding: gzip, deflate, br
//Accept-Language: zh-CN,zh;q=0.8
//-------------------------------------------------------------------
// http response protocol sample
//-------------------------------------------------------------------
//HTTP/1.1 302 Found
//Server: openresty
//Date: Fri, 10 Nov 2017 03:11:50 GMT
//Content-Type: text/html; charset=utf-8
//Transfer-Encoding: chunked
//Connection: keep-alive
//Keep-Alive: timeout=20
//Location: http://bbs.csdn.net/home
//Cache-Control: no-cache
//
//5a
//<html><body>You are being <a href="http://bbs.csdn.net/home">redirected</a>.</body></html>
//0
<file_sep>#
# Copyright (c) 2017-2023 zhllxt
#
# author : zhllxt
# email : <EMAIL>
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
#
# export CC=/usr/local/bin/gcc
# export CXX=/usr/local/bin/g++
#
# cmake -G "Visual Studio 15 Win64" .
#
cmake_minimum_required (VERSION 2.8...3.20)
# remove last end of "/"
string(REGEX REPLACE "/$" "" CMAKELISTS_DIR_PATH ${CMAKE_CURRENT_SOURCE_DIR})
# get current relative dir name and set target name
string(REGEX REPLACE ".*/(.*)" "\\1" CMAKELISTS_DIR_NAME ${CMAKELISTS_DIR_PATH})
# get above dir name and set target group name
get_filename_component(ASIO2_ROOT_DIR ${CMAKELISTS_DIR_PATH} DIRECTORY)
message("ASIO2_ROOT_DIR = ${ASIO2_ROOT_DIR}")
#-------------------------------------------------------------------------------
function (DoGroupSources curdir rootdir foldername folder)
file (GLOB children RELATIVE ${ASIO2_ROOT_DIR}/${curdir} ${ASIO2_ROOT_DIR}/${curdir}/*)
foreach (child ${children})
if (IS_DIRECTORY ${ASIO2_ROOT_DIR}/${curdir}/${child})
DoGroupSources (${curdir}/${child} ${rootdir} ${foldername} ${folder})
elseif (${child} STREQUAL "CMakeLists.txt")
source_group("" FILES ${ASIO2_ROOT_DIR}/${curdir}/${child})
else()
string (REGEX REPLACE ^${rootdir} ${folder} groupname ${curdir})
string (REPLACE "/" "\\" groupname ${groupname})
source_group (${foldername}${groupname} FILES ${ASIO2_ROOT_DIR}/${curdir}/${child})
endif()
endforeach()
endfunction()
function (GroupSources curdir folder)
string (FIND ${curdir} "/" Separator)
if(${Separator} EQUAL -1)
set(Separator 0)
else ()
math(EXPR Separator "${Separator} + 1")
endif()
string (SUBSTRING ${curdir} ${Separator} -1 foldername)
DoGroupSources (${curdir} ${curdir} ${foldername} ${folder})
endfunction()
#-------------------------------------------------------------------------------
#
# project
#
#-------------------------------------------------------------------------------
project (asio2_test)
set_property (GLOBAL PROPERTY USE_FOLDERS ON)
# how to detect current is 32 bit or 64 bit ?
#if(NOT "${CMAKE_GENERATOR}" MATCHES "(Win64|IA64)")
#endif()
#
#if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4")
#endif()
#
#if(NOT CMAKE_CL_64)
#endif()
#
#if(NOT ("${CMAKE_GENERATOR_PLATFORM}" STREQUAL "Win64"))
#endif()
#
#if ("${CMAKE_VS_PLATFORM_NAME}" STREQUAL "Win32")
#endif ()
#if(CMAKE_CL_64)
# set(ASIO2_LIBS_DIR ${ASIO2_ROOT_DIR}/lib/x64)
#else(CMAKE_CL_64)
# set(ASIO2_LIBS_DIR ${ASIO2_ROOT_DIR}/lib/x86)
#endif(CMAKE_CL_64)
# ---------------------------------------------------------------------------------------
# Set default build to debug
# ---------------------------------------------------------------------------------------
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE)
message("CMAKE_BUILD_TYPE is not set, Set default build to Release.")
endif()
message("CMAKE_BUILD_TYPE = ${CMAKE_BUILD_TYPE}")
IF (CMAKE_SYSTEM_NAME MATCHES "Windows")
ELSE ()
if(${CMAKE_BUILD_TYPE} STREQUAL "Debug")
add_definitions(-D_DEBUG)
endif()
ENDIF (CMAKE_SYSTEM_NAME MATCHES "Windows")
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(ASIO2_EXES_DIR ${ASIO2_ROOT_DIR}/test/bin/x64)
elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
set(ASIO2_EXES_DIR ${ASIO2_ROOT_DIR}/test/bin/x86)
endif()
IF (CMAKE_SYSTEM_NAME MATCHES "Linux")
set(OPENSSL_LIBS libssl.a libcrypto.a)
set(GENERAL_LIBS -lpthread -lrt -ldl stdc++fs)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(ASIO2_LIBS_DIR ${ASIO2_ROOT_DIR}/3rd/openssl/prebuilt/linux/x64)
elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
set(ASIO2_LIBS_DIR ${ASIO2_ROOT_DIR}/3rd/openssl/prebuilt/linux/x86)
endif()
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "Windows")
set(OPENSSL_LIBS "libssl.lib;libcrypto.lib;Crypt32.lib;")
set(GENERAL_LIBS "ws2_32;mswsock;")
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(ASIO2_LIBS_DIR ${ASIO2_ROOT_DIR}/3rd/openssl/prebuilt/windows/x64)
elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
set(ASIO2_LIBS_DIR ${ASIO2_ROOT_DIR}/3rd/openssl/prebuilt/windows/x86)
endif()
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
set(OPENSSL_LIBS libssl.a libcrypto.a)
set(GENERAL_LIBS -lpthread -lrt -ldl stdc++fs)
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "Darwin")
set(OPENSSL_LIBS libssl.a libcrypto.a)
set(GENERAL_LIBS -lpthread -ldl)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(ASIO2_LIBS_DIR ${ASIO2_ROOT_DIR}/3rd/openssl/prebuilt/mac)
elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
set(ASIO2_LIBS_DIR ${ASIO2_ROOT_DIR}/3rd/openssl/prebuilt/mac)
endif()
ELSE ()
set(OPENSSL_LIBS libssl.a libcrypto.a)
set(GENERAL_LIBS -lpthread -lrt -ldl stdc++fs)
ENDIF (CMAKE_SYSTEM_NAME MATCHES "Linux")
message("ASIO2_LIBS_DIR = ${ASIO2_LIBS_DIR}")
message("ASIO2_EXES_DIR = ${ASIO2_EXES_DIR}")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${ASIO2_EXES_DIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${ASIO2_EXES_DIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${ASIO2_EXES_DIR})
set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "" FORCE)
# ---------------------------------------------------------------------------------------
# Compiler config
# ---------------------------------------------------------------------------------------
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
endif()
set(CMAKE_CXX_EXTENSIONS OFF)
if(CMAKE_SYSTEM_NAME MATCHES "CYGWIN" OR CMAKE_SYSTEM_NAME MATCHES "MSYS")
set(CMAKE_CXX_EXTENSIONS ON)
endif()
if (MSVC)
set (CMAKE_VERBOSE_MAKEFILE FALSE)
#add_definitions (
# -D_WIN32_WINNT=0x0601
# -D_SCL_SECURE_NO_WARNINGS=1
# -D_CRT_SECURE_NO_WARNINGS=1
# -D_SILENCE_CXX17_ALLOCATOR_VOID_DEPRECATION_WARNING
# -D_SILENCE_CXX17_ADAPTOR_TYPEDEFS_DEPRECATION_WARNING
#)
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
add_compile_options(
/bigobj # large object file format
#/permissive- # strict C++
#/wd4503 # decorated name length exceeded, name was truncated
/W4 # enable all warnings
/JMC
)
set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /std:c++17 /MTd")
set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /std:c++17 /Zi /Ob2 /Oi /Ot /MT")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wrange-loop-analysis -Wthread-safety")
else()
add_compile_options(
/bigobj # large object file format
#/permissive- # strict C++
#/wd4503 # decorated name length exceeded, name was truncated
/W4 # enable all warnings
/MP # Multi-processor compilation
/JMC
/Zc:__cplusplus
)
set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /std:c++17 /MTd /Zi")
set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /std:c++17 /Zi /Ob2 /Oi /Ot /GL /MT")
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO")
set (CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /LTCG:incremental")
endif ()
else()
set (THREADS_PREFER_PTHREAD_FLAG ON)
find_package (Threads)
set( CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=c++17 -Wall -Wextra -Wpedantic -Wno-unused-parameter")
#set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -ggdb")
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wrange-loop-analysis -Wthread-safety")
endif ()
endif()
# https://stackoverflow.com/questions/44705845/file-too-big-compiling-on-cygwin-g
if(MINGW OR CYGWIN)
add_definitions(-O3)
add_compile_options(-Wa,-mbig-obj)
endif()
#include_directories (/usr/local/include) # for boost header file include
#include_directories (D:/boost) # for boost header file include
include_directories (${ASIO2_ROOT_DIR}/3rd)
include_directories (${ASIO2_ROOT_DIR}/3rd/openssl/include)
include_directories (${ASIO2_ROOT_DIR}/include)
#link_directories (/usr/local/lib) # for boost library file include
#link_directories (D:/boost/stage/lib) # for boost library file include
file (GLOB_RECURSE ASIO2_FILES ${ASIO2_ROOT_DIR}/include/asio2/*.*)
file (GLOB_RECURSE ASIO_FILES ${ASIO2_ROOT_DIR}/3rd/asio/*.*)
file (GLOB_RECURSE CEREAL_FILES ${ASIO2_ROOT_DIR}/3rd/cereal/*.*)
# exclude : asio/impl/src.cpp
list(REMOVE_ITEM ASIO_FILES ${ASIO2_ROOT_DIR}/3rd/asio/impl/src.cpp)
add_subdirectory (${ASIO2_ROOT_DIR}/test/bench asio2_test_project/bench )
add_subdirectory (${ASIO2_ROOT_DIR}/test/unit asio2_test_project/unit )<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at g<EMAIL> dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_SRC_HPP
#define BHO_BEAST_SRC_HPP
/*
This file is meant to be included once, in a translation unit of
the program, with the macro BHO_BEAST_SEPARATE_COMPILATION defined.
*/
#define BHO_BEAST_SOURCE
#include <asio2/bho/beast/core/detail/config.hpp>
#if defined(BEAST_HEADER_ONLY)
# error Do not compile Beast library source with BEAST_HEADER_ONLY defined
#endif
#include <asio2/bho/beast/core/detail/base64.ipp>
#include <asio2/bho/beast/core/detail/sha1.ipp>
#include <asio2/bho/beast/core/detail/impl/temporary_buffer.ipp>
#include <asio2/bho/beast/core/impl/error.ipp>
#include <asio2/bho/beast/core/impl/file_stdio.ipp>
#include <asio2/bho/beast/core/impl/flat_static_buffer.ipp>
#include <asio2/bho/beast/core/impl/saved_handler.ipp>
#include <asio2/bho/beast/core/impl/static_buffer.ipp>
#include <asio2/bho/beast/core/impl/string.ipp>
#include <asio2/bho/beast/http/detail/basic_parser.ipp>
#include <asio2/bho/beast/http/detail/rfc7230.ipp>
#include <asio2/bho/beast/http/impl/basic_parser.ipp>
#include <asio2/bho/beast/http/impl/error.ipp>
#include <asio2/bho/beast/http/impl/field.ipp>
#include <asio2/bho/beast/http/impl/fields.ipp>
#include <asio2/bho/beast/http/impl/rfc7230.ipp>
#include <asio2/bho/beast/http/impl/status.ipp>
#include <asio2/bho/beast/http/impl/verb.ipp>
#include <asio2/bho/beast/websocket/detail/hybi13.ipp>
#include <asio2/bho/beast/websocket/detail/mask.ipp>
#include <asio2/bho/beast/websocket/detail/pmd_extension.ipp>
#include <asio2/bho/beast/websocket/detail/prng.ipp>
#include <asio2/bho/beast/websocket/detail/service.ipp>
#include <asio2/bho/beast/websocket/detail/utf8_checker.ipp>
#include <asio2/bho/beast/websocket/impl/error.ipp>
#include <asio2/bho/beast/zlib/detail/deflate_stream.ipp>
#include <asio2/bho/beast/zlib/detail/inflate_stream.ipp>
#include <asio2/bho/beast/zlib/impl/error.ipp>
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_PGI_H
#define BHO_PREDEF_COMPILER_PGI_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_PGI`
http://en.wikipedia.org/wiki/The_Portland_Group[Portland Group C/{CPP}] compiler.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__PGI+` | {predef_detection}
| `+__PGIC__+`, `+__PGIC_MINOR__+`, `+__PGIC_PATCHLEVEL__+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_PGI BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__PGI)
# if !defined(BHO_COMP_PGI_DETECTION) && (defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__))
# define BHO_COMP_PGI_DETECTION BHO_VERSION_NUMBER(__PGIC__,__PGIC_MINOR__,__PGIC_PATCHLEVEL__)
# endif
# if !defined(BHO_COMP_PGI_DETECTION)
# define BHO_COMP_PGI_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_COMP_PGI_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_PGI_EMULATED BHO_COMP_PGI_DETECTION
# else
# undef BHO_COMP_PGI
# define BHO_COMP_PGI BHO_COMP_PGI_DETECTION
# endif
# define BHO_COMP_PGI_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_PGI_NAME "Portland Group C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_PGI,BHO_COMP_PGI_NAME)
#ifdef BHO_COMP_PGI_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_PGI_EMULATED,BHO_COMP_PGI_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
// No header guard
// the tests trigger deprecation warnings when compiled with msvc in C++17 mode
// warning STL4009: std::allocator<void> is deprecated in C++17
#if defined(_MSVC_LANG) && _MSVC_LANG > 201402
# ifndef _SILENCE_CXX17_ALLOCATOR_VOID_DEPRECATION_WARNING
# define _SILENCE_CXX17_ALLOCATOR_VOID_DEPRECATION_WARNING
# endif
# ifndef _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING
# define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING
# endif
# ifndef _SILENCE_CXX17_ADAPTOR_TYPEDEFS_DEPRECATION_WARNING
# define _SILENCE_CXX17_ADAPTOR_TYPEDEFS_DEPRECATION_WARNING
# endif
# ifndef _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS
# define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS
# endif
#endif
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable:4100) // warning C4100: Unreferenced formal parameters
# pragma warning(disable:4189) // warning C4189: Local variables are initialized but not referenced
# pragma warning(disable:4191) // asio inner : from FARPROC to cancel_io_ex_t is unsafe
# pragma warning(disable:4267) // warning C4267: Convert from size_t to uint32_t may be loss data
# pragma warning(disable:4311)
# pragma warning(disable:4312)
# pragma warning(disable:4505) // Unreferenced local function removed
# pragma warning(disable:4702) // unreachable code
# pragma warning(disable:4996) // warning STL4009: std::allocator<void> is deprecated in C++17
# pragma warning(disable:5054) // Operator '|': deprecated between enumerations of different types
#endif
#if defined(__GNUC__) || defined(__GNUG__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Woverflow"
# pragma GCC diagnostic ignored "-Wunused-variable"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wunused-local-typedefs"
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
# pragma GCC diagnostic ignored "-Wpedantic"
# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
# if((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 70101)
# pragma GCC diagnostic ignored "-Wimplicit-fallthrough="
# pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
# endif
#endif
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Woverflow"
# pragma clang diagnostic ignored "-Wunused-variable"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wunused-function"
# pragma clang diagnostic ignored "-Wexceptions"
# pragma clang diagnostic ignored "-Wdeprecated-declarations"
# pragma clang diagnostic ignored "-Wunused-private-field"
# pragma clang diagnostic ignored "-Wunused-local-typedef"
# pragma clang diagnostic ignored "-Wunknown-warning-option"
# pragma clang diagnostic ignored "-Wpedantic"
# pragma clang diagnostic ignored "-Wmissing-field-initializers"
# pragma clang diagnostic ignored "-Wimplicit-fallthrough="
# pragma clang diagnostic ignored "-Wunused-but-set-parameter"
#endif
/*
* see : https://github.com/retf/Boost.Application/pull/40
*/
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || \
defined(_WINDOWS_) || defined(__WINDOWS__) || defined(__TOS_WIN__)
# ifndef _WIN32_WINNT
# if __has_include(<winsdkver.h>)
# include <winsdkver.h>
# define _WIN32_WINNT _WIN32_WINNT_WIN7
# endif
# if __has_include(<SDKDDKVer.h>)
# include <SDKDDKVer.h>
# endif
# endif
# if __has_include(<crtdbg.h>)
# include <crtdbg.h>
# endif
#endif
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_HTTP_IMPL_SERIALIZER_HPP
#define BHO_BEAST_HTTP_IMPL_SERIALIZER_HPP
#include <asio2/bho/beast/core/buffer_traits.hpp>
#include <asio2/bho/beast/core/detail/buffers_ref.hpp>
#include <asio2/bho/beast/http/error.hpp>
#include <asio2/bho/beast/http/status.hpp>
#include <asio2/bho/beast/core/detail/config.hpp>
#include <asio2/bho/assert.hpp>
#include <ostream>
namespace bho {
namespace beast {
namespace http {
template<
bool isRequest, class Body, class Fields>
void
serializer<isRequest, Body, Fields>::
fwrinit(std::true_type)
{
fwr_.emplace(m_, m_.version(), m_.method());
}
template<
bool isRequest, class Body, class Fields>
void
serializer<isRequest, Body, Fields>::
fwrinit(std::false_type)
{
fwr_.emplace(m_, m_.version(), m_.result_int());
}
template<
bool isRequest, class Body, class Fields>
template<std::size_t I, class Visit>
inline
void
serializer<isRequest, Body, Fields>::
do_visit(error_code& ec, Visit& visit)
{
pv_.template emplace<I-1>(limit_, &std::get<I-1>(v_));
visit(ec, beast::detail::make_buffers_ref(
std::get<I-1>(pv_)));
}
//------------------------------------------------------------------------------
template<
bool isRequest, class Body, class Fields>
serializer<isRequest, Body, Fields>::
serializer(value_type& m)
: m_(m)
, wr_(this->m_.base(), this->m_.body())
{
}
template<
bool isRequest, class Body, class Fields>
template<class Visit>
void
serializer<isRequest, Body, Fields>::
next(error_code& ec, Visit&& visit)
{
switch(s_)
{
case do_construct:
{
fwrinit(std::integral_constant<bool,
isRequest>{});
if(m_.chunked())
goto go_init_c;
s_ = do_init;
BHO_FALLTHROUGH;
}
case do_init:
{
wr_.init(ec);
if(ec)
return;
if(split_)
goto go_header_only;
auto result = wr_.get(ec);
if(ec == error::need_more)
goto go_header_only;
if(ec)
return;
if(! result)
goto go_header_only;
more_ = result->second;
v_.template emplace<2 - 1>(
std::in_place,
fwr_->get(),
result->first);
s_ = do_header;
BHO_FALLTHROUGH;
}
case do_header:
do_visit<2>(ec, visit);
break;
go_header_only:
v_.template emplace<1 - 1>(fwr_->get());
s_ = do_header_only;
BHO_FALLTHROUGH;
case do_header_only:
do_visit<1>(ec, visit);
break;
case do_body:
s_ = do_body + 1;
BHO_FALLTHROUGH;
case do_body + 1:
{
auto result = wr_.get(ec);
if(ec)
return;
if(! result)
goto go_complete;
more_ = result->second;
v_.template emplace<3 - 1>(result->first);
s_ = do_body + 2;
BHO_FALLTHROUGH;
}
case do_body + 2:
do_visit<3>(ec, visit);
break;
//----------------------------------------------------------------------
go_init_c:
s_ = do_init_c;
BHO_FALLTHROUGH;
case do_init_c:
{
wr_.init(ec);
if(ec)
return;
if(split_)
goto go_header_only_c;
auto result = wr_.get(ec);
if(ec == error::need_more)
goto go_header_only_c;
if(ec)
return;
if(! result)
goto go_header_only_c;
more_ = result->second;
if(! more_)
{
// do it all in one buffer
v_.template emplace<7 - 1>(
std::in_place,
fwr_->get(),
buffer_bytes(result->first),
net::const_buffer{nullptr, 0},
chunk_crlf{},
result->first,
chunk_crlf{},
detail::chunk_last(),
net::const_buffer{nullptr, 0},
chunk_crlf{});
goto go_all_c;
}
v_.template emplace<4 - 1>(
std::in_place,
fwr_->get(),
buffer_bytes(result->first),
net::const_buffer{nullptr, 0},
chunk_crlf{},
result->first,
chunk_crlf{});
s_ = do_header_c;
BHO_FALLTHROUGH;
}
case do_header_c:
do_visit<4>(ec, visit);
break;
go_header_only_c:
v_.template emplace<1 - 1>(fwr_->get());
s_ = do_header_only_c;
BHO_FALLTHROUGH;
case do_header_only_c:
do_visit<1>(ec, visit);
break;
case do_body_c:
s_ = do_body_c + 1;
BHO_FALLTHROUGH;
case do_body_c + 1:
{
auto result = wr_.get(ec);
if(ec)
return;
if(! result)
goto go_final_c;
more_ = result->second;
if(! more_)
{
// do it all in one buffer
v_.template emplace<6 - 1>(
std::in_place,
buffer_bytes(result->first),
net::const_buffer{nullptr, 0},
chunk_crlf{},
result->first,
chunk_crlf{},
detail::chunk_last(),
net::const_buffer{nullptr, 0},
chunk_crlf{});
goto go_body_final_c;
}
v_.template emplace<5 - 1>(
std::in_place,
buffer_bytes(result->first),
net::const_buffer{nullptr, 0},
chunk_crlf{},
result->first,
chunk_crlf{});
s_ = do_body_c + 2;
BHO_FALLTHROUGH;
}
case do_body_c + 2:
do_visit<5>(ec, visit);
break;
go_body_final_c:
s_ = do_body_final_c;
BHO_FALLTHROUGH;
case do_body_final_c:
do_visit<6>(ec, visit);
break;
go_all_c:
s_ = do_all_c;
BHO_FALLTHROUGH;
case do_all_c:
do_visit<7>(ec, visit);
break;
go_final_c:
case do_final_c:
v_.template emplace<8 - 1>(
std::in_place,
detail::chunk_last(),
net::const_buffer{nullptr, 0},
chunk_crlf{});
s_ = do_final_c + 1;
BHO_FALLTHROUGH;
case do_final_c + 1:
do_visit<8>(ec, visit);
break;
//----------------------------------------------------------------------
default:
case do_complete:
BHO_ASSERT(false);
break;
go_complete:
s_ = do_complete;
break;
}
}
template<
bool isRequest, class Body, class Fields>
void
serializer<isRequest, Body, Fields>::
consume(std::size_t n)
{
switch(s_)
{
case do_header:
BHO_ASSERT(
n <= buffer_bytes(std::get<2-1>(v_)));
std::get<2-1>(v_).consume(n);
if(buffer_bytes(std::get<2-1>(v_)) > 0)
break;
header_done_ = true;
v_.template emplace<1 - 1>();
if(! more_)
goto go_complete;
s_ = do_body + 1;
break;
case do_header_only:
BHO_ASSERT(
n <= buffer_bytes(std::get<1-1>(v_)));
std::get<1-1>(v_).consume(n);
if(buffer_bytes(std::get<1-1>(v_)) > 0)
break;
fwr_ = std::nullopt;
header_done_ = true;
if(! split_)
goto go_complete;
s_ = do_body;
break;
case do_body + 2:
{
BHO_ASSERT(
n <= buffer_bytes(std::get<3-1>(v_)));
std::get<3-1>(v_).consume(n);
if(buffer_bytes(std::get<3-1>(v_)) > 0)
break;
v_.template emplace<1 - 1>();
if(! more_)
goto go_complete;
s_ = do_body + 1;
break;
}
//----------------------------------------------------------------------
case do_header_c:
BHO_ASSERT(
n <= buffer_bytes(std::get<4-1>(v_)));
std::get<4-1>(v_).consume(n);
if(buffer_bytes(std::get<4-1>(v_)) > 0)
break;
header_done_ = true;
v_.template emplace<1 - 1>();
if(more_)
s_ = do_body_c + 1;
else
s_ = do_final_c;
break;
case do_header_only_c:
{
BHO_ASSERT(
n <= buffer_bytes(std::get<1-1>(v_)));
std::get<1-1>(v_).consume(n);
if(buffer_bytes(std::get<1-1>(v_)) > 0)
break;
fwr_ = std::nullopt;
header_done_ = true;
if(! split_)
{
s_ = do_final_c;
break;
}
s_ = do_body_c;
break;
}
case do_body_c + 2:
BHO_ASSERT(
n <= buffer_bytes(std::get<5-1>(v_)));
std::get<5-1>(v_).consume(n);
if(buffer_bytes(std::get<5-1>(v_)) > 0)
break;
v_.template emplace<1 - 1>();
if(more_)
s_ = do_body_c + 1;
else
s_ = do_final_c;
break;
case do_body_final_c:
{
BHO_ASSERT(
n <= buffer_bytes(std::get<6-1>(v_)));
std::get<6-1>(v_).consume(n);
if(buffer_bytes(std::get<6-1>(v_)) > 0)
break;
v_.template emplace<1 - 1>();
s_ = do_complete;
break;
}
case do_all_c:
{
BHO_ASSERT(
n <= buffer_bytes(std::get<7-1>(v_)));
std::get<7-1>(v_).consume(n);
if(buffer_bytes(std::get<7-1>(v_)) > 0)
break;
header_done_ = true;
v_.template emplace<1 - 1>();
s_ = do_complete;
break;
}
case do_final_c + 1:
BHO_ASSERT(buffer_bytes(std::get<8-1>(v_)));
std::get<8-1>(v_).consume(n);
if(buffer_bytes(std::get<8-1>(v_)) > 0)
break;
v_.template emplace<1 - 1>();
goto go_complete;
//----------------------------------------------------------------------
default:
BHO_ASSERT(false);
case do_complete:
break;
go_complete:
s_ = do_complete;
break;
}
}
} // http
} // beast
} // bho
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_UDP_CLIENT_HPP__
#define __ASIO2_UDP_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/client.hpp>
#include <asio2/base/detail/linear_buffer.hpp>
#include <asio2/udp/detail/kcp_util.hpp>
#include <asio2/udp/impl/udp_send_op.hpp>
#include <asio2/udp/impl/udp_recv_op.hpp>
#include <asio2/udp/impl/kcp_stream_cp.hpp>
namespace asio2::detail
{
struct template_args_udp_client
{
static constexpr bool is_session = false;
static constexpr bool is_client = true;
static constexpr bool is_server = false;
using socket_t = asio::ip::udp::socket;
using buffer_t = asio2::linear_buffer;
using send_data_t = std::string_view;
using recv_data_t = std::string_view;
static constexpr std::size_t allocator_storage_size = 256;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_CLIENT;
template<class derived_t, class args_t = template_args_udp_client>
class udp_client_impl_t
: public client_impl_t<derived_t, args_t>
, public udp_send_op <derived_t, args_t>
, public udp_recv_op <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_CLIENT;
public:
using super = client_impl_t <derived_t, args_t>;
using self = udp_client_impl_t<derived_t, args_t>;
using args_type = args_t;
using buffer_type = typename args_t::buffer_t;
using send_data_t = typename args_t::send_data_t;
using recv_data_t = typename args_t::recv_data_t;
public:
/**
* @brief constructor
*/
explicit udp_client_impl_t(
std::size_t init_buf_size = udp_frame_size,
std::size_t max_buf_size = max_buffer_size,
std::size_t concurrency = 1
)
: super(init_buf_size, max_buf_size, concurrency)
, udp_send_op<derived_t, args_t>()
, udp_recv_op<derived_t, args_t>()
{
this->set_connect_timeout(std::chrono::milliseconds(udp_connect_timeout));
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit udp_client_impl_t(
std::size_t init_buf_size,
std::size_t max_buf_size,
Scheduler && scheduler
)
: super(init_buf_size, max_buf_size, std::forward<Scheduler>(scheduler))
, udp_send_op<derived_t, args_t>()
, udp_recv_op<derived_t, args_t>()
{
this->set_connect_timeout(std::chrono::milliseconds(udp_connect_timeout));
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit udp_client_impl_t(Scheduler && scheduler)
: udp_client_impl_t(udp_frame_size, max_buffer_size, std::forward<Scheduler>(scheduler))
{
}
/**
* @brief destructor
*/
~udp_client_impl_t()
{
this->stop();
}
/**
* @brief start the client, blocking connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& port, Args&&... args)
{
return this->derived().template _do_connect<false>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
/**
* @brief start the client, asynchronous connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool async_start(String&& host, StrOrInt&& port, Args&&... args)
{
return this->derived().template _do_connect<true>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
/**
* @brief stop the client
* You can call this function in the communication thread and anywhere to stop the client.
* If this function is called in the communication thread, it will post a asynchronous
* event into the event queue, then return immediately.
* If this function is called not in the communication thread, it will blocking forever
* util the client is stopped completed.
*/
inline void stop()
{
if (this->is_iopool_stopped())
return;
derived_t& derive = this->derived();
derive.io().unregobj(&derive);
// use promise to get the result of stop
std::promise<state_t> promise;
std::future<state_t> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[this, p = std::move(promise)]() mutable
{
p.set_value(this->state().load());
}
};
// if user call stop in the recv callback, use post event to executed a async event.
derive.post_event([&derive, this_ptr = derive.selfptr(), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
// first close the reconnect timer
derive._stop_reconnect_timer();
derive._do_disconnect(asio::error::operation_aborted, derive.selfptr(), defer_event
{
[&derive, this_ptr = std::move(this_ptr), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
derive._do_stop(asio::error::operation_aborted, std::move(this_ptr), defer_event
{
[pg = std::move(pg)](event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
});
}, std::move(g)
});
});
while (!derive.running_in_this_thread())
{
std::future_status status = future.wait_for(std::chrono::milliseconds(100));
if (status == std::future_status::ready)
{
ASIO2_ASSERT(future.get() == state_t::stopped);
break;
}
else
{
if (derive.get_thread_id() == std::thread::id{})
break;
if (derive.io().context().stopped())
break;
}
}
this->stop_iopool();
}
public:
/**
* @brief get the kcp pointer, just used for kcp mode
* default mode : ikcp_nodelay(kcp, 0, 10, 0, 0);
* generic mode : ikcp_nodelay(kcp, 0, 10, 0, 1);
* fast mode : ikcp_nodelay(kcp, 1, 10, 2, 1);
*/
inline kcp::ikcpcb* get_kcp() noexcept
{
return (this->kcp_ ? this->kcp_->kcp_ : nullptr);
}
/**
* @brief get the kcp pointer, just used for kcp mode. same as get_kcp
* default mode : ikcp_nodelay(kcp, 0, 10, 0, 0);
* generic mode : ikcp_nodelay(kcp, 0, 10, 0, 1);
* fast mode : ikcp_nodelay(kcp, 1, 10, 2, 1);
*/
inline kcp::ikcpcb* kcp() noexcept
{
return this->get_kcp();
}
/**
* @brief Provide a kcp conv, If the conv is not provided, it will be generated by the server.
*/
inline derived_t& set_kcp_conv(std::uint32_t conv)
{
this->kcp_conv_ = conv;
return (this->derived());
}
public:
/**
* @brief bind recv listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void(std::string_view data)
*/
template<class F, class ...C>
inline derived_t & bind_recv(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::recv,
observer_t<std::string_view>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind connect listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called after the client connection completed, whether successful or unsuccessful
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_connect(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::connect,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind disconnect listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called before the client is ready to disconnect
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_disconnect(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::disconnect,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind init listener,we should set socket options at here
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_init(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::init,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind kcp handshake listener, just used fo kcp mode
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_handshake(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::handshake,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<bool IsAsync, typename String, typename StrOrInt, typename C>
inline bool _do_connect(String&& host, StrOrInt&& port, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = this->derived();
// if log is enabled, init the log first, otherwise when "Too many open files" error occurs,
// the log file will be created failed too.
#if defined(ASIO2_ENABLE_LOG)
asio2::detail::get_logger();
#endif
this->start_iopool();
if (!this->is_iopool_started())
{
set_last_error(asio::error::operation_aborted);
return false;
}
asio::dispatch(derive.io().context(), [&derive, this_ptr = derive.selfptr()]() mutable
{
detail::ignore_unused(this_ptr);
// init the running thread id
derive.io().init_thread_id();
});
// use promise to get the result of async connect
std::promise<error_code> promise;
std::future<error_code> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[promise = std::move(promise)]() mutable
{
promise.set_value(get_last_error());
}
};
// if user call start in the recv callback, use post event to executed a async event.
derive.post_event(
[this, this_ptr = derive.selfptr(), ecs = std::move(ecs), pg = std::move(pg),
host = std::forward<String>(host), port = std::forward<StrOrInt>(port)]
(event_queue_guard<derived_t> g) mutable
{
derived_t& derive = this->derived();
defer_event chain
{
[pg = std::move(pg)] (event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
};
state_t expected = state_t::stopped;
if (!derive.state_.compare_exchange_strong(expected, state_t::starting))
{
// if the state is not stopped, set the last error to already_started
set_last_error(asio::error::already_started);
return;
}
// must read/write ecs in the io_context thread.
derive.ecs_ = ecs;
clear_last_error();
derive.io().regobj(&derive);
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_reconnect_timer_called_ = false;
this->is_post_reconnect_timer_called_ = false;
this->is_stop_connect_timeout_timer_called_ = false;
this->is_disconnect_called_ = false;
#endif
// convert to string maybe throw some exception.
this->host_ = detail::to_string(std::move(host));
this->port_ = detail::to_string(std::move(port));
super::start();
derive._do_init(ecs);
// ecs init
derive._rdc_init(ecs);
derive._socks5_init(ecs);
derive.template _start_connect<IsAsync>(std::move(this_ptr), std::move(ecs), std::move(chain));
});
if constexpr (IsAsync)
{
set_last_error(asio::error::in_progress);
return true;
}
else
{
if (!derive.io().running_in_this_thread())
{
set_last_error(future.get());
return static_cast<bool>(!get_last_error());
}
else
{
set_last_error(asio::error::in_progress);
}
// if the state is stopped , the return value is "is_started()".
// if the state is stopping, the return value is false, the last error is already_started
// if the state is starting, the return value is false, the last error is already_started
// if the state is started , the return value is true , the last error is already_started
return derive.is_started();
}
}
template<typename C>
inline void _do_init(std::shared_ptr<ecs_t<C>>&)
{
if constexpr (std::is_same_v<typename ecs_t<C>::condition_lowest_type, use_kcp_t>)
this->kcp_ = std::make_unique<kcp_stream_cp<derived_t, args_t>>(this->derived(), this->io_);
else
this->kcp_.reset();
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
set_last_error(ec);
derived_t& derive = static_cast<derived_t&>(*this);
if (ec)
return derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
if constexpr (std::is_same_v<typename ecs_t<C>::condition_lowest_type, use_kcp_t>)
this->kcp_->_post_handshake(std::move(this_ptr), std::move(ecs), std::move(chain));
else
derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename C, typename DeferEvent>
inline void _do_start(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
this->derived().update_alive_time();
this->derived().reset_connect_time();
if constexpr (std::is_same_v<typename ecs_t<C>::condition_lowest_type, use_kcp_t>)
{
ASIO2_ASSERT(this->kcp_);
if (this->kcp_)
this->kcp_->send_fin_ = true;
}
this->derived()._start_recv(std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename DeferEvent>
inline void _handle_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(this->state_ == state_t::stopped);
this->derived()._rdc_stop();
if (this->kcp_)
this->kcp_->_kcp_stop();
error_code ec_ignore{};
// call socket's close function to notify the _handle_recv function response with
// error > 0 ,then the socket can get notify to exit
// Call shutdown() to indicate that you will not write any more data to the socket.
this->socket().shutdown(asio::socket_base::shutdown_both, ec_ignore);
this->socket().cancel(ec_ignore);
// Call close,otherwise the _handle_recv will never return
this->socket().close(ec_ignore);
super::_handle_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _do_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_ASSERT(this->state_ == state_t::stopped);
this->derived()._post_stop(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _post_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
// All pending sending events will be cancelled after enter the callback below.
this->derived().disp_event(
[this, ec, this_ptr = std::move(this_ptr), e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
set_last_error(ec);
defer_event chain(std::move(e), std::move(g));
// call the base class stop function
super::stop();
// call CRTP polymorphic stop
this->derived()._handle_stop(ec, std::move(this_ptr), std::move(chain));
}, chain.move_guard());
}
template<typename DeferEvent>
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
detail::ignore_unused(ec, this_ptr, chain);
ASIO2_ASSERT(this->state_ == state_t::stopped);
}
template<typename C, typename DeferEvent>
inline void _start_recv(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
// Connect succeeded. post recv request.
asio::dispatch(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
detail::ignore_unused(chain);
this->derived().buffer().consume(this->derived().buffer().size());
this->derived()._post_recv(std::move(this_ptr), std::move(ecs));
}));
}
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
if (!this->kcp_)
return this->derived()._udp_send(data, std::forward<Callback>(callback));
return this->kcp_->_kcp_send(data, std::forward<Callback>(callback));
}
template<class Data>
inline send_data_t _rdc_convert_to_send_data(Data& data) noexcept
{
auto buffer = asio::buffer(data);
return send_data_t{ reinterpret_cast<
std::string_view::const_pointer>(buffer.data()),buffer.size() };
}
template<class Invoker>
inline void _rdc_invoke_with_none(const error_code& ec, Invoker& invoker)
{
if (invoker)
invoker(ec, send_data_t{}, recv_data_t{});
}
template<class Invoker>
inline void _rdc_invoke_with_recv(const error_code& ec, Invoker& invoker, recv_data_t data)
{
if (invoker)
invoker(ec, send_data_t{}, data);
}
template<class Invoker>
inline void _rdc_invoke_with_send(const error_code& ec, Invoker& invoker, send_data_t data)
{
if (invoker)
invoker(ec, data, recv_data_t{});
}
protected:
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._udp_post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._udp_handle_recv(ec, bytes_recvd, this_ptr, ecs);
}
inline void _fire_init()
{
// the _fire_init must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(!get_last_error());
this->listener_.notify(event_type::init);
}
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, data);
this->derived()._rdc_handle_recv(this_ptr, ecs, data);
}
inline void _fire_handshake(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_handshake must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
detail::ignore_unused(this_ptr);
this->listener_.notify(event_type::handshake);
}
template<typename C>
inline void _fire_connect(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
// the _fire_connect must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_disconnect_called_ == false);
#endif
if (!get_last_error())
{
this->derived()._rdc_start(this_ptr, ecs);
}
this->listener_.notify(event_type::connect);
}
inline void _fire_disconnect(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_disconnect must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
this->is_disconnect_called_ = true;
#endif
detail::ignore_unused(this_ptr);
this->listener_.notify(event_type::disconnect);
}
protected:
std::unique_ptr<kcp_stream_cp<derived_t, args_t>> kcp_;
std::uint32_t kcp_conv_ = 0;
#if defined(_DEBUG) || defined(DEBUG)
bool is_disconnect_called_ = false;
#endif
};
}
namespace asio2
{
using udp_client_args = detail::template_args_udp_client;
template<class derived_t, class args_t>
using udp_client_impl_t = detail::udp_client_impl_t<derived_t, args_t>;
/**
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
template<class derived_t>
class udp_client_t : public detail::udp_client_impl_t<derived_t, detail::template_args_udp_client>
{
public:
using detail::udp_client_impl_t<derived_t, detail::template_args_udp_client>::udp_client_impl_t;
};
/**
* If this object is created as a shared_ptr like std::shared_ptr<asio2::udp_client> client;
* you must call the client->stop() manual when exit, otherwise maybe cause memory leaks.
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
class udp_client : public udp_client_t<udp_client>
{
public:
using udp_client_t<udp_client>::udp_client_t;
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_UDP_CLIENT_HPP__
<file_sep>#include "unit_test.hpp"
#include <asio2/util/des.hpp>
#include <asio2/util/base64.hpp>
void des_test()
{
std::string src = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// maybe has some problem : the result is not equal to the http://tool.chacuo.net/cryptdes
{
std::string password = "<PASSWORD>";
std::string base64 = "<KEY>;
asio2::des des1(password);
std::string en = des1.encrypt(src);
std::string de = des1.decrypt(en);
//ASIO2_CHECK(asio2::base64_encode(en) == base64);
ASIO2_CHECK(src == de);
}
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
std::string str;
{
int len = 500 + std::rand() % (500);
for (int i = 0; i < len; i++)
{
// the character should not be '\0'
str += (char)(1 + std::rand() % 255);
}
}
{
std::string password;
int len = std::rand() % (10);
for (int i = 0; i < len; i++)
{
password += (char)(std::rand() % 255);
}
asio2::des des1(password);
std::string en = des1.encrypt(str);
std::string de = des1.decrypt(en);
ASIO2_CHECK(str == de);
}
ASIO2_TEST_END_LOOP;
}
ASIO2_TEST_SUITE
(
"des",
ASIO2_TEST_CASE(des_test)
)
<file_sep>/*
Copyright <NAME> 2011-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ARCHITECTURE_PYRAMID_H
#define BHO_PREDEF_ARCHITECTURE_PYRAMID_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_ARCH_PYRAMID`
Pyramid 9810 architecture.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `pyr` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_ARCH_PYRAMID BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(pyr)
# undef BHO_ARCH_PYRAMID
# define BHO_ARCH_PYRAMID BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_ARCH_PYRAMID
# define BHO_ARCH_PYRAMID_AVAILABLE
#endif
#if BHO_ARCH_PYRAMID
# undef BHO_ARCH_WORD_BITS_32
# define BHO_ARCH_WORD_BITS_32 BHO_VERSION_NUMBER_AVAILABLE
#endif
#define BHO_ARCH_PYRAMID_NAME "Pyramid 9810"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ARCH_PYRAMID,BHO_ARCH_PYRAMID_NAME)
<file_sep>#ifndef BHO_MP11_DETAIL_CONFIG_HPP_INCLUDED
#define BHO_MP11_DETAIL_CONFIG_HPP_INCLUDED
// Copyright 2016, 2018, 2019 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// BHO_MP11_WORKAROUND
#if defined( BHO_STRICT_CONFIG ) || defined( BHO_MP11_NO_WORKAROUNDS )
# define BHO_MP11_WORKAROUND( symbol, test ) 0
#else
# define BHO_MP11_WORKAROUND( symbol, test ) ((symbol) != 0 && ((symbol) test))
#endif
//
#define BHO_MP11_CUDA 0
#define BHO_MP11_CLANG 0
#define BHO_MP11_INTEL 0
#define BHO_MP11_GCC 0
#define BHO_MP11_MSVC 0
#define BHO_MP11_CONSTEXPR constexpr
#if defined( __CUDACC__ )
// nvcc
# undef BHO_MP11_CUDA
# define BHO_MP11_CUDA (__CUDACC_VER_MAJOR__ * 1000000 + __CUDACC_VER_MINOR__ * 10000 + __CUDACC_VER_BUILD__)
// CUDA (8.0) has no constexpr support in msvc mode:
# if defined(_MSC_VER) && (BHO_MP11_CUDA < 9000000)
# define BHO_MP11_NO_CONSTEXPR
# undef BHO_MP11_CONSTEXPR
# define BHO_MP11_CONSTEXPR
# endif
#endif
#if defined(__clang__)
// Clang
# undef BHO_MP11_CLANG
# define BHO_MP11_CLANG (__clang_major__ * 100 + __clang_minor__)
# if defined(__has_cpp_attribute)
# if __has_cpp_attribute(fallthrough) && __cplusplus >= 201406L // Clang 3.9+ in c++1z mode
# define BHO_MP11_HAS_FOLD_EXPRESSIONS
# endif
# endif
#if BHO_MP11_CLANG < 400 && __cplusplus >= 201402L \
&& defined( __GLIBCXX__ ) && !__has_include(<shared_mutex>)
// Clang pre-4 in C++14 mode, libstdc++ pre-4.9, ::gets is not defined,
// but Clang tries to import it into std
extern "C" char *gets (char *__s);
#endif
#elif defined(__INTEL_COMPILER)
// Intel C++
# undef BHO_MP11_INTEL
# define BHO_MP11_INTEL __INTEL_COMPILER
#elif defined(__GNUC__)
// g++
# undef BHO_MP11_GCC
# define BHO_MP11_GCC (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#elif defined(_MSC_VER)
// MS Visual C++
# undef BHO_MP11_MSVC
# define BHO_MP11_MSVC _MSC_VER
# if BHO_MP11_WORKAROUND( BHO_MP11_MSVC, < 1920 )
# define BHO_MP11_NO_CONSTEXPR
# endif
#if _MSC_FULL_VER < 190024210 // 2015u3
# undef BHO_MP11_CONSTEXPR
# define BHO_MP11_CONSTEXPR
#endif
#endif
// BHO_MP11_HAS_CXX14_CONSTEXPR
#if !defined(BHO_MP11_NO_CONSTEXPR) && defined(__cpp_constexpr) && __cpp_constexpr >= 201304
# define BHO_MP11_HAS_CXX14_CONSTEXPR
#endif
// BHO_MP11_HAS_FOLD_EXPRESSIONS
#if !defined(BHO_MP11_HAS_FOLD_EXPRESSIONS) && defined(__cpp_fold_expressions) && __cpp_fold_expressions >= 201603
# define BHO_MP11_HAS_FOLD_EXPRESSIONS
#endif
// BHO_MP11_HAS_TYPE_PACK_ELEMENT
#if defined(__has_builtin)
# if __has_builtin(__type_pack_element)
# define BHO_MP11_HAS_TYPE_PACK_ELEMENT
# endif
#endif
// BHO_MP11_DEPRECATED(msg)
#if BHO_MP11_WORKAROUND( BHO_MP11_CLANG, < 304 )
# define BHO_MP11_DEPRECATED(msg)
#elif defined(__GNUC__) || defined(__clang__)
# define BHO_MP11_DEPRECATED(msg) __attribute__((deprecated(msg)))
#elif defined(_MSC_VER) && _MSC_VER >= 1900
# define BHO_MP11_DEPRECATED(msg) [[deprecated(msg)]]
#else
# define BHO_MP11_DEPRECATED(msg)
#endif
#endif // #ifndef BHO_MP11_DETAIL_CONFIG_HPP_INCLUDED
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_ASIO_HPP__
#define __ASIO2_ASIO_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/config.hpp>
#ifdef ASIO2_HEADER_ONLY
# ifndef ASIO_STANDALONE
# define ASIO_STANDALONE
# endif
#endif
#ifdef ASIO_STANDALONE
# ifndef ASIO_HEADER_ONLY
# define ASIO_HEADER_ONLY
# endif
#endif
#include <asio2/base/detail/push_options.hpp>
#ifdef ASIO_STANDALONE
#if __has_include(<asio.hpp>)
#include <asio.hpp>
#elif __has_include(<asio/asio.hpp>)
#include <asio/asio.hpp>
#else
#include "asio/associated_allocator.hpp"
#include "asio/associated_executor.hpp"
#include "asio/async_result.hpp"
#include "asio/awaitable.hpp"
#include "asio/basic_datagram_socket.hpp"
#include "asio/basic_deadline_timer.hpp"
#include "asio/basic_io_object.hpp"
#include "asio/basic_raw_socket.hpp"
#include "asio/basic_seq_packet_socket.hpp"
#include "asio/basic_serial_port.hpp"
#include "asio/basic_signal_set.hpp"
#include "asio/basic_socket.hpp"
#include "asio/basic_socket_acceptor.hpp"
#include "asio/basic_socket_iostream.hpp"
#include "asio/basic_socket_streambuf.hpp"
#include "asio/basic_stream_socket.hpp"
#include "asio/basic_streambuf.hpp"
#include "asio/basic_waitable_timer.hpp"
#include "asio/bind_executor.hpp"
#include "asio/buffer.hpp"
#include "asio/buffered_read_stream_fwd.hpp"
#include "asio/buffered_read_stream.hpp"
#include "asio/buffered_stream_fwd.hpp"
#include "asio/buffered_stream.hpp"
#include "asio/buffered_write_stream_fwd.hpp"
#include "asio/buffered_write_stream.hpp"
#include "asio/buffers_iterator.hpp"
#include "asio/co_spawn.hpp"
#include "asio/completion_condition.hpp"
#include "asio/compose.hpp"
#include "asio/connect.hpp"
#include "asio/coroutine.hpp"
#include "asio/deadline_timer.hpp"
#include "asio/defer.hpp"
#include "asio/detached.hpp"
#include "asio/dispatch.hpp"
#include "asio/error.hpp"
#include "asio/error_code.hpp"
#include "asio/execution.hpp"
#include "asio/execution/allocator.hpp"
#include "asio/execution/any_executor.hpp"
#include "asio/execution/blocking.hpp"
#include "asio/execution/blocking_adaptation.hpp"
#include "asio/execution/bulk_execute.hpp"
#include "asio/execution/bulk_guarantee.hpp"
#include "asio/execution/connect.hpp"
#include "asio/execution/context.hpp"
#include "asio/execution/context_as.hpp"
#include "asio/execution/execute.hpp"
#include "asio/execution/executor.hpp"
#include "asio/execution/invocable_archetype.hpp"
#include "asio/execution/mapping.hpp"
#include "asio/execution/occupancy.hpp"
#include "asio/execution/operation_state.hpp"
#include "asio/execution/outstanding_work.hpp"
#include "asio/execution/prefer_only.hpp"
#include "asio/execution/receiver.hpp"
#include "asio/execution/receiver_invocation_error.hpp"
#include "asio/execution/relationship.hpp"
#include "asio/execution/schedule.hpp"
#include "asio/execution/scheduler.hpp"
#include "asio/execution/sender.hpp"
#include "asio/execution/set_done.hpp"
#include "asio/execution/set_error.hpp"
#include "asio/execution/set_value.hpp"
#include "asio/execution/start.hpp"
#include "asio/execution_context.hpp"
#include "asio/executor.hpp"
#include "asio/executor_work_guard.hpp"
#include "asio/generic/basic_endpoint.hpp"
#include "asio/generic/datagram_protocol.hpp"
#include "asio/generic/raw_protocol.hpp"
#include "asio/generic/seq_packet_protocol.hpp"
#include "asio/generic/stream_protocol.hpp"
#include "asio/handler_alloc_hook.hpp"
#include "asio/handler_continuation_hook.hpp"
#include "asio/handler_invoke_hook.hpp"
#include "asio/high_resolution_timer.hpp"
#include "asio/io_context.hpp"
#include "asio/io_context_strand.hpp"
#include "asio/io_service.hpp"
#include "asio/io_service_strand.hpp"
#include "asio/ip/address.hpp"
#include "asio/ip/address_v4.hpp"
#include "asio/ip/address_v4_iterator.hpp"
#include "asio/ip/address_v4_range.hpp"
#include "asio/ip/address_v6.hpp"
#include "asio/ip/address_v6_iterator.hpp"
#include "asio/ip/address_v6_range.hpp"
#include "asio/ip/network_v4.hpp"
#include "asio/ip/network_v6.hpp"
#include "asio/ip/bad_address_cast.hpp"
#include "asio/ip/basic_endpoint.hpp"
#include "asio/ip/basic_resolver.hpp"
#include "asio/ip/basic_resolver_entry.hpp"
#include "asio/ip/basic_resolver_iterator.hpp"
#include "asio/ip/basic_resolver_query.hpp"
#include "asio/ip/host_name.hpp"
#include "asio/ip/icmp.hpp"
#include "asio/ip/multicast.hpp"
#include "asio/ip/resolver_base.hpp"
#include "asio/ip/resolver_query_base.hpp"
#include "asio/ip/tcp.hpp"
#include "asio/ip/udp.hpp"
#include "asio/ip/unicast.hpp"
#include "asio/ip/v6_only.hpp"
#include "asio/is_applicable_property.hpp"
#include "asio/is_executor.hpp"
#include "asio/is_read_buffered.hpp"
#include "asio/is_write_buffered.hpp"
#include "asio/local/basic_endpoint.hpp"
#include "asio/local/connect_pair.hpp"
#include "asio/local/datagram_protocol.hpp"
#include "asio/local/stream_protocol.hpp"
#include "asio/multiple_exceptions.hpp"
#include "asio/packaged_task.hpp"
#include "asio/placeholders.hpp"
#include "asio/posix/basic_descriptor.hpp"
#include "asio/posix/basic_stream_descriptor.hpp"
#include "asio/posix/descriptor.hpp"
#include "asio/posix/descriptor_base.hpp"
#include "asio/posix/stream_descriptor.hpp"
#include "asio/post.hpp"
#include "asio/prefer.hpp"
#include "asio/query.hpp"
#include "asio/read.hpp"
#include "asio/read_at.hpp"
#include "asio/read_until.hpp"
#include "asio/redirect_error.hpp"
#include "asio/require.hpp"
#include "asio/require_concept.hpp"
#include "asio/serial_port.hpp"
#include "asio/serial_port_base.hpp"
#include "asio/signal_set.hpp"
#include "asio/socket_base.hpp"
#include "asio/static_thread_pool.hpp"
#include "asio/steady_timer.hpp"
#include "asio/strand.hpp"
#include "asio/streambuf.hpp"
#include "asio/system_context.hpp"
#include "asio/system_error.hpp"
#include "asio/system_executor.hpp"
#include "asio/system_timer.hpp"
#include "asio/this_coro.hpp"
#include "asio/thread.hpp"
#include "asio/thread_pool.hpp"
#include "asio/time_traits.hpp"
#include "asio/use_awaitable.hpp"
#include "asio/use_future.hpp"
#include "asio/uses_executor.hpp"
#include "asio/version.hpp"
#include "asio/wait_traits.hpp"
#include "asio/windows/basic_object_handle.hpp"
#include "asio/windows/basic_overlapped_handle.hpp"
#include "asio/windows/basic_random_access_handle.hpp"
#include "asio/windows/basic_stream_handle.hpp"
#include "asio/windows/object_handle.hpp"
#include "asio/windows/overlapped_handle.hpp"
#include "asio/windows/overlapped_ptr.hpp"
#include "asio/windows/random_access_handle.hpp"
#include "asio/windows/stream_handle.hpp"
#include "asio/write.hpp"
#include "asio/write_at.hpp"
#endif
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#include <asio/ssl.hpp>
#endif
#else
#include <boost/asio.hpp>
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
#include <boost/asio/ssl.hpp>
#endif
#ifndef ASIO_VERSION
#define ASIO_VERSION BOOST_ASIO_VERSION
#endif
#ifndef ASIO_CONST_BUFFER
#define ASIO_CONST_BUFFER BOOST_ASIO_CONST_BUFFER
#endif
#ifndef ASIO_MUTABLE_BUFFER
#define ASIO_MUTABLE_BUFFER BOOST_ASIO_MUTABLE_BUFFER
#endif
#ifndef ASIO_NOEXCEPT
#define ASIO_NOEXCEPT BOOST_ASIO_NOEXCEPT
#endif
#ifndef ASIO_CORO_REENTER
#define ASIO_CORO_REENTER BOOST_ASIO_CORO_REENTER
#endif
#ifndef ASIO_CORO_YIELD
#define ASIO_CORO_YIELD BOOST_ASIO_CORO_YIELD
#endif
#ifndef ASIO_CORO_FORK
#define ASIO_CORO_FORK BOOST_ASIO_CORO_FORK
#endif
#ifndef ASIO_INITFN_AUTO_RESULT_TYPE
#define ASIO_INITFN_AUTO_RESULT_TYPE BOOST_ASIO_INITFN_AUTO_RESULT_TYPE
#endif
#ifndef ASIO_COMPLETION_TOKEN_FOR
#define ASIO_COMPLETION_TOKEN_FOR BOOST_ASIO_COMPLETION_TOKEN_FOR
#endif
#ifndef ASIO_DEFAULT_COMPLETION_TOKEN
#define ASIO_DEFAULT_COMPLETION_TOKEN BOOST_ASIO_DEFAULT_COMPLETION_TOKEN
#endif
#ifndef ASIO_DEFAULT_COMPLETION_TOKEN_TYPE
#define ASIO_DEFAULT_COMPLETION_TOKEN_TYPE BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE
#endif
#ifndef ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX
#define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX
#endif
#ifndef ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX
#define ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX
#endif
#ifdef BOOST_ASIO_NO_TS_EXECUTORS
#ifndef ASIO_NO_TS_EXECUTORS
#define ASIO_NO_TS_EXECUTORS BOOST_ASIO_NO_TS_EXECUTORS
#endif
#endif
#ifndef ASIO_HANDLER_LOCATION
#define ASIO_HANDLER_LOCATION BOOST_ASIO_HANDLER_LOCATION
#endif
#ifdef BOOST_ASIO_ENABLE_BUFFER_DEBUGGING
#ifndef ASIO_ENABLE_BUFFER_DEBUGGING
#define ASIO_ENABLE_BUFFER_DEBUGGING BOOST_ASIO_ENABLE_BUFFER_DEBUGGING
#endif
#endif
#ifndef ASIO_MOVE_ARG
#define ASIO_MOVE_ARG BOOST_ASIO_MOVE_ARG
#endif
#ifndef ASIO_MOVE_CAST
#define ASIO_MOVE_CAST BOOST_ASIO_MOVE_CAST
#endif
#ifndef ASIO_HANDLER_TYPE
#define ASIO_HANDLER_TYPE BOOST_ASIO_HANDLER_TYPE
#endif
#ifdef BOOST_ASIO_HAS_STD_HASH
#ifndef ASIO_HAS_STD_HASH
#define ASIO_HAS_STD_HASH BOOST_ASIO_HAS_STD_HASH
#endif
#endif
#ifndef ASIO_SYNC_OP_VOID
#define ASIO_SYNC_OP_VOID BOOST_ASIO_SYNC_OP_VOID
#endif
#ifndef ASIO_SYNC_OP_VOID_RETURN
#define ASIO_SYNC_OP_VOID_RETURN BOOST_ASIO_SYNC_OP_VOID_RETURN
#endif
#endif // ASIO_STANDALONE
#ifdef ASIO_STANDALONE
namespace asio
{
using error_condition = std::error_condition;
}
#else
namespace boost::asio
{
using error_code = ::boost::system::error_code;
using system_error = ::boost::system::system_error;
using error_condition = ::boost::system::error_condition;
using error_category = ::boost::system::error_category;
}
namespace asio = ::boost::asio;
namespace bho = ::boost; // bho means boost header only
// [ adding definitions to namespace alias ]
// This is currently not allowed and probably won't be in C++1Z either,
// but note that a recent proposal is allowing
// https://stackoverflow.com/questions/31629101/adding-definitions-to-namespace-alias?r=SearchResults
//namespace asio
//{
// using error_code = ::boost::system::error_code;
// using system_error = ::boost::system::system_error;
//}
#endif // ASIO_STANDALONE
namespace asio2
{
using error_code = ::asio::error_code;
using system_error = ::asio::system_error;
using error_condition = ::asio::error_condition;
using error_category = ::asio::error_category;
}
#ifdef ASIO_STANDALONE
namespace asio
#else
namespace boost::asio
#endif
{
/*
* used for rdc mode, call("abc") or async_call("abc")
* Without the following overload, the compilation will fail.
*/
template<class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char > ||
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, wchar_t > ||
#if defined(__cpp_lib_char8_t)
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char8_t > ||
#endif
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char16_t> ||
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char32_t>,
ASIO_CONST_BUFFER> buffer(CharT* & data) ASIO_NOEXCEPT
{
return asio::buffer(std::basic_string_view<CharT>(data));
}
template<class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char > ||
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, wchar_t > ||
#if defined(__cpp_lib_char8_t)
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char8_t > ||
#endif
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char16_t> ||
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char32_t>,
ASIO_CONST_BUFFER> buffer(const CharT* & data) ASIO_NOEXCEPT
{
return asio::buffer(std::basic_string_view<CharT>(data));
}
template<class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char > ||
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, wchar_t > ||
#if defined(__cpp_lib_char8_t)
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char8_t > ||
#endif
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char16_t> ||
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char32_t>,
ASIO_CONST_BUFFER> buffer(CharT* const& data) ASIO_NOEXCEPT
{
return asio::buffer(std::basic_string_view<CharT>(data));
}
template<class CharT, class Traits = std::char_traits<CharT>>
inline typename std::enable_if_t<
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char > ||
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, wchar_t > ||
#if defined(__cpp_lib_char8_t)
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char8_t > ||
#endif
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char16_t> ||
std::is_same_v<std::remove_cv_t<std::remove_reference_t<CharT>>, char32_t>,
ASIO_CONST_BUFFER> buffer(const CharT* const& data) ASIO_NOEXCEPT
{
return asio::buffer(std::basic_string_view<CharT>(data));
}
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_ASIO_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* socks5 protocol : https://www.ddhigh.com/2019/08/24/socks5-protocol.html
* UDP Associate : https://blog.csdn.net/whatday/article/details/40183555
*/
#ifndef __ASIO2_SOCKS5_SERVER_HPP__
#define __ASIO2_SOCKS5_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <asio2/base/error.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/ecs.hpp>
#include <asio2/component/socks/socks5_core.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class SocketT, class Sock5OptT, class HandlerT>
class socks5_server_accept_op : public asio::coroutine
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
asio::io_context & context_;
std::string host_{}, port_{};
SocketT& socket_;
Sock5OptT sock5_;
HandlerT handler_;
#if defined(ASIO2_ENABLE_LOG)
static_assert(detail::is_template_instance_of_v<std::shared_ptr, Sock5OptT>);
#endif
std::unique_ptr<asio::streambuf> stream{ std::make_unique<asio::streambuf>() };
asio::mutable_buffer buffer{};
std::size_t bytes{};
char* p{};
asio::ip::address endpoint{};
std::string username{}, password{};
std::uint8_t addr_type{}, addr_size{};
socks5::method method{};
template<class SKT, class S5Opt, class H>
socks5_server_accept_op(
asio::io_context& context,
std::string host, std::string port,
SKT& skt, S5Opt s5, H&& h
)
: context_(context)
, host_ (std::move(host))
, port_ (std::move(port))
, socket_ (skt)
, sock5_ (std::move(s5))
, handler_(std::forward<H>(h))
{
(*this)();
}
template<typename = void>
void operator()(error_code ec = {}, std::size_t bytes_transferred = 0)
{
detail::ignore_unused(ec, bytes_transferred);
asio::streambuf& strbuf = *stream;
// There is no need to use a timeout timer because there is already has
// connect_timeout_cp
ASIO_CORO_REENTER(*this)
{
// The client connects to the server, and sends a version
// identifier / method selection message :
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+
stream->consume(stream->size());
bytes = 1 + 1 + sock5_->methods_count();
buffer = stream->prepare(bytes);
p = static_cast<char*>(buffer.data());
write(p, std::uint8_t(0x05)); // SOCKS VERSION 5.
write(p, std::uint8_t(sock5_->methods_count())); // NMETHODS
for (auto m : sock5_->methods())
{
write(p, std::uint8_t(detail::to_underlying(m))); // METHODS
}
stream->commit(bytes);
ASIO_CORO_YIELD
asio::async_write(socket_, strbuf, asio::transfer_exactly(bytes), std::move(*this));
if (ec)
goto end;
// The server selects from one of the methods given in METHODS, and
// sends a METHOD selection message :
// +----+--------+
// |VER | METHOD |
// +----+--------+
// | 1 | 1 |
// +----+--------+
stream->consume(stream->size());
ASIO_CORO_YIELD
asio::async_read(socket_, strbuf, asio::transfer_exactly(1 + 1), std::move(*this));
if (ec)
goto end;
p = const_cast<char*>(static_cast<const char*>(stream->data().data()));
if (std::uint8_t version = read<std::uint8_t>(p); version != std::uint8_t(0x05))
{
ec = socks5::make_error_code(socks5::error::unsupported_version);
goto end;
}
// If the selected METHOD is X'FF', none of the methods listed by the
// client are acceptable, and the client MUST close the connection.
//
// The values currently defined for METHOD are:
//
// o X'00' NO AUTHENTICATION REQUIRED
// o X'01' GSSAPI
// o X'02' USERNAME/PASSWORD
// o X'03' to X'7F' IANA ASSIGNED
// o X'80' to X'FE' RESERVED FOR PRIVATE METHODS
// o X'FF' NO ACCEPTABLE METHODS
// Once the method-dependent subnegotiation has completed, the client
// sends the request details. If the negotiated method includes
// encapsulation for purposes of integrity checking and/or
// confidentiality, these requests MUST be encapsulated in the method-
// dependent encapsulation.
//
// The SOCKS request is formed as follows:
//
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
//
// Where:
//
// o VER protocol version: X'05'
// o CMD
// o CONNECT X'01'
// o BIND X'02'
// o UDP ASSOCIATE X'03'
// o RSV RESERVED
// o ATYP address type of following address
// o IP V4 address: X'01'
// o DOMAINNAME: X'03'
// o IP V6 address: X'04'
// o DST.ADDR desired destination address
// o DST.PORT desired destination port in network octet
// order
//
// The SOCKS server will typically evaluate the request based on source
// and destination addresses, and return one or more reply messages, as
// appropriate for the request type.
method = socks5::method(read<std::uint8_t>(p));
// cannot use "switch", only "if else" can be used otherwise ASIO_CORO_YIELD will be exception.
if /**/ (method == socks5::method::anonymous)
{
}
else if (method == socks5::method::gssapi)
{
ec = socks5::make_error_code(socks5::error::unsupported_method);
goto end;
}
else if (method == socks5::method::password)
{
// Once the SOCKS V5 server has started, and the client has selected the
// Username/Password Authentication protocol, the Username/Password
// subnegotiation begins. This begins with the client producing a
// Username/Password request:
//
// +----+------+----------+------+----------+
// |VER | ULEN | UNAME | PLEN | PASSWD |
// +----+------+----------+------+----------+
// | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
// +----+------+----------+------+----------+
if constexpr (socks5::detail::has_member_username<typename Sock5OptT::element_type>::value)
{
username = sock5_->username();
}
else
{
ASIO2_ASSERT(false);
}
if constexpr (socks5::detail::has_member_password<typename Sock5OptT::element_type>::value)
{
password = <PASSWORD>_-><PASSWORD>();
}
else
{
ASIO2_ASSERT(false);
}
if (username.empty() && password.empty())
{
ASIO2_ASSERT(false);
ec = socks5::make_error_code(socks5::error::username_required);
goto end;
}
stream->consume(stream->size());
bytes = 1 + 1 + username.size() + 1 + password.size();
buffer = stream->prepare(bytes);
p = static_cast<char*>(buffer.data());
// The VER field contains the current version of the subnegotiation,
// which is X'01'. The ULEN field contains the length of the UNAME field
// that follows. The UNAME field contains the username as known to the
// source operating system. The PLEN field contains the length of the
// PASSWD field that follows. The PASSWD field contains the password
// association with the given UNAME.
// VER
write(p, std::uint8_t(0x01));
// ULEN
write(p, std::uint8_t(username.size()));
// UNAME
std::copy(username.begin(), username.end(), p);
p += username.size();
// PLEN
write(p, std::uint8_t(password.size()));
// PASSWD
std::copy(password.begin(), password.end(), p);
p += password.size();
stream->commit(bytes);
// send username and password to server
ASIO_CORO_YIELD
asio::async_write(socket_, strbuf, asio::transfer_exactly(bytes), std::move(*this));
if (ec)
goto end;
// The server verifies the supplied UNAME and PASSWD, and sends the
// following response:
//
// +----+--------+
// |VER | STATUS |
// +----+--------+
// | 1 | 1 |
// +----+--------+
//
// A STATUS field of X'00' indicates success. If the server returns a
// `failure' (STATUS value other than X'00') status, it MUST close the
// connection.
// read reply
stream->consume(stream->size());
ASIO_CORO_YIELD
asio::async_read(socket_, strbuf, asio::transfer_exactly(1 + 1), std::move(*this));
if (ec)
goto end;
// parse reply
p = const_cast<char*>(static_cast<const char*>(stream->data().data()));
if (std::uint8_t ver = read<std::uint8_t>(p); ver != std::uint8_t(0x01))
{
ec = socks5::make_error_code(socks5::error::unsupported_authentication_version);
goto end;
}
if (std::uint8_t status = read<std::uint8_t>(p); status != std::uint8_t(0x00))
{
ec = socks5::make_error_code(socks5::error::authentication_failed);
goto end;
}
}
//else if (method == socks5::method::iana)
//{
// ec = socks5::make_error_code(socks5::error::unsupported_method);
// goto end;
//}
//else if (method == socks5::method::reserved)
//{
// ec = socks5::make_error_code(socks5::error::unsupported_method);
// goto end;
//}
else if (method == socks5::method::noacceptable)
{
ec = socks5::make_error_code(socks5::error::no_acceptable_methods);
goto end;
}
else
{
ec = socks5::make_error_code(socks5::error::no_acceptable_methods);
goto end;
}
stream->consume(stream->size());
// the address field contains a fully-qualified domain name. The first
// octet of the address field contains the number of octets of name that
// follow, there is no terminating NUL octet.
buffer = stream->prepare(1 + 1 + 1 + 1 + (std::max)(16, int(host_.size() + 1)) + 2);
p = static_cast<char*>(buffer.data());
write(p, std::uint8_t(0x05)); // VER 5.
write(p, std::uint8_t(detail::to_underlying(sock5_->command()))); // CMD CONNECT .
write(p, std::uint8_t(0x00)); // RSV.
// ATYP
endpoint = asio::ip::make_address(host_, ec);
if (ec)
{
ASIO2_ASSERT(host_.size() <= std::size_t(0xff));
// real length
bytes = 1 + 1 + 1 + 1 + 1 + host_.size() + 2;
// type is domain
write(p, std::uint8_t(0x03));
// domain size
write(p, std::uint8_t(host_.size()));
// domain name
std::copy(host_.begin(), host_.end(), p);
p += host_.size();
}
else
{
if /**/ (endpoint.is_v4())
{
// real length
bytes = 1 + 1 + 1 + 1 + 4 + 2;
// type is ipv4
write(p, std::uint8_t(0x01));
write(p, std::uint32_t(endpoint.to_v4().to_uint()));
}
else if (endpoint.is_v6())
{
// real length
bytes = 1 + 1 + 1 + 1 + 16 + 2;
// type is ipv6
write(p, std::uint8_t(0x04));
auto addr_bytes = endpoint.to_v6().to_bytes();
std::copy(addr_bytes.begin(), addr_bytes.end(), p);
p += 16;
}
else
{
ASIO2_ASSERT(false);
}
}
// port
write(p, std::uint16_t(std::strtoul(port_.data(), nullptr, 10)));
stream->commit(bytes);
ASIO_CORO_YIELD
asio::async_write(socket_, strbuf, asio::transfer_exactly(bytes), std::move(*this));
if (ec)
goto end;
// The SOCKS request information is sent by the client as soon as it has
// established a connection to the SOCKS server, and completed the
// authentication negotiations. The server evaluates the request, and
// returns a reply formed as follows:
//
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
//
// Where:
//
// o VER protocol version: X'05'
// o REP Reply field:
// o X'00' succeeded
// o X'01' general SOCKS server failure
// o X'02' connection not allowed by ruleset
// o X'03' Network unreachable
// o X'04' Host unreachable
// o X'05' Connection refused
// o X'06' TTL expired
// o X'07' Command not supported
// o X'08' Address type not supported
// o X'09' to X'FF' unassigned
// o RSV RESERVED
// o ATYP address type of following address
stream->consume(stream->size());
// 1. read the first 5 bytes : VER REP RSV ATYP [LEN]
ASIO_CORO_YIELD
asio::async_read(socket_, strbuf, asio::transfer_exactly(5), std::move(*this));
if (ec)
goto end;
p = const_cast<char*>(static_cast<const char*>(stream->data().data()));
// VER
if (std::uint8_t ver = read<std::uint8_t>(p); ver != std::uint8_t(0x05))
{
ec = socks5::make_error_code(socks5::error::unsupported_version);
goto end;
}
// REP
switch (read<std::uint8_t>(p))
{
case std::uint8_t(0x00): ec = {} ; break;
case std::uint8_t(0x02): ec = asio::error::no_permission ; break;
case std::uint8_t(0x03): ec = asio::error::network_unreachable ; break;
case std::uint8_t(0x04): ec = asio::error::host_unreachable ; break;
case std::uint8_t(0x05): ec = asio::error::connection_refused ; break;
case std::uint8_t(0x06): ec = asio::error::timed_out ; break;
case std::uint8_t(0x08): ec = asio::error::address_family_not_supported ; break;
case std::uint8_t(0x01): ec = socks5::make_error_code(socks5::error::general_socks_server_failure) ; break;
case std::uint8_t(0x07): ec = socks5::make_error_code(socks5::error::command_not_supported) ; break;
case std::uint8_t(0x09): ec = socks5::make_error_code(socks5::error::unassigned) ; break;
default: ec = socks5::make_error_code(socks5::error::unassigned) ; break;
}
if (ec)
goto end;
// skip RSV.
read<std::uint8_t>(p);
addr_type = read<std::uint8_t>(p); // ATYP
addr_size = read<std::uint8_t>(p); // [LEN]
// ATYP
switch (addr_type)
{
case std::uint8_t(0x01): bytes = 4 + 2 - 1; break; // IP V4 address: X'01'
case std::uint8_t(0x03): bytes = addr_size + 2 - 0; break; // DOMAINNAME: X'03'
case std::uint8_t(0x04): bytes = 16 + 2 - 1; break; // IP V6 address: X'04'
default:
{
ec = socks5::make_error_code(socks5::error::general_failure);
goto end;
}
}
stream->consume(stream->size());
ASIO_CORO_YIELD
asio::async_read(socket_, strbuf, asio::transfer_exactly(bytes), std::move(*this));
if (ec)
goto end;
p = const_cast<char*>(static_cast<const char*>(stream->data().data()));
switch (addr_type)
{
case std::uint8_t(0x01): // IP V4 address: X'01'
{
std::uint8_t addr[4]{ 0 };
addr[0] = addr_size;
addr[1] = read<std::uint8_t>(p);
addr[2] = read<std::uint8_t>(p);
addr[3] = read<std::uint8_t>(p);
if (is_little_endian())
{
swap_bytes<4>(reinterpret_cast<std::uint8_t *>(addr));
}
std::uint16_t port = read<std::uint16_t>(p);
detail::ignore_unused(addr, port);
}
break;
case std::uint8_t(0x03): // DOMAINNAME: X'03'
{
std::string addr;
addr.resize(addr_size);
std::copy(p, p + addr_size, addr.data());
p += addr_size;
std::uint16_t port = read<std::uint16_t>(p);
detail::ignore_unused(addr, port);
}
break;
case std::uint8_t(0x04): // IP V6 address: X'04'
{
std::uint8_t addr[16]{ 0 };
addr[0] = addr_size;
for (int i = 1; i < 16; i++)
{
addr[i] = read<std::uint8_t>(p);
}
std::uint16_t port = read<std::uint16_t>(p);
detail::ignore_unused(addr, port);
}
break;
}
ec = {};
end:
handler_(ec);
}
}
};
// C++17 class template argument deduction guides
template<class SKT, class S5Opt, class H>
socks5_server_accept_op(asio::io_context&, std::string, std::string,
SKT&, S5Opt, H)->socks5_server_accept_op<SKT, S5Opt, H>;
template<class derived_t, class args_t>
class socks5_server_impl
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
/**
* @brief constructor
*/
socks5_server_impl() {}
/**
* @brief destructor
*/
~socks5_server_impl() = default;
protected:
template<typename C>
inline void _socks5_init(std::shared_ptr<ecs_t<C>>& ecs)
{
detail::ignore_unused(ecs);
}
template<typename C>
inline void _socks5_start(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = static_cast<derived_t&>(*this);
if constexpr (ecs_helper::has_socks5<C>())
{
}
else
{
ASIO2_ASSERT(!get_last_error());
derive._handle_proxy(error_code{}, std::move(this_ptr), std::move(ecs));
}
}
inline void _socks5_stop()
{
}
};
}
#endif // !__ASIO2_SOCKS5_SERVER_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : mqtt_cpp/include/mqtt/broker/retained_messages.hpp
*/
#ifndef __ASIO2_MQTT_RETAINED_MESSAGES_HPP__
#define __ASIO2_MQTT_RETAINED_MESSAGES_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <algorithm>
#include <optional>
#include <deque>
#include <asio2/base/detail/shared_mutex.hpp>
#include <asio2/mqtt/message.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
namespace asio2::mqtt
{
template<typename Value>
class retained_messages
{
public:
using key_type = std::pair<std::size_t, std::string_view>;
struct hasher
{
inline std::size_t operator()(key_type const& pair) const noexcept
{
std::size_t v = asio2::detail::fnv1a_hash<std::size_t>(
(const unsigned char*)(std::addressof(pair.first)), sizeof(std::size_t));
return asio2::detail::fnv1a_hash<std::size_t>(v,
(const unsigned char*)(pair.second.data()), pair.second.size());
}
};
protected:
// Exceptions used
static void throw_max_stored_topics()
{
throw std::overflow_error("Retained map maximum number of topics reached");
}
static void throw_no_wildcards_allowed()
{
throw std::runtime_error("Retained map no wildcards allowed in retained topic name");
}
static constexpr std::size_t root_parent_id = 0;
static constexpr std::size_t root_node_id = 1;
static constexpr std::size_t max_node_id = (std::numeric_limits<std::size_t>::max)();
struct path_entry
{
std::size_t parent_id;
std::string_view name;
std::size_t id;
std::size_t count = 1;
static constexpr std::size_t max_count = (std::numeric_limits<std::size_t>::max)();
// Increase the count for this node
inline void increase_count()
{
if (count == max_count)
{
throw_max_stored_topics();
}
++count;
}
// Decrease the count for this node
inline void decrease_count()
{
ASIO2_ASSERT(count >= 1);
--count;
}
std::optional<Value> value;
path_entry(std::size_t parent_id, std::string_view name, std::size_t id)
: parent_id(parent_id)
, name(name)
, id(id)
{ }
};
using map_type = std::unordered_map<key_type, path_entry, hasher>;
using map_iterator = typename map_type::iterator;
using map_const_iterator = typename map_type::const_iterator;
/// use rwlock to make thread safe
mutable asio2::shared_mutexer retained_mutex_;
std::unordered_map <key_type, path_entry, hasher> map_ ASIO2_GUARDED_BY(retained_mutex_);
std::unordered_multimap<std::size_t, path_entry* > wildcard_map_ ASIO2_GUARDED_BY(retained_mutex_);
std::size_t map_size ASIO2_GUARDED_BY(retained_mutex_);
std::size_t next_node_id ASIO2_GUARDED_BY(retained_mutex_);
inline map_iterator create_topic(std::string_view topic_name) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
map_iterator parent = get_root();
topic_filter_tokenizer(topic_name, [this, &parent](std::string_view t) mutable
{
return this->create_topic_subfun(parent, t);
});
return parent;
}
inline bool create_topic_subfun(map_iterator& parent, std::string_view t) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
if (t == "+" || t == "#")
{
throw_no_wildcards_allowed();
}
std::size_t parent_id = parent->second.id;
map_iterator it = map_.find(key_type(parent_id, t));
if (it == map_.end())
{
it = map_.emplace(
key_type(parent_id, t),
path_entry(parent_id, t, next_node_id++)
).first;
wildcard_map_.emplace(parent_id, std::addressof(it->second));
if (next_node_id == max_node_id)
{
throw_max_stored_topics();
}
}
else
{
it->second.increase_count();
}
parent = it;
return true;
}
inline std::vector<map_iterator> find_topic(std::string_view topic_name) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::vector<map_iterator> path;
map_iterator parent = get_root();
topic_filter_tokenizer(topic_name, [this, &path, &parent](std::string_view t) mutable
{
return this->find_topic_subfun(path, parent, t);
});
return path;
}
inline bool find_topic_subfun(std::vector<map_iterator>& path, map_iterator& parent, std::string_view t)
ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
auto it = map_.find(key_type(parent->second.id, t));
if (it == map_.end())
{
path.clear();
return false;
}
path.push_back(it);
parent = it;
return true;
}
// Match all underlying topics when a hash entry is matched
// perform a breadth-first iteration over all items in the tree below
template<typename Output>
inline void match_hash_entries(std::size_t parent_id, Output&& callback, bool ignore_system)
ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::deque<std::size_t> ids;
ids.push_back(parent_id);
std::deque<std::size_t> new_ids;
while (!ids.empty())
{
new_ids.resize(0);
for (auto it : ids)
{
auto range = wildcard_map_.equal_range(it);
for (auto i = range.first; i != range.second && i->second->parent_id == it; ++i)
{
// Should we ignore system matches
if (!ignore_system || i->second->name.empty() || i->second->name[0] != '$')
{
if (i->second->value)
{
callback(i->second->value.value());
}
new_ids.push_back(i->second->id);
}
}
}
// Ignore system only on first level
ignore_system = false;
std::swap(ids, new_ids);
}
}
// Find all topics that match the specified topic filter
template<typename Output>
inline void find_match(std::string_view topic_filter, Output&& callback) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::deque<map_iterator> iters;
iters.push_back(get_root());
std::deque<map_iterator> new_iters;
topic_filter_tokenizer(topic_filter,
[this, &iters, &new_iters, &callback](std::string_view t) mutable
{
return this->find_match_subfun(iters, new_iters, callback, t);
});
for (auto& it : iters)
{
if (it->second.value)
{
callback(it->second.value.value());
}
}
}
template<typename Output>
inline bool find_match_subfun(
std::deque<map_iterator>& iters, std::deque<map_iterator>& new_iters, Output& callback, std::string_view t)
ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
new_iters.resize(0);
for (auto& it : iters)
{
std::size_t parent_id = it->second.id;
if (t == std::string_view("+"))
{
auto range = wildcard_map_.equal_range(parent_id);
for (auto i = range.first; i != range.second && i->second->parent_id == parent_id; ++i)
{
if (parent_id != root_node_id || i->second->name.empty() || i->second->name[0] != '$')
{
auto j = map_.find(key_type(i->second->parent_id, i->second->name));
ASIO2_ASSERT(j != map_.end());
new_iters.push_back(j);
}
else
{
break;
}
}
}
else if (t == std::string_view("#"))
{
match_hash_entries(parent_id, callback, parent_id == root_node_id);
return false;
}
else
{
map_iterator i = map_.find(key_type(parent_id, t));
if (i != map_.end())
{
new_iters.push_back(i);
}
}
}
std::swap(new_iters, iters);
return !iters.empty();
}
// Remove a value at the specified topic name
inline std::size_t erase_topic(std::string_view topic_name) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
auto path = find_topic(topic_name);
// Reset the value if there is actually something stored
if (!path.empty() && path.back()->second.value)
{
path.back()->second.value = std::nullopt;
// Do iterators stay valid when erasing ? I think they do ?
for (auto iter : path)
{
iter->second.decrease_count();
if (iter->second.count == 0)
{
auto range = wildcard_map_.equal_range(std::get<0>(iter->first));
for (auto it = range.first; it != range.second; ++it)
{
if (std::addressof(iter->second) == it->second)
{
wildcard_map_.erase(it);
break;
}
}
map_.erase(iter);
}
}
return 1;
}
return 0;
}
// Increase the number of topics for this path
inline void increase_topics(std::vector<map_iterator> const &path) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
for (auto& it : path)
{
it->second.increase_count();
}
}
// Increase the map size (total number of topics stored)
inline void increase_map_size() ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
if (map_size == (std::numeric_limits<decltype(map_size)>::max)())
{
throw_max_stored_topics();
}
++map_size;
}
// Decrease the map size (total number of topics stored)
inline void decrease_map_size(std::size_t count) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
ASIO2_ASSERT(map_size >= count);
map_size -= count;
}
inline void init_map() ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
map_size = 0;
// Create the root node
auto it = map_.emplace(key_type(root_parent_id, ""),
path_entry(root_parent_id, "", root_node_id)).first;
next_node_id = root_node_id + 1;
//
wildcard_map_.emplace(root_parent_id, std::addressof(it->second));
}
inline map_iterator get_root() ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
return map_.find(key_type(root_parent_id, ""));
}
public:
retained_messages()
{
init_map();
}
// Insert a value at the specified topic name
template<typename V>
inline std::size_t insert_or_assign(std::string_view topic_name, V&& value)
{
asio2::unique_locker g(this->retained_mutex_);
auto path = this->find_topic(topic_name);
if (path.empty())
{
auto new_topic = this->create_topic(topic_name);
new_topic->second.value.emplace(std::forward<V>(value));
increase_map_size();
return 1;
}
if (!path.back()->second.value)
{
this->increase_topics(path);
path.back()->second.value.emplace(std::forward<V>(value));
increase_map_size();
return 1;
}
// replace the value
path.back()->second.value.emplace(std::forward<V>(value));
return 0;
}
// Find all stored topics that math the specified topic_filter
template<typename Output>
inline void find(std::string_view topic_filter, Output&& callback)
{
asio2::shared_locker g(this->retained_mutex_);
find_match(topic_filter, std::forward<Output>(callback));
}
// Remove a stored value at the specified topic name
inline std::size_t erase(std::string_view topic_name)
{
asio2::unique_locker g(this->retained_mutex_);
auto result = erase_topic(topic_name);
decrease_map_size(result);
return result;
}
inline std::size_t size() const
{
asio2::shared_locker g(this->retained_mutex_);
return map_size;
}
inline std::size_t internal_size() const
{
asio2::shared_locker g(this->retained_mutex_);
return map_.size();
}
// Clear all topics
inline void clear()
{
asio2::unique_locker g(this->retained_mutex_);
map_.clear();
wildcard_map_.clear();
init_map();
}
// Dump debug information
template<typename Output>
inline void dump(Output &out)
{
asio2::shared_locker g(this->retained_mutex_);
for (auto const&[k, v] : map_)
{
std::ignore = k;
out << v.parent_id << " " << v.name << " " << (v.value ? "init" : "-")
<< " " << v.count << std::endl;
}
}
};
// A collection of messages that have been retained in
// case clients add a new subscription to the associated topics.
struct rmnode
{
template<class Message>
explicit rmnode(Message&& msg, std::shared_ptr<asio::steady_timer> expiry_timer)
: message(std::forward<Message>(msg))
, message_expiry_timer(std::move(expiry_timer))
{
}
mqtt::message message;
std::shared_ptr<asio::steady_timer> message_expiry_timer;
};
}
#endif // !__ASIO2_MQTT_RETAINED_MESSAGES_HPP__
<file_sep>//#include <asio2/asio2.hpp>
#include <iostream>
#include <asio2/udp/udp_server.hpp>
int main()
{
std::string_view host = "0.0.0.0";
std::string_view port = "8036";
asio2::udp_server server;
server.bind_recv([](std::shared_ptr<asio2::udp_session>& session_ptr, std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
session_ptr->async_send(data);
}).bind_connect([](auto & session_ptr)
{
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([](auto & session_ptr)
{
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
}).bind_handshake([](auto & session_ptr)
{
if (asio2::get_last_error())
printf("client handshake failure : %s %u %d %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("client handshake success : %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port());
}).bind_start([&]()
{
if (asio2::get_last_error())
printf("start udp server kcp failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("start udp server kcp success : %s %u\n",
server.listen_address().c_str(), server.listen_port());
}).bind_stop([&]()
{
printf("stop udp server kcp : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_init([&]()
{
//// Join the multicast group. you can set this option in the on_init(_fire_init) function.
//server.acceptor().set_option(
// // for ipv6, the host must be a ipv6 address like 0::0
// asio::ip::multicast::join_group(asio::ip::make_address("fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:1234")));
// // for ipv4, the host must be a ipv4 address like 0.0.0.0
// //asio::ip::multicast::join_group(asio::ip::make_address("192.168.127.12")));
});
// to use kcp, the last param must be : asio2::use_kcp
server.start(host, port, asio2::use_kcp);
while (std::getchar() != '\n');
server.stop();
return 0;
}
<file_sep>// (C) Copyright <NAME> 2009.
// (C) Copyright <NAME> 2001 - 2003.
// (C) Copyright <NAME> 2001 - 2003.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// symbian specific config options:
#define BHO_PLATFORM "Symbian"
#define BHO_SYMBIAN 1
#if defined(__S60_3X__)
// Open C / C++ plugin was introdused in this SDK, earlier versions don't have CRT / STL
# define BHO_S60_3rd_EDITION_FP2_OR_LATER_SDK
// make sure we have __GLIBC_PREREQ if available at all
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif// boilerplate code:
# define BHO_HAS_UNISTD_H
# include <asio2/bho/config/detail/posix_features.hpp>
// S60 SDK defines _POSIX_VERSION as POSIX.1
# ifndef BHO_HAS_STDINT_H
# define BHO_HAS_STDINT_H
# endif
# ifndef BHO_HAS_GETTIMEOFDAY
# define BHO_HAS_GETTIMEOFDAY
# endif
# ifndef BHO_HAS_DIRENT_H
# define BHO_HAS_DIRENT_H
# endif
# ifndef BHO_HAS_SIGACTION
# define BHO_HAS_SIGACTION
# endif
# ifndef BHO_HAS_PTHREADS
# define BHO_HAS_PTHREADS
# endif
# ifndef BHO_HAS_NANOSLEEP
# define BHO_HAS_NANOSLEEP
# endif
# ifndef BHO_HAS_SCHED_YIELD
# define BHO_HAS_SCHED_YIELD
# endif
# ifndef BHO_HAS_PTHREAD_MUTEXATTR_SETTYPE
# define BHO_HAS_PTHREAD_MUTEXATTR_SETTYPE
# endif
# ifndef BHO_HAS_LOG1P
# define BHO_HAS_LOG1P
# endif
# ifndef BHO_HAS_EXPM1
# define BHO_HAS_EXPM1
# endif
# ifndef BHO_POSIX_API
# define BHO_POSIX_API
# endif
// endianess support
# include <sys/endian.h>
// Symbian SDK provides _BYTE_ORDER instead of __BYTE_ORDER
# ifndef __LITTLE_ENDIAN
# ifdef _LITTLE_ENDIAN
# define __LITTLE_ENDIAN _LITTLE_ENDIAN
# else
# define __LITTLE_ENDIAN 1234
# endif
# endif
# ifndef __BIG_ENDIAN
# ifdef _BIG_ENDIAN
# define __BIG_ENDIAN _BIG_ENDIAN
# else
# define __BIG_ENDIAN 4321
# endif
# endif
# ifndef __BYTE_ORDER
# define __BYTE_ORDER __LITTLE_ENDIAN // Symbian is LE
# endif
// Known limitations
# define BHO_ASIO_DISABLE_SERIAL_PORT
# define BHO_DATE_TIME_NO_LOCALE
# define BHO_NO_STD_WSTRING
# define BHO_EXCEPTION_DISABLE
# define BHO_NO_EXCEPTIONS
#else // TODO: More platform support e.g. UIQ
# error "Unsuppoted Symbian SDK"
#endif
#if defined(__WINSCW__) && !defined(BHO_DISABLE_WIN32)
# define BHO_DISABLE_WIN32 // winscw defines WIN32 macro
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#if !defined(BHO_PREDEF_LIBRARY_H) || defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BHO_PREDEF_LIBRARY_H
#define BHO_PREDEF_LIBRARY_H
#endif
#include <asio2/bho/predef/library/c.h>
#include <asio2/bho/predef/library/std.h>
#endif
<file_sep>//
// Copyright (c) 2016-2019 <NAME> (<EMAIL>)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BHO_BEAST_CORE_DETAIL_CONFIG_HPP
#define BHO_BEAST_CORE_DETAIL_CONFIG_HPP
// Available to every header
#include <asio2/bho/config.hpp>
#include <asio2/bho/version.hpp>
#include <asio2/bho/core/ignore_unused.hpp>
#include <asio2/bho/static_assert.hpp>
#include <asio2/external/asio.hpp>
namespace bho {
namespace beast {
#ifdef ASIO_STANDALONE
namespace net = ::asio;
#else
namespace net = ::boost::asio;
#endif
} // beast
} // bho
/*
_MSC_VER and _MSC_FULL_VER by version:
14.0 (2015) 1900 190023026
14.0 (2015 Update 1) 1900 190023506
14.0 (2015 Update 2) 1900 190023918
14.0 (2015 Update 3) 1900 190024210
*/
#if defined(BHO_MSVC)
# if BHO_MSVC_FULL_VER < 190024210
# error Beast requires C++11: Visual Studio 2015 Update 3 or later needed
# endif
#elif defined(BHO_GCC)
# if(BHO_GCC < 40801)
# error Beast requires C++11: gcc version 4.8 or later needed
# endif
#else
# if \
defined(BHO_NO_CXX11_DECLTYPE) || \
defined(BHO_NO_CXX11_HDR_TUPLE) || \
defined(BHO_NO_CXX11_TEMPLATE_ALIASES) || \
defined(BHO_NO_CXX11_VARIADIC_TEMPLATES)
# error Beast requires C++11: a conforming compiler is needed
# endif
#endif
#define BHO_BEAST_DEPRECATION_STRING \
"This is a deprecated interface, #define BHO_BEAST_ALLOW_DEPRECATED to allow it"
#ifndef BHO_BEAST_ASSUME
# ifdef BHO_GCC
# define BHO_BEAST_ASSUME(cond) \
do { if (!(cond)) __builtin_unreachable(); } while (0)
# else
# define BHO_BEAST_ASSUME(cond) do { } while(0)
# endif
#endif
// Default to a header-only implementation. The user must specifically
// request separate compilation by defining BHO_BEAST_SEPARATE_COMPILATION
#ifndef BEAST_HEADER_ONLY
# ifndef BHO_BEAST_SEPARATE_COMPILATION
# define BEAST_HEADER_ONLY 1
# endif
#endif
#if BHO_BEAST_DOXYGEN
# define BHO_BEAST_DECL
#elif defined(BEAST_HEADER_ONLY)
# define BHO_BEAST_DECL inline
#else
# define BHO_BEAST_DECL
#endif
#ifndef BHO_BEAST_ASYNC_RESULT1
#define BHO_BEAST_ASYNC_RESULT1(type) \
ASIO_INITFN_AUTO_RESULT_TYPE(type, void(::bho::beast::error_code))
#endif
#ifndef BHO_BEAST_ASYNC_RESULT2
#define BHO_BEAST_ASYNC_RESULT2(type) \
ASIO_INITFN_AUTO_RESULT_TYPE(type, void(::bho::beast::error_code, ::std::size_t))
#endif
#ifndef BHO_BEAST_ASYNC_TPARAM1
#define BHO_BEAST_ASYNC_TPARAM1 ASIO_COMPLETION_TOKEN_FOR(void(::bho::beast::error_code))
#endif
#ifndef BHO_BEAST_ASYNC_TPARAM2
#define BHO_BEAST_ASYNC_TPARAM2 ASIO_COMPLETION_TOKEN_FOR(void(::bho::beast::error_code, ::std::size_t))
#endif
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_COMPAQ_H
#define BHO_PREDEF_COMPILER_COMPAQ_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_DEC`
http://www.openvms.compaq.com/openvms/brochures/deccplus/[Compaq C/{CPP}] compiler.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__DECCXX+` | {predef_detection}
| `+__DECC+` | {predef_detection}
| `+__DECCXX_VER+` | V.R.P
| `+__DECC_VER+` | V.R.P
|===
*/ // end::reference[]
#define BHO_COMP_DEC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__DECC) || defined(__DECCXX)
# if !defined(BHO_COMP_DEC_DETECTION) && defined(__DECCXX_VER)
# define BHO_COMP_DEC_DETECTION BHO_PREDEF_MAKE_10_VVRR0PP00(__DECCXX_VER)
# endif
# if !defined(BHO_COMP_DEC_DETECTION) && defined(__DECC_VER)
# define BHO_COMP_DEC_DETECTION BHO_PREDEF_MAKE_10_VVRR0PP00(__DECC_VER)
# endif
# if !defined(BHO_COMP_DEC_DETECTION)
# define BHO_COMP_DEC_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_COMP_DEC_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_DEC_EMULATED BHO_COMP_DEC_DETECTION
# else
# undef BHO_COMP_DEC
# define BHO_COMP_DEC BHO_COMP_DEC_DETECTION
# endif
# define BHO_COMP_DEC_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_DEC_NAME "Compaq C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_DEC,BHO_COMP_DEC_NAME)
#ifdef BHO_COMP_DEC_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_DEC_EMULATED,BHO_COMP_DEC_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_SERVER_HPP__
#define __ASIO2_MQTT_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_server.hpp>
#include <asio2/mqtt/mqtt_session.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
template<class derived_t, class session_t>
class mqtt_server_impl_t
: public tcp_server_impl_t<derived_t, session_t>
, public mqtt_options
, public mqtt_invoker_t <session_t, typename session_t::args_type>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
public:
using super = tcp_server_impl_t <derived_t, session_t>;
using self = mqtt_server_impl_t<derived_t, session_t>;
using session_type = session_t;
using super::async_send;
public:
/**
* @brief constructor
*/
explicit mqtt_server_impl_t(
std::size_t init_buf_size = tcp_frame_size,
std::size_t max_buf_size = mqtt::max_payload,
std::size_t concurrency = default_concurrency() + 1 // The 1 is used for tcp acceptor
)
: super(init_buf_size, max_buf_size, concurrency)
, mqtt_options()
, mqtt_invoker_t<session_t, typename session_t::args_type>()
, broker_state_(*this, *this)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit mqtt_server_impl_t(
std::size_t init_buf_size,
std::size_t max_buf_size,
Scheduler&& scheduler
)
: super(init_buf_size, max_buf_size, std::forward<Scheduler>(scheduler))
, mqtt_options()
, mqtt_invoker_t<session_t, typename session_t::args_type>()
, broker_state_(*this, *this)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit mqtt_server_impl_t(Scheduler&& scheduler)
: mqtt_server_impl_t(tcp_frame_size, mqtt::max_payload, std::forward<Scheduler>(scheduler))
{
}
/**
* @brief destructor
*/
~mqtt_server_impl_t()
{
this->stop();
}
/**
* @brief start the server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param service - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
bool start(String&& host, StrOrInt&& service, Args&&... args)
{
return this->derived()._do_start(
std::forward<String>(host), std::forward<StrOrInt>(service),
ecs_helper::make_ecs(asio::transfer_at_least(1),
mqtt::mqtt_match_role, std::forward<Args>(args)...));
}
protected:
template<typename C>
inline void _handle_start(
error_code ec, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._bind_default_mqtt_handler(ecs);
return super::_handle_start(std::move(ec), std::move(this_ptr), std::move(ecs));
}
inline void _post_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state)
{
asio::dispatch(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, this_ptr]() mutable
{
this->mqtt_sessions().clear_mqtt_sessions();
}));
super::_post_stop(ec, std::move(this_ptr), old_state);
}
template<typename C>
inline void _bind_default_mqtt_handler(std::shared_ptr<ecs_t<C>>& ecs)
{
detail::ignore_unused(ecs);
// must set default callback for every mqtt message.
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::connect ))) this->on_connect ([](std::shared_ptr<session_t>&, mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::connack ))) this->on_connack ([](std::shared_ptr<session_t>&, mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::publish ))) this->on_publish ([](std::shared_ptr<session_t>&, mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::puback ))) this->on_puback ([](std::shared_ptr<session_t>&, mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pubrec ))) this->on_pubrec ([](std::shared_ptr<session_t>&, mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pubrel ))) this->on_pubrel ([](std::shared_ptr<session_t>&, mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pubcomp ))) this->on_pubcomp ([](std::shared_ptr<session_t>&, mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::subscribe ))) this->on_subscribe ([](std::shared_ptr<session_t>&, mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::suback ))) this->on_suback ([](std::shared_ptr<session_t>&, mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::unsubscribe))) this->on_unsubscribe([](std::shared_ptr<session_t>&, mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::unsuback ))) this->on_unsuback ([](std::shared_ptr<session_t>&, mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pingreq ))) this->on_pingreq ([](std::shared_ptr<session_t>&, mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pingresp ))) this->on_pingresp ([](std::shared_ptr<session_t>&, mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::disconnect ))) this->on_disconnect ([](std::shared_ptr<session_t>&, mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::auth ))) this->on_auth ([](std::shared_ptr<session_t>&, mqtt::message&, mqtt::message&) mutable {});
}
template<typename... Args>
inline std::shared_ptr<session_t> _make_session(Args&&... args)
{
std::shared_ptr<session_t> p = super::_make_session(std::forward<Args>(args)..., this->broker_state_);
// Copy the parameter configuration of user calls for the "server" to each "session"
p->_mqtt_options_copy_from(*this);
return p;
}
inline auto& invoker () noexcept { return this->broker_state_.invoker_ ; }
inline auto& mqtt_sessions () noexcept { return this->broker_state_.mqtt_sessions_ ; }
inline auto& subs_map () noexcept { return this->broker_state_.subs_map_ ; }
inline auto& shared_targets () noexcept { return this->broker_state_.shared_targets_ ; }
inline auto& retained_messages() noexcept { return this->broker_state_.retained_messages_; }
public:
inline auto& security () noexcept { return this->broker_state_.security_; }
inline auto& get_security () noexcept { return this->broker_state_.security_; }
protected:
///
mqtt::broker_state<session_t, typename session_t::args_type> broker_state_;
};
}
namespace asio2
{
template<class derived_t, class session_t>
using mqtt_server_impl_t = detail::mqtt_server_impl_t<derived_t, session_t>;
template<class session_t>
class mqtt_server_t : public detail::mqtt_server_impl_t<mqtt_server_t<session_t>, session_t>
{
public:
using detail::mqtt_server_impl_t<mqtt_server_t<session_t>, session_t>::mqtt_server_impl_t;
};
using mqtt_server = mqtt_server_t<mqtt_session>;
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_MQTT_SERVER_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : mqtt_cpp/include/mqtt/broker/subscription_map.hpp
*/
#ifndef __ASIO2_MQTT_SUBSCRIPTION_MAP_HPP__
#define __ASIO2_MQTT_SUBSCRIPTION_MAP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <optional>
#include <vector>
#include <cinttypes>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
#include <asio2/mqtt/detail/mqtt_topic_util.hpp>
#include <asio2/mqtt/idmgr.hpp>
#include <asio2/mqtt/message.hpp>
namespace asio2::mqtt
{
template<
class Key, // client id
class Value, // subscribe data
class Container = std::unordered_map<Key, Value>
>
class subscription_map
{
public:
using key_type = std::pair<std::size_t, std::string_view>;
struct hasher
{
inline std::size_t operator()(key_type const& pair) const noexcept
{
std::size_t v = asio2::detail::fnv1a_hash<std::size_t>(
(const unsigned char*)(std::addressof(pair.first)), sizeof(std::size_t));
return asio2::detail::fnv1a_hash<std::size_t>(v,
(const unsigned char*)(pair.second.data()), pair.second.size());
}
};
struct node
{
std::size_t id;
std::size_t count = 1;
bool has_plus = false;
bool has_hash = false;
key_type parent;
std::vector<char> tokenize; // vector has no SSO
Container subscribers;
inline std::string_view tokenize_view()
{
return std::string_view{ tokenize.data(), tokenize.size() };
}
explicit node(std::size_t i, key_type p, std::string_view t) : id(i), parent(p)
{
tokenize.resize(t.size());
std::memcpy((void*)tokenize.data(), (const void*)t.data(), t.size());
}
};
using map_type = std::unordered_map<key_type, node, hasher>;
using map_iterator = typename map_type::iterator;
using map_const_iterator = typename map_type::const_iterator;
public:
subscription_map()
{
this->root_node_id_ = idmgr_.get();
ASIO2_ASSERT(this->root_node_id_ == 1);
map_.emplace(root_key_, node(this->root_node_id_, root_key_, ""));
}
// Return the number of registered topic filters
inline std::size_t get_subscribe_count() const
{
return this->subscribe_count_;
}
template<typename Function>
void match(std::string_view topic, Function&& callback)
{
std::vector<map_iterator> iters;
asio2::shared_locker g(this->submap_mutex_);
iters.emplace_back(this->get_root());
topic_filter_tokenizer(topic, [this, &iters, &callback](std::string_view t) mutable
{
return this->match_subfun(iters, callback, t);
});
for (auto& it : iters)
{
for (auto&[k, v] : it->second.subscribers)
{
callback(k, v);
}
}
}
// Insert a key => value at the specified topic filter
// returns the handle and true if key was inserted, false if key was updated
template <typename K, typename V>
std::pair<key_type, bool> insert_or_assign(std::string_view topic_filter, K&& key, V&& val)
{
asio2::unique_locker g(this->submap_mutex_);
std::vector<map_iterator> iters = this->get_nodes_by_topic_filter(topic_filter);
if (iters.empty())
{
iters = this->emplace(topic_filter);
this->emplace_subscriber_node(key, iters.back()->first);
iters.back()->second.subscribers.insert_or_assign(std::forward<K>(key), std::forward<V>(val));
this->increase_subscribe_count();
return std::pair(iters.back()->first, true);
}
else
{
auto& subscribers = iters.back()->second.subscribers;
this->emplace_subscriber_node(key, iters.back()->first);
auto[_1, inserted] = subscribers.insert_or_assign(std::forward<K>(key), std::forward<V>(val));
asio2::ignore_unused(_1, inserted);
if (inserted)
{
this->increase_subscriptions(iters);
this->increase_subscribe_count();
}
return std::pair(iters.back()->first, inserted);
}
}
// Insert a key => value with a handle to the topic filter
// returns the handle and true if key was inserted, false if key was updated
template <typename K, typename V>
std::pair<key_type, bool> insert_or_assign(key_type const& h, K&& key, V&& val)
{
asio2::unique_locker g(this->submap_mutex_);
auto it = this->map_.find(h);
if (it == this->map_.end())
{
return std::pair(key_type(0, "null"), false);
}
auto& subscribers = it->second.subscribers;
this->emplace_subscriber_node(key, it->first);
auto[_1, inserted] = subscribers.insert_or_assign(std::forward<K>(key), std::forward<V>(val));
asio2::ignore_unused(_1, inserted);
if (inserted)
{
this->increase_subscriptions(h);
this->increase_subscribe_count();
}
return std::pair(h, inserted);
}
// returns the number of removed elements
std::size_t erase(key_type const& h, Key const& key)
{
asio2::unique_locker g(this->submap_mutex_);
auto it = this->map_.find(h);
if (it == this->map_.end())
{
return 0;
}
this->erase_subscriber_node(key, h);
auto amount = it->second.subscribers.erase(key);
if (amount)
{
std::vector<map_iterator> v = this->handle_to_iterators(h);
this->erase(v);
this->decrease_subscribe_count();
}
return amount;
}
// returns the number of removed elements
std::size_t erase(std::string_view topic_filter, Key const& key)
{
asio2::unique_locker g(this->submap_mutex_);
std::vector<map_iterator> iters = this->get_nodes_by_topic_filter(topic_filter);
if (iters.empty())
{
return 0;
}
this->erase_subscriber_node(key, iters.back()->first);
auto amount = iters.back()->second.subscribers.erase(key);
if (amount)
{
this->decrease_subscribe_count();
this->erase(iters);
}
return amount;
}
// returns the number of removed elements
std::size_t erase(Key const& key)
{
asio2::unique_locker g(this->submap_mutex_);
auto iter = this->subscriber_nodes_.find(key);
if (iter == this->subscriber_nodes_.end())
return 0;
std::size_t total = 0;
for (auto& h : iter->second)
{
auto it = this->map_.find(h);
if (it == this->map_.end())
continue;
auto amount = it->second.subscribers.erase(key);
if (amount)
{
std::vector<map_iterator> v = this->handle_to_iterators(h);
this->erase(v);
this->decrease_subscribe_count();
}
total += amount;
}
this->subscriber_nodes_.erase(key);
return total;
}
protected:
inline map_iterator get_root() ASIO2_NO_THREAD_SAFETY_ANALYSIS { return map_.find(root_key_); };
inline map_const_iterator get_root() const ASIO2_NO_THREAD_SAFETY_ANALYSIS { return map_.find(root_key_); };
// Increase the map size (total number of subscriptions stored)
inline void increase_subscribe_count()
{
++subscribe_count_;
}
// Decrease the map size (total number of subscriptions stored)
inline void decrease_subscribe_count()
{
ASIO2_ASSERT(subscribe_count_ > 0);
--subscribe_count_;
}
inline void increase_subscriptions(key_type const& h)
{
handle_to_iterators(h, [](map_iterator it) mutable
{
it->second.count++;
});
}
// Increase the number of subscriptions for this path
inline void increase_subscriptions(std::vector<map_iterator>& iters)
{
for (auto i : iters)
{
i->second.count++;
}
}
std::optional<key_type> lookup(std::string_view topic_filter)
{
std::vector<map_iterator> iters = this->get_nodes_by_topic_filter(topic_filter);
if (iters.empty())
return std::nullopt;
else
return iters.back()->first;
}
std::vector<map_iterator> emplace(std::string_view topic_filter) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
map_iterator parent = this->get_root();
std::vector<map_iterator> iters;
topic_filter_tokenizer(topic_filter, [this, &iters, &parent](std::string_view t) mutable
{
return emplace_subfun(iters, parent, t);
});
return iters;
}
inline bool emplace_subfun(std::vector<map_iterator>& iters, map_iterator& parent, std::string_view t)
ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
node& pn = parent->second;
auto it = map_.find(key_type(pn.id, t));
if (it == map_.end())
{
node val{ idmgr_.get(), parent->first, t };
key_type key{ pn.id, val.tokenize_view() };
it = map_.emplace(std::move(key), std::move(val)).first;
pn.has_plus |= (t == "+");
pn.has_hash |= (t == "#");
}
else
{
it->second.count++;
}
iters.emplace_back(it);
parent = std::move(it);
return true;
}
void erase(std::vector<map_iterator>& iters) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
bool remove_plus_flag = false;
bool remove_hash_flag = false;
std::reverse(iters.begin(), iters.end());
for (map_iterator& it : iters)
{
node& n = it->second;
if (remove_plus_flag)
{
n.has_plus = false;
remove_plus_flag = false;
}
if (remove_hash_flag)
{
n.has_hash = false;
remove_hash_flag = false;
}
ASIO2_ASSERT(n.count > 0);
n.count--;
if (n.count == 0)
{
remove_plus_flag = (it->first.second == "+");
remove_hash_flag = (it->first.second == "#");
this->idmgr_.release(it->second.id);
// std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::erase
// References and iterators to the erased elements are invalidated.
// Other iterators and references are not invalidated.
map_.erase(it);
}
}
map_iterator root = this->get_root();
if (remove_plus_flag)
{
root->second.has_plus = false;
}
if (remove_hash_flag)
{
root->second.has_hash = false;
}
}
template <typename K>
inline void emplace_subscriber_node(K&& key, key_type node_key) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::unordered_set<key_type, hasher>& node_keys = this->subscriber_nodes_[key];
node_keys.emplace(std::move(node_key));
}
inline void erase_subscriber_node(const Key& key, const key_type& node_key) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::unordered_set<key_type, hasher>& node_keys = this->subscriber_nodes_[key];
node_keys.erase(node_key);
if (node_keys.empty())
{
this->subscriber_nodes_.erase(key);
}
}
std::vector<map_iterator> get_nodes_by_topic_filter(std::string_view topic_filter)
ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::size_t id = this->get_root()->second.id;
std::vector<map_iterator> iters;
topic_filter_tokenizer(topic_filter, [this, &iters, &id](std::string_view t) mutable
{
return this->get_nodes_by_topic_filter_subfun(iters, id, t);
});
return iters;
}
inline bool get_nodes_by_topic_filter_subfun(
std::vector<map_iterator>& iters, std::size_t& id, std::string_view t) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
auto it = map_.find(key_type(id, t));
if (it == map_.end())
{
iters.clear();
return false;
}
id = it->second.id;
iters.emplace_back(it);
return true;
}
template<typename Function>
bool match_subfun(std::vector<map_iterator>& iters, Function& callback, std::string_view t)
ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::vector<map_iterator> new_iters;
for (auto& it : iters)
{
node& pn = it->second;
auto i = this->map_.find(key_type(pn.id, t));
if (i != this->map_.end())
{
new_iters.emplace_back(i);
}
if (pn.has_plus)
{
i = this->map_.find(key_type(pn.id, std::string_view("+")));
if (i != this->map_.end())
{
if (pn.id != this->root_node_id_ || t.empty() || t[0] != '$')
{
new_iters.emplace_back(i);
}
}
}
if (pn.has_hash)
{
i = this->map_.find(key_type(pn.id, std::string_view("#")));
if (i != this->map_.end())
{
if (pn.id != this->root_node_id_ || t.empty() || t[0] != '$')
{
for (auto& [k, v] : i->second.subscribers)
{
callback(k, v);
}
}
}
}
}
std::swap(iters, new_iters);
return !iters.empty();
}
template<typename Function>
void handle_to_iterators(key_type const& h, Function&& callback) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
key_type k = h;
while (k != this->root_key_)
{
auto it = this->map_.find(k);
if (it == this->map_.end())
{
return;
}
callback(it);
k = it->second.parent;
}
}
inline std::vector<map_iterator> handle_to_iterators(key_type const& h) ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::vector<map_iterator> iters;
this->handle_to_iterators(h, [&iters](map_iterator it) mutable
{
iters.emplace_back(it);
});
std::reverse(iters.begin(), iters.end());
return iters;
}
// Get path of topic_filter
std::string handle_to_topic_filter(key_type const& h) const ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::string result;
handle_to_iterators(h, [&result](map_iterator it) mutable
{
if (result.empty())
{
result = std::string(it->first.second);
}
else
{
result.insert(0, "/");
result.insert(0, it->first.second);
}
});
return result;
}
protected:
static constexpr key_type root_key_{ 0, "" };
/// use rwlock to make thread safe
mutable asio2::shared_mutexer submap_mutex_;
std::size_t root_node_id_ = 1;
map_type map_ ASIO2_GUARDED_BY(submap_mutex_);
// Key - client id, Val - all nodes keys for the subscriber
std::unordered_map<Key, std::unordered_set<key_type, hasher>> subscriber_nodes_ ASIO2_GUARDED_BY(submap_mutex_);
// Map size tracks the total number of subscriptions within the map
std::atomic<std::size_t> subscribe_count_ = 0;
mqtt::idmgr<std::set<std::size_t>> idmgr_;
};
}
#endif // !__ASIO2_MQTT_SUBSCRIPTION_MAP_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from : mqtt_cpp/include/mqtt/topic_filter_tokenizer.hpp
*/
#ifndef __ASIO2_MQTT_TOPIC_UTIL_HPP__
#define __ASIO2_MQTT_TOPIC_UTIL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <string>
#include <string_view>
#include <type_traits>
#include <asio2/base/detail/util.hpp>
namespace asio2::mqtt
{
template<typename = void>
inline bool is_topic_name_valid(std::string_view str)
{
// All Topic Names and Topic Filters MUST be at least one character long [MQTT-4.7.3-1]
return ((!str.empty()) && (str.find_first_of("+#") == std::string_view::npos));
}
/**
* @return std::pair<shared_name, topic_filter>
*/
template<typename = void>
inline std::pair<std::string_view, std::string_view> parse_topic_filter(std::string_view topic_filter)
{
using namespace std::literals;
constexpr std::string_view shared_prefix = "$share/"sv;
if (topic_filter.empty())
return { ""sv, ""sv };
if (topic_filter.substr(0, shared_prefix.size()) != shared_prefix)
return { ""sv, std::move(topic_filter) };
// Remove $share/
topic_filter.remove_prefix(shared_prefix.size());
// This is the '/' seperating the subscription group from the actual topic_filter.
std::string_view::size_type idx = topic_filter.find('/');
if (idx == std::string_view::npos)
return { ""sv, ""sv };
// We return the share_name and the topic_filter as buffers that point to the same
// storage. So we grab the substr for "share", and then remove it from topic_filter.
std::string_view share_name = topic_filter.substr(0, idx);
topic_filter.remove_prefix(idx + 1);
if (share_name.empty() || topic_filter.empty())
return { ""sv, ""sv };
return { std::move(share_name), std::move(topic_filter) };
}
static constexpr char topic_filter_separator = '/';
template<typename Iterator>
inline Iterator topic_filter_tokenizer_next(Iterator first, Iterator last)
{
return std::find(first, last, topic_filter_separator);
}
template<typename Iterator, typename Function>
inline std::size_t topic_filter_tokenizer(Iterator&& first, Iterator&& last, Function&& callback)
{
if (first >= last)
{
ASIO2_ASSERT(false);
return static_cast<std::size_t>(0);
}
std::size_t count = static_cast<std::size_t>(1);
auto iter = topic_filter_tokenizer_next(first, last);
while (callback(asio2::detail::to_string_view(first, iter)) && iter != last)
{
first = std::next(iter);
if (first >= last)
break;
iter = topic_filter_tokenizer_next(first, last);
++count;
}
return count;
}
template<typename Function>
inline std::size_t topic_filter_tokenizer(std::string_view str, Function&& callback)
{
return topic_filter_tokenizer(std::begin(str), std::end(str), std::forward<Function>(callback));
}
// TODO: Technically this function is simply wrong, since it's treating the
// topic pattern as if it were an ASCII sequence.
// To make this function correct per the standard, it would be necessary
// to conduct the search for the wildcard characters using a proper
// UTF-8 API to avoid problems of interpreting parts of multi-byte characters
// as if they were individual ASCII characters
constexpr inline bool validate_topic_filter(std::string_view topic_filter)
{
// Confirm the topic pattern is valid before registering it.
// Use rules from http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718106
// All Topic Names and Topic Filters MUST be at least one character long
// Topic Names and Topic Filters are UTF-8 Encoded Strings; they MUST NOT encode to more than 65,535 bytes
if (topic_filter.empty() || (topic_filter.size() > (std::numeric_limits<std::uint16_t>::max)()))
{
return false;
}
for (std::string_view::size_type idx = topic_filter.find_first_of(std::string_view("\0+#", 3));
std::string_view::npos != idx;
idx = topic_filter.find_first_of(std::string_view("\0+#", 3), idx + 1))
{
ASIO2_ASSERT(
('\0' == topic_filter[idx]) ||
('+' == topic_filter[idx]) ||
('#' == topic_filter[idx])
);
if ('\0' == topic_filter[idx])
{
// Topic Names and Topic Filters MUST NOT include the null character (Unicode U+0000)
return false;
}
else if ('+' == topic_filter[idx])
{
/*
* Either must be the first character,
* or be preceeded by a topic seperator.
*/
if ((0 != idx) && ('/' != topic_filter[idx - 1]))
{
return false;
}
/*
* Either must be the last character,
* or be followed by a topic seperator.
*/
if ((topic_filter.size() - 1 != idx) && ('/' != topic_filter[idx + 1]))
{
return false;
}
}
// multilevel wildcard
else if ('#' == topic_filter[idx])
{
/*
* Must be absolute last character.
* Must only be one multi level wild card.
*/
if (idx != topic_filter.size() - 1)
{
return false;
}
/*
* If not the first character, then the
* immediately preceeding character must
* be a topic level separator.
*/
if ((0 != idx) && ('/' != topic_filter[idx - 1]))
{
return false;
}
}
else
{
return false;
}
}
return true;
}
}
#endif // !__ASIO2_MQTT_TOPIC_UTIL_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_HTTP_SESSION_HPP__
#define __ASIO2_HTTP_SESSION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/tcp/tcp_session.hpp>
#include <asio2/http/impl/ws_stream_cp.hpp>
#include <asio2/http/impl/http_send_op.hpp>
#include <asio2/http/impl/http_recv_op.hpp>
#include <asio2/http/impl/ws_send_op.hpp>
#include <asio2/http/detail/http_router.hpp>
namespace asio2::detail
{
struct template_args_http_session : public template_args_tcp_session
{
using stream_t = websocket::stream<typename template_args_tcp_session::socket_t&>;
using body_t = http::string_body;
using buffer_t = beast::flat_buffer;
using send_data_t = std::string_view;
using recv_data_t = std::string_view;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
template<class derived_t, class args_t = template_args_http_session>
class http_session_impl_t
: public tcp_session_impl_t<derived_t, args_t>
, public http_send_op <derived_t, args_t>
, public http_recv_op <derived_t, args_t>
, public ws_stream_cp <derived_t, args_t>
, public ws_send_op <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
public:
using super = tcp_session_impl_t <derived_t, args_t>;
using self = http_session_impl_t<derived_t, args_t>;
using args_type = args_t;
using key_type = std::size_t;
using body_type = typename args_t::body_t;
using buffer_type = typename args_t::buffer_t;
using send_data_t = typename args_t::send_data_t;
using recv_data_t = typename args_t::recv_data_t;
using ws_stream_comp = ws_stream_cp<derived_t, args_t>;
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
explicit http_session_impl_t(
http_router_t<derived_t, args_t> & router,
std::filesystem::path & root_directory,
bool is_arg0_session,
bool support_websocket,
session_mgr_t<derived_t> & sessions,
listener_t & listener,
io_t & rwio,
std::size_t init_buf_size,
std::size_t max_buf_size
)
: super(sessions, listener, rwio, init_buf_size, max_buf_size)
, http_send_op<derived_t, args_t>()
, ws_stream_cp<derived_t, args_t>()
, ws_send_op <derived_t, args_t>()
, req_()
, rep_()
, router_(router)
, root_directory_ (root_directory)
, is_arg0_session_ (is_arg0_session)
, support_websocket_(support_websocket)
{
this->silence_timeout_ = std::chrono::milliseconds(http_silence_timeout);
}
/**
* @brief destructor
*/
~http_session_impl_t()
{
}
protected:
/**
* @brief start the session for prepare to recv/send msg
*/
template<typename C>
inline void start(std::shared_ptr<ecs_t<C>> ecs)
{
this->rep_.set_root_directory(this->root_directory_);
this->rep_.session_ptr_ = this->derived().selfptr();
this->rep_.defer_callback_ = [this, ecs, wptr = std::weak_ptr<derived_t>(this->derived().selfptr())]
() mutable
{
std::shared_ptr<derived_t> this_ptr = wptr.lock();
ASIO2_ASSERT(this_ptr);
if (this_ptr)
{
this->derived()._do_send_http_response(std::move(this_ptr), std::move(ecs), this->rep_.base());
}
};
super::start(std::move(ecs));
}
public:
/**
* @brief get this object hash key,used for session map
*/
inline key_type hash_key() const noexcept
{
return reinterpret_cast<key_type>(this);
}
inline bool is_websocket() noexcept { return (bool(this->websocket_router_)); }
inline bool is_http () noexcept { return (!(this->is_websocket())); }
/**
* @brief get the request object, same as get_request
*/
inline const http::web_request & request() noexcept { return this->req_; }
/**
* @brief get the response object, same as get_response
*/
inline const http::web_response& response() noexcept { return this->rep_; }
/**
* @brief get the request object
*/
inline const http::web_request & get_request() noexcept { return this->req_; }
/**
* @brief get the response object
*/
inline const http::web_response& get_response() noexcept { return this->rep_; }
/**
* @brief set how to send the http response in the bind_recv callback
* automatic - The framework automatically send the http response
* manual - You need to send the http response youself
*/
inline derived_t& set_response_mode(asio2::response_mode mode)
{
this->response_mode_ = mode;
return (static_cast<derived_t&>(*this));
}
/**
* @brief get the response mode
*/
inline asio2::response_mode get_response_mode() { return this->response_mode_; }
protected:
inline http_router_t<derived_t, args_t>& _router() noexcept
{
return (this->router_);
}
template<typename C>
inline void _do_init(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
super::_do_init(this_ptr, ecs);
if (this->support_websocket_)
{
this->derived()._ws_init(ecs, this->derived().stream());
}
}
template<typename DeferEvent>
inline void _post_shutdown(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
ASIO2_LOG_DEBUG("http_session::_post_shutdown: {} {}", ec.value(), ec.message());
if (this->derived().is_http())
{
super::_post_shutdown(ec, std::move(this_ptr), std::move(chain));
}
else
{
this->derived()._ws_stop(this_ptr, defer_event
{
[this, ec, this_ptr, e = chain.move_event()] (event_queue_guard<derived_t> g) mutable
{
super::_post_shutdown(ec, std::move(this_ptr), defer_event(std::move(e), std::move(g)));
}, chain.move_guard()
});
}
}
template<typename DeferEvent>
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
// can not use std::move(this_ptr), beacuse after handle stop with std::move(this_ptr),
// this object maybe destroyed, then call "this" will crash.
super::_handle_stop(ec, this_ptr, std::move(chain));
// reset the callback shared_ptr, to avoid the callback owned this self shared_ptr.
this->websocket_router_.reset();
}
template<typename C, class MessageT>
inline void _send_http_response(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, MessageT& msg)
{
if (this->rep_.defer_guard_)
{
this->rep_.defer_guard_.reset();
}
else
{
if (this->response_mode_ == asio2::response_mode::automatic)
{
this->derived()._do_send_http_response(std::move(this_ptr), std::move(ecs), msg);
}
}
}
template<typename C, class MessageT>
inline void _do_send_http_response_impl(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, MessageT& msg)
{
ASIO2_ASSERT(this->is_http());
derived_t& derive = this->derived();
if (derive.is_websocket())
return;
if (!derive.is_started())
return;
// be careful: here we pushed the reference of the msg into the queue, so the msg object
// must can't be destroyed or modifyed.
derive.push_event([&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), &msg]
(event_queue_guard<derived_t> g) mutable
{
// use this_ptr to instead of std::move(this_ptr) in the lambda capture has better safety.
derive._do_send(msg,
[&derive, this_ptr, ecs = std::move(ecs), g = std::move(g)]
(const error_code&, std::size_t) mutable
{
ASIO2_ASSERT(!g.is_empty());
#if defined(ASIO2_ENABLE_LOG)
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
ASIO2_LOG_TRACE("http_session::send {:%Y-%m-%d %H:%M:%S}.{:03d} {}",
now, ms % 1000, derive.req_.target());
#endif
// after send the response, we check if the client should be disconnect.
if (derive.req_.need_eof())
{
ASIO2_LOG_DEBUG("http_session send response need_eof");
// session maybe don't need check the state.
//if (derive.state() == state_t::started)
derive._do_disconnect(asio::error::operation_aborted, std::move(this_ptr));
}
else
{
derive._post_recv(std::move(this_ptr), std::move(ecs));
}
});
});
}
template<typename C, class MessageT>
inline void _do_send_http_response(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, MessageT& msg)
{
derived_t& derive = this->derived();
if (derive.io().running_in_this_thread())
{
derive._do_send_http_response_impl(std::move(this_ptr), std::move(ecs), msg);
return;
}
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), &msg]() mutable
{
derive._do_send_http_response_impl(std::move(this_ptr), std::move(ecs), msg);
}));
}
protected:
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
if (this->derived().is_websocket())
return this->derived()._ws_send(data, std::forward<Callback>(callback));
return this->derived()._http_send(data, std::forward<Callback>(callback));
}
template<class Data>
inline send_data_t _rdc_convert_to_send_data(Data& data) noexcept
{
ASIO2_ASSERT(this->websocket_router_ && "Only available in websocket mode");
set_last_error(asio::error::operation_not_supported);
auto buffer = asio::buffer(data);
return send_data_t{ reinterpret_cast<
std::string_view::const_pointer>(buffer.data()),buffer.size() };
}
template<class Invoker>
inline void _rdc_invoke_with_none(const error_code& ec, Invoker& invoker)
{
ASIO2_ASSERT(this->websocket_router_ && "Only available in websocket mode");
if (this->derived().is_websocket() && invoker)
invoker(ec, send_data_t{}, recv_data_t{});
}
template<class Invoker>
inline void _rdc_invoke_with_recv(const error_code& ec, Invoker& invoker, recv_data_t data)
{
ASIO2_ASSERT(this->websocket_router_ && "Only available in websocket mode");
if (this->derived().is_websocket() && invoker)
invoker(ec, send_data_t{}, data);
}
template<class Invoker>
inline void _rdc_invoke_with_send(const error_code& ec, Invoker& invoker, send_data_t data)
{
ASIO2_ASSERT(this->websocket_router_ && "Only available in websocket mode");
if (this->derived().is_websocket() && invoker)
invoker(ec, data, recv_data_t{});
}
protected:
template<typename C>
inline void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._http_post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename C>
inline void _handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
this->derived()._http_handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}
template<typename C, typename DeferEvent>
inline void _handle_upgrade(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
this->derived().sessions().post(
[this, ec, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
set_last_error(ec);
this->derived()._fire_upgrade(this_ptr);
if (ec)
{
this->derived()._do_disconnect(ec, std::move(this_ptr), std::move(chain));
return;
}
asio::post(this->derived().io().context(), make_allocator(this->derived().wallocator(),
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
() mutable
{
detail::ignore_unused(chain);
this->derived()._post_recv(std::move(this_ptr), std::move(ecs));
}));
});
}
template<typename C>
inline bool _check_upgrade(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
if (this->support_websocket_ && this->derived().is_http() && this->req_.is_upgrade())
{
this->websocket_router_ = this->router_.template _find<false>(this->req_, this->rep_);
if (this->websocket_router_)
{
this->req_.ws_frame_type_ = websocket::frame::open;
this->req_.ws_frame_data_ = {};
if (this->router_._route(this_ptr, this->req_, this->rep_))
{
this->derived().silence_timeout_ = std::chrono::milliseconds(tcp_silence_timeout);
this->derived()._ws_start(this_ptr, ecs, this->derived().stream());
this->derived()._post_control_callback(this_ptr, ecs);
this->derived().push_event(
[this, this_ptr, ecs](event_queue_guard<derived_t> g) mutable
{
this->derived()._post_upgrade(
this_ptr, std::move(ecs), this->req_.base(),
defer_event([](event_queue_guard<derived_t>) {}, std::move(g)));
});
}
else
{
this->req_.ws_frame_type_ = websocket::frame::unknown;
this->req_.ws_frame_data_ = {};
this->websocket_router_.reset();
this->derived()._send_http_response(this_ptr, ecs, this->rep_.base());
}
// If find websocket router, the router callback must has been called,
// so as long as we find the websocket router, we return true
// If don't do this, the fire recv will be called, then the router callback
// will be called again.
return true;
}
}
return false;
}
template<typename C>
inline void _handle_control_ping(
beast::string_view payload, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
detail::ignore_unused(payload, this_ptr, ecs);
this->req_.ws_frame_type_ = websocket::frame::ping;
this->req_.ws_frame_data_ = payload;
this->router_._route(this_ptr, this->req_, this->rep_);
}
template<typename C>
inline void _handle_control_pong(
beast::string_view payload, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
detail::ignore_unused(payload, this_ptr, ecs);
this->req_.ws_frame_type_ = websocket::frame::pong;
this->req_.ws_frame_data_ = payload;
this->router_._route(this_ptr, this->req_, this->rep_);
}
template<typename C>
inline void _handle_control_close(
beast::string_view payload, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
detail::ignore_unused(payload, this_ptr, ecs);
this->req_.ws_frame_type_ = websocket::frame::close;
this->req_.ws_frame_data_ = payload;
this->router_._route(this_ptr, this->req_, this->rep_);
// session maybe don't need check the state.
//if (this->derived().state() == state_t::started)
{
ASIO2_LOG_DEBUG("http_session::_handle_control_close _do_disconnect");
this->derived()._do_disconnect(websocket::error::closed, std::move(this_ptr));
}
}
inline void _fire_upgrade(std::shared_ptr<derived_t>& this_ptr)
{
// the _fire_upgrade must be executed in the thread 0.
ASIO2_ASSERT(this->sessions().io().running_in_this_thread());
this->listener_.notify(event_type::upgrade, this_ptr);
}
template<typename C>
inline void _fire_recv(std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs)
{
if (this->is_arg0_session_)
this->listener_.notify(event_type::recv, this_ptr, this->req_, this->rep_);
else
this->listener_.notify(event_type::recv, this->req_, this->rep_);
#if defined(ASIO2_ENABLE_LOG)
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
ASIO2_LOG_TRACE("http_session::recv {:%Y-%m-%d %H:%M:%S}.{:03d} {}",
now, ms % 1000, this->req_.target());
#endif
auto* prep = this->router_._route(this_ptr, this->req_, this->rep_);
if (this->derived().is_websocket())
{
this->derived()._rdc_handle_recv(this_ptr, ecs, this->req_.ws_frame_data_);
}
else
{
this->derived()._send_http_response(this_ptr, ecs, *prep);
}
}
protected:
http::web_request req_;
http::web_response rep_;
http_router_t<derived_t, args_t> & router_;
std::filesystem::path & root_directory_;
bool is_arg0_session_ = false;
bool support_websocket_ = false;
asio2::response_mode response_mode_ = asio2::response_mode::automatic;
std::shared_ptr<typename http_router_t<derived_t, args_t>::opfun> websocket_router_;
};
}
namespace asio2
{
using http_session_args = detail::template_args_http_session;
template<class derived_t, class args_t>
using http_session_impl_t = detail::http_session_impl_t<derived_t, args_t>;
template<class derived_t>
class http_session_t : public detail::http_session_impl_t<derived_t, detail::template_args_http_session>
{
public:
using detail::http_session_impl_t<derived_t, detail::template_args_http_session>::http_session_impl_t;
};
class http_session : public http_session_t<http_session>
{
public:
using http_session_t<http_session>::http_session_t;
};
}
#if defined(ASIO2_INCLUDE_RATE_LIMIT)
#include <asio2/tcp/tcp_stream.hpp>
namespace asio2
{
struct http_rate_session_args : public http_session_args
{
using socket_t = asio2::tcp_stream<asio2::simple_rate_policy>;
using stream_t = websocket::stream<socket_t&>;
};
template<class derived_t>
class http_rate_session_t : public asio2::http_session_impl_t<derived_t, http_rate_session_args>
{
public:
using asio2::http_session_impl_t<derived_t, http_rate_session_args>::http_session_impl_t;
};
class http_rate_session : public asio2::http_rate_session_t<http_rate_session>
{
public:
using asio2::http_rate_session_t<http_rate_session>::http_rate_session_t;
};
}
#endif
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_HTTP_SESSION_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_SESSION_MGR_HPP__
#define __ASIO2_SESSION_MGR_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <algorithm>
#include <memory>
#include <functional>
#include <unordered_map>
#include <type_traits>
#include <asio2/base/iopool.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/log.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SERVER;
ASIO2_CLASS_FORWARD_DECLARE_UDP_SESSION;
/**
* the session manager interface
*/
template<class session_t>
class session_mgr_t
{
friend session_t; // C++11
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SERVER;
ASIO2_CLASS_FRIEND_DECLARE_UDP_SESSION;
public:
using self = session_mgr_t<session_t>;
using args_type = typename session_t::args_type;
using key_type = typename session_t::key_type;
/**
* @brief constructor
*/
explicit session_mgr_t(io_t& acceptor_io, std::atomic<state_t>& server_state)
: io_ (acceptor_io )
, state_(server_state)
{
this->sessions_.reserve(64);
}
/**
* @brief destructor
*/
~session_mgr_t() = default;
/**
* @brief emplace the session
* @callback : void(bool inserted);
*/
template<class Fun>
inline void emplace(std::shared_ptr<session_t> session_ptr, Fun&& callback)
{
if (!session_ptr)
return;
asio::dispatch(this->io().context(), make_allocator(this->allocator_,
[this, session_ptr = std::move(session_ptr), callback = std::forward<Fun>(callback)]
() mutable
{
bool inserted = false;
// when run to here, the server state maybe started or stopping or stopped,
// if server state is not started, must can't push the session to the map
// again, and we need disconnect the session directly, otherwise the server
// maybe stopping, and the iopool's wait_iothreas is running in the "sleep"
// this will cause the server.stop() never return;
if (this->state_ == state_t::started)
{
// when code run to here, user maybe call server.stop() at other thread,
// if user do this, at this time, the state_ is not started already( it
// will be stopping ), but beacuase the server's sessions_.for_each ->
// session_ptr->stop(); is execute in the thread 0, and this code is
// executed in thread 0 too, so when code run to here, beacuse we have
// " if (this->state_ == state_t::started) " judgment statement, so the
// server's sessions_.for_each -> session_ptr->stop(); must not be
// executed yet, so even if we put the session in the map here, it will
// not have a problem, beacuse the server's sessions_.for_each ->
// session_ptr->stop(); will be called a later, and this session will be
// stopped at there.
// we use a assert to check the server's sessions_.for_each ->
// session_ptr->stop(); must not be executed yet.
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(is_all_session_stop_called_ == false);
#endif
// this thread is same as the server's io thread, when code run to here,
// the server's _post_stop must not be executed, so the server's sessions_.for_each
// -> session_ptr->stop() must not be executed.
asio2::unique_locker guard(this->mutex_);
inserted = this->sessions_.try_emplace(session_ptr->hash_key(), session_ptr).second;
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(is_all_session_stop_called_ == false);
#endif
}
(callback)(inserted);
}));
}
/**
* @brief erase the session
* @callback : void(bool erased);
*/
template<class Fun>
inline void erase(std::shared_ptr<session_t> session_ptr, Fun&& callback)
{
if (!session_ptr)
return;
asio::dispatch(this->io().context(), make_allocator(this->allocator_,
[this, session_ptr = std::move(session_ptr), callback = std::forward<Fun>(callback)]
() mutable
{
bool erased = false;
{
asio2::unique_locker guard(this->mutex_);
erased = (this->sessions_.erase(session_ptr->hash_key()) > 0);
}
(callback)(erased);
}));
}
/**
* @brief Submits a completion token or function object for execution.
* @task : void();
*/
template<class Fun>
inline void post(Fun&& task)
{
asio::post(this->io().context(), make_allocator(this->allocator_, std::forward<Fun>(task)));
}
/**
* @brief Submits a completion token or function object for execution.
* @task : void();
*/
template<class Fun>
inline void dispatch(Fun&& task)
{
asio::dispatch(this->io().context(), make_allocator(this->allocator_, std::forward<Fun>(task)));
}
/**
* @brief call user custom callback function for every session
* the custom callback function is like this :
* void on_callback(std::shared_ptr<tcp_session> & session_ptr)
*/
template<class Fun>
inline void for_each(Fun&& fn)
{
// thred safety for each
//
std::vector<std::shared_ptr<session_t>> sessions;
{
asio2::shared_locker guard(this->mutex_);
sessions.reserve(this->sessions_.size());
for (const auto& [k, session_ptr] : this->sessions_)
{
std::ignore = k;
sessions.emplace_back(session_ptr);
}
}
for (std::shared_ptr<session_t>& session_ptr : sessions)
{
fn(session_ptr);
}
// if the unique locker was called in the callback inner, then will cause deadlock.
// and if the callback is a time-consuming operation, the new session will can't enter.
//
//asio2::shared_locker guard(this->mutex_);
//for (auto& [k, session_ptr] : this->sessions_)
//{
// std::ignore = k;
// fn(session_ptr);
//}
}
/**
* @brief find the session by map key
*/
inline std::shared_ptr<session_t> find(const key_type & key)
{
asio2::shared_locker guard(this->mutex_);
auto iter = this->sessions_.find(key);
return (iter == this->sessions_.end() ? std::shared_ptr<session_t>() : iter->second);
}
/**
* @brief find the session by user custom role
* bool on_callback(std::shared_ptr<tcp_session> & session_ptr)
*/
template<class Fun>
inline std::shared_ptr<session_t> find_if(Fun&& fn)
{
// if the unique locker was called in the callback inner, then will cause deadlock.
asio2::shared_locker guard(this->mutex_);
auto iter = std::find_if(this->sessions_.begin(), this->sessions_.end(),
[&fn](auto &pair) mutable
{
return fn(pair.second);
});
return (iter == this->sessions_.end() ? std::shared_ptr<session_t>() : iter->second);
}
/**
* @brief get session count
*/
inline std::size_t size() const noexcept
{
asio2::shared_locker guard(this->mutex_);
// is std map.size() thread safety?
//
// https://stackoverflow.com/questions/2170541/what-operations-are-thread-safe-on-stdmap
// https://en.cppreference.com/w/cpp/container
// https://timsong-cpp.github.io/cppwp/n3337/container.requirements.dataraces
// https://stackoverflow.com/questions/15067160/stdmap-thread-safety
// https://stackoverflow.com/questions/14127379/does-const-mean-thread-safe-in-c11
// There is no one consensus:
// The C++11 standard guarantees that const method access to containers is safe from
// different threads (ie, both use const methods).
// It should be thread-safe to call a const function from multiple threads simultaneously,
// without calling a non-const function at the same time in another thread.
// after my test on windows and linux:
// multithread call const function without mutex, and multithread call no-const function
// with mutex at the same time, the result of the const function seems to be no problem.
//#include <unordered_map>
//#include <shared_mutex>
//#include <thread>
//
//int main()
//{
// std::shared_mutex mtx;
// std::unordered_map<int, int> map;
//
// std::srand((unsigned int)std::time(nullptr));
//
// for (std::size_t i = 0; i < std::thread::hardware_concurrency() * 2; i++)
// {
// std::thread([&]() mutable
// {
// for (;;)
// {
// int n = std::rand();
// std::unique_lock g(mtx);
// if (map.size() < 1000)
// map.emplace(n, n);
// else
// std::this_thread::sleep_for(std::chrono::milliseconds(0));
// }
// }).detach();
// }
//
// for (std::size_t i = 0; i < std::thread::hardware_concurrency() * 2; i++)
// {
// std::thread([&]() mutable
// {
// for (;;)
// {
// std::unique_lock g(mtx);
// if (map.size() > 500)
// map.erase(map.begin());
// else
// std::this_thread::sleep_for(std::chrono::milliseconds(0));
// }
// }).detach();
// }
//
// std::this_thread::sleep_for(std::chrono::seconds(5));
//
// for (std::size_t i = 0; i < std::thread::hardware_concurrency() * 2; i++)
// {
// std::thread([&]() mutable
// {
// for (;;)
// {
// int n = int(map.size());
// if (n < 500 || n > 1000 || map.empty())
// {
// printf("error %d\n", n);
// }
// }
// }).detach();
// }
//
// while (std::getchar() != '\n');
//
// return 0;
//}
return this->sessions_.size();
}
/**
* @brief Checks if the session container has no elements
*/
inline bool empty() const noexcept
{
asio2::shared_locker guard(this->mutex_);
return this->sessions_.empty();
}
/**
* @brief get the io object refrence
*/
inline io_t & io() noexcept
{
return this->io_;
}
protected:
/// use rwlock to make this session map thread safe
mutable asio2::shared_mutexer mutex_;
/// session unorder map,these session is already connected session
std::unordered_map<key_type, std::shared_ptr<session_t>> sessions_ ASIO2_GUARDED_BY(mutex_);
/// the zero io_context refrence in the iopool
io_t & io_;
/// The memory to use for handler-based custom memory allocation.
handler_memory<std::false_type, assizer<args_type>> allocator_;
/// server state refrence
std::atomic<state_t> & state_;
#if defined(_DEBUG) || defined(DEBUG)
bool is_all_session_stop_called_ = false;
#endif
};
}
#endif // !__ASIO2_SESSION_MGR_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_MQTT_CLIENT_HPP__
#define __ASIO2_MQTT_CLIENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
#include <asio2/tcp/tcp_client.hpp>
#include <asio2/mqtt/impl/mqtt_send_connect_op.hpp>
#include <asio2/mqtt/impl/mqtt_send_op.hpp>
#include <asio2/mqtt/detail/mqtt_handler.hpp>
#include <asio2/mqtt/detail/mqtt_invoker.hpp>
#include <asio2/mqtt/detail/mqtt_topic_alias.hpp>
#include <asio2/mqtt/detail/mqtt_session_state.hpp>
#include <asio2/mqtt/detail/mqtt_message_router.hpp>
#include <asio2/mqtt/detail/mqtt_subscribe_router.hpp>
#include <asio2/mqtt/options.hpp>
#include <asio2/util/uuid.hpp>
namespace asio2::detail
{
struct template_args_mqtt_client : public template_args_tcp_client
{
static constexpr bool rdc_call_cp_enabled = false;
template<class caller_t>
struct subnode
{
explicit subnode(
std::weak_ptr<caller_t> c,
mqtt::subscription s,
mqtt::v5::properties_set p = mqtt::v5::properties_set{}
)
: caller(std::move(c))
, sub (std::move(s))
, props (std::move(p))
{
}
inline std::string_view share_name () { return sub.share_name (); }
inline std::string_view topic_filter() { return sub.topic_filter(); }
//
std::weak_ptr<caller_t> caller;
// subscription info
mqtt::subscription sub;
// subscription properties
mqtt::v5::properties_set props;
detail::function<void(mqtt::message&)> callback;
};
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
template<class derived_t, class args_t = template_args_mqtt_client>
class mqtt_client_impl_t
: public tcp_client_impl_t <derived_t, args_t>
, public mqtt_options
, public mqtt_handler_t <derived_t, args_t>
, public mqtt_invoker_t <derived_t, args_t>
, public mqtt_message_router_t <derived_t, args_t>
, public mqtt_subscribe_router_t<derived_t, args_t>
, public mqtt_topic_alias_t <derived_t, args_t>
, public mqtt_send_op <derived_t, args_t>
, public mqtt::session_state
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
public:
using super = tcp_client_impl_t <derived_t, args_t>;
using self = mqtt_client_impl_t<derived_t, args_t>;
using args_type = args_t;
using subnode_type = typename args_type::template subnode<derived_t>;
using super::send;
using super::async_send;
public:
/**
* @brief constructor
*/
explicit mqtt_client_impl_t(
std::size_t init_buf_size = tcp_frame_size,
std::size_t max_buf_size = mqtt::max_payload,
std::size_t concurrency = 1
)
: super(init_buf_size, max_buf_size, concurrency)
, mqtt_options ()
, mqtt_handler_t <derived_t, args_t>()
, mqtt_invoker_t <derived_t, args_t>()
, mqtt_message_router_t <derived_t, args_t>()
, mqtt_subscribe_router_t<derived_t, args_t>()
, mqtt_topic_alias_t <derived_t, args_t>()
, mqtt_send_op <derived_t, args_t>()
, pingreq_timer_(this->io_.context())
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit mqtt_client_impl_t(
std::size_t init_buf_size,
std::size_t max_buf_size,
Scheduler&& scheduler
)
: super(init_buf_size, max_buf_size, std::forward<Scheduler>(scheduler))
, mqtt_options ()
, mqtt_handler_t <derived_t, args_t>()
, mqtt_invoker_t <derived_t, args_t>()
, mqtt_message_router_t <derived_t, args_t>()
, mqtt_subscribe_router_t<derived_t, args_t>()
, mqtt_topic_alias_t <derived_t, args_t>()
, mqtt_send_op <derived_t, args_t>()
, pingreq_timer_(this->io_.context())
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit mqtt_client_impl_t(Scheduler&& scheduler)
: mqtt_client_impl_t(tcp_frame_size, mqtt::max_payload, std::forward<Scheduler>(scheduler))
{
}
/**
* @brief destructor
*/
~mqtt_client_impl_t()
{
this->stop();
}
/**
* @brief start the client, blocking connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& port, Args&&... args)
{
if constexpr (sizeof...(Args) > std::size_t(0))
return this->derived().template _do_connect_with_connect_message<false>(
std::forward<String>(host), std::forward<StrOrInt>(port),
std::forward<Args>(args)...);
else
return this->derived().template _do_connect<false>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs(asio::transfer_at_least(1),
mqtt::mqtt_match_role, std::forward<Args>(args)...));
}
/**
* @brief start the client, asynchronous connect to server
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param port - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool async_start(String&& host, StrOrInt&& port, Args&&... args)
{
if constexpr (sizeof...(Args) > std::size_t(0))
return this->derived().template _do_connect_with_connect_message<true>(
std::forward<String>(host), std::forward<StrOrInt>(port),
std::forward<Args>(args)...);
else
return this->derived().template _do_connect<true>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs(asio::transfer_at_least(1),
mqtt::mqtt_match_role, std::forward<Args>(args)...));
}
public:
/**
* @brief get the mqtt version number
*/
inline mqtt::version version()
{
return this->get_version();
}
/**
* @brief get the mqtt version number
*/
inline mqtt::version get_version()
{
if /**/ (std::holds_alternative<mqtt::v3::connect>(connect_message_.base()))
{
return mqtt::version::v3;
}
else if (std::holds_alternative<mqtt::v4::connect>(connect_message_.base()))
{
return mqtt::version::v4;
}
else if (std::holds_alternative<mqtt::v5::connect>(connect_message_.base()))
{
return mqtt::version::v5;
}
ASIO2_ASSERT(false);
return static_cast<mqtt::version>(0);
}
/**
* @brief get the mqtt client identifier
*/
inline std::string_view client_id()
{
return this->get_client_id();
}
/**
* @brief get the mqtt client identifier
*/
inline std::string_view get_client_id()
{
std::string_view v{};
if (!this->connect_message_.empty())
{
if /**/ (std::holds_alternative<mqtt::v3::connect>(connect_message_.base()))
{
v = connect_message_.template get<mqtt::v3::connect>().client_id();
}
else if (std::holds_alternative<mqtt::v4::connect>(connect_message_.base()))
{
v = connect_message_.template get<mqtt::v4::connect>().client_id();
}
else if (std::holds_alternative<mqtt::v5::connect>(connect_message_.base()))
{
v = connect_message_.template get<mqtt::v5::connect>().client_id();
}
}
if (v.empty())
{
if (mqtt::v5::connack* m = std::get_if<mqtt::v5::connack>(std::addressof(connack_message_.base())))
{
mqtt::v5::assigned_client_identifier* p =
m->properties().get_if<mqtt::v5::assigned_client_identifier>();
if (p)
v = p->value();
}
}
return v;
}
/**
* @brief get the mqtt Keep Alive which is a time interval measured in seconds.
*/
inline std::uint16_t keep_alive_time()
{
return this->get_keep_alive_time();
}
/**
* @brief get the mqtt Keep Alive which is a time interval measured in seconds.
*/
inline std::uint16_t get_keep_alive_time()
{
//The Keep Alive is a Two Byte Integer which is a time interval measured in seconds.
// It is the maximum time interval that is permitted to elapse between the point at
// which the Client finishes transmitting one MQTT Control Packet and the point it
// starts sending the next. It is the responsibility of the Client to ensure that
// the interval between MQTT Control Packets being sent does not exceed the Keep
// Alive value. If Keep Alive is non-zero and in the absence of sending any other
// MQTT Control Packets, the Client MUST send a PINGREQ packet [MQTT-3.1.2-20].
// If the Server returns a Server Keep Alive on the CONNACK packet, the Client MUST
// use that value instead of the value it sent as the Keep Alive [MQTT-3.1.2-21].
if (mqtt::v5::connack* m = std::get_if<mqtt::v5::connack>(std::addressof(connack_message_.base())))
{
mqtt::v5::server_keep_alive* p =
m->properties().get_if<mqtt::v5::server_keep_alive>();
if (p)
return p->value();
}
// Default to 60 seconds
std::uint16_t v = 60;
if (!this->connect_message_.empty())
{
if /**/ (std::holds_alternative<mqtt::v3::connect>(connect_message_.base()))
{
v = this->connect_message_.template get_if<mqtt::v3::connect>()->keep_alive();
}
else if (std::holds_alternative<mqtt::v4::connect>(connect_message_.base()))
{
v = this->connect_message_.template get_if<mqtt::v4::connect>()->keep_alive();
}
else if (std::holds_alternative<mqtt::v5::connect>(connect_message_.base()))
{
v = this->connect_message_.template get_if<mqtt::v5::connect>()->keep_alive();
}
}
return v;
}
/**
* @brief set the mqtt connect message packet
*/
template<class Message>
inline derived_t& set_connect_message(Message&& connect_msg)
{
using msg_type = typename detail::remove_cvref_t<Message>;
if constexpr (
std::is_same_v<msg_type, mqtt::v3::connect> ||
std::is_same_v<msg_type, mqtt::v4::connect> ||
std::is_same_v<msg_type, mqtt::v5::connect>)
{
this->connect_message_ = std::forward<Message>(connect_msg);
}
else
{
static_assert(detail::always_false_v<Message>);
}
return (static_cast<derived_t&>(*this));
}
/**
* @brief get the mqtt connect message refrence
*/
inline mqtt::message& get_connect_message() { return this->connect_message_; }
/**
* @brief get the mqtt connect message packet refrence
*/
template<mqtt::version v>
inline auto& get_connect_packet()
{
if constexpr /**/ (mqtt::version::v3 == v)
{
return std::get<mqtt::v3::connect>(this->connect_message_.base());
}
else if constexpr (mqtt::version::v4 == v)
{
return std::get<mqtt::v4::connect>(this->connect_message_.base());
}
else if constexpr (mqtt::version::v5 == v)
{
return std::get<mqtt::v5::connect>(this->connect_message_.base());
}
else
{
static_assert(mqtt::version::v3 == v || mqtt::version::v4 == v || mqtt::version::v5 == v);
}
}
protected:
template<bool IsAsync, typename String, typename StrOrInt, typename Arg1, typename... Args>
bool _do_connect_with_connect_message(String&& host, StrOrInt&& port, Arg1&& arg1, Args&&... args)
{
using arg1_type = typename detail::remove_cvref_t<Arg1>;
if constexpr (
std::is_same_v<arg1_type, mqtt::v3::connect> ||
std::is_same_v<arg1_type, mqtt::v4::connect> ||
std::is_same_v<arg1_type, mqtt::v5::connect>)
{
this->connect_message_ = std::forward<Arg1>(arg1);
return this->derived().template _do_connect<IsAsync>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs(asio::transfer_at_least(1),
mqtt::mqtt_match_role, std::forward<Args>(args)...));
}
else
{
return this->derived().template _do_connect<IsAsync>(
std::forward<String>(host), std::forward<StrOrInt>(port),
ecs_helper::make_ecs(asio::transfer_at_least(1),
mqtt::mqtt_match_role, std::forward<Arg1>(arg1), std::forward<Args>(args)...));
}
}
template<bool IsAsync, typename String, typename StrOrInt, typename C>
inline bool _do_connect(String&& host, StrOrInt&& port, std::shared_ptr<ecs_t<C>> ecs)
{
if (!this->connect_message_.template holds<mqtt::v3::connect, mqtt::v4::connect, mqtt::v5::connect>())
{
ASIO2_ASSERT(false);
set_last_error(asio::error::invalid_argument);
return false;
}
return super::template _do_connect<IsAsync>(
std::forward<String>(host), std::forward<StrOrInt>(port), std::move(ecs));
}
template<typename C>
inline void _bind_default_mqtt_handler(std::shared_ptr<ecs_t<C>>& ecs)
{
detail::ignore_unused(ecs);
// must set default callback for every mqtt message.
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::connect ))) this->on_connect ([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::connack ))) this->on_connack ([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::publish ))) this->on_publish ([](mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::puback ))) this->on_puback ([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pubrec ))) this->on_pubrec ([](mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pubrel ))) this->on_pubrel ([](mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pubcomp ))) this->on_pubcomp ([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::subscribe ))) this->on_subscribe ([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::suback ))) this->on_suback ([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::unsubscribe))) this->on_unsubscribe([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::unsuback ))) this->on_unsuback ([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pingreq ))) this->on_pingreq ([](mqtt::message&, mqtt::message&) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::pingresp ))) this->on_pingresp ([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::disconnect ))) this->on_disconnect ([](mqtt::message& ) mutable {});
if (!(this->_find_mqtt_handler(mqtt::control_packet_type::auth ))) this->on_auth ([](mqtt::message&, mqtt::message&) mutable {});
}
protected:
template<typename C>
inline void _do_init(std::shared_ptr<ecs_t<C>>& ecs)
{
// must set default callback for every mqtt message.
this->derived()._bind_default_mqtt_handler(ecs);
super::_do_init(ecs);
}
template<typename E = defer_event<void, derived_t>>
inline void _do_disconnect(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, E chain = defer_event<void, derived_t>{})
{
state_t expected = state_t::started;
if (this->derived().state_.compare_exchange_strong(expected, state_t::started))
{
mqtt::version ver = this->derived().version();
if /**/ (ver == mqtt::version::v3)
{
mqtt::v3::disconnect disconnect;
this->derived().async_send(std::move(disconnect));
}
else if (ver == mqtt::version::v4)
{
mqtt::v4::disconnect disconnect;
this->derived().async_send(std::move(disconnect));
}
else if (ver == mqtt::version::v5)
{
mqtt::v5::disconnect disconnect;
switch (ec.value())
{
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901208
case 0 : // Client or Server
case 4 : // Client
case 128 : // Client or Server
case 129 : // Client or Server
case 130 : // Client or Server
case 131 : // Client or Server
case 144 : // Client or Server
case 147 : // Client or Server
case 148 : // Client or Server
case 149 : // Client or Server
case 150 : // Client or Server
case 151 : // Client or Server
case 152 : // Client or Server
case 153 : // Client or Server
disconnect.reason_code(static_cast<std::uint8_t>(ec.value())); break;
default: break;
}
this->derived().async_send(std::move(disconnect));
}
}
super::_do_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename C, typename DeferEvent>
inline void _handle_connect(
const error_code& ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
derived_t& derive = this->derived();
set_last_error(ec);
if (ec)
{
return derive._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
// send connect message to server use coroutine
mqtt_send_connect_op
{
derive.io().context(),
derive.connect_message_,
derive.stream(),
[&derive, this_ptr = std::move(this_ptr), ecs = std::move(ecs), chain = std::move(chain)]
(error_code ec, std::unique_ptr<asio::streambuf> stream) mutable
{
derive._handle_mqtt_connect_response(ec, std::move(this_ptr), std::move(ecs),
std::move(stream), std::move(chain));
}
};
}
template<typename C, typename DeferEvent>
inline void _handle_mqtt_connect_response(
error_code ec,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs,
std::unique_ptr<asio::streambuf> stream, DeferEvent chain)
{
if (ec)
{
this->derived()._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
std::string_view data{ reinterpret_cast<std::string_view::const_pointer>(
static_cast<const char*>(stream->data().data())), stream->size() };
mqtt::control_packet_type type = mqtt::message_type_from_data(data);
bool valid_message = (type == mqtt::control_packet_type::connack) ||
(this->derived().version() == mqtt::version::v5 && type == mqtt::control_packet_type::auth);
// -- the connect_timeout_cp will disconnect after a reasonable amount of time.
// If the client does not receive a CONNACK message from the server within a reasonable amount
// of time, the client should close the TCP/IP socket connection,
// and restart the session by opening a new socket to the server and issuing a CONNECT message.
if (!valid_message)
{
ASIO2_ASSERT(false);
ec = mqtt::make_error_code(mqtt::error::malformed_packet);
this->derived()._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
this->idmgr_.clear();
ec = mqtt::make_error_code(mqtt::error::server_unavailable);
this->derived()._call_mqtt_handler(type, ec, this_ptr, static_cast<derived_t*>(this), data);
this->derived()._done_connect(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
}
template<typename C, typename DeferEvent>
inline void _do_start(
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
super::_do_start(this_ptr, std::move(ecs), std::move(chain));
this->derived()._post_pingreq_timer(
std::move(this_ptr), std::chrono::seconds(this->derived().keep_alive_time()));
}
template<class Rep, class Period>
inline void _post_pingreq_timer(
std::shared_ptr<derived_t> this_ptr, std::chrono::duration<Rep, Period> duration)
{
derived_t& derive = this->derived();
// start the timer
if (duration > std::chrono::duration<Rep, Period>::zero() && this->is_started())
{
this->pingreq_timer_.expires_after(duration);
this->pingreq_timer_.async_wait(
[&derive, this_ptr = std::move(this_ptr)](const error_code& ec) mutable
{
derive._handle_pingreq_timer(ec, std::move(this_ptr));
});
}
}
inline void _handle_pingreq_timer(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
{
derived_t& derive = this->derived();
ASIO2_ASSERT((!ec) || ec == asio::error::operation_aborted);
if (ec)
return;
// The Client can send PINGREQ at any time, irrespective of the Keep Alive value, and check
// for a corresponding PINGRESP to determine that the network and the Server are available.
// If the Keep Alive value is non-zero and the Server does not receive an MQTT Control Packet
// from the Client within one and a half times the Keep Alive time period, it MUST close the
// Network Connection to the Client as if the network had failed [MQTT-3.1.2-22].
// If a Client does not receive a PINGRESP packet within a reasonable amount of time after it
// has sent a PINGREQ, it SHOULD close the Network Connection to the Server.
// A Keep Alive value of 0 has the effect of turning off the Keep Alive mechanism. If Keep Alive
// is 0 the Client is not obliged to send MQTT Control Packets on any particular schedule.
// send pingreq message, don't case the last sent and recved time.
mqtt::version ver = derive.version();
if /**/ (ver == mqtt::version::v3)
{
derive.async_send(mqtt::v3::pingreq{});
}
else if (ver == mqtt::version::v4)
{
derive.async_send(mqtt::v4::pingreq{});
}
else if (ver == mqtt::version::v5)
{
derive.async_send(mqtt::v5::pingreq{});
}
// do next timer
derive._post_pingreq_timer(std::move(this_ptr), std::chrono::seconds(derive.keep_alive_time()));
}
inline void _stop_pingreq_timer()
{
detail::cancel_timer(this->pingreq_timer_);
}
template<typename DeferEvent>
inline void _handle_disconnect(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
this->derived()._stop_pingreq_timer();
super::_handle_disconnect(ec, std::move(this_ptr), std::move(chain));
}
template<typename DeferEvent>
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
super::_handle_stop(ec, std::move(this_ptr), std::move(chain));
}
template<class Data, class Callback>
inline bool _do_send(Data& data, Callback&& callback)
{
return this->derived()._mqtt_send(data, std::forward<Callback>(callback));
}
protected:
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, data);
this->derived()._rdc_handle_recv(this_ptr, ecs, data);
mqtt::control_packet_type type = mqtt::message_type_from_data(data);
if (type > mqtt::control_packet_type::auth)
{
ASIO2_ASSERT(false);
// give a error callback and call it ?
return;
}
error_code ec;
this->derived()._call_mqtt_handler(type, ec, this_ptr, static_cast<derived_t*>(this), data);
if (ec)
{
// give a error callback and call it ?
}
}
protected:
/// Should we set a default mqtt version to v4, default client id to a uuid string ?
mqtt::message connect_message_{/* mqtt::v4::connect{ asio2::uuid().next().str() } */};
///
mqtt::message connack_message_{};
/// timer for pingreq
asio::steady_timer pingreq_timer_;
/// packet id manager
mqtt::idmgr<std::atomic<mqtt::two_byte_integer::value_type>> idmgr_;
};
}
namespace asio2
{
using mqtt_client_args = detail::template_args_mqtt_client;
template<class derived_t, class args_t>
using mqtt_client_impl_t = detail::mqtt_client_impl_t<derived_t, args_t>;
template<class derived_t>
class mqtt_client_t : public detail::mqtt_client_impl_t<derived_t, detail::template_args_mqtt_client>
{
public:
using detail::mqtt_client_impl_t<derived_t, detail::template_args_mqtt_client>::mqtt_client_impl_t;
};
class mqtt_client : public mqtt_client_t<mqtt_client>
{
public:
using mqtt_client_t<mqtt_client>::mqtt_client_t;
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_MQTT_CLIENT_HPP__
<file_sep>// (C) Copyright <NAME> 2001 - 2002.
// (C) Copyright <NAME> 2001.
// (C) Copyright <NAME> 2002.
// (C) Copyright <NAME> 2002.
// (C) Copyright <NAME> 2005.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
//
// Options common to all edg based compilers.
//
// This is included from within the individual compiler mini-configs.
#ifndef __EDG_VERSION__
# error This file requires that __EDG_VERSION__ be defined.
#endif
#if (__EDG_VERSION__ <= 238)
# define BHO_NO_INTEGRAL_INT64_T
# define BHO_NO_SFINAE
#endif
#if (__EDG_VERSION__ <= 240)
# define BHO_NO_VOID_RETURNS
#endif
#if (__EDG_VERSION__ <= 241) && !defined(BHO_NO_ARGUMENT_DEPENDENT_LOOKUP)
# define BHO_NO_ARGUMENT_DEPENDENT_LOOKUP
#endif
#if (__EDG_VERSION__ <= 244) && !defined(BHO_NO_TEMPLATE_TEMPLATES)
# define BHO_NO_TEMPLATE_TEMPLATES
#endif
#if (__EDG_VERSION__ < 300) && !defined(BHO_NO_IS_ABSTRACT)
# define BHO_NO_IS_ABSTRACT
#endif
#if (__EDG_VERSION__ <= 303) && !defined(BHO_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL)
# define BHO_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL
#endif
// See also kai.hpp which checks a Kai-specific symbol for EH
# if !defined(__KCC) && !defined(__EXCEPTIONS) && !defined(BHO_NO_EXCEPTIONS)
# define BHO_NO_EXCEPTIONS
# endif
# if !defined(__NO_LONG_LONG)
# define BHO_HAS_LONG_LONG
# else
# define BHO_NO_LONG_LONG
# endif
// Not sure what version was the first to support #pragma once, but
// different EDG-based compilers (e.g. Intel) supported it for ages.
// Add a proper version check if it causes problems.
#define BHO_HAS_PRAGMA_ONCE
//
// C++0x features
//
// See above for BHO_NO_LONG_LONG
//
#if (__EDG_VERSION__ < 310)
# define BHO_NO_CXX11_EXTERN_TEMPLATE
#endif
#if (__EDG_VERSION__ <= 310)
// No support for initializer lists
# define BHO_NO_CXX11_HDR_INITIALIZER_LIST
#endif
#if (__EDG_VERSION__ < 400)
# define BHO_NO_CXX11_VARIADIC_MACROS
#endif
#define BHO_NO_CXX11_AUTO_DECLARATIONS
#define BHO_NO_CXX11_AUTO_MULTIDECLARATIONS
#define BHO_NO_CXX11_DEFAULTED_FUNCTIONS
#define BHO_NO_CXX11_DELETED_FUNCTIONS
#define BHO_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#define BHO_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define BHO_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define BHO_NO_CXX11_NOEXCEPT
#define BHO_NO_CXX11_NULLPTR
#define BHO_NO_CXX11_RVALUE_REFERENCES
#define BHO_NO_CXX11_SCOPED_ENUMS
#define BHO_NO_SFINAE_EXPR
#define BHO_NO_CXX11_SFINAE_EXPR
#define BHO_NO_CXX11_STATIC_ASSERT
#define BHO_NO_CXX11_TEMPLATE_ALIASES
#define BHO_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
#define BHO_NO_CXX11_ALIGNAS
#define BHO_NO_CXX11_TRAILING_RESULT_TYPES
#define BHO_NO_CXX11_INLINE_NAMESPACES
#define BHO_NO_CXX11_REF_QUALIFIERS
#define BHO_NO_CXX11_FINAL
#define BHO_NO_CXX11_OVERRIDE
#define BHO_NO_CXX11_THREAD_LOCAL
#define BHO_NO_CXX11_UNRESTRICTED_UNION
//__cpp_decltype 200707 possibly?
#define BHO_NO_CXX11_DECLTYPE
#define BHO_NO_CXX11_DECLTYPE_N3276
#if !defined(__cpp_unicode_characters) || (__cpp_unicode_characters < 200704)
# define BHO_NO_CXX11_CHAR16_T
# define BHO_NO_CXX11_CHAR32_T
#endif
#if !defined(__cpp_unicode_literals) || (__cpp_unicode_literals < 200710)
# define BHO_NO_CXX11_UNICODE_LITERALS
#endif
#if !defined(__cpp_user_defined_literals) || (__cpp_user_defined_literals < 200809)
# define BHO_NO_CXX11_USER_DEFINED_LITERALS
#endif
#if !defined(__cpp_variadic_templates) || (__cpp_variadic_templates < 200704)
# define BHO_NO_CXX11_VARIADIC_TEMPLATES
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 200907)
# define BHO_NO_CXX11_CONSTEXPR
#endif
#if !defined(__cpp_lambdas) || (__cpp_lambdas < 200907)
# define BHO_NO_CXX11_LAMBDAS
#endif
#if !defined(__cpp_range_based_for) || (__cpp_range_based_for < 200710)
# define BHO_NO_CXX11_RANGE_BASED_FOR
#endif
#if !defined(__cpp_raw_strings) || (__cpp_raw_strings < 200610)
# define BHO_NO_CXX11_RAW_LITERALS
#endif
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BHO_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BHO_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BHO_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BHO_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BHO_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BHO_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BHO_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BHO_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BHO_NO_CXX14_VARIABLE_TEMPLATES
#endif
// C++17
#if !defined(__cpp_structured_bindings) || (__cpp_structured_bindings < 201606)
# define BHO_NO_CXX17_STRUCTURED_BINDINGS
#endif
#if !defined(__cpp_inline_variables) || (__cpp_inline_variables < 201606)
# define BHO_NO_CXX17_INLINE_VARIABLES
#endif
#if !defined(__cpp_fold_expressions) || (__cpp_fold_expressions < 201603)
# define BHO_NO_CXX17_FOLD_EXPRESSIONS
#endif
#if !defined(__cpp_if_constexpr) || (__cpp_if_constexpr < 201606)
# define BHO_NO_CXX17_IF_CONSTEXPR
#endif
#ifdef c_plusplus
// EDG has "long long" in non-strict mode
// However, some libraries have insufficient "long long" support
// #define BHO_HAS_LONG_LONG
#endif
<file_sep>#ifndef ASIO2_ENABLE_SSL
#define ASIO2_ENABLE_SSL
#endif
#include <asio2/websocket/wss_client.hpp>
#include <iostream>
int main()
{
std::string_view host = "127.0.0.1";
std::string_view port = "8007";
asio2::wss_client client;
client.set_connect_timeout(std::chrono::seconds(10));
client.set_verify_mode(asio::ssl::verify_peer);
client.set_cert_file(
"../../cert/ca.crt",
"../../cert/client.crt",
"../../cert/client.key",
"123456");
if (asio2::get_last_error())
std::cout << "load cert files failed: " << asio2::last_error_msg() << std::endl;
client.bind_init([&]()
{
// how to set custom websocket request data :
client.ws_stream().set_option(
websocket::stream_base::decorator([](websocket::request_type& req)
{
req.set(http::field::authorization, "ssl-websocket-client-coro");
}));
}).bind_recv([&](std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
std::string str;
str += '<';
int len = 128 + std::rand() % (300);
for (int i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
str += '>';
client.async_send(std::move(str));
}).bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n",
client.local_address().c_str(), client.local_port());
// a new thread.....
std::thread([&]()
{
// inner this new thread, we post a task, the task must be executed
// in the client's io_context thread, not in this new thread.
client.post([&]()
{
ASIO2_ASSERT(client.running_in_this_thread());
std::string str;
str += '<';
int len = 128 + std::rand() % (300);
for (int i = 0; i < len; i++)
{
str += (char)((std::rand() % 26) + 'a');
}
str += '>';
client.async_send(std::move(str));
});
}).join();
}).bind_upgrade([&]()
{
if (asio2::get_last_error())
printf("upgrade failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
{
const websocket::response_type& rep = client.get_upgrade_response();
beast::string_view auth = rep.at(http::field::authentication_results);
std::cout << auth << std::endl;
ASIO2_ASSERT(auth == "200 OK");
std::cout << "upgrade success : " << rep << std::endl;
}
}).bind_disconnect([]()
{
printf("disconnect : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
});
// the /ws is the websocket upgraged target
client.async_start(host, port, "/ws");
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_INI_HPP__
#define __ASIO2_INI_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if defined(__GNUC__) || defined(__GNUG__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Warray-bounds"
#endif
#include <cstring>
#include <cctype>
#include <cstdarg>
#include <clocale>
#include <climits>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <memory>
#include <string>
#include <locale>
#include <string_view>
#include <vector>
#include <mutex>
#include <shared_mutex>
#include <fstream>
#include <sstream>
#include <type_traits>
#include <system_error>
#include <limits>
#include <algorithm>
#include <tuple>
#include <chrono>
/*
*
* How to determine whether to use <filesystem> or <experimental/filesystem>
* https://stackoverflow.com/questions/53365538/how-to-determine-whether-to-use-filesystem-or-experimental-filesystem/53365539#53365539
*
*
*/
// We haven't checked which filesystem to include yet
#ifndef INCLUDE_STD_FILESYSTEM_EXPERIMENTAL
// Check for feature test macro for <filesystem>
# if defined(__cpp_lib_filesystem)
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 0
// Check for feature test macro for <experimental/filesystem>
# elif defined(__cpp_lib_experimental_filesystem)
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 1
// We can't check if headers exist...
// Let's assume experimental to be safe
# elif !defined(__has_include)
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 1
// Check if the header "<filesystem>" exists
# elif __has_include(<filesystem>)
// If we're compiling on Visual Studio and are not compiling with C++17, we need to use experimental
# ifdef _MSC_VER
// Check and include header that defines "_HAS_CXX17"
# if __has_include(<yvals_core.h>)
# include <yvals_core.h>
// Check for enabled C++17 support
# if defined(_HAS_CXX17) && _HAS_CXX17
// We're using C++17, so let's use the normal version
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 0
# endif
# endif
// If the marco isn't defined yet, that means any of the other VS specific checks failed, so we need to use experimental
# ifndef INCLUDE_STD_FILESYSTEM_EXPERIMENTAL
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 1
# endif
// Not on Visual Studio. Let's use the normal version
# else // #ifdef _MSC_VER
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 0
# endif
// Check if the header "<filesystem>" exists
# elif __has_include(<experimental/filesystem>)
# define INCLUDE_STD_FILESYSTEM_EXPERIMENTAL 1
// Fail if neither header is available with a nice error message
# else
# error Could not find system header "<filesystem>" or "<experimental/filesystem>"
# endif
// We priously determined that we need the exprimental version
# if INCLUDE_STD_FILESYSTEM_EXPERIMENTAL
// Include it
# include <experimental/filesystem>
// We need the alias from std::experimental::filesystem to std::filesystem
namespace std {
namespace filesystem = experimental::filesystem;
}
// We have a decent compiler and can use the normal version
# else
// Include it
# include <filesystem>
# endif
#endif // #ifndef INCLUDE_STD_FILESYSTEM_EXPERIMENTAL
// when compiled with "Visual Studio 2017 - Windows XP (v141_xp)"
// there is hasn't shared_mutex
#ifndef ASIO2_HAS_SHARED_MUTEX
#if defined(_MSC_VER)
#if defined(_HAS_SHARED_MUTEX)
#if _HAS_SHARED_MUTEX
#define ASIO2_HAS_SHARED_MUTEX 1
#define asio2_shared_mutex std::shared_mutex
#define asio2_shared_lock std::shared_lock
#define asio2_unique_lock std::unique_lock
#else
#define ASIO2_HAS_SHARED_MUTEX 0
#define asio2_shared_mutex std::mutex
#define asio2_shared_lock std::lock_guard
#define asio2_unique_lock std::lock_guard
#endif
#else
#define ASIO2_HAS_SHARED_MUTEX 1
#define asio2_shared_mutex std::shared_mutex
#define asio2_shared_lock std::shared_lock
#define asio2_unique_lock std::unique_lock
#endif
#else
#define ASIO2_HAS_SHARED_MUTEX 1
#define asio2_shared_mutex std::shared_mutex
#define asio2_shared_lock std::shared_lock
#define asio2_unique_lock std::unique_lock
#endif
#endif
#if defined(unix) || defined(__unix) || defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE) || \
defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
# if __has_include(<unistd.h>)
# include <unistd.h>
# endif
# if __has_include(<sys/types.h>)
# include <sys/types.h>
# endif
# if __has_include(<sys/stat.h>)
# include <sys/stat.h>
# endif
# if __has_include(<dirent.h>)
# include <dirent.h>
# endif
#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || \
defined(_WINDOWS_) || defined(__WINDOWS__) || defined(__TOS_WIN__)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# if __has_include(<Windows.h>)
# include <Windows.h>
# endif
# if __has_include(<tchar.h>)
# include <tchar.h>
# endif
# if __has_include(<io.h>)
# include <io.h>
# endif
# if __has_include(<direct.h>)
# include <direct.h>
# endif
#elif defined(__APPLE__) && defined(__MACH__)
# if __has_include(<mach-o/dyld.h>)
# include <mach-o/dyld.h>
# endif
#endif
/*
* mutex:
* Linux platform needs to add -lpthread option in link libraries
*/
namespace asio2
{
template<class T>
struct convert;
template<>
struct convert<bool>
{
/**
* @brief Returns `true` if two strings are equal, using a case-insensitive comparison.
*/
template<typename = void>
inline static bool iequals(std::string_view lhs, std::string_view rhs) noexcept
{
auto n = lhs.size();
if (rhs.size() != n)
return false;
auto p1 = lhs.data();
auto p2 = rhs.data();
char a, b;
// fast loop
while (n--)
{
a = *p1++;
b = *p2++;
if (a != b)
goto slow;
}
return true;
slow:
do
{
if (std::tolower(a) != std::tolower(b))
return false;
a = *p1++;
b = *p2++;
} while (n--);
return true;
}
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
inline static bool stov(std::basic_string<CharT, Traits, Allocator>& val)
{
if (iequals(val, "true"))
return true;
if (iequals(val, "false"))
return false;
return (!(std::stoi(val) == 0));
}
};
template<>
struct convert<char>
{
template<class ...Args>
inline static char stov(Args&&... args)
{ return static_cast<char>(std::stoi(std::forward<Args>(args)...)); }
};
template<>
struct convert<signed char>
{
template<class ...Args>
inline static signed char stov(Args&&... args)
{ return static_cast<signed char>(std::stoi(std::forward<Args>(args)...)); }
};
template<>
struct convert<unsigned char>
{
template<class ...Args>
inline static unsigned char stov(Args&&... args)
{ return static_cast<unsigned char>(std::stoul(std::forward<Args>(args)...)); }
};
template<>
struct convert<short>
{
template<class ...Args>
inline static short stov(Args&&... args)
{ return static_cast<short>(std::stoi(std::forward<Args>(args)...)); }
};
template<>
struct convert<unsigned short>
{
template<class ...Args>
inline static unsigned short stov(Args&&... args)
{ return static_cast<unsigned short>(std::stoul(std::forward<Args>(args)...)); }
};
template<>
struct convert<int>
{
template<class ...Args>
inline static int stov(Args&&... args)
{ return std::stoi(std::forward<Args>(args)...); }
};
template<>
struct convert<unsigned int>
{
template<class ...Args>
inline static unsigned int stov(Args&&... args)
{ return static_cast<unsigned int>(std::stoul(std::forward<Args>(args)...)); }
};
template<>
struct convert<long>
{
template<class ...Args>
inline static long stov(Args&&... args)
{ return std::stol(std::forward<Args>(args)...); }
};
template<>
struct convert<unsigned long>
{
template<class ...Args>
inline static unsigned long stov(Args&&... args)
{ return std::stoul(std::forward<Args>(args)...); }
};
template<>
struct convert<long long>
{
template<class ...Args>
inline static long long stov(Args&&... args)
{ return std::stoll(std::forward<Args>(args)...); }
};
template<>
struct convert<unsigned long long>
{
template<class ...Args>
inline static unsigned long long stov(Args&&... args)
{ return std::stoull(std::forward<Args>(args)...); }
};
template<>
struct convert<float>
{
template<class ...Args>
inline static float stov(Args&&... args)
{ return std::stof(std::forward<Args>(args)...); }
};
template<>
struct convert<double>
{
template<class ...Args>
inline static double stov(Args&&... args)
{ return std::stod(std::forward<Args>(args)...); }
};
template<>
struct convert<long double>
{
template<class ...Args>
inline static long double stov(Args&&... args)
{ return std::stold(std::forward<Args>(args)...); }
};
template<class CharT, class Traits, class Allocator>
struct convert<std::basic_string<CharT, Traits, Allocator>>
{
template<class ...Args>
inline static std::basic_string<CharT, Traits, Allocator> stov(Args&&... args)
{ return std::basic_string<CharT, Traits, Allocator>(std::forward<Args>(args)...); }
};
template<class CharT, class Traits>
struct convert<std::basic_string_view<CharT, Traits>>
{
template<class ...Args>
inline static std::basic_string_view<CharT, Traits> stov(Args&&... args)
{ return std::basic_string_view<CharT, Traits>(std::forward<Args>(args)...); }
};
template<class Rep, class Period>
struct convert<std::chrono::duration<Rep, Period>>
{
// referenced from: C# TimeSpan
// 30 - 30 seconds
// 00:00:00.0000036 - 36 milliseconds
// 00:00:00 - 0 seconds
// 2.10:36:45 - 2 days 10 hours 36 minutes 45 seconds
// 2.00:00:00.0000036 -
template<class S>
inline static std::chrono::duration<Rep, Period> stov(S&& s)
{
std::size_t n1 = s.find(':');
if (n1 == std::string::npos)
return std::chrono::seconds(std::stoll(s));
int day = 0, hour = 0, min = 0, sec = 0, msec = 0;
std::size_t m1 = s.find('.');
if (m1 < n1)
{
day = std::stoi(s.substr(0, m1));
s.erase(0, m1 + 1);
}
n1 = s.find(':');
hour = std::stoi(s.substr(0, n1));
s.erase(0, n1 + 1);
n1 = s.find(':');
min = std::stoi(s.substr(0, n1));
s.erase(0, n1 + 1);
n1 = s.find('.');
sec = std::stoi(s.substr(0, n1));
if (n1 != std::string::npos)
{
s.erase(0, n1 + 1);
msec = std::stoi(s);
}
return
std::chrono::hours(day * 24) +
std::chrono::hours(hour) +
std::chrono::minutes(min) +
std::chrono::seconds(sec) +
std::chrono::milliseconds(msec);
}
};
template<class Clock, class Duration>
struct convert<std::chrono::time_point<Clock, Duration>>
{
template<class S>
inline static std::chrono::time_point<Clock, Duration> stov(S&& s)
{
std::stringstream ss;
ss << std::forward<S>(s);
std::tm t{};
if (s.find('/') != std::string::npos)
ss >> std::get_time(&t, "%m/%d/%Y %H:%M:%S");
else
ss >> std::get_time(&t, "%Y-%m-%d %H:%M:%S");
return Clock::from_time_t(std::mktime(&t));
}
};
}
namespace asio2
{
// use namespace asio2::detail::util to avoid conflict with asio2::detail in file "asio2/base/detail/util.hpp"
// is_string_view ...
namespace detail::util
{
template<typename, typename = void>
struct is_fstream : std::false_type {};
template<typename T>
struct is_fstream<T, std::void_t<typename T::char_type, typename T::traits_type,
typename std::enable_if_t<std::is_same_v<T,
std::basic_fstream<typename T::char_type, typename T::traits_type>>>>> : std::true_type {};
template<class T>
inline constexpr bool is_fstream_v = is_fstream<std::remove_cv_t<std::remove_reference_t<T>>>::value;
template<typename, typename = void>
struct is_ifstream : std::false_type {};
template<typename T>
struct is_ifstream<T, std::void_t<typename T::char_type, typename T::traits_type,
typename std::enable_if_t<std::is_same_v<T,
std::basic_ifstream<typename T::char_type, typename T::traits_type>>>>> : std::true_type {};
template<class T>
inline constexpr bool is_ifstream_v = is_ifstream<std::remove_cv_t<std::remove_reference_t<T>>>::value;
template<typename, typename = void>
struct is_ofstream : std::false_type {};
template<typename T>
struct is_ofstream<T, std::void_t<typename T::char_type, typename T::traits_type,
typename std::enable_if_t<std::is_same_v<T,
std::basic_ofstream<typename T::char_type, typename T::traits_type>>>>> : std::true_type {};
template<class T>
inline constexpr bool is_ofstream_v = is_ofstream<std::remove_cv_t<std::remove_reference_t<T>>>::value;
template<class T>
inline constexpr bool is_file_stream_v = is_fstream_v<T> || is_ifstream_v<T> || is_ofstream_v<T>;
template<typename, typename = void>
struct is_string_view : std::false_type {};
template<typename T>
struct is_string_view<T, std::void_t<typename T::value_type, typename T::traits_type,
typename std::enable_if_t<std::is_same_v<T,
std::basic_string_view<typename T::value_type, typename T::traits_type>>>>> : std::true_type {};
template<class T>
inline constexpr bool is_string_view_v = is_string_view<T>::value;
template<typename, typename = void>
struct is_char_pointer : std::false_type {};
// char const *
// std::remove_cv_t<std::remove_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>
// char
template<typename T>
struct is_char_pointer<T, std::void_t<typename std::enable_if_t <
std::is_pointer_v< std::remove_cv_t<std::remove_reference_t<T>>> &&
!std::is_pointer_v<std::remove_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>> &&
(
std::is_same_v<std::remove_cv_t<std::remove_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>>, char > ||
std::is_same_v<std::remove_cv_t<std::remove_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>>, wchar_t > ||
#if defined(__cpp_lib_char8_t)
std::is_same_v<std::remove_cv_t<std::remove_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>>, char8_t > ||
#endif
std::is_same_v<std::remove_cv_t<std::remove_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>>, char16_t> ||
std::is_same_v<std::remove_cv_t<std::remove_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>>, char32_t>
)
>>> : std::true_type {};
template<class T>
inline constexpr bool is_char_pointer_v = is_char_pointer<T>::value;
template<typename, typename = void>
struct is_char_array : std::false_type {};
template<typename T>
struct is_char_array<T, std::void_t<typename std::enable_if_t <
std::is_array_v<std::remove_cv_t<std::remove_reference_t<T>>> &&
(
std::is_same_v<std::remove_cv_t<std::remove_all_extents_t<std::remove_cv_t<std::remove_reference_t<T>>>>, char > ||
std::is_same_v<std::remove_cv_t<std::remove_all_extents_t<std::remove_cv_t<std::remove_reference_t<T>>>>, wchar_t > ||
#if defined(__cpp_lib_char8_t)
std::is_same_v<std::remove_cv_t<std::remove_all_extents_t<std::remove_cv_t<std::remove_reference_t<T>>>>, char8_t > ||
#endif
std::is_same_v<std::remove_cv_t<std::remove_all_extents_t<std::remove_cv_t<std::remove_reference_t<T>>>>, char16_t> ||
std::is_same_v<std::remove_cv_t<std::remove_all_extents_t<std::remove_cv_t<std::remove_reference_t<T>>>>, char32_t>
)
>>> : std::true_type {};
template<class T>
inline constexpr bool is_char_array_v = is_char_array<T>::value;
template<class R>
struct return_type
{
template<class T, bool> struct string_view_traits { using type = T; };
template<class T> struct string_view_traits<T, true>
{
using type = std::basic_string<typename std::remove_cv_t<std::remove_reference_t<R>>::value_type>;
};
using type = typename std::conditional_t<is_char_pointer_v<R> || is_char_array_v<R>,
std::basic_string<std::remove_cv_t<std::remove_all_extents_t<
std::remove_pointer_t<std::remove_cv_t<std::remove_reference_t<R>>>>>>,
typename string_view_traits<R, is_string_view_v<R>>::type>;
};
}
namespace detail
{
template<class Stream>
class basic_file_ini_impl : public Stream
{
public:
template<class ...Args>
basic_file_ini_impl(Args&&... args)
{
std::ios_base::openmode mode{};
if constexpr /**/ (sizeof...(Args) == 0)
{
#if defined(unix) || defined(__unix) || defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE) || \
defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
filepath_.resize(PATH_MAX);
auto r = readlink("/proc/self/exe", (char *)filepath_.data(), PATH_MAX);
std::ignore = r; // gcc 7 warning: ignoring return value of ... [-Wunused-result]
#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || \
defined(_WINDOWS_) || defined(__WINDOWS__) || defined(__TOS_WIN__)
filepath_.resize(MAX_PATH);
filepath_.resize(::GetModuleFileNameA(NULL, (LPSTR)filepath_.data(), MAX_PATH));
#elif defined(__APPLE__) && defined(__MACH__)
filepath_.resize(PATH_MAX);
std::uint32_t bufsize = std::uint32_t(PATH_MAX);
_NSGetExecutablePath(filepath_.data(), std::addressof(bufsize));
#endif
if (std::string::size_type pos = filepath_.find('\0'); pos != std::string::npos)
filepath_.resize(pos);
#if defined(_DEBUG) || defined(DEBUG)
assert(!filepath_.empty());
#endif
std::filesystem::path path{ filepath_ };
std::string name = path.filename().string();
std::string ext = path.extension().string();
name.resize(name.size() - ext.size());
filepath_ = path.parent_path().append(name).string() + ".ini";
}
else if constexpr (sizeof...(Args) == 1)
{
filepath_ = std::move(std::get<0>(std::make_tuple(std::forward<Args>(args)...)));
}
else if constexpr (sizeof...(Args) == 2)
{
auto t = std::make_tuple(std::forward<Args>(args)...);
filepath_ = std::move(std::get<0>(t));
mode |= std::get<1>(t);
}
else
{
std::ignore = true;
}
std::error_code ec;
// if file is not exists, create it
if (bool b = std::filesystem::exists(filepath_, ec); !b && !ec)
{
Stream f(filepath_, std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
}
if constexpr /**/ (detail::util::is_fstream_v<Stream>)
{
mode |= std::ios_base::in | std::ios_base::out | std::ios_base::binary;
}
else if constexpr (detail::util::is_ifstream_v<Stream>)
{
mode |= std::ios_base::in | std::ios_base::binary;
}
else if constexpr (detail::util::is_ofstream_v<Stream>)
{
mode |= std::ios_base::out | std::ios_base::binary;
}
else
{
mode |= std::ios_base::in | std::ios_base::out | std::ios_base::binary;
}
Stream::open(filepath_, mode);
}
~basic_file_ini_impl()
{
using pos_type = typename Stream::pos_type;
Stream::clear();
Stream::seekg(0, std::ios::end);
auto filesize = Stream::tellg();
if (filesize)
{
pos_type spaces = pos_type(0);
do
{
Stream::clear();
Stream::seekg(filesize - spaces - pos_type(1));
char c;
if (!Stream::get(c))
break;
if (c == ' ' || c == '\0')
spaces = spaces + pos_type(1);
else
break;
} while (true);
if (spaces)
{
std::error_code ec;
std::filesystem::resize_file(filepath_, filesize - spaces, ec);
}
}
}
inline std::string filepath() { return filepath_; }
protected:
std::string filepath_;
};
template<class Stream>
class basic_ini_impl : public Stream
{
public:
template<class ...Args>
basic_ini_impl(Args&&... args) : Stream(std::forward<Args>(args)...) {}
};
template<class... Ts>
class basic_ini_impl<std::basic_fstream<Ts...>> : public basic_file_ini_impl<std::basic_fstream<Ts...>>
{
public:
template<class ...Args>
basic_ini_impl(Args&&... args) : basic_file_ini_impl<std::basic_fstream<Ts...>>(std::forward<Args>(args)...) {}
};
template<class... Ts>
class basic_ini_impl<std::basic_ifstream<Ts...>> : public basic_file_ini_impl<std::basic_ifstream<Ts...>>
{
public:
template<class ...Args>
basic_ini_impl(Args&&... args) : basic_file_ini_impl<std::basic_ifstream<Ts...>>(std::forward<Args>(args)...) {}
};
template<class... Ts>
class basic_ini_impl<std::basic_ofstream<Ts...>> : public basic_file_ini_impl<std::basic_ofstream<Ts...>>
{
public:
template<class ...Args>
basic_ini_impl(Args&&... args) : basic_file_ini_impl<std::basic_ofstream<Ts...>>(std::forward<Args>(args)...) {}
};
}
/**
* basic_ini operator class
*/
template<class Stream>
class basic_ini : public detail::basic_ini_impl<Stream>
{
public:
using char_type = typename Stream::char_type;
using pos_type = typename Stream::pos_type;
using size_type = typename std::basic_string<char_type>::size_type;
template<class ...Args>
basic_ini(Args&&... args) : detail::basic_ini_impl<Stream>(std::forward<Args>(args)...)
{
this->endl_ = { '\n' };
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || \
defined(_WINDOWS_) || defined(__WINDOWS__) || defined(__TOS_WIN__)
this->endl_ = { '\r','\n' };
#elif defined(__APPLE__) && defined(__MACH__)
// on the macos 9, the newline character is '\r'.
// the last macos 9 version is 9.2.2 (20011205)
//this->endl_ = { '\r' };
#endif
}
protected:
template<class Traits = std::char_traits<char_type>, class Allocator = std::allocator<char_type>>
bool _get(
std::basic_string_view<char_type, Traits> sec,
std::basic_string_view<char_type, Traits> key,
std::basic_string<char_type, Traits, Allocator> & val)
{
asio2_shared_lock guard(this->mutex_);
Stream::clear();
if (Stream::operator bool())
{
std::basic_string<char_type, Traits, Allocator> line;
std::basic_string<char_type, Traits, Allocator> s, k, v;
pos_type posg;
Stream::seekg(0, std::ios::beg);
char ret;
while ((ret = this->_getline(line, s, k, v, posg)) != 'n')
{
switch (ret)
{
case 'a':break;
case 's':
if (s == sec)
{
do
{
ret = this->_getline(line, s, k, v, posg);
if (ret == 'k' && k == key)
{
val = std::move(v);
return true;
}
} while (ret == 'k' || ret == 'a' || ret == 'o');
return false;
}
break;
case 'k':
if (s == sec)
{
if (k == key)
{
val = std::move(v);
return true;
}
}
break;
case 'o':break;
default:break;
}
}
}
return false;
}
public:
/**
* get the value associated with a key in the specified section of an ini file.
* This function does not throw an exception.
* example :
* asio2::ini ini("config.ini");
* std::string host = ini.get("main", "host", "127.0.0.1");
* std::uint16_t port = ini.get("main", "port", 8080);
* or :
* std::string host = ini.get<std::string >("main", "host");
* std::uint16_t port = ini.get<std::uint16_t>("main", "port");
*/
template<class R, class Sec, class Key, class Traits = std::char_traits<char_type>,
class Allocator = std::allocator<char_type>>
inline typename detail::util::return_type<R>::type
get(const Sec& sec, const Key& key, R default_val = R())
{
using return_t = typename detail::util::return_type<R>::type;
try
{
std::basic_string<char_type, Traits, Allocator> val;
bool flag = this->_get(
std::basic_string_view<char_type, Traits>(sec),
std::basic_string_view<char_type, Traits>(key),
val);
if constexpr (detail::util::is_char_pointer_v<R> || detail::util::is_char_array_v<R>)
{
return (flag ? val : return_t{ default_val });
}
else if constexpr (detail::util::is_string_view_v<R>)
{
return (flag ? val : return_t{ default_val });
}
else
{
return (flag ? asio2::convert<R>::stov(val) : default_val);
}
}
catch (std::invalid_argument const&)
{
}
catch (std::out_of_range const&)
{
}
catch (std::exception const&)
{
}
return return_t{ default_val };
}
/**
* set the value associated with a key in the specified section of an ini file.
* example :
* asio2::ini ini("config.ini");
* ini.set("main", "host", "127.0.0.1");
* ini.set("main", "port", 8080);
*/
template<class Sec, class Key, class Val, class Traits = std::char_traits<char_type>>
inline typename std::enable_if_t<std::is_same_v<decltype(
std::basic_string_view<char_type, Traits>(std::declval<Sec>()),
std::basic_string_view<char_type, Traits>(std::declval<Key>()),
std::basic_string_view<char_type, Traits>(std::declval<Val>()),
std::true_type()), std::true_type>, bool>
set(const Sec& sec, const Key& key, const Val& val)
{
return this->set(
std::basic_string_view<char_type, Traits>(sec),
std::basic_string_view<char_type, Traits>(key),
std::basic_string_view<char_type, Traits>(val));
}
/**
* set the value associated with a key in the specified section of an ini file.
* example :
* asio2::ini ini("config.ini");
* ini.set("main", "host", "127.0.0.1");
* ini.set("main", "port", 8080);
*/
template<class Sec, class Key, class Val, class Traits = std::char_traits<char_type>>
inline typename std::enable_if_t<std::is_same_v<decltype(
std::basic_string_view<char_type, Traits>(std::declval<Sec>()),
std::basic_string_view<char_type, Traits>(std::declval<Key>()),
std::to_string(std::declval<Val>()),
std::true_type()), std::true_type>, bool>
set(const Sec& sec, const Key& key, Val val)
{
std::basic_string<char_type, Traits> v = std::to_string(val);
return this->set(
std::basic_string_view<char_type, Traits>(sec),
std::basic_string_view<char_type, Traits>(key),
std::basic_string_view<char_type, Traits>(v));
}
/**
* set the value associated with a key in the specified section of an ini file.
* example :
* asio2::ini ini("config.ini");
* ini.set("main", "host", "127.0.0.1");
* ini.set("main", "port", 8080);
*/
template<class Traits = std::char_traits<char_type>, class Allocator = std::allocator<char_type>>
bool set(
std::basic_string_view<char_type, Traits> sec,
std::basic_string_view<char_type, Traits> key,
std::basic_string_view<char_type, Traits> val)
{
asio2_unique_lock guard(this->mutex_);
Stream::clear();
if (Stream::operator bool())
{
std::basic_string<char_type, Traits, Allocator> line;
std::basic_string<char_type, Traits, Allocator> s, k, v;
pos_type posg = 0;
char ret;
auto update_v = [&]() mutable -> bool
{
try
{
if (val != v)
{
Stream::clear();
Stream::seekg(0, std::ios::end);
auto filesize = Stream::tellg();
std::basic_string<char_type, Traits, Allocator> content;
auto pos = line.find_first_of('=');
++pos;
while (pos < line.size() && (line[pos] == ' ' || line[pos] == '\t'))
++pos;
content += line.substr(0, pos);
content += val;
content += this->endl_;
int pos_diff = int(line.size() + 1 - content.size());
Stream::clear();
Stream::seekg(posg + pos_type(line.size() + 1));
int remain = int(filesize - (posg + pos_type(line.size() + 1)));
if (remain > 0)
{
content.resize(size_type(content.size() + remain));
Stream::read(content.data() + content.size() - remain, remain);
}
if (pos_diff > 0) content.append(pos_diff, ' ');
while (!content.empty() &&
(pos_type(content.size()) + posg > filesize) &&
content.back() == ' ')
{
content.erase(content.size() - 1);
}
Stream::clear();
Stream::seekp(posg);
//*this << content;
Stream::write(content.data(), content.size());
Stream::flush();
}
return true;
}
catch (std::exception &) {}
return false;
};
Stream::seekg(0, std::ios::beg);
while ((ret = this->_getline(line, s, k, v, posg)) != 'n')
{
switch (ret)
{
case 'a':break;
case 's':
if (s == sec)
{
do
{
ret = this->_getline(line, s, k, v, posg);
if (ret == 'k' && k == key)
{
return update_v();
}
} while (ret == 'k' || ret == 'a' || ret == 'o');
// can't find the key, add a new key
std::basic_string<char_type, Traits, Allocator> content;
if (posg == pos_type(-1))
{
Stream::clear();
Stream::seekg(0, std::ios::end);
posg = Stream::tellg();
}
content += this->endl_;
content += key;
content += '=';
content += val;
content += this->endl_;
Stream::clear();
Stream::seekg(0, std::ios::end);
auto filesize = Stream::tellg();
Stream::clear();
Stream::seekg(posg);
int remain = int(filesize - posg);
if (remain > 0)
{
content.resize(size_type(content.size() + remain));
Stream::read(content.data() + content.size() - remain, remain);
}
while (!content.empty() &&
(pos_type(content.size()) + posg > filesize) &&
content.back() == ' ')
{
content.erase(content.size() - 1);
}
Stream::clear();
Stream::seekp(posg);
//*this << content;
Stream::write(content.data(), content.size());
Stream::flush();
return true;
}
break;
case 'k':
if (s == sec)
{
if (k == key)
{
return update_v();
}
}
break;
case 'o':break;
default:break;
}
}
// can't find the sec and key, add a new sec and key.
std::basic_string<char_type, Traits, Allocator> content;
Stream::clear();
Stream::seekg(0, std::ios::end);
auto filesize = Stream::tellg();
content.resize(size_type(filesize));
Stream::clear();
Stream::seekg(0, std::ios::beg);
Stream::read(content.data(), content.size());
if (!content.empty() && content.back() == '\n') content.erase(content.size() - 1);
if (!content.empty() && content.back() == '\r') content.erase(content.size() - 1);
std::basic_string<char_type, Traits, Allocator> buffer;
if (!sec.empty())
{
buffer += '[';
buffer += sec;
buffer += ']';
buffer += this->endl_;
}
buffer += key;
buffer += '=';
buffer += val;
buffer += this->endl_;
if (!sec.empty())
{
if (content.empty())
content = std::move(buffer);
else
content = content + this->endl_ + buffer;
}
// if the sec is empty ( mean global), must add the key at the begin.
else
{
if (content.empty())
content = std::move(buffer);
else
content = buffer + content;
}
while (!content.empty() &&
(pos_type(content.size()) > filesize) &&
content.back() == ' ')
{
content.erase(content.size() - 1);
}
Stream::clear();
Stream::seekp(0, std::ios::beg);
//*this << content;
Stream::write(content.data(), content.size());
Stream::flush();
return true;
}
return false;
}
protected:
template<class Traits = std::char_traits<char_type>, class Allocator = std::allocator<char_type>>
char _getline(
std::basic_string<char_type, Traits, Allocator> & line,
std::basic_string<char_type, Traits, Allocator> & sec,
std::basic_string<char_type, Traits, Allocator> & key,
std::basic_string<char_type, Traits, Allocator> & val,
pos_type & posg)
{
Stream::clear();
if (Stream::good() && !Stream::eof())
{
posg = Stream::tellg();
if (posg != pos_type(-1) && std::getline(*this, line, this->endl_.back()))
{
auto trim_line = line;
trim_left(trim_line);
trim_right(trim_line);
if (trim_line.empty())
{
return 'o'; // other
}
// current line is code annotation
if (
(trim_line.size() > 0 && (trim_line[0] == ';' || trim_line[0] == '#' || trim_line[0] == ':'))
||
(trim_line.size() > 1 && trim_line[0] == '/' && trim_line[1] == '/')
)
{
return 'a'; // annotation
}
auto pos1 = trim_line.find_first_of('[');
auto pos2 = trim_line.find_first_of(']');
// current line is section
if (
pos1 == 0
&&
pos2 != std::basic_string<char_type, Traits, Allocator>::npos
&&
pos2 > pos1
)
{
sec = trim_line.substr(pos1 + 1, pos2 - pos1 - 1);
trim_left(sec);
trim_right(sec);
return 's'; // section
}
auto sep = trim_line.find_first_of('=');
// current line is key and val
if (sep != std::basic_string<char_type, Traits, Allocator>::npos && sep > 0)
{
key = trim_line.substr(0, sep);
trim_left(key);
trim_right(key);
val = trim_line.substr(sep + 1);
trim_left(val);
trim_right(val);
return 'k'; // kv
}
return 'o'; // other
}
}
return 'n'; // null
}
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
std::basic_string<CharT, Traits, Allocator>& trim_left(std::basic_string<CharT, Traits, Allocator>& s)
{
if (s.empty())
return s;
using size_type = typename std::basic_string<CharT, Traits, Allocator>::size_type;
size_type pos = 0;
for (; pos < s.size(); ++pos)
{
if (!std::isspace(static_cast<unsigned char>(s[pos])))
break;
}
s.erase(0, pos);
return s;
}
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
std::basic_string<CharT, Traits, Allocator>& trim_right(std::basic_string<CharT, Traits, Allocator>& s)
{
if (s.empty())
return s;
using size_type = typename std::basic_string<CharT, Traits, Allocator>::size_type;
size_type pos = s.size() - 1;
for (; pos != size_type(-1); pos--)
{
if (!std::isspace(static_cast<unsigned char>(s[pos])))
break;
}
s.erase(pos + 1);
return s;
}
protected:
mutable asio2_shared_mutex mutex_;
std::basic_string<char_type> endl_;
};
using ini = basic_ini<std::fstream>;
}
#if defined(__GNUC__) || defined(__GNUG__)
# pragma GCC diagnostic pop
#endif
#endif // !__ASIO2_INI_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_USER_TIMER_COMPONENT_HPP__
#define __ASIO2_USER_TIMER_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <chrono>
#include <functional>
#include <unordered_map>
#include <string>
#include <string_view>
#include <future>
#include <asio2/base/iopool.hpp>
#include <asio2/base/log.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/function_traits.hpp>
namespace asio2::detail
{
struct user_timer_handle
{
template<typename T, typename = std::void_t<typename std::enable_if_t<!std::is_same_v<
std::remove_cv_t<std::remove_reference_t<T>>, user_timer_handle>, void>>>
user_timer_handle(T&& id)
{
bind(std::forward<T>(id));
}
user_timer_handle(user_timer_handle&& other) = default;
user_timer_handle(user_timer_handle const& other) = default;
user_timer_handle& operator=(user_timer_handle&& other) = default;
user_timer_handle& operator=(user_timer_handle const& other) = default;
template<typename T>
inline typename std::enable_if_t<!std::is_same_v<std::remove_cv_t<
std::remove_reference_t<T>>, user_timer_handle>, void>
operator=(T&& id)
{
bind(std::forward<T>(id));
}
inline bool operator==(const user_timer_handle& r) const noexcept
{
return (r.handle == this->handle);
}
template<typename T>
inline void bind(T&& id)
{
using type = std::remove_cv_t<std::remove_reference_t<T>>;
using rtype = std::remove_pointer_t<std::remove_all_extents_t<type>>;
if /**/ constexpr (std::is_same_v<std::string, type>)
{
handle = std::forward<T>(id);
}
else if constexpr (detail::is_string_view_v<type>)
{
handle.resize(sizeof(typename type::value_type) * id.size());
std::memcpy((void*)handle.data(), (const void*)id.data(),
sizeof(typename type::value_type) * id.size());
}
else if constexpr (detail::is_string_v<type>)
{
handle.resize(sizeof(typename type::value_type) * id.size());
std::memcpy((void*)handle.data(), (const void*)id.data(),
sizeof(typename type::value_type) * id.size());
}
else if constexpr (std::is_integral_v<type>)
{
handle.resize(sizeof(type));
std::memcpy((void*)handle.data(), (const void*)&id, sizeof(type));
}
else if constexpr (std::is_floating_point_v<type>)
{
handle.resize(sizeof(type));
std::memcpy((void*)handle.data(), (const void*)&id, sizeof(type));
}
else if constexpr (detail::is_char_pointer_v<type>)
{
ASIO2_ASSERT(id && (*id));
if (id)
{
std::basic_string_view<rtype> sv{ id };
handle.resize(sizeof(rtype) * sv.size());
std::memcpy((void*)handle.data(), (const void*)sv.data(), sizeof(rtype) * sv.size());
}
}
else if constexpr (detail::is_char_array_v<type>)
{
std::basic_string_view<rtype> sv{ id };
handle.resize(sizeof(rtype) * sv.size());
std::memcpy((void*)handle.data(), (const void*)sv.data(), sizeof(rtype) * sv.size());
}
else if constexpr (std::is_pointer_v<type>)
{
handle = std::to_string(std::size_t(id));
}
else if constexpr (std::is_array_v<type>)
{
static_assert(detail::always_false_v<T>);
}
else if constexpr (std::is_same_v<user_timer_handle, type>)
{
static_assert(detail::always_false_v<T>);
}
else
{
static_assert(detail::always_false_v<T>);
}
}
std::string handle;
};
struct user_timer_handle_hash
{
inline std::size_t operator()(const user_timer_handle& k) const noexcept
{
return std::hash<std::string>{}(k.handle);
}
};
struct user_timer_handle_equal
{
inline bool operator()(const user_timer_handle& lhs, const user_timer_handle& rhs) const noexcept
{
return lhs.handle == rhs.handle;
}
};
struct user_timer_obj
{
user_timer_handle id;
asio::steady_timer timer;
std::function<void()> callback{};
typename asio::steady_timer::duration interval{};
mutable std::size_t repeat = static_cast<std::size_t>(-1);
mutable bool exited = false;
user_timer_obj(user_timer_handle Id, asio::io_context& context)
: id(std::move(Id)), timer(context)
{
}
};
template<class derived_t, class args_t = void>
class user_timer_cp
{
public:
using user_timer_map = std::unordered_map<user_timer_handle, std::shared_ptr<user_timer_obj>,
user_timer_handle_hash, user_timer_handle_equal>;
/**
* @brief constructor
*/
user_timer_cp() {}
/**
* @brief destructor
*/
~user_timer_cp() noexcept {}
public:
/**
* @brief start a timer
* @param timer_id - The timer id can be integer or string, example : 1,2,3 or "id1" "id2",
* If a timer with this id already exists, that timer will be forced to canceled.
* @param interval - An integer millisecond value for the amount of time between set and firing.
* @param fun - The callback function signature : [](){}
*/
template<class TimerId, class IntegerMilliseconds, class Fun, class... Args>
inline typename std::enable_if_t<is_callable_v<Fun>
&& std::is_integral_v<detail::remove_cvref_t<IntegerMilliseconds>>, void>
start_timer(TimerId&& timer_id, IntegerMilliseconds interval, Fun&& fun, Args&&... args)
{
this->start_timer(std::forward<TimerId>(timer_id), std::chrono::milliseconds(interval), std::size_t(-1),
std::chrono::milliseconds(interval), std::forward<Fun>(fun), std::forward<Args>(args)...);
}
/**
* @brief start a timer
* @param timer_id - The timer id can be integer or string, example : 1,2,3 or "id1" "id2",
* If a timer with this id already exists, that timer will be forced to canceled.
* @param interval - An integer millisecond value for the amount of time between set and firing.
* @param repeat - An integer value to indicate the number of times the timer is repeated.
* @param fun - The callback function signature : [](){}
*/
template<class TimerId, class IntegerMilliseconds, class Integer, class Fun, class... Args>
inline typename std::enable_if_t<is_callable_v<Fun>
&& std::is_integral_v<detail::remove_cvref_t<IntegerMilliseconds>>
&& std::is_integral_v<detail::remove_cvref_t<Integer>>, void>
start_timer(TimerId&& timer_id, IntegerMilliseconds interval, Integer repeat, Fun&& fun, Args&&... args)
{
this->start_timer(std::forward<TimerId>(timer_id), std::chrono::milliseconds(interval), repeat,
std::chrono::milliseconds(interval), std::forward<Fun>(fun), std::forward<Args>(args)...);
}
// ----------------------------------------------------------------------------------------
/**
* @brief start a timer
* @param timer_id - The timer id can be integer or string, example : 1,2,3 or "id1" "id2",
* If a timer with this id already exists, that timer will be forced to canceled.
* @param interval - The amount of time between set and firing.
* @param fun - The callback function signature : [](){}
*/
template<class TimerId, class Rep, class Period, class Fun, class... Args>
inline typename std::enable_if_t<is_callable_v<Fun>, void>
start_timer(TimerId&& timer_id, std::chrono::duration<Rep, Period> interval, Fun&& fun, Args&&... args)
{
this->start_timer(std::forward<TimerId>(timer_id), interval, std::size_t(-1), interval,
std::forward<Fun>(fun), std::forward<Args>(args)...);
}
/**
* @brief start a timer
* @param timer_id - The timer id can be integer or string, example : 1,2,3 or "id1" "id2",
* If a timer with this id already exists, that timer will be forced to canceled.
* @param interval - The amount of time between set and firing.
* @param repeat - An integer value to indicate the number of times the timer is repeated.
* @param fun - The callback function signature : [](){}
*/
template<class TimerId, class Rep, class Period, class Integer, class Fun, class... Args>
inline typename std::enable_if_t<
is_callable_v<Fun> && std::is_integral_v<detail::remove_cvref_t<Integer>>, void>
start_timer(TimerId&& timer_id, std::chrono::duration<Rep, Period> interval, Integer repeat,
Fun&& fun, Args&&... args)
{
this->start_timer(std::forward<TimerId>(timer_id), interval, repeat, interval,
std::forward<Fun>(fun), std::forward<Args>(args)...);
}
/**
* @brief start a timer
* @param timer_id - The timer id can be integer or string, example : 1,2,3 or "id1" "id2",
* If a timer with this id already exists, that timer will be forced to canceled.
* @param interval - The amount of time between set and firing.
* @param first_delay - The timeout for the first execute of timer.
* @param fun - The callback function signature : [](){}
*/
template<class TimerId, class Rep1, class Period1, class Rep2, class Period2, class Fun, class... Args>
inline typename std::enable_if_t<is_callable_v<Fun>, void>
start_timer(TimerId&& timer_id, std::chrono::duration<Rep1, Period1> interval,
std::chrono::duration<Rep2, Period2> first_delay, Fun&& fun, Args&&... args)
{
this->start_timer(std::forward<TimerId>(timer_id), interval, std::size_t(-1), first_delay,
std::forward<Fun>(fun), std::forward<Args>(args)...);
}
/**
* @brief start a timer
* @param timer_id - The timer id can be integer or string, example : 1,2,3 or "id1" "id2",
* If a timer with this id already exists, that timer will be forced to canceled.
* @param interval - The amount of time between set and firing.
* @param repeat - Total number of times the timer is executed.
* @param first_delay - The timeout for the first execute of timer.
* @param fun - The callback function signature : [](){}
*/
template<class TimerId, class Rep1, class Period1, class Rep2, class Period2, class Integer, class Fun, class... Args>
inline typename std::enable_if_t<
is_callable_v<Fun> && std::is_integral_v<detail::remove_cvref_t<Integer>>, void>
start_timer(TimerId&& timer_id, std::chrono::duration<Rep1, Period1> interval, Integer repeat,
std::chrono::duration<Rep2, Period2> first_delay, Fun&& fun, Args&&... args)
{
if (repeat == static_cast<std::size_t>(0))
{
ASIO2_ASSERT(false);
return;
}
if (interval > std::chrono::duration_cast<
std::chrono::duration<Rep1, Period1>>((asio::steady_timer::duration::max)()))
interval = std::chrono::duration_cast<std::chrono::duration<Rep1, Period1>>(
(asio::steady_timer::duration::max)());
if (first_delay > std::chrono::duration_cast<
std::chrono::duration<Rep2, Period2>>((asio::steady_timer::duration::max)()))
first_delay = std::chrono::duration_cast<std::chrono::duration<Rep2, Period2>>(
(asio::steady_timer::duration::max)());
derived_t& derive = static_cast<derived_t&>(*this);
std::function<void()> t = std::bind(std::forward<Fun>(fun), std::forward<Args>(args)...);
// Whether or not we run on the io_context thread, We all start the timer by post an asynchronous
// event, in order to avoid unexpected problems caused by the user start or stop the
// timer again in the timer callback function.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, &derive, this_ptr = derive.selfptr(),
timer_handle = user_timer_handle(std::forward<TimerId>(timer_id)),
interval, repeat, first_delay, callback = std::move(t)]() mutable
{
// if the timer is already exists, cancel it first.
auto iter = this->user_timers_.find(timer_handle);
if (iter != this->user_timers_.end())
{
iter->second->exited = true;
detail::cancel_timer(iter->second->timer);
}
// the asio::steady_timer's constructor may be throw some exception.
std::shared_ptr<user_timer_obj> timer_obj_ptr = std::make_shared<user_timer_obj>(
timer_handle, derive.io().context());
// after asio::steady_timer's constructor is successed, then set the callback,
// avoid the callback is empty by std::move(callback) when asio::steady_timer's
// constructor throw some exception.
timer_obj_ptr->callback = std::move(callback);
timer_obj_ptr->interval = interval;
timer_obj_ptr->repeat = static_cast<std::size_t>(repeat);
this->user_timers_[std::move(timer_handle)] = timer_obj_ptr;
derive.io().timers().emplace(std::addressof(timer_obj_ptr->timer));
derive._post_user_timers(std::move(this_ptr), std::move(timer_obj_ptr), first_delay);
}));
}
/**
* @brief stop the timer by timer id
*/
template<class TimerId>
inline void stop_timer(TimerId&& timer_id)
{
derived_t& derive = static_cast<derived_t&>(*this);
// must use post, otherwise when call stop_timer immediately after start_timer
// will cause the stop_timer has no effect.
// can't use dispatch, otherwise if call stop_timer in timer callback, it will
// cause this : the stop_timer will cancel the timer, after stop_timer, the callback
// will executed continue, then it will post next timer, beacuse the cancel is
// before the post next timer, so the cancel will has no effect. (so there was
// a flag "exit" to ensure this : even if use dispatch, the timer also can be
// canceled success)
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = derive.selfptr(), timer_id = std::forward<TimerId>(timer_id)]
() mutable
{
detail::ignore_unused(this_ptr);
auto iter = this->user_timers_.find(timer_id);
if (iter != this->user_timers_.end())
{
iter->second->exited = true;
detail::cancel_timer(iter->second->timer);
this->user_timers_.erase(iter);
}
}));
}
/**
* @brief stop all timers
*/
inline void stop_all_timers()
{
derived_t& derive = static_cast<derived_t&>(*this);
// must use post, otherwise when call stop_all_timers immediately after start_timer
// will cause the stop_all_timers has no effect.
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = derive.selfptr()]() mutable
{
// close user custom timers
for (auto &[id, timer_obj_ptr] : this->user_timers_)
{
detail::ignore_unused(this_ptr, id);
timer_obj_ptr->exited = true;
detail::cancel_timer(timer_obj_ptr->timer);
}
this->user_timers_.clear();
}));
}
/**
* @brief Returns true if the specified timer exists
*/
template<class TimerId>
inline bool is_timer_exists(TimerId&& timer_id)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (derive.io().running_in_this_thread())
{
return (this->user_timers_.find(timer_id) != this->user_timers_.end());
}
std::promise<bool> p;
std::future<bool> f = p.get_future();
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = derive.selfptr(), timer_id = std::forward<TimerId>(timer_id), &p]
() mutable
{
detail::ignore_unused(this_ptr);
p.set_value(this->user_timers_.find(timer_id) != this->user_timers_.end());
}));
return f.get();
}
/**
* @brief Get the interval for the specified timer.
*/
template<class TimerId>
inline typename asio::steady_timer::duration get_timer_interval(TimerId&& timer_id)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (derive.io().running_in_this_thread())
{
auto iter = this->user_timers_.find(timer_id);
if (iter != this->user_timers_.end())
{
return iter->second->interval;
}
else
{
return typename asio::steady_timer::duration{};
}
}
std::promise<typename asio::steady_timer::duration> p;
std::future<typename asio::steady_timer::duration> f = p.get_future();
asio::post(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = derive.selfptr(), timer_id = std::forward<TimerId>(timer_id), &p]
() mutable
{
detail::ignore_unused(this_ptr);
auto iter = this->user_timers_.find(timer_id);
if (iter != this->user_timers_.end())
{
p.set_value(iter->second->interval);
}
else
{
p.set_value(typename asio::steady_timer::duration{});
}
}));
return f.get();
}
/**
* @brief Set the interval for the specified timer.
*/
template<class TimerId, class Rep, class Period>
inline void set_timer_interval(TimerId&& timer_id, std::chrono::duration<Rep, Period> interval)
{
derived_t& derive = static_cast<derived_t&>(*this);
if (interval > std::chrono::duration_cast<
std::chrono::duration<Rep, Period>>((asio::steady_timer::duration::max)()))
interval = std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(
(asio::steady_timer::duration::max)());
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = derive.selfptr(), timer_id = std::forward<TimerId>(timer_id), interval]
() mutable
{
detail::ignore_unused(this_ptr);
auto iter = this->user_timers_.find(timer_id);
if (iter != this->user_timers_.end())
{
iter->second->interval = interval;
}
}));
}
/**
* @brief Set the interval for the specified timer.
*/
template<class TimerId, class IntegerMilliseconds>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<IntegerMilliseconds>>, void>
set_timer_interval(TimerId&& timer_id, IntegerMilliseconds interval)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.set_timer_interval(std::forward<TimerId>(timer_id), std::chrono::milliseconds(interval));
}
/**
* @brief Reset the interval for the specified timer.
*/
template<class TimerId, class Rep, class Period>
inline void reset_timer_interval(TimerId&& timer_id, std::chrono::duration<Rep, Period> interval)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.set_timer_interval(std::forward<TimerId>(timer_id), interval);
}
/**
* @brief Reset the interval for the specified timer.
*/
template<class TimerId, class IntegerMilliseconds>
inline typename std::enable_if_t<std::is_integral_v<detail::remove_cvref_t<IntegerMilliseconds>>, void>
reset_timer_interval(TimerId&& timer_id, IntegerMilliseconds interval)
{
derived_t& derive = static_cast<derived_t&>(*this);
return derive.set_timer_interval(std::forward<TimerId>(timer_id), interval);
}
protected:
/**
* @brief stop all timers
* Use dispatch instead of post, this function is used for inner.
*/
inline void _dispatch_stop_all_timers()
{
derived_t& derive = static_cast<derived_t&>(*this);
// must use post, otherwise when call stop_all_timers immediately after start_timer
// will cause the stop_all_timers has no effect.
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = derive.selfptr()]() mutable
{
// close user custom timers
for (auto &[id, timer_obj_ptr] : this->user_timers_)
{
detail::ignore_unused(this_ptr, id);
timer_obj_ptr->exited = true;
detail::cancel_timer(timer_obj_ptr->timer);
}
this->user_timers_.clear();
}));
}
protected:
template<class Rep, class Period>
inline void _post_user_timers(std::shared_ptr<derived_t> this_ptr,
std::shared_ptr<user_timer_obj> timer_obj_ptr, std::chrono::duration<Rep, Period> expiry)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT(this->user_timers_.find(timer_obj_ptr->id) != this->user_timers_.end());
asio::steady_timer& timer = timer_obj_ptr->timer;
timer.expires_after(expiry);
timer.async_wait(
[&derive, this_ptr = std::move(this_ptr), timer_ptr = std::move(timer_obj_ptr)]
(const error_code& ec) mutable
{
derive._handle_user_timers(ec, std::move(this_ptr), std::move(timer_ptr));
});
}
inline void _handle_user_timers(const error_code& ec, std::shared_ptr<derived_t> this_ptr,
std::shared_ptr<user_timer_obj> timer_obj_ptr)
{
derived_t& derive = static_cast<derived_t&>(*this);
ASIO2_ASSERT((!ec) || ec == asio::error::operation_aborted);
set_last_error(ec);
// Should the callback function also be called if there is an error in the timer ?
// It made me difficult to choose.After many adjustments and the requirements of the
// actual project, it is more reasonable to still call the callback function when
// there are some errors.
// eg. user call start_timer, then call stop_timer after a later, but the timer's
// timeout is not reached, perhaps the user wants the timer callback function also
// can be called even if the timer is aborted by stop_timer.
if (timer_obj_ptr->repeat == static_cast<std::size_t>(-1))
{
derive._invoke_user_timer_callback(ec, timer_obj_ptr);
}
else
{
ASIO2_ASSERT(timer_obj_ptr->repeat > static_cast<std::size_t>(0));
derive._invoke_user_timer_callback(ec, timer_obj_ptr);
timer_obj_ptr->repeat--;
}
/**
* @note If the timer has already expired when cancel() is called, then the
* handlers for asynchronous wait operations will:
*
* @li have already been invoked; or
*
* @li have been queued for invocation in the near future.
*
* These handlers can no longer be cancelled, and therefore are passed an
* error code that indicates the successful completion of the wait operation.
*/
// must detect whether the timer is still exists by "exited", in some cases,
// after remove and cancel a timer, the ec is 0 (not operation_aborted) and
// the steady_timer is still exist
if (timer_obj_ptr->exited)
{
// if exited is true, can't erase the timer object from the "user_timers_",
// beacuse maybe user start timer multi times with same id.
derive.io().timers().erase(std::addressof(timer_obj_ptr->timer));
return;
}
if (ec == asio::error::operation_aborted || timer_obj_ptr->repeat == static_cast<std::size_t>(0))
{
derive.io().timers().erase(std::addressof(timer_obj_ptr->timer));
auto iter = this->user_timers_.find(timer_obj_ptr->id);
if (iter != this->user_timers_.end())
{
iter->second->exited = true;
this->user_timers_.erase(iter);
}
return;
}
typename asio::steady_timer::duration expiry = timer_obj_ptr->interval;
derive._post_user_timers(std::move(this_ptr), std::move(timer_obj_ptr), expiry);
}
inline void _invoke_user_timer_callback(const error_code& ec, std::shared_ptr<user_timer_obj>& timer_obj_ptr)
{
detail::ignore_unused(ec);
#if defined(ASIO2_ENABLE_TIMER_CALLBACK_WHEN_ERROR)
(timer_obj_ptr->callback)();
#else
if (!ec)
{
(timer_obj_ptr->callback)();
}
#endif
}
protected:
/// user-defined timer
user_timer_map user_timers_;
};
}
#endif // !__ASIO2_USER_TIMER_COMPONENT_HPP__
<file_sep>/*
Copyright <NAME> 2014
Copyright <NAME> 2014-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_HAIKU_H
#define BHO_PREDEF_OS_HAIKU_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_HAIKU`
http://en.wikipedia.org/wiki/Haiku_(operating_system)[Haiku] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__HAIKU__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_OS_HAIKU BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(__HAIKU__) \
)
# undef BHO_OS_HAIKU
# define BHO_OS_HAIKU BHO_VERSION_NUMBER_AVAILABLE
#endif
#if BHO_OS_HAIKU
# define BHO_OS_HAIKU_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_HAIKU_NAME "Haiku"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_HAIKU,BHO_OS_HAIKU_NAME)
<file_sep>#include <asio2/base/detail/push_options.hpp>
#define ASIO_STANDALONE
// https://github.com/qicosmos/rest_rpc
// first : unzip the "asio2/test/bench/rpc/rest_rpc-master.zip"
// the unziped path is like this : "asio2/test/bench/rpc/rest_rpc-master/include"
#if defined(_MSC_VER)
#pragma warning(disable:4189)
#pragma warning(disable:4244)
#endif
#include <thread>
#include <iostream>
#include <rpc_client.hpp>
#include <chrono>
#include <fstream>
#include "codec.h"
#include <string>
using namespace rest_rpc;
using namespace rest_rpc::rpc_service;
std::string str(128, 'A');
void test_performance1() {
rpc_client client("127.0.0.1", 8080);
bool r = client.connect();
if (!r) {
std::cout << "connect timeout" << std::endl;
return;
}
for (;;) {
auto future = client.async_call<FUTURE>("echo", str);
auto status = future.wait_for(std::chrono::seconds(2));
if (status == std::future_status::deferred) {
std::cout << "deferred\n";
}
else if (status == std::future_status::timeout) {
std::cout << "timeout\n";
}
else if (status == std::future_status::ready) {
}
}
}
int main() {
test_performance1();
return 0;
}
#include <asio2/base/detail/pop_options.hpp>
<file_sep>#include "unit_test.hpp"
#include <asio2/util/uuid.hpp>
#include <asio2/util/string.hpp>
#include <vector>
#include <unordered_set>
#include <ctype.h>
#include <locale>
void uuid_test()
{
std::string number = "0123456789";
std::string lowers = "abcdef";
std::string uppers = "ABCDEF";
std::string empty = "00000000-0000-0000-0000-000000000000";
static std::string const short_uuid_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
std::vector<int> short_uuid_chars_flags;
short_uuid_chars_flags.resize(short_uuid_chars.size());
std::unordered_set<std::string> uuid_set;
ASIO2_TEST_BEGIN_LOOP(test_loop_times);
std::uint8_t d1[16]{};
std::uint8_t d2[16]{};
std::uint8_t d3[16]{};
std::uint8_t d4[16]{};
asio2::uuid u1;
u1.generate();
std::memcpy(d1, u1.data, 16);
ASIO2_CHECK(u1.version() == asio2::uuid::version_type::random_number_based);
ASIO2_CHECK(u1.variant() == asio2::uuid::variant_type::rfc);
{
std::string str = u1.str(false, true);
ASIO2_CHECK(str.size() == 36);
bool has_upper = false, has_group = false;
for (auto c : str)
{
if (c == '-')
{
has_group = true;
}
if (uppers.find(c) != std::string::npos)
{
has_upper = true;
}
}
ASIO2_CHECK(has_upper == false);
ASIO2_CHECK(has_group == true);
for (std::size_t i = 0; i < empty.size(); ++i)
{
if (empty[i] == '-')
{
ASIO2_CHECK(str[i] == '-');
}
else
{
ASIO2_CHECK(lowers.find(str[i]) != std::string::npos || number.find(str[i]) != std::string::npos);
}
}
asio2::replace(str, "-", "");
ASIO2_CHECK(str.find('-') == std::string::npos);
ASIO2_CHECK(str.size() == 32);
bool inserted = uuid_set.emplace(std::move(str)).second;
ASIO2_CHECK(inserted);
}
u1.generate();
std::memcpy(d2, u1.data, 16);
ASIO2_CHECK(u1.version() == asio2::uuid::version_type::random_number_based);
ASIO2_CHECK(u1.variant() == asio2::uuid::variant_type::rfc);
{
std::string str = u1.str(true, true);
ASIO2_CHECK(str.size() == 36);
bool has_lower = false, has_group = false;
for (auto c : str)
{
if (c == '-')
{
has_group = true;
}
if (lowers.find(c) != std::string::npos)
{
has_lower = true;
}
}
ASIO2_CHECK(has_lower == false);
ASIO2_CHECK(has_group == true);
for (std::size_t i = 0; i < empty.size(); ++i)
{
if (empty[i] == '-')
{
ASIO2_CHECK(str[i] == '-');
}
else
{
ASIO2_CHECK(uppers.find(str[i]) != std::string::npos || number.find(str[i]) != std::string::npos);
}
}
asio2::replace(str, "-", "");
ASIO2_CHECK(str.find('-') == std::string::npos);
ASIO2_CHECK(str.size() == 32);
std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); });
bool inserted = uuid_set.emplace(std::move(str)).second;
ASIO2_CHECK(inserted);
}
u1.generate();
std::memcpy(d3, u1.data, 16);
ASIO2_CHECK(u1.version() == asio2::uuid::version_type::random_number_based);
ASIO2_CHECK(u1.variant() == asio2::uuid::variant_type::rfc);
{
std::string str = u1.str(false, false);
ASIO2_CHECK(str.size() == 32);
bool has_upper = false, has_group = false;
for (auto c : str)
{
if (c == '-')
{
has_group = true;
}
if (uppers.find(c) != std::string::npos)
{
has_upper = true;
}
}
ASIO2_CHECK(has_upper == false);
ASIO2_CHECK(has_group == false);
bool inserted = uuid_set.emplace(std::move(str)).second;
ASIO2_CHECK(inserted);
}
u1.generate();
std::memcpy(d4, u1.data, 16);
ASIO2_CHECK(u1.version() == asio2::uuid::version_type::random_number_based);
ASIO2_CHECK(u1.variant() == asio2::uuid::variant_type::rfc);
{
std::string str = u1.str(true, false);
ASIO2_CHECK(str.size() == 32);
bool has_lower = false, has_group = false;
for (auto c : str)
{
if (c == '-')
{
has_group = true;
}
if (lowers.find(c) != std::string::npos)
{
has_lower = true;
}
}
ASIO2_CHECK(has_lower == false);
ASIO2_CHECK(has_group == false);
std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); });
bool inserted = uuid_set.emplace(std::move(str)).second;
ASIO2_CHECK(inserted);
}
{
int len = 8 + std::rand() % 24;
std::string s2 = u1.short_uuid(len);
ASIO2_CHECK(s2.size() == std::size_t(len));
for (auto c : s2)
{
auto pos = short_uuid_chars.find(c);
ASIO2_CHECK(pos != std::string::npos);
short_uuid_chars_flags[pos] = 1;
}
}
ASIO2_CHECK(std::memcmp(d1, d2, 16) != 0);
ASIO2_CHECK(std::memcmp(d1, d3, 16) != 0);
ASIO2_CHECK(std::memcmp(d1, d4, 16) != 0);
ASIO2_CHECK(std::memcmp(d2, d3, 16) != 0);
ASIO2_CHECK(std::memcmp(d2, d4, 16) != 0);
ASIO2_CHECK(std::memcmp(d3, d4, 16) != 0);
ASIO2_TEST_END_LOOP;
for (auto i : short_uuid_chars_flags)
{
ASIO2_CHECK(i == 1);
}
}
ASIO2_TEST_SUITE
(
"uuid",
ASIO2_TEST_CASE(uuid_test)
)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_RDC_OPTION_HPP__
#define __ASIO2_RDC_OPTION_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <memory>
#include <functional>
#include <type_traits>
#include <any>
#include <asio2/base/error.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/function_traits.hpp>
#include <asio2/component/rdc/rdc_invoker.hpp>
namespace asio2::rdc
{
struct option_base
{
virtual ~option_base() {}
virtual std::any call_parser(bool is_send, void* data) = 0;
virtual void emplace_request(std::any& k, void* v) = 0;
virtual void execute_and_erase(std::any& k, std::function<void(void*)> cb) = 0;
virtual void foreach_and_clear(std::function<void(void*, void*)> cb) = 0;
};
template<class IdT, class SendDataT, class RecvDataT = SendDataT>
class option : public rdc::option_base
{
protected:
using send_parser_fun = std::function<IdT(SendDataT)>;
using recv_parser_fun = std::function<IdT(RecvDataT)>;
send_parser_fun rdc_send_parser_;
recv_parser_fun rdc_recv_parser_;
using invoker_type = detail::rdc_invoker_t<IdT, SendDataT, RecvDataT>;
using iterator_type = typename invoker_type::iterator_type;
using key_type = IdT;
using val_type = typename invoker_type::value_type;
invoker_type rdc_invoker_;
public:
option(option&&) noexcept = default;
option(option const&) = default;
option& operator=(option&&) noexcept = default;
option& operator=(option const&) = default;
template<class ParserFun, std::enable_if_t<
!std::is_base_of_v<option, detail::remove_cvref_t<ParserFun>>, int> = 0>
explicit option(ParserFun&& parser)
: rdc_send_parser_(std::forward<ParserFun>(parser))
, rdc_recv_parser_(rdc_send_parser_)
{
}
template<class SendParserFun, class RecvParserFun>
explicit option(SendParserFun&& send_parser, RecvParserFun&& recv_parser)
: rdc_send_parser_(std::forward<SendParserFun>(send_parser))
, rdc_recv_parser_(std::forward<RecvParserFun>(recv_parser))
{
}
template<class ParserFun>
option& set_send_parser(ParserFun&& parser)
{
rdc_send_parser_ = std::forward<ParserFun>(parser);
return (*this);
}
template<class ParserFun>
option& set_recv_parser(ParserFun&& parser)
{
rdc_recv_parser_ = std::forward<ParserFun>(parser);
return (*this);
}
send_parser_fun& get_send_parser() noexcept { return rdc_send_parser_; }
recv_parser_fun& get_recv_parser() noexcept { return rdc_recv_parser_; }
detail::rdc_invoker_t<IdT, SendDataT, RecvDataT>& invoker() noexcept { return rdc_invoker_; }
virtual std::any call_parser(bool is_send, void* data) override
{
if (is_send)
{
typename detail::remove_cvref_t<SendDataT>& d = *((typename detail::remove_cvref_t<SendDataT>*)data);
key_type id = rdc_send_parser_(d);
return std::any(std::move(id));
}
else
{
typename detail::remove_cvref_t<RecvDataT>& d = *((typename detail::remove_cvref_t<RecvDataT>*)data);
key_type id = rdc_recv_parser_(d);
return std::any(std::move(id));
}
}
virtual void emplace_request(std::any& k, void* v) override
{
key_type& key = *std::any_cast<key_type>(&k);
val_type& val = *((val_type*)v);
rdc_invoker_.emplace(std::move(key), std::move(val));
}
virtual void execute_and_erase(std::any& k, std::function<void(void*)> cb) override
{
key_type& key = *std::any_cast<key_type>(&k);
if (auto iter = rdc_invoker_.find(key); iter != rdc_invoker_.end())
{
cb((void*)(&(iter->second)));
rdc_invoker_.erase(iter);
}
}
virtual void foreach_and_clear(std::function<void(void*, void*)> cb) override
{
for (auto& [k, v] : rdc_invoker_.reqs())
{
cb((void*)&k, (void*)&v);
}
rdc_invoker_.reqs().clear();
}
};
// C++17 class template argument deduction guides
template<class ParserFun>
option(ParserFun)->option<
typename detail::function_traits<detail::remove_cvref_t<ParserFun>>::return_type,
typename detail::function_traits<detail::remove_cvref_t<ParserFun>>::template args<0>::type,
typename detail::function_traits<detail::remove_cvref_t<ParserFun>>::template args<0>::type
>;
template<class SendParserFun, class RecvParserFun>
option(SendParserFun, RecvParserFun)->option<
typename detail::function_traits<detail::remove_cvref_t<SendParserFun>>::return_type,
typename detail::function_traits<detail::remove_cvref_t<SendParserFun>>::template args<0>::type,
typename detail::function_traits<detail::remove_cvref_t<RecvParserFun>>::template args<0>::type
>;
}
#endif // !__ASIO2_RDC_OPTION_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* refrenced from https://github.com/fffaraz/cppDES
*/
#ifndef __ASIO2_DES_IMPL_HPP__
#define __ASIO2_DES_IMPL_HPP__
#include <cassert>
#include <cstdint>
#include <cstring>
#include <string>
#include <sstream>
namespace asio2
{
class des
{
public:
des(uint64_t key)
{
keygen(key);
}
/*
* key.size() should be 8,if less than 8,key will be padded with '\0',
* if greater than 8,key will be truncate to 8
*/
des(std::string key)
{
uint64_t k = 0;
key.resize(sizeof(k));
std::memcpy((void*)&k, (const void*)key.data(), (std::min)(key.size(), sizeof(k)));
keygen(k);
}
~des()
{
}
des(const des & other)
{
std::memcpy((void *)(this->sub_key), (const void *)(other.sub_key), sizeof(this->sub_key));
}
des & operator=(const des & other)
{
std::memcpy((void *)(this->sub_key), (const void *)(other.sub_key), sizeof(this->sub_key));
return (*this);
}
des(des && other)
{
std::memcpy((void *)(this->sub_key), (const void *)(other.sub_key), sizeof(this->sub_key));
}
des & operator=(des && other)
{
std::memcpy((void *)(this->sub_key), (const void *)(other.sub_key), sizeof(this->sub_key));
return (*this);
}
uint64_t encrypt(uint64_t block)
{
return do_des(block, false);
}
uint64_t decrypt(uint64_t block)
{
return do_des(block, true);
}
/*
* note : if msg contains '\0',there may be a wrong result when decrypt
*/
std::string encrypt(std::string msg)
{
if (msg.empty())
return std::string{};
// Amount of padding needed
uint8_t padding = uint8_t(0);
if ((msg.size() % 8) != 0)
{
padding = uint8_t(8 - (msg.size() % 8));
msg.resize(msg.size() + padding);
}
uint64_t block = uint64_t(0);
uint8_t * buf = (uint8_t*)msg.data();
for (std::size_t i = 0; i < msg.size();)
{
i += 8;
memcpy(&block, buf, 8);
if (!(i < msg.size()))
{
// Pad block with a 1 followed by 0s
uint8_t shift = static_cast<uint8_t>(padding * uint8_t(8));
block <<= shift;
//buffer |= uint64_t(0x0000000000000001) << (shift - uint8_t(1));
}
block = encrypt(block);
memcpy(buf, &block, 8);
buf += 8;
}
return msg;
}
std::string decrypt(std::string msg)
{
if (msg.empty() || (msg.size() % 8) != 0)
return std::string();
uint64_t block = uint64_t(0);
uint8_t * buf = (uint8_t*)msg.data();
for (std::size_t i = 0; i < msg.size();)
{
i += 8;
memcpy(&block, buf, 8);
block = decrypt(block);
if (!(i < msg.size()))
{
// Amount of padding on file
[[maybe_unused]] uint8_t padding = uint8_t(0);
// Check for and record padding on end
while (!(block & uint64_t(0x00000000000000ff)))
{
block >>= 8;
++padding;
}
}
memcpy(buf, &block, 8);
buf += 8;
}
while (!msg.empty() && msg.back() == '\0')
msg.erase(msg.size() - 1);
return msg;
}
protected:
uint64_t do_des(uint64_t block, bool mode)
{
// applying initial permutation
block = ip(block);
// dividing T' into two 32-bit parts
uint32_t L = static_cast<uint32_t>((block >> 32) & L64_MASK);
uint32_t R = static_cast<uint32_t>(block & L64_MASK);
// 16 rounds
for (uint8_t i = 0; i < 16; ++i)
{
uint32_t F = mode ? f(R, sub_key[15 - i]) : f(R, sub_key[i]);
feistel(L, R, F);
}
// swapping the two parts
block = (((uint64_t)R) << 32) | (uint64_t)L;
// applying final permutation
return fp(block);
}
void keygen(uint64_t key)
{
// initial key schedule calculation
uint64_t permuted_choice_1 = 0; // 56 bits
for (uint8_t i = 0; i < 56; ++i)
{
permuted_choice_1 <<= 1;
permuted_choice_1 |= (key >> (64 - PC1[i])) & LB64_MASK;
}
// 28 bits
uint32_t C = (uint32_t)((permuted_choice_1 >> 28) & 0x000000000fffffff);
uint32_t D = (uint32_t)(permuted_choice_1 & 0x000000000fffffff);
// Calculation of the 16 keys
for (uint8_t i = 0; i < 16; ++i)
{
// key schedule, shifting Ci and Di
for (uint8_t j = 0; j < ITERATION_SHIFT[i]; ++j)
{
C = (0x0fffffff & (C << 1)) | (0x00000001 & (C >> 27));
D = (0x0fffffff & (D << 1)) | (0x00000001 & (D >> 27));
}
uint64_t permuted_choice_2 = (((uint64_t)C) << 28) | (uint64_t)D;
sub_key[i] = 0; // 48 bits (2*24)
for (uint8_t j = 0; j < 48; ++j)
{
sub_key[i] <<= 1;
sub_key[i] |= (permuted_choice_2 >> (56 - PC2[j])) & LB64_MASK;
}
}
}
uint64_t ip(uint64_t block)
{
// initial permutation
uint64_t result = 0;
for (uint8_t i = 0; i < 64; ++i)
{
result <<= 1;
result |= (block >> (64 - IP[i])) & LB64_MASK;
}
return result;
}
uint64_t fp(uint64_t block)
{
// inverse initial permutation
uint64_t result = 0;
for (uint8_t i = 0; i < 64; ++i)
{
result <<= 1;
result |= (block >> (64 - FP[i])) & LB64_MASK;
}
return result;
}
void feistel(uint32_t &L, uint32_t &R, uint32_t F)
{
uint32_t temp = R;
R = L ^ F;
L = temp;
}
uint32_t f(uint32_t R, uint64_t k) // f(R,k) function
{
// applying expansion permutation and returning 48-bit data
uint64_t s_input = 0;
for (uint8_t i = 0; i < 48; ++i)
{
s_input <<= 1;
s_input |= (uint64_t)((R >> (32 - EXPANSION[i])) & LB32_MASK);
}
// XORing expanded Ri with Ki, the round key
s_input = s_input ^ k;
// applying S-Boxes function and returning 32-bit data
uint32_t s_output = 0;
for (uint8_t i = 0; i < 8; ++i)
{
// Outer bits
char row = static_cast<char>((s_input & (0x0000840000000000 >> 6 * i)) >> (42 - 6 * i));
row = static_cast<char>((row >> 4) | (row & 0x01));
// Middle 4 bits of input
char column = (char)((s_input & (0x0000780000000000 >> 6 * i)) >> (43 - 6 * i));
s_output <<= 4;
s_output |= (uint32_t)(SBOX[i][16 * row + column] & 0x0f);
}
// applying the round permutation
uint32_t f_result = 0;
for (uint8_t i = 0; i < 32; ++i)
{
f_result <<= 1;
f_result |= (s_output >> (32 - PBOX[i])) & LB32_MASK;
}
return f_result;
}
private:
uint64_t sub_key[16] = { 0 }; // 48 bits each
// Permuted Choice 1 Table [7*8]
const char PC1[7 * 8] =
{
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4
};
// Permuted Choice 2 Table [6*8]
const char PC2[6 * 8] =
{
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
};
// Iteration Shift Array
const char ITERATION_SHIFT[16] =
{
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
};
const uint32_t LB32_MASK = 0x00000001;
const uint64_t LB64_MASK = 0x0000000000000001;
const uint64_t L64_MASK = 0x00000000ffffffff;
// Initial Permutation Table [8*8]
const char IP[8 * 8] =
{
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
};
// Inverse Initial Permutation Table [8*8]
const char FP[8 * 8] =
{
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
};
// Expansion table [6*8]
const char EXPANSION[6 * 8] =
{
32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1
};
// The S-Box tables [8*16*4]
const char SBOX[8][64] =
{
{
// S1
14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13
},
{
// S2
15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9
},
{
// S3
10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12
},
{
// S4
7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14
},
{
// S5
2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3
},
{
// S6
12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13
},
{
// S7
4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12
},
{
// S8
13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11
}
};
// Post S-Box permutation [4*8]
const char PBOX[4 * 8] =
{
16, 7, 20, 21,
29, 12, 28, 17,
1, 15, 23, 26,
5, 18, 31, 10,
2, 8, 24, 14,
32, 27, 3, 9,
19, 13, 30, 6,
22, 11, 4, 25
};
};
}
#endif // !__ASIO2_DES_IMPL_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_LIBRARY_C_GNU_H
#define BHO_PREDEF_LIBRARY_C_GNU_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
#include <asio2/bho/predef/library/c/_prefix.h>
#if defined(__STDC__)
#include <stddef.h>
#elif defined(__cplusplus)
#include <cstddef>
#endif
/* tag::reference[]
= `BHO_LIB_C_GNU`
http://en.wikipedia.org/wiki/Glibc[GNU glibc] Standard C library.
Version number available as major, and minor.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__GLIBC__+` | {predef_detection}
| `+__GNU_LIBRARY__+` | {predef_detection}
| `+__GLIBC__+`, `+__GLIBC_MINOR__+` | V.R.0
| `+__GNU_LIBRARY__+`, `+__GNU_LIBRARY_MINOR__+` | V.R.0
|===
*/ // end::reference[]
#define BHO_LIB_C_GNU BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__GLIBC__) || defined(__GNU_LIBRARY__)
# undef BHO_LIB_C_GNU
# if defined(__GLIBC__)
# define BHO_LIB_C_GNU \
BHO_VERSION_NUMBER(__GLIBC__,__GLIBC_MINOR__,0)
# else
# define BHO_LIB_C_GNU \
BHO_VERSION_NUMBER(__GNU_LIBRARY__,__GNU_LIBRARY_MINOR__,0)
# endif
#endif
#if BHO_LIB_C_GNU
# define BHO_LIB_C_GNU_AVAILABLE
#endif
#define BHO_LIB_C_GNU_NAME "GNU"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_LIB_C_GNU,BHO_LIB_C_GNU_NAME)
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_TENDRA_H
#define BHO_PREDEF_COMPILER_TENDRA_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_TENDRA`
http://en.wikipedia.org/wiki/TenDRA_Compiler[TenDRA C/{CPP}] compiler.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__TenDRA__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_COMP_TENDRA BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__TenDRA__)
# define BHO_COMP_TENDRA_DETECTION BHO_VERSION_NUMBER_AVAILABLE
#endif
#ifdef BHO_COMP_TENDRA_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_TENDRA_EMULATED BHO_COMP_TENDRA_DETECTION
# else
# undef BHO_COMP_TENDRA
# define BHO_COMP_TENDRA BHO_COMP_TENDRA_DETECTION
# endif
# define BHO_COMP_TENDRA_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_TENDRA_NAME "TenDRA C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_TENDRA,BHO_COMP_TENDRA_NAME)
#ifdef BHO_COMP_TENDRA_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_TENDRA_EMULATED,BHO_COMP_TENDRA_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_IOPOOL_HPP__
#define __ASIO2_IOPOOL_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <vector>
#include <thread>
#include <mutex>
#include <chrono>
#include <type_traits>
#include <memory>
#include <algorithm>
#include <atomic>
#include <unordered_set>
#include <map>
#include <functional>
#include <asio2/base/error.hpp>
#include <asio2/base/define.hpp>
#include <asio2/base/log.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/shared_mutex.hpp>
namespace asio2::detail
{
using io_context_work_guard = asio::executor_work_guard<asio::io_context::executor_type>;
// unbelievable :
// the 1 sfinae need use std::declval<std::decay_t<T>>()
// the 2 sfinae need use (std::declval<std::decay_t<T>>())
// the 3 sfinae need use ((std::declval<std::decay_t<T>>()))
//-----------------------------------------------------------------------------------
template<class T, class R = void>
struct is_io_context_pointer : std::false_type {};
template<class T>
struct is_io_context_pointer<T, std::void_t<decltype(
std::declval<std::decay_t<T>>()->~io_context()), void>> : std::true_type {};
template<class T, class R = void>
struct is_io_context_object : std::false_type {};
template<class T>
struct is_io_context_object<T, std::void_t<decltype(
std::declval<std::decay_t<T>>().~io_context()), void>> : std::true_type {};
//-----------------------------------------------------------------------------------
template<class T, class R = void>
struct is_executor_work_guard_pointer : std::false_type {};
template<class T>
struct is_executor_work_guard_pointer<T, std::void_t<decltype(
(std::declval<std::decay_t<T>>())->~executor_work_guard()), void>> : std::true_type {};
template<class T, class R = void>
struct is_executor_work_guard_object : std::false_type {};
template<class T>
struct is_executor_work_guard_object<T, std::void_t<decltype(
(std::declval<std::decay_t<T>>()).~executor_work_guard()), void>> : std::true_type {};
//-----------------------------------------------------------------------------------
#if defined(ASIO2_ENABLE_LOG)
static_assert(is_io_context_pointer<asio::io_context* >::value);
static_assert(is_io_context_pointer<asio::io_context*& >::value);
static_assert(is_io_context_pointer<asio::io_context*&&>::value);
static_assert(is_io_context_pointer<std::shared_ptr<asio::io_context> >::value);
static_assert(is_io_context_pointer<std::shared_ptr<asio::io_context>& >::value);
static_assert(is_io_context_pointer<std::shared_ptr<asio::io_context>&&>::value);
static_assert(is_io_context_pointer<std::shared_ptr<asio::io_context>const&>::value);
static_assert(is_io_context_object<asio::io_context >::value);
static_assert(is_io_context_object<asio::io_context& >::value);
static_assert(is_io_context_object<asio::io_context&&>::value);
#endif
//-----------------------------------------------------------------------------------
class iopool;
template<class, class> class iopool_cp;
class io_t
{
friend class iopool;
template<class, class> friend class iopool_cp;
public:
io_t(asio::io_context* ioc) noexcept : context_(ioc)
{
}
~io_t() noexcept
{
}
inline asio::io_context & context() noexcept { return (*(this->context_)); }
inline std::atomic<std::size_t> & pending() noexcept { return this->pending_ ; }
inline std::unordered_set<asio::steady_timer*> & timers () noexcept { return this->timers_ ; }
template<class Object>
inline void regobj(Object* p)
{
if (!p)
return;
// should hold a io_contxt guard to ensure that the unregobj must be called, otherwise
// the objects maybe is not empty and the unregobj maybe not be called.
asio::dispatch(this->context(), [this, p, optr = p->derived().selfptr()]() mutable
{
std::size_t k = reinterpret_cast<std::size_t>(p);
io_context_work_guard iocg(this->context_->get_executor());
this->objects_[k] = [p, optr = std::move(optr), iocg = std::move(iocg)]() mutable
{
detail::ignore_unused(optr, iocg);
p->stop();
};
});
}
template<class Object>
inline void unregobj(Object* p)
{
if (!p)
return;
// must use post, beacuse the "for each objects_" was called in the iopool.stop,
// then the object->stop is called in the for each, then the unregobj is called
// in the object->stop, if we erase the elem of the objects_ directly at here,
// it will cause the iterator is invalid when executed at "for each objects_" .
asio::post(this->context(), [this, p, optr = p->derived().selfptr()]() mutable
{
detail::ignore_unused(optr);
this->objects_.erase(reinterpret_cast<std::size_t>(p));
});
}
/**
* @brief
*/
inline void cancel()
{
// moust read write the timers_ in io_context thread by "post"
// when code run to here, the io_context maybe stopped already.
asio::post(this->context(), [this]() mutable
{
for (asio::steady_timer* timer : this->timers_)
{
// when the timer is canceled, it will erase itself from timers_.
detail::cancel_timer(*timer);
}
for (auto&[ptr, fun] : this->objects_)
{
detail::ignore_unused(ptr);
if (fun)
{
fun();
}
}
this->timers_.clear();
this->objects_.clear();
});
}
/**
* @brief initialize the thread id to "std::this_thread::get_id()"
*/
inline void init_thread_id() noexcept
{
if (this->thread_id_ != std::this_thread::get_id())
{
this->thread_id_ = std::this_thread::get_id();
}
}
/**
* @brief uninitialize the thread id to empty.
*/
inline void fini_thread_id() noexcept
{
this->thread_id_ = std::thread::id{};
}
/**
* @brief return the thread id of the current io_context running in.
*/
inline std::thread::id get_thread_id() noexcept
{
return this->thread_id_;
}
/**
* @brief Determine whether the current io_context is running in the current thread.
*/
inline bool running_in_this_thread() noexcept
{
return (std::this_thread::get_id() == this->thread_id_);
}
protected:
// Do not use shared_ptr<io_context>, it will cause a lot of problems. If the user
// calls asio::post([ptr = shared_ptr<io_context>(context)](){}) after io_context is
// stopped, it will cause io_context can't be destructed, because io_context's destructor
// will clear it's task queue which generated by asio::post, but because the queue
// saved the shared_ptr<io_context> of itself, then circular reference is occured,
// when use io_context for steady_timer, it maybe create a thread, and the circular
// reference will cause the thread can not quit, and finally the thread will be
// more and more, then cause the program crash.
asio::io_context * context_ = nullptr;
// the strand will cause some problem when used in dll.
// 1. when declare a strand in dll, and export it, when use the strand in exe which
// exported by the dll, the strand.running_in_this_thread will false, even if it
// is called in the io_context thread.
// 2. when declare a strand in dll, and export it, when use asio::bind_executor(strand
// in exe, it will cause deak lock.
// eg: async_connect(endpoint, asio::bind_executor(strand, callback)); the callback
// will never be called.
//asio::io_context::strand strand_;
// Use this variable to ensure async_send function was executed correctly.
// see : send_cp.hpp "# issue x:"
std::atomic<std::size_t> pending_{};
// Use this variable to save the timers that have not been closed properly.
// If we don't do this, the following problem will occurs:
// user call client.stop, when the code is run to before the iopool's
// wait_for_io_context_stopped, and user call client.start_timer at another
// thread, this will cause the wait_for_io_context_stopped will block forever
// until the timer expires.
// e.g:
// {
// asio2::timer timer;
// timer.post([&]()
// {
// timer.start_timer(1, std::chrono::seconds(1), []() {});
// });
// } // the timer's destructor will be called here.
// when the timer's destructor is called, it will call the "stop_all_timers"
// function, the "stop_all_timers" will "post a event", this "post a event"
// will executed before the "timer.start_timer(1,...)", so when the
// "timer.start_timer(1,...)" is executed, nobody has a chance to cancel it,
// and this will cause the iopool's wait_for_io_context_stopped function
// blocked forever.
std::unordered_set<asio::steady_timer*> timers_;
// Used to save the server or client or other objects, when iopool.stop is called,
// the objects.stop will be called automaticly.
std::map<std::size_t, std::function<void()>> objects_;
// the thread id of the current io_context running in.
std::thread::id thread_id_{};
};
//-----------------------------------------------------------------------------------
template<class T, class R = void>
struct is_io_t_pointer : std::false_type {};
template<class T>
struct is_io_t_pointer<T, std::void_t<decltype(
((std::declval<std::decay_t<T>>()))->~io_t()), void>> : std::true_type {};
template<class T, class R = void>
struct is_io_t_object : std::false_type {};
template<class T>
struct is_io_t_object<T, std::void_t<decltype(
((std::declval<std::decay_t<T>>())).~io_t()), void>> : std::true_type {};
//-----------------------------------------------------------------------------------
/**
* io_context pool
*/
class iopool
{
template<class, class> friend class iopool_cp;
public:
/**
* @brief constructor
* @param concurrency - the pool size, default is double the number of CPU cores
*/
explicit iopool(std::size_t concurrency = default_concurrency()) : state_(state_t::stopped), next_(0)
{
if (concurrency == 0)
{
concurrency = default_concurrency();
}
for (std::size_t i = 0; i < concurrency; ++i)
{
this->iocs_.emplace_back(std::make_unique<asio::io_context>(1));
}
for (std::size_t i = 0; i < concurrency; ++i)
{
this->iots_.emplace_back(std::make_unique<io_t>(this->iocs_[i].get()));
}
this->threads_.reserve(this->iots_.size());
this->guards_ .reserve(this->iots_.size());
}
/**
* @brief destructor
*/
~iopool()
{
this->stop();
// only call object's stop function in io_context thread and hasn't call object's
// stop function in non io_context thread maybe cause this problem:
// the io_context do one task, and at this time, the shared ptr object reference
// counter is 1 in the task,
// when the task is finished, the shared ptr object will be destroyed, when
// it destroyed, the iopool will be destroyed too, but at this time, the iopool
// stop is running in the io_context thread, so the iopool and the iopool thread
// will can not stopped, then this caused a crash.
// so we must ensure that: we must hold a shared ptr object manual, to avoid
// the shared ptr object destroyed in the io_context thread, so a method is:
// we call stop in non io_context thread can solve this problem.
#if defined(ASIO2_ENABLE_LOG)
if (!this->threads_.empty())
{
ASIO2_LOG_FATAL(
"fatal error: the object is destroyed in the io_context thread. {}",
this->threads_.size());
}
#endif
ASIO2_ASSERT(!this->running_in_threads());
ASIO2_ASSERT(this->threads_.empty());
}
/**
* @brief run all io_context objects in the pool.
*/
bool start()
{
clear_last_error();
// use read lock to check the state, to avoid deadlock.
{
asio2::shared_locker guard(this->mutex_);
if (this->state_ != state_t::stopped)
{
set_last_error(asio::error::already_started);
return true;
}
if (!this->guards_.empty() || !this->threads_.empty())
{
set_last_error(asio::error::already_started);
return true;
}
}
// then must use write lock again yet.
asio2::unique_locker guard(this->mutex_);
if (this->state_ != state_t::stopped)
{
set_last_error(asio::error::already_started);
return true;
}
if (!this->guards_.empty() || !this->threads_.empty())
{
set_last_error(asio::error::already_started);
return true;
}
this->state_ = state_t::starting;
std::vector<std::promise<void>> promises(this->iots_.size());
// Create a pool of threads to run all of the io_contexts.
for (std::size_t i = 0; i < this->iots_.size(); ++i)
{
auto& iot = this->iots_[i];
std::promise<void>& promise = promises[i];
/// Restart the io_context in preparation for a subsequent run() invocation.
/**
* This function must be called prior to any second or later set of
* invocations of the run(), run_one(), poll() or poll_one() functions when a
* previous invocation of these functions returned due to the io_context
* being stopped or running out of work. After a call to restart(), the
* io_context object's stopped() function will return @c false.
*
* This function must not be called while there are any unfinished calls to
* the run(), run_one(), poll() or poll_one() functions.
*/
iot->context().restart();
this->guards_.emplace_back(iot->context().get_executor());
// start work thread
this->threads_.emplace_back([&iot, &promise]() mutable
{
iot->thread_id_ = std::this_thread::get_id();
// after the thread id is seted already, we set the promise
promise.set_value();
// should we catch the exception ?
// If an exception occurs here, what should we do ?
// We should handle exceptions in other business functions to ensure that
// exceptions will not be triggered here.
try
{
iot->context().run();
}
catch (system_error const& e)
{
std::ignore = e;
ASIO2_LOG_ERROR("fatal exception in io_context::run:1: {}", e.what());
ASIO2_ASSERT(false);
}
catch (std::exception const& e)
{
std::ignore = e;
ASIO2_LOG_ERROR("fatal exception in io_context::run:2: {}", e.what());
ASIO2_ASSERT(false);
}
catch (...)
{
ASIO2_LOG_ERROR("fatal exception in io_context::run:3");
ASIO2_ASSERT(false);
}
// memory leaks occur when SSL is used in multithreading
// https://github.com/chriskohlhoff/asio/issues/368
#if defined(ASIO2_ENABLE_SSL) || defined(ASIO2_USE_SSL)
OPENSSL_thread_stop();
#endif
});
}
for (std::size_t i = 0; i < this->iots_.size(); ++i)
{
promises[i].get_future().wait();
}
#if defined(_DEBUG) || defined(DEBUG)
for (std::size_t i = 0; i < this->iots_.size(); ++i)
{
ASIO2_ASSERT(this->iots_[i]->get_thread_id() == this->threads_[i].get_id());
}
#endif
this->state_ = state_t::started;
return true;
}
/**
* @brief stop all io_context objects in the pool
* blocking until all posted event has completed already.
* After we call iog.reset(), when an asio::post(io_context,...) execution ends, the count
* of the io_context will be checked. If the count equals 0, the io_context will be closed. Then
* the subsequent call of asio:: post(io_context,...) will fail, and the post event will not
* be executed. When our program exits, it will nest call asio:: post (io_context...) to post
* many events, so when an asio::post(io_context,...) inside someone asio::post(io_context,...)
* has not yet been executed, the io_context may have been closed, which will result in the
* nested asio::post(io_context,...) never being executed.
*/
void stop()
{
// split read and write to avoid deadlock caused by iopool.post([&iopool]() {iopool.stop(); });
{
asio2::shared_locker guard(this->mutex_);
if (this->state_ != state_t::started)
return;
if (this->guards_.empty() && this->threads_.empty())
return;
if (this->running_in_threads_impl())
return this->cancel_impl();
}
{
asio2::unique_locker guard(this->mutex_);
if (this->state_ != state_t::started)
return;
this->state_ = state_t::stopping;
}
// Waiting for all nested events to complete.
// The mutex_ must be released while waiting, otherwise, the stop function may be called
// in the communication thread and the lock will be requested, which is already held here,
// so leading to deadlock.
this->wait_for_io_context_stopped();
{
asio2::unique_locker guard(this->mutex_);
// call executor_work_guard reset,and then the io_context working thread will be exited.
// In fact, the guards has called reset already, but there is no problem with repeated calls
for (auto & iog : this->guards_)
{
ASIO2_ASSERT(iog.owns_work() == false);
iog.reset();
}
// Wait for all threads to exit.
for (auto & thread : this->threads_)
{
thread.join();
}
this->guards_ .clear();
this->threads_.clear();
#if defined(_DEBUG) || defined(DEBUG)
for (std::size_t i = 0; i < this->iots_.size(); ++i)
{
ASIO2_ASSERT(this->iots_[i]->objects_.empty());
}
#endif
this->state_ = state_t::stopped;
}
}
/**
* @brief check whether the io_context pool is started
*/
inline bool started() noexcept
{
asio2::shared_locker guard(this->mutex_);
return (this->state_ == state_t::started);
}
/**
* @brief check whether the io_context pool is stopped
*/
inline bool stopped() noexcept
{
asio2::shared_locker guard(this->mutex_);
return (this->state_ == state_t::stopped);
}
/**
* @brief get an io_t to use
*/
inline io_t& get(std::size_t index = static_cast<std::size_t>(-1)) noexcept
{
asio2::shared_locker guard(this->mutex_);
ASIO2_ASSERT(!this->iots_.empty());
return *(this->iots_[this->next_impl(index)]);
}
/**
* @brief get an io_context to use
*/
inline asio::io_context& get_context(std::size_t index = static_cast<std::size_t>(-1)) noexcept
{
asio2::shared_locker guard(this->mutex_);
ASIO2_ASSERT(!this->iots_.empty());
return this->iots_[this->next_impl(index)]->context();
}
/**
* @brief Determine whether current code is running in the io_context pool threads.
*/
inline bool running_in_threads() noexcept
{
asio2::shared_locker guard(this->mutex_);
return this->running_in_threads_impl();
}
/**
* @brief Determine whether current code is running in the io_context thread by index
*/
inline bool running_in_thread(std::size_t index) noexcept
{
asio2::shared_locker guard(this->mutex_);
ASIO2_ASSERT(index < this->threads_.size());
if (!(index < this->threads_.size()))
return false;
return (std::this_thread::get_id() == this->threads_[index].get_id());
}
/**
* @brief get io_context pool size.
*/
inline std::size_t size() noexcept
{
asio2::shared_locker guard(this->mutex_);
return this->iots_.size();
}
/**
* @brief Get the thread id of the specified thread index.
*/
inline std::thread::id get_thread_id(std::size_t index) noexcept
{
asio2::shared_locker guard(this->mutex_);
return this->threads_[index % this->threads_.size()].get_id();
}
/**
* Use to ensure that all nested asio::post(...) events are fully invoked.
*/
inline void wait_for_io_context_stopped() ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
// split read and write to avoid deadlock caused by iopool.post([&iopool]() {iopool.stop(); });
{
//asio2::shared_locker guard(this->mutex_);
if (this->running_in_threads_impl())
return this->cancel_impl();
// wiat fo all pending events completed.
for (auto& iot : this->iots_)
{
while (iot->pending() > std::size_t(0))
std::this_thread::sleep_for(std::chrono::milliseconds(0));
}
}
{
asio2::unique_locker guard(this->mutex_);
// first reset the acceptor io_context work guard
if (!this->guards_.empty())
this->guards_.front().reset();
}
constexpr auto max = std::chrono::milliseconds(10);
constexpr auto min = std::chrono::milliseconds(1);
{
// don't need lock, maybe cause deadlock in client start iopool
//asio2::shared_locker guard(this->mutex_);
// second wait indefinitely until the acceptor io_context is stopped
for (std::size_t i = 0; i < std::size_t(1) && i < this->iocs_.size(); ++i)
{
auto t1 = std::chrono::steady_clock::now();
auto& ioc = this->iocs_[i];
auto& iot = this->iots_[i];
while (!ioc->stopped())
{
// the timer may not be canceled successed when using visual
// studio break point for debugging, so cancel it at each loop
// must cancel all iots, otherwise maybe cause deaklock like below:
// the client_ptr->bind_recv has hold the session_ptr, and the session_ptr
// is in the indexed 1 iot ( not indexed 0 iot ), so if call iot->cancel,
// the cancel function of indexed 1 iot wont be called, so the stop function
// of client_ptr won't be called too, so the session_ptr which holded by the
// client_ptr will can't be destroyed, so the server's acceptor io will
// can't be stopped(this means the indexed 0 io can't be stopped).
//server.bind_accept([](std::shared_ptr<asio2::tcp_session>& session_ptr)
//{
// std::shared_ptr<asio2::tcp_client> client_ptr = std::make_shared<asio2::tcp_client>(
// 512, 1024, session_ptr->io());
//
// client_ptr->bind_recv([session_ptr](std::string_view data) mutable
// {
// });
//
// client_ptr->async_start("127.0.0.1", 8888);
//});
this->cancel_impl();
auto t2 = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
std::this_thread::sleep_for(std::clamp(ms, min, max));
}
iot->thread_id_ = std::thread::id{};
ASIO2_ASSERT(iot->timers().empty());
ASIO2_ASSERT(iot->objects_.empty());
}
}
{
asio2::unique_locker guard(this->mutex_);
for (std::size_t i = 1; i < this->guards_.size(); ++i)
{
this->guards_[i].reset();
}
}
{
// don't need lock, maybe cause deadlock in client start iopool
//asio2::shared_locker guard(this->mutex_);
for (std::size_t i = 1; i < this->iocs_.size(); ++i)
{
auto t1 = std::chrono::steady_clock::now();
auto& ioc = this->iocs_[i];
auto& iot = this->iots_[i];
while (!ioc->stopped())
{
// the timer may not be canceled successed when using visual
// studio break point for debugging, so cancel it at each loop
this->cancel_impl();
auto t2 = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
std::this_thread::sleep_for(std::clamp(ms, min, max));
}
iot->thread_id_ = std::thread::id{};
ASIO2_ASSERT(iot->timers().empty());
ASIO2_ASSERT(iot->objects_.empty());
}
}
}
/**
*
*/
inline void cancel()
{
asio2::shared_locker guard(this->mutex_);
return this->cancel_impl();
}
/**
* @brief
*/
inline std::size_t next(std::size_t index) noexcept
{
asio2::shared_locker guard(this->mutex_);
return this->next_impl(index);
}
/**
* The wait_for() function blocks until the specified duration has elapsed.
*
* @param rel_time - The duration for which the call may block.
*/
template <typename Rep, typename Period>
void wait_for(const std::chrono::duration<Rep, Period>& rel_time)
{
if (this->running_in_threads())
{
set_last_error(asio::error::operation_not_supported);
return;
}
clear_last_error();
io_t* iot = nullptr;
{
asio2::shared_locker guard(this->mutex_);
iot = this->iots_[0].get();
}
asio::steady_timer timer(iot->context());
timer.expires_after(rel_time);
timer.wait(get_last_error());
}
/**
* The wait_until() function blocks until the specified time has been reached.
*
* @param abs_time - The time point until which the call may block.
*/
template <typename Clock, typename Duration>
void wait_until(const std::chrono::time_point<Clock, Duration>& abs_time)
{
if (this->running_in_threads())
{
set_last_error(asio::error::operation_not_supported);
return;
}
clear_last_error();
io_t* iot = nullptr;
{
asio2::shared_locker guard(this->mutex_);
iot = this->iots_[0].get();
}
asio::steady_timer timer(iot->context());
timer.expires_at(abs_time);
timer.wait(get_last_error());
}
/**
* The wait_signal() function blocks util some signal delivered.
*
* @return The delivered signal number. Maybe invalid value when some exception occured.
*/
template <class... Ints>
int wait_signal(Ints... signal_number)
{
if (this->running_in_threads())
{
set_last_error(asio::error::operation_not_supported);
return 0;
}
clear_last_error();
io_t* iot = nullptr;
{
asio2::shared_locker guard(this->mutex_);
iot = this->iots_[0].get();
}
// note: The variable name signals will conflict with the macro signals of qt
asio::signal_set signalset(iot->context());
(signalset.add(signal_number), ...);
std::promise<int> promise;
std::future<int> future = promise.get_future();
signalset.async_wait([&](const error_code& /*ec*/, int signo)
{
promise.set_value(signo);
});
return future.get();
}
/**
* @brief post a function object into the thread pool, then return immediately,
* the function object will never be executed inside this function. Instead, it will
* be executed asynchronously in the thread pool.
* @param fun - global function,static function,lambda,member function,std::function.
* @return std::future<fun_return_type>
*/
template<class Fun, class... Args>
auto post(Fun&& fun, Args&&... args) -> std::future<std::invoke_result_t<Fun, Args...>>
{
asio2::shared_locker guard(this->mutex_);
using return_type = std::invoke_result_t<Fun, Args...>;
std::size_t index = 0, num = (std::numeric_limits<std::size_t>::max)();
for (std::size_t i = 0, n = this->iots_.size(); i < n; ++i)
{
std::size_t pending = this->iots_[i]->pending().load();
if (pending == 0)
{
index = i;
break;
}
if (pending < num)
{
num = pending;
index = i;
}
}
std::atomic<std::size_t>& pending = this->iots_[index]->pending();
pending++;
std::promise<return_type> promise;
std::future<return_type> future = promise.get_future();
asio::post(*(this->iocs_[index]),
[&pending, promise = std::move(promise), fun = std::forward<Fun>(fun),
args = std::make_tuple(std::forward<Args>(args) ...)]() mutable
{
if constexpr (std::is_void_v<return_type>)
{
std::apply(std::move(fun), std::move(args));
promise.set_value();
}
else
{
promise.set_value(std::apply(std::move(fun), std::move(args)));
}
pending--;
});
return future;
}
/**
* @brief post a function object into the thread pool with specified thread index,
* then return immediately, the function object will never be executed inside this
* function. Instead, it will be executed asynchronously in the thread pool.
* @param thread_index - which thread to execute the function.
* @param fun - global function,static function,lambda,member function,std::function.
* @return std::future<fun_return_type>
*/
template<class IntegerT, class Fun, class... Args,
std::enable_if_t<std::is_integral_v<std::remove_cv_t<std::remove_reference_t<IntegerT>>>, int> = 0>
auto post(IntegerT thread_index, Fun&& fun, Args&&... args) -> std::future<std::invoke_result_t<Fun, Args...>>
{
asio2::shared_locker guard(this->mutex_);
using return_type = std::invoke_result_t<Fun, Args...>;
std::promise<return_type> promise;
std::future<return_type> future = promise.get_future();
asio::post(*(this->iocs_[thread_index % this->iocs_.size()]),
[promise = std::move(promise), fun = std::forward<Fun>(fun),
args = std::make_tuple(std::forward<Args>(args) ...)]() mutable
{
if constexpr (std::is_void_v<return_type>)
{
std::apply(std::move(fun), std::move(args));
promise.set_value();
}
else
{
promise.set_value(std::apply(std::move(fun), std::move(args)));
}
});
return future;
}
protected:
inline bool running_in_threads_impl() noexcept ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::thread::id curr_tid = std::this_thread::get_id();
for (auto& thread : this->threads_)
{
if (curr_tid == thread.get_id())
return true;
}
return false;
}
inline void cancel_impl() ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
for (std::size_t i = 0; i < this->iocs_.size(); ++i)
{
auto& ioc = this->iocs_[i];
auto& iot = this->iots_[i];
if (!ioc->stopped())
{
iot->cancel();
}
}
}
inline std::size_t next_impl(std::size_t index) noexcept ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
// Use a round-robin scheme to choose the next io_context to use.
return (index == static_cast<std::size_t>(-1) ?
((++(this->next_)) % this->iots_.size()) : (index % this->iots_.size()));
}
protected:
///
mutable asio2::shared_mutexer mutex_;
/// threads to run all of the io_context
std::vector<std::thread> threads_ ASIO2_GUARDED_BY(mutex_);
/// The pool of io_context.
std::vector<std::unique_ptr<asio::io_context>> iocs_ ASIO2_GUARDED_BY(mutex_);
/// The pool of io_context.
std::vector<std::unique_ptr<io_t>> iots_ ASIO2_GUARDED_BY(mutex_);
/// Flag whether the io_context pool has stopped already
detail::state_t state_ ASIO2_GUARDED_BY(mutex_);
/// The next io_context to use for a connection.
std::size_t next_;
// Give all the io_contexts executor_work_guard to do so that their run() functions will not
// exit until they are explicitly stopped.
std::vector<io_context_work_guard> guards_ ASIO2_GUARDED_BY(mutex_);
// for debug, to see the derived object details.
#if defined(_DEBUG) || defined(DEBUG)
std::function<void()> derive_pointer_;
#endif
};
class iopool_base
{
public:
iopool_base() = default;
virtual ~iopool_base() {}
virtual bool start () = 0;
virtual void stop () = 0;
virtual bool started() noexcept = 0;
virtual bool stopped() noexcept = 0;
virtual io_t & get (std::size_t index) noexcept = 0;
virtual std::size_t size () noexcept = 0;
virtual bool running_in_threads() noexcept = 0;
};
class default_iopool : public iopool_base
{
template<class, class> friend class iopool_cp;
public:
explicit default_iopool(std::size_t concurrency) : impl_(concurrency)
{
}
/**
* @brief destructor
*/
virtual ~default_iopool()
{
this->impl_.stop();
}
/**
* @brief run all io_context objects in the pool.
*/
virtual bool start() override
{
return this->impl_.start();
}
/**
* @brief stop all io_context objects in the pool
*/
virtual void stop() override
{
this->impl_.stop();
}
/**
* @brief check whether the io_context pool is started
*/
virtual bool started() noexcept override
{
return this->impl_.started();
}
/**
* @brief check whether the io_context pool is stopped
*/
virtual bool stopped() noexcept override
{
return this->impl_.stopped();
}
/**
* @brief get an io_t to use
*/
virtual io_t& get(std::size_t index) noexcept override
{
return this->impl_.get(index);
}
/**
* @brief get io_context pool size.
*/
virtual std::size_t size() noexcept override
{
return this->impl_.size();
}
/**
* @brief Determine whether current code is running in the io_context pool threads.
*/
virtual bool running_in_threads() noexcept override
{
return this->impl_.running_in_threads();
}
protected:
detail::iopool impl_;
};
/**
* This io_context pool is passed in by the user
*/
template<class Container>
class user_iopool : public iopool_base
{
template<class, class> friend class iopool_cp;
public:
using copy_container_type = typename detail::remove_cvref_t<Container>;
using copy_value_type = typename copy_container_type::value_type;
using io_container_type = std::conditional_t<
is_io_context_pointer<copy_value_type>::value,
std::vector<std::unique_ptr<io_t>>, std::vector<io_t*>>;
using io_value_type = typename io_container_type::value_type;
/**
* @brief constructor
*/
template<class C>
explicit user_iopool(C&& copy) : copy_(std::forward<C>(copy)), stopped_(true), next_(0)
{
// std::shared_ptr<io_context> , io_context*
if constexpr (is_io_context_pointer<copy_value_type>::value)
{
// why use std::addressof(*ioc) ?
// the io_context pointer maybe "std::shared_ptr<io_context> , io_context*"
for (auto& ioc : copy_)
{
iots_.emplace_back(std::make_unique<io_t>(std::addressof(*ioc)));
}
}
// std::shared_ptr<io_t> , io_t*
else
{
for (auto& iot : copy_)
{
iots_.emplace_back(std::addressof(*iot));
}
}
}
/**
* @brief destructor
*/
virtual ~user_iopool()
{
this->stop();
}
/**
* @brief run all io_context objects in the pool.
*/
virtual bool start() override
{
clear_last_error();
asio2::unique_locker guard(this->mutex_);
if (!this->stopped_)
{
set_last_error(asio::error::already_started);
return true;
}
this->stopped_ = false;
return true;
}
/**
* @brief stop all io_context objects in the pool
*/
virtual void stop() override
{
{
asio2::shared_locker guard(this->mutex_);
if (this->stopped_)
return;
// wiat fo all pending events completed.
for (auto& iot : this->iots_)
{
while (iot->pending() > std::size_t(0))
std::this_thread::sleep_for(std::chrono::milliseconds(0));
}
}
{
asio2::unique_locker guard(this->mutex_);
if (this->stopped_)
return;
this->stopped_ = true;
}
}
/**
* @brief check whether the io_context pool is started
*/
virtual bool started() noexcept override
{
asio2::shared_locker guard(this->mutex_);
return (!this->stopped_);
}
/**
* @brief check whether the io_context pool is stopped
*/
virtual bool stopped() noexcept override
{
asio2::shared_locker guard(this->mutex_);
return (this->stopped_);
}
/**
* @brief get an io_t to use
*/
virtual io_t& get(std::size_t index) noexcept override
{
asio2::shared_locker guard(this->mutex_);
return *(this->iots_[this->next_impl(index)]);
}
/**
* @brief get io_context pool size.
*/
virtual std::size_t size() noexcept override
{
asio2::shared_locker guard(this->mutex_);
return this->iots_.size();
}
/**
* @brief
*/
inline std::size_t next(std::size_t index) noexcept
{
asio2::shared_locker guard(this->mutex_);
return this->next_impl(index);
}
/**
* @brief Determine whether current code is running in the io_context pool threads.
*/
virtual bool running_in_threads() noexcept override
{
asio2::shared_locker guard(this->mutex_);
return this->running_in_threads_impl();
}
protected:
inline bool running_in_threads_impl() noexcept ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
std::thread::id curr_tid = std::this_thread::get_id();
for (auto& iot : this->iots_)
{
if (curr_tid == iot->get_thread_id())
return true;
}
return false;
}
inline std::size_t next_impl(std::size_t index) noexcept ASIO2_NO_THREAD_SAFETY_ANALYSIS
{
// Use a round-robin scheme to choose the next io_context to use.
// Use this->iots_.size() instead of this->size() to avoid call virtual function.
return (index == static_cast<std::size_t>(-1) ?
((++(this->next_)) % this->iots_.size()) : (index % this->iots_.size()));
}
protected:
///
mutable asio2::shared_mutexer mutex_;
/// user container copy, maybe the user passed shared_ptr, and expect us to keep it
copy_container_type copy_ ASIO2_GUARDED_BY(mutex_);
/// The pool of io_t.
io_container_type iots_ ASIO2_GUARDED_BY(mutex_);
/// Flag whether the io_context pool has stopped already
bool stopped_ ASIO2_GUARDED_BY(mutex_);
/// The next io_context to use for a connection.
std::size_t next_;
};
template<class derived_t, class args_t = void>
class iopool_cp
{
public:
template<class T>
explicit iopool_cp(T&& v) : next_(0)
{
using type = typename detail::remove_cvref_t<T>;
if /**/ constexpr (std::is_integral_v<type>)
{
using pool_type = default_iopool;
this->iopool_ = std::make_unique<pool_type>(v);
#if defined(_DEBUG) || defined(DEBUG)
derived_t& derive = static_cast<derived_t&>(*this);
static_cast<default_iopool*>(this->iopool_.get())->impl_.derive_pointer_ = [&derive]() {};
#endif
}
else if constexpr (std::is_same_v<type, detail::iopool>)
{
using container = std::vector<io_t*>;
container copy{};
for (std::size_t i = 0; i < v.size(); ++i)
{
copy.emplace_back(&(v.get(i)));
}
using pool_type = user_iopool<container>;
this->iopool_ = std::make_unique<pool_type>(std::move(copy));
}
else if constexpr (is_io_context_pointer<type>::value)
{
ASIO2_ASSERT(v && "The io_context pointer is nullptr.");
using container = std::vector<type>;
container copy{ std::forward<T>(v) };
using pool_type = user_iopool<container>;
this->iopool_ = std::make_unique<pool_type>(std::move(copy));
}
else if constexpr (is_io_context_object<type>::value)
{
static_assert(std::is_reference_v<std::remove_cv_t<T>>);
using container = std::vector<std::add_pointer_t<type>>;
container copy{ &v };
using pool_type = user_iopool<container>;
this->iopool_ = std::make_unique<pool_type>(std::move(copy));
}
else if constexpr (is_io_t_pointer<type>::value)
{
ASIO2_ASSERT(v && "The io_t pointer is nullptr.");
using container = std::vector<type>;
container copy{ std::forward<T>(v) };
using pool_type = user_iopool<container>;
this->iopool_ = std::make_unique<pool_type>(std::move(copy));
}
else if constexpr (is_io_t_object<type>::value)
{
static_assert(std::is_reference_v<std::remove_cv_t<T>>);
using container = std::vector<std::add_pointer_t<type>>;
container copy{ &v };
using pool_type = user_iopool<container>;
this->iopool_ = std::make_unique<pool_type>(std::move(copy));
}
else
{
ASIO2_ASSERT(!v.empty() && "The container is empty.");
using pool_type = user_iopool<type>;
this->iopool_ = std::make_unique<pool_type>(std::forward<T>(v));
}
for (std::size_t i = 0, size = iopool_->size(); i < size; ++i)
{
iots_.emplace_back(std::addressof(iopool_->get(i)));
}
}
~iopool_cp() = default;
/**
* The wait_stop() function blocks until the stop() function has been called.
*/
void wait_stop()
{
if (this->iopool().running_in_threads())
{
set_last_error(asio::error::operation_not_supported);
return;
}
clear_last_error();
derived_t& derive = static_cast<derived_t&>(*this);
std::promise<error_code> promise;
std::future<error_code> future = promise.get_future();
io_t* iot = this->iots_[0];
// We must use asio::post to ensure the wait_stop_timer_ is read write in the
// same thread.
asio::post(iot->context(), [this, iot, this_ptr = derive.selfptr(), promise = std::move(promise)]
() mutable
{
if (this->wait_stop_timer_)
{
iot->timers().erase(this->wait_stop_timer_.get());
detail::cancel_timer(*(this->wait_stop_timer_));
}
this->wait_stop_timer_ = std::make_unique<asio::steady_timer>(iot->context());
iot->timers().emplace(this->wait_stop_timer_.get());
this->wait_stop_timer_->expires_after((std::chrono::nanoseconds::max)());
this->wait_stop_timer_->async_wait(
[this_ptr = std::move(this_ptr), promise = std::move(promise)]
(const error_code&) mutable
{
detail::ignore_unused(this_ptr);
promise.set_value(error_code{});
});
});
set_last_error(future.get());
}
/**
* The wait_for() function blocks until the specified duration has elapsed.
*
* @param rel_time - The duration for which the call may block.
*/
template <typename Rep, typename Period>
void wait_for(const std::chrono::duration<Rep, Period>& rel_time)
{
if (this->iopool().running_in_threads())
{
set_last_error(asio::error::operation_not_supported);
return;
}
clear_last_error();
asio::steady_timer timer(this->iots_[0]->context());
timer.expires_after(rel_time);
timer.wait(get_last_error());
}
/**
* The wait_until() function blocks until the specified time has been reached.
*
* @param abs_time - The time point until which the call may block.
*/
template <typename Clock, typename Duration>
void wait_until(const std::chrono::time_point<Clock, Duration>& abs_time)
{
if (this->iopool().running_in_threads())
{
set_last_error(asio::error::operation_not_supported);
return;
}
clear_last_error();
asio::steady_timer timer(this->iots_[0]->context());
timer.expires_at(abs_time);
timer.wait(get_last_error());
}
/**
* The wait_signal() function blocks util some signal delivered.
*
* @return The delivered signal number. Maybe invalid value when some exception occured.
*/
template <class... Ints>
int wait_signal(Ints... signal_number)
{
if (this->iopool().running_in_threads())
{
set_last_error(asio::error::operation_not_supported);
return 0;
}
clear_last_error();
// note: The variable name signals will conflict with the macro signals of qt
asio::signal_set signalset(this->iots_[0]->context());
(signalset.add(signal_number), ...);
std::promise<int> promise;
std::future<int> future = promise.get_future();
signalset.async_wait([&](const error_code& /*ec*/, int signo)
{
promise.set_value(signo);
});
return future.get();
}
/**
* Get the iopool_base interface reference.
*/
inline iopool_base& iopool() noexcept { return (*(this->iopool_)); }
protected:
inline io_t& _get_io(std::size_t index = static_cast<std::size_t>(-1)) noexcept
{
ASIO2_ASSERT(!iots_.empty());
std::size_t n = (index == static_cast<std::size_t>(-1) ?
((++(this->next_)) % this->iots_.size()) : (index % this->iots_.size()));
return *(this->iots_[n]);
}
inline bool is_iopool_started() noexcept
{
return this->iopool_->started();
}
inline bool is_iopool_stopped() noexcept
{
return this->iopool_->stopped();
}
inline bool start_iopool()
{
bool ret = this->iopool_->start();
// if the io_context is customed that passed by the user, then when the server
// accepted a new session, then the session's fire init will be called, but at
// this time, the session io_t's thread id is not inited, if use call the thread
// id function in the fire init callback, it will be failed, so we do all ios
// init thread at here first.
if (ret)
{
for (io_t* iot : this->iots_)
{
asio::dispatch(iot->context(), [iot]() mutable
{
iot->init_thread_id();
});
}
}
return ret;
}
inline void stop_iopool()
{
if (this->is_iopool_stopped())
return;
derived_t& derive = static_cast<derived_t&>(*this);
io_t* iot = this->iots_[0];
// if the server's or client's iopool is user_iopool, and when the server.stop
// or client.stop is called, we need notify the timer to cancel for the function
// wait_stop, otherwise the wait_stop function will blocked forever.
// We must use asio::post to ensure the wait_stop_timer_ is read write in the
// same thread.
asio::post(iot->context(), [this, iot, this_ptr = derive.selfptr()]() mutable
{
detail::ignore_unused(this_ptr);
if (this->wait_stop_timer_)
{
iot->timers().erase(this->wait_stop_timer_.get());
detail::cancel_timer(*(this->wait_stop_timer_));
}
});
this->iopool_->stop();
}
protected:
/// the io_context pool for socket event
std::unique_ptr<iopool_base> iopool_;
/// Use a copy to avoid calling the virtual function "iopool_base::get"
std::vector<io_t*> iots_;
/// The next io_context to use for a connection.
std::size_t next_;
/// the timer used for wait_stop function.
std::unique_ptr<asio::steady_timer> wait_stop_timer_;
};
}
namespace asio2
{
using io_t = detail::io_t;
using iopool = detail::iopool;
}
#endif // !__ASIO2_IOPOOL_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Copyright <NAME> 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_OS_MACOS_H
#define BHO_PREDEF_OS_MACOS_H
/* Special case: iOS will define the same predefs as MacOS, and additionally
'__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__'. We can guard against that,
but only if we detect iOS first. Hence we will force include iOS detection
* before doing any MacOS detection.
*/
#include <asio2/bho/predef/os/ios.h>
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_OS_MACOS`
http://en.wikipedia.org/wiki/Mac_OS[Mac OS] operating system.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `macintosh` | {predef_detection}
| `Macintosh` | {predef_detection}
| `+__APPLE__+` | {predef_detection}
| `+__MACH__+` | {predef_detection}
| `+__APPLE__+`, `+__MACH__+` | 10.0.0
| `_otherwise_` | 9.0.0
|===
*/ // end::reference[]
#define BHO_OS_MACOS BHO_VERSION_NUMBER_NOT_AVAILABLE
#if !defined(BHO_PREDEF_DETAIL_OS_DETECTED) && ( \
defined(macintosh) || defined(Macintosh) || \
(defined(__APPLE__) && defined(__MACH__)) \
)
# undef BHO_OS_MACOS
# if !defined(BHO_OS_MACOS) && defined(__APPLE__) && defined(__MACH__)
# define BHO_OS_MACOS BHO_VERSION_NUMBER(10,0,0)
# endif
# if !defined(BHO_OS_MACOS)
# define BHO_OS_MACOS BHO_VERSION_NUMBER(9,0,0)
# endif
#endif
#if BHO_OS_MACOS
# define BHO_OS_MACOS_AVAILABLE
# include <asio2/bho/predef/detail/os_detected.h>
#endif
#define BHO_OS_MACOS_NAME "Mac OS"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_OS_MACOS,BHO_OS_MACOS_NAME)
<file_sep>//
// unit_test.hpp
// ~~~~~~~~~~~~~
//
// Copyright (c) 2003-2022 <NAME> (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef __ASIO2_UNIT_TEST_HPP__
#define __ASIO2_UNIT_TEST_HPP__
#include <asio2/base/detail/push_options.hpp>
#include <cstdlib>
#include <ctime>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <limits>
#include <iomanip>
#include <mutex>
#include <iterator>
#include <string>
#include <string_view>
#ifndef ASIO2_ENABLE_LOG
#define ASIO2_ENABLE_LOG
#endif
#include <asio2/external/asio.hpp>
#if defined(__sun)
# include <stdlib.h> // Needed for lrand48.
#endif // defined(__sun)
#if defined(__BORLANDC__) && !defined(__clang__)
// Prevent use of intrinsic for strcmp.
# include <cstring>
# undef strcmp
// Suppress error about condition always being true.
# pragma option -w-ccc
#endif // defined(__BORLANDC__) && !defined(__clang__)
#if !defined(ASIO2_TEST_IOSTREAM)
# define ASIO2_TEST_IOSTREAM std::cerr
#endif // !defined(ASIO2_TEST_IOSTREAM)
static const int test_loop_times = 100;
static const int test_client_count = 10;
static const int test_wait_count = 600000;
static const int test_timer_deviation = 300;
bool test_has_error = false;
namespace asio2 {
namespace detail {
inline const char*& test_name()
{
static const char* name = 0;
return name;
}
inline std::atomic<long>& test_errors()
{
static std::atomic<long> errors(0);
return errors;
}
inline std::mutex& test_lock()
{
static std::mutex mtx{};
return mtx;
}
#define ASIO2_TEST_LOCK_GUARD \
std::lock_guard guard(asio2::detail::test_lock());
inline void begin_test_suite(const char* name)
{
asio2::detail::test_name();
asio2::detail::test_errors();
ASIO2_TEST_IOSTREAM << name << " test suite begins" << std::endl;
}
inline int end_test_suite(const char* name)
{
ASIO2_TEST_IOSTREAM << name << " test suite ends" << std::endl;
ASIO2_TEST_IOSTREAM << "\n*** ";
long errors = asio2::detail::test_errors();
ASIO2_TEST_IOSTREAM << errors << " errors detected." << std::endl;
ASIO2_TEST_IOSTREAM << std::endl;
return errors == 0 ? 0 : 1;
}
template <void (*Test)()>
inline void run_test(const char* name)
{
test_name() = name;
long errors_before = asio2::detail::test_errors();
Test();
if (!test_has_error)
{
ASIO2_TEST_IOSTREAM << std::endl;
}
if (test_errors() == errors_before)
ASIO2_TEST_IOSTREAM << name << " passed" << std::endl;
else
ASIO2_TEST_IOSTREAM << name << " failed" << std::endl;
}
template <void (*)()>
inline void compile_test(const char* name)
{
ASIO2_TEST_IOSTREAM << name << " passed" << std::endl;
}
#if defined(ASIO_NO_EXCEPTIONS) || defined(BOOST_ASIO_NO_EXCEPTIONS)
template <typename T>
void throw_exception(const T& t)
{
ASIO2_TEST_IOSTREAM << "Exception: " << t.what() << std::endl;
std::abort();
}
#endif
void check_memory_leaks()
{
#if defined(WIN32) || defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
// Detected memory leaks on windows system
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
}
void pause_cmd_window()
{
#if defined(WIN32) || defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
while (std::getchar() != '\n');
#endif
}
} // namespace detail
} // namespace asio2
#define ASIO2_CHECK(expr) \
do { if (!(expr)) { \
ASIO2_TEST_LOCK_GUARD \
if (!test_has_error) \
{ \
ASIO2_TEST_IOSTREAM << std::endl; \
test_has_error = true; \
} \
std::string_view file{__FILE__}; \
ASIO2_TEST_IOSTREAM \
<< std::next(std::next(file.data(), file.find_last_of("\\/"))) << "(" << __LINE__ << "): " \
<< asio2::detail::test_name() << ": " \
<< "check '" << #expr << "' failed" << std::endl; \
++asio2::detail::test_errors(); \
} } while (0)
#define ASIO2_CHECK_VALUE(val, expr) \
do { if (!(expr)) { \
ASIO2_TEST_LOCK_GUARD \
if (!test_has_error) \
{ \
ASIO2_TEST_IOSTREAM << std::endl; \
test_has_error = true; \
} \
std::string_view file{__FILE__}; \
ASIO2_TEST_IOSTREAM \
<< #val << "=" << val << " \t" \
<< std::next(std::next(file.data(), file.find_last_of("\\/"))) << "(" << __LINE__ << "): " \
<< asio2::detail::test_name() << ": " \
<< "check '" << #expr << "' failed" << std::endl; \
++asio2::detail::test_errors(); \
} } while (0)
#define ASIO2_CHECK_MESSAGE(expr, msg) \
do { if (!(expr)) { \
ASIO2_TEST_LOCK_GUARD \
if (!test_has_error) \
{ \
ASIO2_TEST_IOSTREAM << std::endl; \
test_has_error = true; \
} \
std::string_view file{__FILE__}; \
ASIO2_TEST_IOSTREAM \
<< std::next(std::next(file.data(), file.find_last_of("\\/"))) << "(" << __LINE__ << "): " \
<< asio2::detail::test_name() << ": " \
<< msg << std::endl; \
++asio2::detail::test_errors(); \
} } while (0)
#define ASIO2_WARN_MESSAGE(expr, msg) \
do { if (!(expr)) { \
ASIO2_TEST_LOCK_GUARD \
if (!test_has_error) \
{ \
ASIO2_TEST_IOSTREAM << std::endl; \
test_has_error = true; \
} \
std::string_view file{__FILE__}; \
ASIO2_TEST_IOSTREAM \
<< std::next(std::next(file.data(), file.find_last_of("\\/"))) << "(" << __LINE__ << "): " \
<< asio2::detail::test_name() << ": " \
<< msg << std::endl; \
} } while (0)
#define ASIO2_ERROR(msg) \
do { \
ASIO2_TEST_LOCK_GUARD \
std::string_view file{__FILE__}; \
ASIO2_TEST_IOSTREAM \
<< std::next(std::next(file.data(), file.find_last_of("\\/"))) << "(" << __LINE__ << "): " \
<< asio2::detail::test_name() << ": " \
<< msg << std::endl; \
++asio2::detail::test_errors(); \
} while (0)
#define ASIO2_TEST_SUITE_IMPL(name, tests) \
int main() \
{ \
std::srand((unsigned int)time(nullptr)); \
asio2::detail::check_memory_leaks(); \
asio2::detail::begin_test_suite(name); \
tests \
int ret = asio2::detail::end_test_suite(name); \
asio2::detail::pause_cmd_window(); \
return ret; \
}
#define ASIO2_TEST_SUITE(name, tests) \
ASIO2_TEST_SUITE_IMPL(name, tests)
#define ASIO2_TEST_CASE(test) \
asio2::detail::run_test<&test>(#test);
#define ASIO2_TEST_CASE2(test1, test2) \
asio2::detail::run_test<&test1, test2>(#test1 "," #test2);
#define ASIO2_TEST_CASE3(test1, test2, test3) \
asio2::detail::run_test<&test1, test2, test3>( \
#test1 "," #test2 "," #test3);
#define ASIO2_TEST_CASE4(test1, test2, test3, test4) \
asio2::detail::run_test<&test1, test2, test3, test4>( \
#test1 "," #test2 "," #test3 "," #test4);
#define ASIO2_TEST_CASE5(test1, test2, test3, test4, test5) \
asio2::detail::run_test<&test1, test2, test3, test4, test5>( \
#test1 "," #test2 "," #test3 "," #test4 "," #test5);
#define ASIO2_COMPILE_TEST_CASE(test) \
asio2::detail::compile_test<&test>(#test);
#define ASIO2_TEST_BEGIN_LOOP(__loops__) \
int loops = __loops__; \
for (int loop = 0; loop < loops; ++loop) \
{ \
static auto __time1__ = std::chrono::steady_clock::now(); \
if(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - __time1__).count() > 1) \
{ \
__time1__ = std::chrono::steady_clock::now(); \
ASIO2_TEST_LOCK_GUARD \
ASIO2_TEST_IOSTREAM << '#'; \
}
#define ASIO2_TEST_END_LOOP \
if (loop + 1 < loops) \
{ \
ASIO2_TEST_LOCK_GUARD \
test_has_error = false; \
} \
}
template<class... Args>
void print(Args&&... args) { ((ASIO2_TEST_IOSTREAM << args << " "), ...); }
#define ASIO2_TEST_WAIT_CHECK(...) \
std::this_thread::sleep_for(std::chrono::milliseconds(1)); \
static int waits = 0; \
if ((++waits) > test_wait_count) \
{ \
ASIO2_TEST_LOCK_GUARD \
std::string_view file{__FILE__}; \
ASIO2_TEST_IOSTREAM \
<< "wait timeout: " \
<< std::next(std::next(file.data(), file.find_last_of("\\/"))) << "(" << __LINE__ << "): "; \
print(__VA_ARGS__); \
ASIO2_TEST_IOSTREAM << std::endl; \
waits = 0; \
} \
std::ignore = waits
inline void null_test()
{
}
#if defined(__GNUC__) && defined(_AIX)
// AIX needs this symbol defined in asio, even if it doesn't do anything.
int test_main(int, char**)
{
}
#endif // defined(__GNUC__) && defined(_AIX)
#include <asio2/base/detail/pop_options.hpp>
#endif // __ASIO2_UNIT_TEST_HPP__
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_CONDITION_EVENT_COMPONENT_HPP__
#define __ASIO2_CONDITION_EVENT_COMPONENT_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstddef>
#include <map>
#include <limits>
#include <memory>
#include <type_traits>
#include <chrono>
#include <mutex>
#include <asio2/base/iopool.hpp>
#include <asio2/base/detail/object.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/util/spin_lock.hpp>
namespace asio2::detail
{
template<class, class> class condition_event_cp;
template<class, class> class rdc_call_cp_impl;
}
namespace asio2
{
class [[deprecated("Replace async_event with condition_event")]] async_event : public detail::object_t<async_event>
{
};
class condition_event : public detail::object_t<condition_event>
{
template<class, class> friend class asio2::detail::condition_event_cp;
template<class, class> friend class asio2::detail::rdc_call_cp_impl;
public:
explicit condition_event(detail::io_t& io)
: event_timer_io_(io)
, event_timer_(io.context())
{
}
~condition_event() noexcept
{
}
protected:
template <typename WaitHandler>
inline void async_wait(WaitHandler&& handler)
{
// when code run to here, it means that the io_context is started already,
// then we set the flag to true, if the io_context is not started, we can't
// set the flag to true, otherwise maybe cause crash.
// eg :
// asio2::udp_cast udp;
// auto ptr = udp.post_condition_event([](){});
// std::thread([ptr]() mutable
// {
// std::this_thread::sleep_for(std::chrono::seconds(5));
// ptr->notify();
// }).detach();
// // udp.start(...); // udp.start is not called,
// then the udp is destroyed, after 5 seconds, the code will run to ptr->notify,
// then it cause crash...
// when code run to here, the io_context must be not destroy.
{
std::lock_guard g{ this->event_life_lock_ };
this->event_life_flag_ = true;
}
this->event_timer_io_.timers().emplace(std::addressof(event_timer_));
// Setting expiration to infinity will cause handlers to
// wait on the timer until cancelled.
this->event_timer_.expires_after((std::chrono::nanoseconds::max)());
// bind is used to adapt the user provided handler to the
// timer's wait handler type requirement.
// the "handler" has hold the derive_ptr already, so this lambda don't need hold it again.
// this event_ptr (means selfptr) has holded by the map "condition_events_" already,
// so this lambda don't need hold selfptr again.
this->event_timer_.async_wait(
[this, handler = std::forward<WaitHandler>(handler)](const error_code& ec) mutable
{
ASIO2_ASSERT((!ec) || ec == asio::error::operation_aborted);
detail::ignore_unused(ec);
// after this lambda is executed, the io_context maybe destroyed,
// we set the flag to false.
{
std::lock_guard g{ this->event_life_lock_ };
this->event_life_flag_ = false;
}
this->event_timer_io_.timers().erase(std::addressof(event_timer_));
handler();
});
}
public:
/**
* @brief wakeup the waiting condition event.
*/
inline void notify()
{
// must use dispatch, otherwise if use called post_condition_event, and then called
// notify() immediately, the event will can't be notifyed.
// when code run to here, the io_context maybe destroyed already, if the
// io_context is destroyed already, the flag must be false, so the io_context
// will can't be used.
std::lock_guard g{ this->event_life_lock_ };
if (this->event_life_flag_ == false)
return;
asio::dispatch(this->event_timer_io_.context(), [this, this_ptr = this->selfptr()]() mutable
{
detail::ignore_unused(this_ptr);
detail::cancel_timer(this->event_timer_);
});
}
protected:
/// The io used for the timer.
detail::io_t & event_timer_io_;
/// Used to implementing asynchronous condition event
asio::steady_timer event_timer_;
///
mutable std::mutex event_life_lock_;
///
bool event_life_flag_ = false;
};
}
namespace asio2::detail
{
template<class derived_t, class args_t = void>
class condition_event_cp
{
public:
/**
* @brief constructor
*/
condition_event_cp() = default;
/**
* @brief destructor
*/
~condition_event_cp() = default;
public:
/**
* @brief Post a asynchronous condition event to execution util the event is notifyed by user.
* Before you call event_ptr->notify(); the event will not execute forever.
* The function signature of the handler must be : void handler();
*/
template<typename Function>
inline std::shared_ptr<condition_event> post_condition_event(Function&& f)
{
derived_t& derive = static_cast<derived_t&>(*this);
std::shared_ptr<condition_event> event_ptr = std::make_shared<condition_event>(derive.io());
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = derive.selfptr(), event_ptr, f = std::forward<Function>(f)]() mutable
{
condition_event* evt = event_ptr.get();
this->condition_events_.emplace(evt, std::move(event_ptr));
evt->async_wait([this, this_ptr = std::move(this_ptr), key = evt, f = std::move(f)]() mutable
{
f();
this->condition_events_.erase(key);
});
}));
return event_ptr;
}
/**
* @brief Notify all async_events to execute.
*/
[[deprecated("Replace notify_all_events with notify_all_condition_events")]]
inline derived_t& notify_all_events()
{
ASIO2_ASSERT(false);
return (static_cast<derived_t&>(*this));
}
/**
* @brief Notify all condition events to execute.
*/
inline derived_t& notify_all_condition_events()
{
derived_t& derive = static_cast<derived_t&>(*this);
// Make sure we run on the io_context thread
asio::dispatch(derive.io().context(), make_allocator(derive.wallocator(),
[this, this_ptr = derive.selfptr()]() mutable
{
for (auto&[key, event_ptr] : this->condition_events_)
{
detail::ignore_unused(this_ptr, key);
event_ptr->notify();
}
}));
return (derive);
}
protected:
/// Used to exit the condition event when component is ready to stop.
/// if user don't notify the event to execute, the io_context will
/// block forever, so we need notify the condition event when component
/// is ready to stop.
std::map<condition_event*, std::shared_ptr<condition_event>> condition_events_;
};
}
#endif // !__ASIO2_CONDITION_EVENT_COMPONENT_HPP__
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_PLAT_MINGW64_H
#define BHO_PREDEF_PLAT_MINGW64_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_PLAT_MINGW64`
https://mingw-w64.org/[MinGW-w64] platform.
Version number available as major, minor, and patch.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__MINGW64__+` | {predef_detection}
| `+__MINGW64_VERSION_MAJOR+`, `+__MINGW64_VERSION_MINOR+` | V.R.0
|===
*/ // end::reference[]
#define BHO_PLAT_MINGW64 BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__MINGW64__)
# include <_mingw.h>
# if !defined(BHO_PLAT_MINGW64_DETECTION) && (defined(__MINGW64_VERSION_MAJOR) && defined(__MINGW64_VERSION_MINOR))
# define BHO_PLAT_MINGW64_DETECTION \
BHO_VERSION_NUMBER(__MINGW64_VERSION_MAJOR,__MINGW64_VERSION_MINOR,0)
# endif
# if !defined(BHO_PLAT_MINGW64_DETECTION)
# define BHO_PLAT_MINGW64_DETECTION BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
#ifdef BHO_PLAT_MINGW64_DETECTION
# define BHO_PLAT_MINGW64_AVAILABLE
# if defined(BHO_PREDEF_DETAIL_PLAT_DETECTED)
# define BHO_PLAT_MINGW64_EMULATED BHO_PLAT_MINGW64_DETECTION
# else
# undef BHO_PLAT_MINGW64
# define BHO_PLAT_MINGW64 BHO_PLAT_MINGW64_DETECTION
# endif
# include <asio2/bho/predef/detail/platform_detected.h>
#endif
#define BHO_PLAT_MINGW64_NAME "MinGW-w64"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_MINGW64,BHO_PLAT_MINGW64_NAME)
#ifdef BHO_PLAT_MINGW64_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_PLAT_MINGW64_EMULATED,BHO_PLAT_MINGW64_NAME)
#endif
<file_sep>/*
Copyright <NAME> 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_COMPILER_METAWARE_H
#define BHO_PREDEF_COMPILER_METAWARE_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
/* tag::reference[]
= `BHO_COMP_HIGHC`
MetaWare High C/{CPP} compiler.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__HIGHC__+` | {predef_detection}
|===
*/ // end::reference[]
#define BHO_COMP_HIGHC BHO_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__HIGHC__)
# define BHO_COMP_HIGHC_DETECTION BHO_VERSION_NUMBER_AVAILABLE
#endif
#ifdef BHO_COMP_HIGHC_DETECTION
# if defined(BHO_PREDEF_DETAIL_COMP_DETECTED)
# define BHO_COMP_HIGHC_EMULATED BHO_COMP_HIGHC_DETECTION
# else
# undef BHO_COMP_HIGHC
# define BHO_COMP_HIGHC BHO_COMP_HIGHC_DETECTION
# endif
# define BHO_COMP_HIGHC_AVAILABLE
# include <asio2/bho/predef/detail/comp_detected.h>
#endif
#define BHO_COMP_HIGHC_NAME "MetaWare High C/C++"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_HIGHC,BHO_COMP_HIGHC_NAME)
#ifdef BHO_COMP_HIGHC_EMULATED
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_COMP_HIGHC_EMULATED,BHO_COMP_HIGHC_NAME)
#endif
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_UDP_CAST_HPP__
#define __ASIO2_UDP_CAST_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <cstdint>
#include <memory>
#include <chrono>
#include <functional>
#include <atomic>
#include <string>
#include <string_view>
#include <queue>
#include <any>
#include <future>
#include <tuple>
#include <unordered_map>
#include <asio2/base/iopool.hpp>
#include <asio2/base/listener.hpp>
#include <asio2/base/detail/object.hpp>
#include <asio2/base/detail/allocator.hpp>
#include <asio2/base/detail/util.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
#include <asio2/base/detail/ecs.hpp>
#include <asio2/base/impl/thread_id_cp.hpp>
#include <asio2/base/impl/alive_time_cp.hpp>
#include <asio2/base/impl/user_data_cp.hpp>
#include <asio2/base/impl/socket_cp.hpp>
#include <asio2/base/impl/user_timer_cp.hpp>
#include <asio2/base/impl/post_cp.hpp>
#include <asio2/base/impl/event_queue_cp.hpp>
#include <asio2/base/impl/condition_event_cp.hpp>
#include <asio2/base/detail/linear_buffer.hpp>
#include <asio2/udp/impl/udp_send_cp.hpp>
#include <asio2/udp/impl/udp_send_op.hpp>
namespace asio2::detail
{
struct template_args_udp_cast
{
using socket_t = asio::ip::udp::socket;
using buffer_t = asio2::linear_buffer;
static constexpr std::size_t function_storage_size = 88;
static constexpr std::size_t allocator_storage_size = 256;
};
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_UDP_BASE;
template<class derived_t, class args_t = template_args_udp_cast>
class udp_cast_impl_t
: public object_t <derived_t >
, public iopool_cp <derived_t, args_t>
, public thread_id_cp <derived_t, args_t>
, public event_queue_cp <derived_t, args_t>
, public user_data_cp <derived_t, args_t>
, public alive_time_cp <derived_t, args_t>
, public socket_cp <derived_t, args_t>
, public user_timer_cp <derived_t, args_t>
, public post_cp <derived_t, args_t>
, public condition_event_cp<derived_t, args_t>
, public udp_send_cp <derived_t, args_t>
, public udp_send_op <derived_t, args_t>
{
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_UDP_BASE;
public:
using super = object_t <derived_t >;
using self = udp_cast_impl_t<derived_t, args_t>;
using iopoolcp = iopool_cp <derived_t, args_t>;
using args_type = args_t;
using buffer_type = typename args_t::buffer_t;
/**
* @brief constructor
* @throws maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
explicit udp_cast_impl_t(
std::size_t init_buf_size = udp_frame_size,
std::size_t max_buf_size = max_buffer_size,
std::size_t concurrency = 1
)
: super()
, iopool_cp <derived_t, args_t>(concurrency)
, event_queue_cp <derived_t, args_t>()
, user_data_cp <derived_t, args_t>()
, alive_time_cp <derived_t, args_t>()
, socket_cp <derived_t, args_t>(iopoolcp::_get_io(0).context())
, user_timer_cp <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp<derived_t, args_t>()
, udp_send_cp <derived_t, args_t>(iopoolcp::_get_io(0))
, udp_send_op <derived_t, args_t>()
, rallocator_()
, wallocator_()
, listener_ ()
, io_ (iopoolcp::_get_io(0))
, buffer_ (init_buf_size, max_buf_size)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit udp_cast_impl_t(
std::size_t init_buf_size,
std::size_t max_buf_size,
Scheduler && scheduler
)
: super()
, iopool_cp <derived_t, args_t>(std::forward<Scheduler>(scheduler))
, event_queue_cp <derived_t, args_t>()
, user_data_cp <derived_t, args_t>()
, alive_time_cp <derived_t, args_t>()
, socket_cp <derived_t, args_t>(iopoolcp::_get_io(0).context())
, user_timer_cp <derived_t, args_t>()
, post_cp <derived_t, args_t>()
, condition_event_cp<derived_t, args_t>()
, udp_send_cp <derived_t, args_t>(iopoolcp::_get_io(0))
, udp_send_op <derived_t, args_t>()
, rallocator_()
, wallocator_()
, listener_ ()
, io_ (iopoolcp::_get_io(0))
, buffer_ (init_buf_size, max_buf_size)
{
}
template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
explicit udp_cast_impl_t(Scheduler&& scheduler)
: udp_cast_impl_t(udp_frame_size, max_buffer_size, std::forward<Scheduler>(scheduler))
{
}
/**
* @brief destructor
*/
~udp_cast_impl_t()
{
this->stop();
}
/**
* @brief start the udp cast
* @param host - A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param service - A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& service, Args&&... args)
{
#if defined(ASIO2_ENABLE_LOG)
#if defined(ASIO2_ALLOCATOR_STORAGE_SIZE)
static_assert(decltype(rallocator_)::storage_size == ASIO2_ALLOCATOR_STORAGE_SIZE);
static_assert(decltype(wallocator_)::storage_size == ASIO2_ALLOCATOR_STORAGE_SIZE);
#else
static_assert(decltype(rallocator_)::storage_size == args_t::allocator_storage_size);
static_assert(decltype(wallocator_)::storage_size == args_t::allocator_storage_size);
#endif
#endif
return this->derived()._do_start(
std::forward<String>(host), std::forward<StrOrInt>(service),
ecs_helper::make_ecs('0', std::forward<Args>(args)...));
}
/**
* @brief stop the udp cast
* You can call this function in the communication thread and anywhere to stop the udp cast.
* If this function is called in the communication thread, it will post a asynchronous
* event into the event queue, then return immediately.
* If this function is called not in the communication thread, it will blocking forever
* util the udp cast is stopped completed.
*/
inline void stop()
{
if (this->is_iopool_stopped())
return;
derived_t& derive = this->derived();
derive.io().unregobj(&derive);
// use promise to get the result of stop
std::promise<state_t> promise;
std::future<state_t> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[this, p = std::move(promise)]() mutable
{
p.set_value(this->state().load());
}
};
derive.post_event([&derive, this_ptr = derive.selfptr(), pg = std::move(pg)]
(event_queue_guard<derived_t> g) mutable
{
derive._do_stop(asio::error::operation_aborted, std::move(this_ptr), defer_event
{
[pg = std::move(pg)](event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
});
});
while (!derive.running_in_this_thread())
{
std::future_status status = future.wait_for(std::chrono::milliseconds(100));
if (status == std::future_status::ready)
{
ASIO2_ASSERT(future.get() == state_t::stopped);
break;
}
else
{
if (derive.get_thread_id() == std::thread::id{})
break;
if (derive.io().context().stopped())
break;
}
}
this->stop_iopool();
}
/**
* @brief check whether the udp cast is started
*/
inline bool is_started()
{
return (this->state_ == state_t::started && this->socket().is_open());
}
/**
* @brief check whether the udp cast is stopped
*/
inline bool is_stopped()
{
return (this->state_ == state_t::stopped && !this->socket().is_open());
}
public:
/**
* @brief bind recv listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void(asio::ip::udp::endpoint& endpoint, std::string_view data)
*/
template<class F, class ...C>
inline derived_t & bind_recv(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::recv,
observer_t<asio::ip::udp::endpoint&, std::string_view>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind init listener,we should set socket options at here
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_init(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::init,
observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind start listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called after the server starts up, whether successful or unsuccessful
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_start(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::start, observer_t<>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
/**
* @brief bind stop listener
* @param fun - a user defined callback function.
* @param obj - a pointer or reference to a class object, this parameter can be none.
* @li if fun is nonmember function, the obj param must be none, otherwise the obj must be the
* the class object's pointer or refrence.
* This notification is called before the server is ready to stop
* Function signature : void()
*/
template<class F, class ...C>
inline derived_t & bind_stop(F&& fun, C&&... obj)
{
this->listener_.bind(event_type::stop, observer_t<>(
std::forward<F>(fun), std::forward<C>(obj)...));
return (this->derived());
}
protected:
template<typename String, typename StrOrInt, typename C>
bool _do_start(String&& host, StrOrInt&& port, std::shared_ptr<ecs_t<C>> ecs)
{
derived_t& derive = this->derived();
// if log is enabled, init the log first, otherwise when "Too many open files" error occurs,
// the log file will be created failed too.
#if defined(ASIO2_ENABLE_LOG)
asio2::detail::get_logger();
#endif
this->start_iopool();
if (!this->is_iopool_started())
{
set_last_error(asio::error::operation_aborted);
return false;
}
asio::dispatch(derive.io().context(), [&derive, this_ptr = derive.selfptr()]() mutable
{
detail::ignore_unused(this_ptr);
// init the running thread id
derive.io().init_thread_id();
});
// use promise to get the result of async connect
std::promise<error_code> promise;
std::future<error_code> future = promise.get_future();
// use derfer to ensure the promise's value must be seted.
detail::defer_event pg
{
[promise = std::move(promise)]() mutable
{
promise.set_value(get_last_error());
}
};
derive.post_event(
[this, this_ptr = derive.selfptr(), ecs = std::move(ecs), pg = std::move(pg),
host = std::forward<String>(host), port = std::forward<StrOrInt>(port)]
(event_queue_guard<derived_t> g) mutable
{
derived_t& derive = this->derived();
defer_event chain
{
[pg = std::move(pg)](event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(pg, g);
// the "pg" should destroyed before the "g", otherwise if the "g"
// is destroyed before "pg", the next event maybe called, then the
// state maybe change to not stopped.
{
[[maybe_unused]] detail::defer_event t{ std::move(pg) };
}
}, std::move(g)
};
state_t expected = state_t::stopped;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
// if the state is not stopped, set the last error to already_started
set_last_error(asio::error::already_started);
return;
}
// must read/write ecs in the io_context thread.
derive.ecs_ = ecs;
derive.io().regobj(&derive);
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_called_ = false;
#endif
// convert to string maybe throw some exception.
std::string h = detail::to_string(std::move(host));
std::string p = detail::to_string(std::move(port));
expected = state_t::starting;
if (!this->state_.compare_exchange_strong(expected, state_t::starting))
{
ASIO2_ASSERT(false);
derive._handle_start(asio::error::operation_aborted,
std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
error_code ec, ec_ignore;
this->socket().cancel(ec_ignore);
this->socket().close(ec_ignore);
// parse address and port
asio::ip::udp::resolver resolver(this->io_.context());
auto results = resolver.resolve(h, p,
asio::ip::resolver_base::flags::passive |
asio::ip::resolver_base::flags::address_configured, ec);
if (ec)
{
derive._handle_start(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
if (results.empty())
{
derive._handle_start(asio::error::host_not_found,
std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
asio::ip::udp::endpoint endpoint = *results.begin();
this->socket().open(endpoint.protocol(), ec);
if (ec)
{
derive._handle_start(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
// when you close socket in linux system,and start socket
// immediate,you will get like this "the address is in use",
// and bind is failed,but i'm suer i close the socket correct
// already before,why does this happen? the reasion is the
// socket option "TIME_WAIT",although you close the socket,
// but the system not release the socket,util 2~4 seconds later,
// so we can use the SO_REUSEADDR option to avoid this problem,
// like below
// set port reuse
this->socket().set_option(asio::ip::udp::socket::reuse_address(true), ec_ignore);
clear_last_error();
derive._fire_init();
this->socket().bind(endpoint, ec);
if (ec)
{
derive._handle_start(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
return;
}
derive._handle_start(ec, std::move(this_ptr), std::move(ecs), std::move(chain));
});
if (!derive.io().running_in_this_thread())
{
set_last_error(future.get());
return static_cast<bool>(!get_last_error());
}
else
{
set_last_error(asio::error::in_progress);
}
// if the state is stopped , the return value is "is_started()".
// if the state is stopping, the return value is false, the last error is already_started
// if the state is starting, the return value is false, the last error is already_started
// if the state is started , the return value is true , the last error is already_started
return derive.is_started();
}
template<typename C, typename DeferEvent>
void _handle_start(
error_code ec, std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs, DeferEvent chain)
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
// Whether the startup succeeds or fails, always call fire_start notification
state_t expected = state_t::starting;
if (!ec)
if (!this->state_.compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
set_last_error(ec);
this->derived()._fire_start();
expected = state_t::started;
if (!ec)
if (!this->state_.compare_exchange_strong(expected, state_t::started))
ec = asio::error::operation_aborted;
if (ec)
{
this->derived()._do_stop(ec, std::move(this_ptr), std::move(chain));
return;
}
this->buffer_.consume(this->buffer_.size());
this->derived()._post_recv(std::move(this_ptr), std::move(ecs));
}
template<typename E = defer_event<void, derived_t>>
inline void _do_stop(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, E chain = defer_event<void, derived_t>{})
{
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
state_t expected = state_t::starting;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
return this->derived()._post_stop(ec, std::move(this_ptr), expected, std::move(chain));
expected = state_t::started;
if (this->state_.compare_exchange_strong(expected, state_t::stopping))
return this->derived()._post_stop(ec, std::move(this_ptr), expected, std::move(chain));
}
template<typename DeferEvent>
inline void _post_stop(
const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state, DeferEvent chain)
{
// psot a recv signal to ensure that all recv events has finished already.
this->derived().disp_event(
[this, ec, this_ptr = std::move(this_ptr), old_state, e = chain.move_event()]
(event_queue_guard<derived_t> g) mutable
{
detail::ignore_unused(old_state);
// When the code runs here,no new session can be emplace or erase to session_mgr.
// stop all the sessions, the session::stop must be no blocking,
// otherwise it may be cause loop lock.
set_last_error(ec);
defer_event chain(std::move(e), std::move(g));
state_t expected = state_t::stopping;
if (this->state_.compare_exchange_strong(expected, state_t::stopped))
{
this->derived()._fire_stop();
// call CRTP polymorphic stop
this->derived()._handle_stop(ec, std::move(this_ptr), std::move(chain));
}
else
{
ASIO2_ASSERT(false);
}
}, chain.move_guard());
}
template<typename DeferEvent>
inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, DeferEvent chain)
{
detail::ignore_unused(ec, this_ptr, chain);
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
// close user custom timers
this->_dispatch_stop_all_timers();
// close all posted timed tasks
this->_dispatch_stop_all_timed_events();
// close all async_events
this->notify_all_condition_events();
error_code ec_ignore{};
// call socket's close function to notify the _handle_recv function
// response with error > 0 ,then the socket can get notify to exit
// Call shutdown() to indicate that you will not write any more data to the socket.
this->socket().shutdown(asio::socket_base::shutdown_both, ec_ignore);
this->socket().cancel(ec_ignore);
// Call close,otherwise the _handle_recv will never return
this->socket().close(ec_ignore);
// clear recv buffer
this->buffer().consume(this->buffer().size());
// destroy user data, maybe the user data is self shared_ptr,
// if don't destroy it, will cause loop refrence.
this->user_data_.reset();
// destroy the ecs
this->ecs_.reset();
//
this->reset_life_id();
}
protected:
template<class Endpoint, class Data, class Callback>
inline bool _do_send(Endpoint& endpoint, Data& data, Callback&& callback)
{
return this->derived()._udp_send_to(endpoint, data, std::forward<Callback>(callback));
}
protected:
/**
* @brief Pre process the data before recv callback was called.
* You can overload this function in a derived class to implement additional
* processing of the data. eg: decrypt data with a custom encryption algorithm.
*/
inline std::string_view data_filter_before_recv(std::string_view data)
{
return data;
}
protected:
template<typename C>
void _post_recv(std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
if (!this->is_started())
{
if (this->derived().state() == state_t::started)
{
this->derived()._do_stop(asio2::get_last_error(), std::move(this_ptr));
}
return;
}
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->derived().post_recv_counter_.load() == 0);
this->derived().post_recv_counter_++;
#endif
this->socket().async_receive_from(
this->buffer_.prepare(this->buffer_.pre_size()),
this->remote_endpoint_,
make_allocator(this->rallocator_,
[this, this_ptr = std::move(this_ptr), ecs = std::move(ecs)]
(const error_code& ec, std::size_t bytes_recvd) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
this->derived().post_recv_counter_--;
#endif
this->derived()._handle_recv(ec, bytes_recvd, std::move(this_ptr), std::move(ecs));
}));
}
template<typename C>
void _handle_recv(
const error_code& ec, std::size_t bytes_recvd,
std::shared_ptr<derived_t> this_ptr, std::shared_ptr<ecs_t<C>> ecs)
{
set_last_error(ec);
if (!this->derived().is_started())
{
if (this->derived().state() == state_t::started)
{
this->derived()._do_stop(ec, std::move(this_ptr));
}
return;
}
if (ec == asio::error::operation_aborted)
{
this->derived()._do_stop(ec, std::move(this_ptr));
return;
}
this->buffer_.commit(bytes_recvd);
if (!ec)
{
this->derived()._fire_recv(this_ptr, ecs,
std::string_view(static_cast<std::string_view::const_pointer>(
this->buffer_.data().data()), bytes_recvd));
}
this->buffer_.consume(this->buffer_.size());
if (bytes_recvd == this->buffer_.pre_size())
{
this->buffer_.pre_size((std::min)(this->buffer_.pre_size() * 2, this->buffer_.max_size()));
}
this->derived()._post_recv(std::move(this_ptr), std::move(ecs));
}
inline void _fire_init()
{
// the _fire_init must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
ASIO2_ASSERT(!get_last_error());
this->listener_.notify(event_type::init);
}
template<typename C>
inline void _fire_recv(
std::shared_ptr<derived_t>& this_ptr, std::shared_ptr<ecs_t<C>>& ecs, std::string_view data)
{
detail::ignore_unused(this_ptr, ecs);
data = this->derived().data_filter_before_recv(data);
this->listener_.notify(event_type::recv, this->remote_endpoint_, data);
}
inline void _fire_start()
{
// the _fire_start must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(this->is_stop_called_ == false);
#endif
this->listener_.notify(event_type::start);
}
inline void _fire_stop()
{
// the _fire_stop must be executed in the thread 0.
ASIO2_ASSERT(this->derived().io().running_in_this_thread());
#if defined(_DEBUG) || defined(DEBUG)
this->is_stop_called_ = true;
#endif
this->listener_.notify(event_type::stop);
}
public:
/**
* @brief get the buffer object refrence
*/
inline buffer_wrap<buffer_type> & buffer() noexcept { return this->buffer_; }
/**
* @brief get the io object refrence
*/
inline io_t & io() noexcept { return this->io_; }
protected:
/**
* @brief get the recv/read allocator object refrence
*/
inline auto & rallocator() noexcept { return this->rallocator_; }
/**
* @brief get the send/write allocator object refrence
*/
inline auto & wallocator() noexcept { return this->wallocator_; }
inline listener_t & listener() noexcept { return this->listener_; }
inline std::atomic<state_t> & state () noexcept { return this->state_; }
inline const char* life_id () noexcept { return this->life_id_.get(); }
inline void reset_life_id () noexcept { this->life_id_ = std::make_unique<char>(); }
protected:
/// The memory to use for handler-based custom memory allocation. used fo recv/read.
handler_memory<std::true_type , assizer<args_t>> rallocator_;
/// The memory to use for handler-based custom memory allocation. used fo send/write.
handler_memory<std::false_type, assizer<args_t>> wallocator_;
/// listener
listener_t listener_;
/// The io_context wrapper used to handle the connect/recv/send event.
io_t & io_;
/// buffer
buffer_wrap<buffer_type> buffer_;
/// state
std::atomic<state_t> state_ = state_t::stopped;
/// endpoint for udp
asio::ip::udp::endpoint remote_endpoint_;
/// the pointer of ecs_t
std::shared_ptr<ecs_base> ecs_;
/// @see client life id
std::unique_ptr<char> life_id_ = std::make_unique<char>();
#if defined(_DEBUG) || defined(DEBUG)
bool is_stop_called_ = false;
std::atomic<int> post_send_counter_ = 0;
std::atomic<int> post_recv_counter_ = 0;
#endif
};
}
namespace asio2
{
using udp_cast_args = detail::template_args_udp_cast;
template<class derived_t, class args_t>
using udp_cast_impl_t = detail::udp_cast_impl_t<derived_t, args_t>;
/**
* udp unicast/multicast/broadcast
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
template<class derived_t>
class udp_cast_t : public detail::udp_cast_impl_t<derived_t, detail::template_args_udp_cast>
{
public:
using detail::udp_cast_impl_t<derived_t, detail::template_args_udp_cast>::udp_cast_impl_t;
};
/*
* udp unicast/multicast/broadcast
* If this object is created as a shared_ptr like std::shared_ptr<asio2::udp_cast> cast;
* you must call the cast->stop() manual when exit, otherwise maybe cause memory leaks.
* @throws constructor maybe throw exception "Too many open files" (exception code : 24)
* asio::error::no_descriptors - Too many open files
*/
class udp_cast : public udp_cast_t<udp_cast>
{
public:
using udp_cast_t<udp_cast>::udp_cast_t;
};
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_UDP_CAST_HPP__
<file_sep>#
# COPYRIGHT (C) 2017-2021, zhllxt
#
# author : zhllxt
# email : <EMAIL>
#
# Distributed under the GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
# (See accompanying file LICENSE or see <http://www.gnu.org/licenses/>)
#
#GroupSources (include/asio2 "/")
#GroupSources (3rd/asio "/")
aux_source_directory(. SRC_FILES)
source_group("" FILES ${SRC_FILES})
set(TARGET_NAME asio_tcp_tps_client)
add_executable (
${TARGET_NAME}
${TARGET_NAME}.cpp
)
set_property(TARGET ${TARGET_NAME} PROPERTY FOLDER "bench/tcp")
#SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ASIO2_EXES_DIR})
set_target_properties(${TARGET_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${ASIO2_EXES_DIR})
target_link_libraries(${TARGET_NAME} ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(${TARGET_NAME} ${GENERAL_LIBS})
include_directories (${ASIO2_ROOT_DIR}/asio)
<file_sep>#include <asio2/external/asio.hpp>
struct userinfo
{
int id;
char name[20];
int8_t age;
};
#ifdef ASIO_STANDALONE
namespace asio
#else
namespace boost::asio
#endif
{
inline asio::const_buffer buffer(const userinfo& u) noexcept
{
return asio::const_buffer(&u, sizeof(userinfo));
}
}
#include <asio2/tcp/tcp_client.hpp>
int main()
{
std::string_view host = "127.0.0.1";
//std::string_view host = "fe80::dc05:d962:f568:39b7"; // ipv6 windows
//std::string_view host = "fe80::bb00:5a10:d713:d293%eth0"; // ipv6 linux
std::string_view port = "8028";
asio2::tcp_client client;
// disable auto reconnect, default reconnect option is "enable"
//client.set_auto_reconnect(false);
// enable auto reconnect and use custom delay, default delay is 1 seconds
client.set_auto_reconnect(true, std::chrono::milliseconds(2000));
client.bind_connect([&]()
{
if (asio2::get_last_error())
printf("connect failure : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n",
client.local_address().c_str(), client.local_port());
// has no error, it means connect success, we can send data at here
if (!asio2::get_last_error())
{
client.async_send("<abcdefghijklmnopqrstovuxyz0123456789>");
}
}).bind_disconnect([&]()
{
printf("disconnect : %d %s\n",
asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_recv([&](std::string_view data)
{
printf("recv : %zu %.*s\n", data.size(), (int)data.size(), data.data());
client.async_send(data);
});
// Asynchronous connect to the server
//client.async_start(host, port);
// Synchronously connect to the server
client.start(host, port);
std::string str = "[abcdefghijklmnopqrstovuxyz0123456789]";
if (client.is_started())
{
// ## All of the following ways of send operation are correct.
client.async_send(str);
client.async_send(str.data(), str.size() / 2);
int intarray[2] = { 1, 2 };
// callback with no params
client.async_send(intarray, []()
{
if (asio2::get_last_error())
printf("send failed : %s\n", asio2::last_error_msg().data());
});
// callback with param
client.async_send(intarray, [](std::size_t sent_bytes)
{
std::ignore = sent_bytes;
});
// use future to wait util the send is finished.
std::future<std::pair<asio::error_code, std::size_t>> future =
client.async_send(str, asio::use_future);
auto[ec, bytes] = future.get();
printf("sent result : %s %zu\n", ec.message().c_str(), bytes);
// use asio::buffer to avoid memory allocation, the underlying
// buffer must be persistent, like the static pointer "msg" below
const char * msg = "<abcdefghijklmnopqrstovuxyz0123456789>";
asio::const_buffer buffer = asio::buffer(msg);
client.async_send(buffer);
// Example for Synchronous send data. The return value is the sent bytes.
// You can use asio2::get_last_error() to check whether some error occured.
std::size_t sent_bytes = client.send(std::move(str));
if (asio2::get_last_error())
{
printf("send data failed : %zu %s\n", sent_bytes, asio2::last_error_msg().data());
}
// send vector, array, .... and others
std::vector<uint8_t> data{ 1,2,3 };
client.send(std::move(data));
// ##Example how to send a struct directly:
userinfo u;
u.id = 11;
memset(u.name, 0, sizeof(u.name));
memcpy(u.name, "abc", 3);
u.age = 20;
client.async_send(u);
}
while (std::getchar() != '\n');
return 0;
}
<file_sep>/*
Copyright <NAME> 2013-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BHO_PREDEF_ENDIAN_H
#define BHO_PREDEF_ENDIAN_H
#include <asio2/bho/predef/version_number.h>
#include <asio2/bho/predef/make.h>
#include <asio2/bho/predef/library/c/gnu.h>
#include <asio2/bho/predef/os/macos.h>
#include <asio2/bho/predef/os/bsd.h>
#include <asio2/bho/predef/platform/android.h>
/* tag::reference[]
= `BHO_ENDIAN_*`
Detection of endian memory ordering. There are four defined macros
in this header that define the various generally possible endian
memory orderings:
* `BHO_ENDIAN_BIG_BYTE`, byte-swapped big-endian.
* `BHO_ENDIAN_BIG_WORD`, word-swapped big-endian.
* `BHO_ENDIAN_LITTLE_BYTE`, byte-swapped little-endian.
* `BHO_ENDIAN_LITTLE_WORD`, word-swapped little-endian.
The detection is conservative in that it only identifies endianness
that it knows for certain. In particular bi-endianness is not
indicated as is it not practically possible to determine the
endianness from anything but an operating system provided
header. And the currently known headers do not define that
programatic bi-endianness is available.
This implementation is a compilation of various publicly available
information and acquired knowledge:
. The indispensable documentation of "Pre-defined Compiler Macros"
http://sourceforge.net/p/predef/wiki/Endianness[Endianness].
. The various endian specifications available in the
http://wikipedia.org/[Wikipedia] computer architecture pages.
. Generally available searches for headers that define endianness.
*/ // end::reference[]
#define BHO_ENDIAN_BIG_BYTE BHO_VERSION_NUMBER_NOT_AVAILABLE
#define BHO_ENDIAN_BIG_WORD BHO_VERSION_NUMBER_NOT_AVAILABLE
#define BHO_ENDIAN_LITTLE_BYTE BHO_VERSION_NUMBER_NOT_AVAILABLE
#define BHO_ENDIAN_LITTLE_WORD BHO_VERSION_NUMBER_NOT_AVAILABLE
/* GNU libc provides a header defining __BYTE_ORDER, or _BYTE_ORDER.
* And some OSs provide some for of endian header also.
*/
#if !BHO_ENDIAN_BIG_BYTE && !BHO_ENDIAN_BIG_WORD && \
!BHO_ENDIAN_LITTLE_BYTE && !BHO_ENDIAN_LITTLE_WORD
# if BHO_LIB_C_GNU || BHO_PLAT_ANDROID || BHO_OS_BSD_OPEN
# include <endian.h>
# else
# if BHO_OS_MACOS
# include <machine/endian.h>
# else
# if BHO_OS_BSD
# include <sys/endian.h>
# endif
# endif
# endif
# if defined(__BYTE_ORDER)
# if defined(__BIG_ENDIAN) && (__BYTE_ORDER == __BIG_ENDIAN)
# undef BHO_ENDIAN_BIG_BYTE
# define BHO_ENDIAN_BIG_BYTE BHO_VERSION_NUMBER_AVAILABLE
# endif
# if defined(__LITTLE_ENDIAN) && (__BYTE_ORDER == __LITTLE_ENDIAN)
# undef BHO_ENDIAN_LITTLE_BYTE
# define BHO_ENDIAN_LITTLE_BYTE BHO_VERSION_NUMBER_AVAILABLE
# endif
# if defined(__PDP_ENDIAN) && (__BYTE_ORDER == __PDP_ENDIAN)
# undef BHO_ENDIAN_LITTLE_WORD
# define BHO_ENDIAN_LITTLE_WORD BHO_VERSION_NUMBER_AVAILABLE
# endif
# endif
# if !defined(__BYTE_ORDER) && defined(_BYTE_ORDER)
# if defined(_BIG_ENDIAN) && (_BYTE_ORDER == _BIG_ENDIAN)
# undef BHO_ENDIAN_BIG_BYTE
# define BHO_ENDIAN_BIG_BYTE BHO_VERSION_NUMBER_AVAILABLE
# endif
# if defined(_LITTLE_ENDIAN) && (_BYTE_ORDER == _LITTLE_ENDIAN)
# undef BHO_ENDIAN_LITTLE_BYTE
# define BHO_ENDIAN_LITTLE_BYTE BHO_VERSION_NUMBER_AVAILABLE
# endif
# if defined(_PDP_ENDIAN) && (_BYTE_ORDER == _PDP_ENDIAN)
# undef BHO_ENDIAN_LITTLE_WORD
# define BHO_ENDIAN_LITTLE_WORD BHO_VERSION_NUMBER_AVAILABLE
# endif
# endif
#endif
/* Built-in byte-swapped big-endian macros.
*/
#if !BHO_ENDIAN_BIG_BYTE && !BHO_ENDIAN_BIG_WORD && \
!BHO_ENDIAN_LITTLE_BYTE && !BHO_ENDIAN_LITTLE_WORD
# if (defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__)) || \
(defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN)) || \
defined(__ARMEB__) || \
defined(__THUMBEB__) || \
defined(__AARCH64EB__) || \
defined(_MIPSEB) || \
defined(__MIPSEB) || \
defined(__MIPSEB__)
# undef BHO_ENDIAN_BIG_BYTE
# define BHO_ENDIAN_BIG_BYTE BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
/* Built-in byte-swapped little-endian macros.
*/
#if !BHO_ENDIAN_BIG_BYTE && !BHO_ENDIAN_BIG_WORD && \
!BHO_ENDIAN_LITTLE_BYTE && !BHO_ENDIAN_LITTLE_WORD
# if (defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \
(defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)) || \
defined(__ARMEL__) || \
defined(__THUMBEL__) || \
defined(__AARCH64EL__) || \
defined(_MIPSEL) || \
defined(__MIPSEL) || \
defined(__MIPSEL__) || \
defined(__riscv) || \
defined(__e2k__)
# undef BHO_ENDIAN_LITTLE_BYTE
# define BHO_ENDIAN_LITTLE_BYTE BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
/* Some architectures are strictly one endianess (as opposed
* the current common bi-endianess).
*/
#if !BHO_ENDIAN_BIG_BYTE && !BHO_ENDIAN_BIG_WORD && \
!BHO_ENDIAN_LITTLE_BYTE && !BHO_ENDIAN_LITTLE_WORD
# include <asio2/bho/predef/architecture.h>
# if BHO_ARCH_M68K || \
BHO_ARCH_PARISC || \
BHO_ARCH_SPARC || \
BHO_ARCH_SYS370 || \
BHO_ARCH_SYS390 || \
BHO_ARCH_Z
# undef BHO_ENDIAN_BIG_BYTE
# define BHO_ENDIAN_BIG_BYTE BHO_VERSION_NUMBER_AVAILABLE
# endif
# if BHO_ARCH_IA64 || \
BHO_ARCH_X86 || \
BHO_ARCH_BLACKFIN
# undef BHO_ENDIAN_LITTLE_BYTE
# define BHO_ENDIAN_LITTLE_BYTE BHO_VERSION_NUMBER_AVAILABLE
# endif
#endif
/* Windows on ARM, if not otherwise detected/specified, is always
* byte-swapped little-endian.
*/
#if !BHO_ENDIAN_BIG_BYTE && !BHO_ENDIAN_BIG_WORD && \
!BHO_ENDIAN_LITTLE_BYTE && !BHO_ENDIAN_LITTLE_WORD
# if BHO_ARCH_ARM
# include <asio2/bho/predef/os/windows.h>
# if BHO_OS_WINDOWS
# undef BHO_ENDIAN_LITTLE_BYTE
# define BHO_ENDIAN_LITTLE_BYTE BHO_VERSION_NUMBER_AVAILABLE
# endif
# endif
#endif
#if BHO_ENDIAN_BIG_BYTE
# define BHO_ENDIAN_BIG_BYTE_AVAILABLE
#endif
#if BHO_ENDIAN_BIG_WORD
# define BHO_ENDIAN_BIG_WORD_BYTE_AVAILABLE
#endif
#if BHO_ENDIAN_LITTLE_BYTE
# define BHO_ENDIAN_LITTLE_BYTE_AVAILABLE
#endif
#if BHO_ENDIAN_LITTLE_WORD
# define BHO_ENDIAN_LITTLE_WORD_BYTE_AVAILABLE
#endif
#define BHO_ENDIAN_BIG_BYTE_NAME "Byte-Swapped Big-Endian"
#define BHO_ENDIAN_BIG_WORD_NAME "Word-Swapped Big-Endian"
#define BHO_ENDIAN_LITTLE_BYTE_NAME "Byte-Swapped Little-Endian"
#define BHO_ENDIAN_LITTLE_WORD_NAME "Word-Swapped Little-Endian"
#endif
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ENDIAN_BIG_BYTE,BHO_ENDIAN_BIG_BYTE_NAME)
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ENDIAN_BIG_WORD,BHO_ENDIAN_BIG_WORD_NAME)
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ENDIAN_LITTLE_BYTE,BHO_ENDIAN_LITTLE_BYTE_NAME)
#include <asio2/bho/predef/detail/test.h>
BHO_PREDEF_DECLARE_TEST(BHO_ENDIAN_LITTLE_WORD,BHO_ENDIAN_LITTLE_WORD_NAME)
<file_sep>/*
* Copyright (c) 2017-2023 zhllxt
*
* author : zhllxt
* email : <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __ASIO2_TCP_SEND_OP_HPP__
#define __ASIO2_TCP_SEND_OP_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <memory>
#include <future>
#include <utility>
#include <string_view>
#include <asio2/base/error.hpp>
#include <asio2/base/detail/buffer_wrap.hpp>
namespace asio2::detail
{
template<class derived_t, class args_t>
class tcp_send_op
{
protected:
template<class, class = std::void_t<>>
struct has_member_dgram : std::false_type {};
template<class T>
struct has_member_dgram<T, std::void_t<decltype(T::dgram_)>> : std::true_type {};
//template<class T>
//struct has_member_dgram<T, std::void_t<decltype(T::dgram_), std::enable_if_t<
// std::is_same_v<decltype(T::dgram_), bool>>>> : std::true_type {};
public:
/**
* @brief constructor
*/
tcp_send_op() noexcept {}
/**
* @brief destructor
*/
~tcp_send_op() = default;
protected:
template<class Data, class Callback>
inline bool _tcp_send(Data& data, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
if constexpr (has_member_dgram<derived_t>::value)
{
if (derive.dgram_)
{
return derive._tcp_send_dgram(asio::buffer(data), std::forward<Callback>(callback));
}
}
else
{
std::ignore = true;
}
return derive._tcp_send_general(asio::buffer(data), std::forward<Callback>(callback));
}
template<class Buffer, class Callback>
inline bool _tcp_send_dgram(Buffer&& buffer, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
int bytes = 0;
std::unique_ptr<std::uint8_t[]> head;
// why don't use std::string for "head"?
// beacuse std::string has a SSO(Small String Optimization) mechanism
// https://stackoverflow.com/questions/34788789/disable-stdstrings-sso
// std::string str;
// str.reserve(sizeof(str) + 1);
// note : need ensure big endian and little endian
if (buffer.size() < std::size_t(254))
{
bytes = 1;
head = std::make_unique<std::uint8_t[]>(bytes);
head[0] = static_cast<std::uint8_t>(buffer.size());
}
else if (buffer.size() <= (std::numeric_limits<std::uint16_t>::max)())
{
bytes = 3;
head = std::make_unique<std::uint8_t[]>(bytes);
head[0] = static_cast<std::uint8_t>(254);
std::uint16_t size = static_cast<std::uint16_t>(buffer.size());
std::memcpy(&head[1], reinterpret_cast<const void*>(&size), sizeof(std::uint16_t));
// use little endian
if (!is_little_endian())
{
swap_bytes<sizeof(std::uint16_t)>(&head[1]);
}
}
else
{
ASIO2_ASSERT(buffer.size() > (std::numeric_limits<std::uint16_t>::max)());
bytes = 9;
head = std::make_unique<std::uint8_t[]>(bytes);
head[0] = static_cast<std::uint8_t>(255);
std::uint64_t size = buffer.size();
std::memcpy(&head[1], reinterpret_cast<const void*>(&size), sizeof(std::uint64_t));
// use little endian
if (!is_little_endian())
{
swap_bytes<sizeof(std::uint64_t)>(&head[1]);
}
}
std::array<asio::const_buffer, 2> buffers
{
asio::buffer(reinterpret_cast<const void*>(head.get()), bytes),
std::forward<Buffer>(buffer)
};
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
asio::async_write(derive.stream(), buffers, make_allocator(derive.wallocator(),
[&derive, p = derive.selfptr(), bytes, head = std::move(head), callback = std::forward<Callback>(callback)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
if (ec)
{
callback(ec, bytes_sent);
// must stop, otherwise re-sending will cause header confusion
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, std::move(p));
}
}
else
{
callback(ec, bytes_sent - bytes);
}
}));
return true;
}
template<class Buffer, class Callback>
inline bool _tcp_send_general(Buffer&& buffer, Callback&& callback)
{
derived_t& derive = static_cast<derived_t&>(*this);
#if defined(_DEBUG) || defined(DEBUG)
ASIO2_ASSERT(derive.post_send_counter_.load() == 0);
derive.post_send_counter_++;
#endif
asio::async_write(derive.stream(), buffer, make_allocator(derive.wallocator(),
[&derive, p = derive.selfptr(), callback = std::forward<Callback>(callback)]
(const error_code& ec, std::size_t bytes_sent) mutable
{
#if defined(_DEBUG) || defined(DEBUG)
derive.post_send_counter_--;
#endif
set_last_error(ec);
callback(ec, bytes_sent);
if (ec)
{
// must stop, otherwise re-sending will cause body confusion
if (derive.state() == state_t::started)
{
derive._do_disconnect(ec, std::move(p));
}
}
}));
return true;
}
protected:
};
}
#endif // !__ASIO2_TCP_SEND_OP_HPP__
<file_sep>/*
Copyright <NAME> 2015
Copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#if !defined(BHO_PREDEF_HARDWARE_H) || defined(BHO_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BHO_PREDEF_HARDWARE_H
#define BHO_PREDEF_HARDWARE_H
#endif
#include <asio2/bho/predef/hardware/simd.h>
#endif
<file_sep>// _ _ __ _____
// | \ | | / _| / ____|_ _
// | \| | __ _ _ __ ___ ___ ___ | |_ | | _| |_ _| |_
// | . ` |/ _` | '_ ` _ \ / _ \/ _ \| _| | | |_ _|_ _|
// | |\ | (_| | | | | | | __/ (_) | | | |____|_| |_|
// |_| \_|\__,_|_| |_| |_|\___|\___/|_| \_____|
// https://github.com/Neargye/nameof
// version 0.10.2
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2016 - 2022 <NAME> <<EMAIL>>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef NEARGYE_NAMEOF_HPP
#define NEARGYE_NAMEOF_HPP
#define NAMEOF_VERSION_MAJOR 0
#define NAMEOF_VERSION_MINOR 10
#define NAMEOF_VERSION_PATCH 2
#include <array>
#include <cassert>
#include <cstdint>
#include <cstddef>
#include <iosfwd>
#include <iterator>
#include <limits>
#include <type_traits>
#include <utility>
#if !defined(NAMEOF_USING_ALIAS_STRING)
#include <string>
#endif
#if !defined(NAMEOF_USING_ALIAS_STRING_VIEW)
#include <string_view>
#endif
#if __has_include(<cxxabi.h>)
#include <cxxabi.h>
#include <cstdlib>
#endif
#if defined(__clang__)
# pragma clang diagnostic push
#elif defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstringop-overflow" // Missing terminating nul 'enum_name_v'.
#elif defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 26495) // Variable 'cstring<N>::chars_' is uninitialized.
# pragma warning(disable : 28020) // Arithmetic overflow: Using operator '-' on a 4 byte value and then casting the result to a 8 byte value.
# pragma warning(disable : 26451) // The expression '0<=_Param_(1)&&_Param_(1)<=1-1' is not true at this call.
# pragma warning(disable : 4514) // Unreferenced inline function has been removed.
#endif
// Checks nameof_type compiler compatibility.
#if defined(__clang__) && __clang_major__ >= 5 || defined(__GNUC__) && __GNUC__ >= 7 || defined(_MSC_VER) && _MSC_VER >= 1910
# undef NAMEOF_TYPE_SUPPORTED
# define NAMEOF_TYPE_SUPPORTED 1
#endif
// Checks nameof_type_rtti compiler compatibility.
#if defined(__clang__)
# if __has_feature(cxx_rtti)
# undef NAMEOF_TYPE_RTTI_SUPPORTED
# define NAMEOF_TYPE_RTTI_SUPPORTED 1
# endif
#elif defined(__GNUC__)
# if defined(__GXX_RTTI)
# undef NAMEOF_TYPE_RTTI_SUPPORTED
# define NAMEOF_TYPE_RTTI_SUPPORTED 1
# endif
#elif defined(_MSC_VER)
# if defined(_CPPRTTI)
# undef NAMEOF_TYPE_RTTI_SUPPORTED
# define NAMEOF_TYPE_RTTI_SUPPORTED 1
# endif
#endif
// Checks nameof_member compiler compatibility.
#if defined(__clang__) && __clang_major__ >= 5 || defined(__GNUC__) && __GNUC__ >= 7 || defined(_MSC_VER) && defined(_MSVC_LANG) && _MSVC_LANG >= 202002L
# undef NAMEOF_MEMBER_SUPPORTED
# define NAMEOF_MEMBER_SUPPORTED 1
#endif
// Checks nameof_enum compiler compatibility.
#if defined(__clang__) && __clang_major__ >= 5 || defined(__GNUC__) && __GNUC__ >= 9 || defined(_MSC_VER) && _MSC_VER >= 1910
# undef NAMEOF_ENUM_SUPPORTED
# define NAMEOF_ENUM_SUPPORTED 1
#endif
// Checks nameof_enum compiler aliases compatibility.
#if defined(__clang__) && __clang_major__ >= 5 || defined(__GNUC__) && __GNUC__ >= 9 || defined(_MSC_VER) && _MSC_VER >= 1920
# undef NAMEOF_ENUM_SUPPORTED_ALIASES
# define NAMEOF_ENUM_SUPPORTED_ALIASES 1
#endif
// Enum value must be greater or equals than NAMEOF_ENUM_RANGE_MIN. By default NAMEOF_ENUM_RANGE_MIN = -128.
// If need another min range for all enum types by default, redefine the macro NAMEOF_ENUM_RANGE_MIN.
#if !defined(NAMEOF_ENUM_RANGE_MIN)
# define NAMEOF_ENUM_RANGE_MIN -128
#endif
// Enum value must be less or equals than NAMEOF_ENUM_RANGE_MAX. By default NAMEOF_ENUM_RANGE_MAX = 128.
// If need another max range for all enum types by default, redefine the macro NAMEOF_ENUM_RANGE_MAX.
#if !defined(NAMEOF_ENUM_RANGE_MAX)
# define NAMEOF_ENUM_RANGE_MAX 128
#endif
namespace nameof {
// If need another string_view type, define the macro NAMEOF_USING_ALIAS_STRING_VIEW.
#if defined(NAMEOF_USING_ALIAS_STRING_VIEW)
NAMEOF_USING_ALIAS_STRING_VIEW
#else
using std::string_view;
#endif
// If need another string type, define the macro NAMEOF_USING_ALIAS_STRING.
#if defined(NAMEOF_USING_ALIAS_STRING)
NAMEOF_USING_ALIAS_STRING
#else
using std::string;
#endif
namespace customize {
// Enum value must be in range [NAMEOF_ENUM_RANGE_MIN, NAMEOF_ENUM_RANGE_MAX]. By default NAMEOF_ENUM_RANGE_MIN = -128, NAMEOF_ENUM_RANGE_MAX = 128.
// If need another range for all enum types by default, redefine the macro NAMEOF_ENUM_RANGE_MIN and NAMEOF_ENUM_RANGE_MAX.
// If need another range for specific enum type, add specialization enum_range for necessary enum type.
template <typename E>
struct enum_range {
static_assert(std::is_enum_v<E>, "nameof::customize::enum_range requires enum type.");
inline static constexpr int min = NAMEOF_ENUM_RANGE_MIN;
inline static constexpr int max = NAMEOF_ENUM_RANGE_MAX;
static_assert(max > min, "nameof::customize::enum_range requires max > min.");
};
static_assert(NAMEOF_ENUM_RANGE_MIN <= 0, "NAMEOF_ENUM_RANGE_MIN must be less or equals than 0.");
static_assert(NAMEOF_ENUM_RANGE_MIN > (std::numeric_limits<std::int16_t>::min)(), "NAMEOF_ENUM_RANGE_MIN must be greater than INT16_MIN.");
static_assert(NAMEOF_ENUM_RANGE_MAX > 0, "NAMEOF_ENUM_RANGE_MAX must be greater than 0.");
static_assert(NAMEOF_ENUM_RANGE_MAX < (std::numeric_limits<std::int16_t>::max)(), "NAMEOF_ENUM_RANGE_MAX must be less than INT16_MAX.");
static_assert(NAMEOF_ENUM_RANGE_MAX > NAMEOF_ENUM_RANGE_MIN, "NAMEOF_ENUM_RANGE_MAX must be greater than NAMEOF_ENUM_RANGE_MIN.");
// If need custom names for enum, add specialization enum_name for necessary enum type.
template <typename E>
constexpr string_view enum_name(E) noexcept {
static_assert(std::is_enum_v<E>, "nameof::customize::enum_name requires enum type.");
return {};
}
// If need custom name for type, add specialization type_name for necessary type.
template <typename T>
constexpr string_view type_name() noexcept {
return {};
}
// If need custom name for member, add specialization member_name for necessary type.
template <auto V>
constexpr string_view member_name() noexcept {
return {};
}
} // namespace nameof::customize
template <std::size_t N>
class [[nodiscard]] cstring {
public:
using value_type = const char;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using pointer = const char*;
using const_pointer = const char*;
using reference = const char&;
using const_reference = const char&;
using iterator = const char*;
using const_iterator = const char*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr explicit cstring(string_view str) noexcept : cstring{str, std::make_index_sequence<N>{}} {
assert(str.size() > 0 && str.size() == N);
}
constexpr cstring() = delete;
constexpr cstring(const cstring&) = default;
constexpr cstring(cstring&&) = default;
~cstring() = default;
cstring& operator=(const cstring&) = default;
cstring& operator=(cstring&&) = default;
[[nodiscard]] constexpr const_pointer data() const noexcept { return chars_; }
[[nodiscard]] constexpr size_type size() const noexcept { return N; }
[[nodiscard]] constexpr const_iterator begin() const noexcept { return data(); }
[[nodiscard]] constexpr const_iterator end() const noexcept { return data() + size(); }
[[nodiscard]] constexpr const_iterator cbegin() const noexcept { return begin(); }
[[nodiscard]] constexpr const_iterator cend() const noexcept { return end(); }
[[nodiscard]] constexpr const_reverse_iterator rbegin() const noexcept { return end(); }
[[nodiscard]] constexpr const_reverse_iterator rend() const noexcept { return begin(); }
[[nodiscard]] constexpr const_reverse_iterator crbegin() const noexcept { return rbegin(); }
[[nodiscard]] constexpr const_reverse_iterator crend() const noexcept { return rend(); }
[[nodiscard]] constexpr const_reference operator[](size_type i) const noexcept { return assert(i < size()), chars_[i]; }
[[nodiscard]] constexpr const_reference front() const noexcept { return chars_[0]; }
[[nodiscard]] constexpr const_reference back() const noexcept { return chars_[N]; }
[[nodiscard]] constexpr size_type length() const noexcept { return size(); }
[[nodiscard]] constexpr bool empty() const noexcept { return false; }
[[nodiscard]] constexpr int compare(string_view str) const noexcept { return string_view{data(), size()}.compare(str); }
[[nodiscard]] constexpr const char* c_str() const noexcept { return data(); }
[[nodiscard]] string str() const { return {begin(), end()}; }
[[nodiscard]] constexpr operator string_view() const noexcept { return {data(), size()}; }
[[nodiscard]] constexpr explicit operator const_pointer() const noexcept { return data(); }
[[nodiscard]] explicit operator string() const { return {begin(), end()}; }
private:
template <std::size_t... I>
constexpr cstring(string_view str, std::index_sequence<I...>) noexcept : chars_{str[I]..., '\0'} {}
char chars_[N + 1];
};
template <>
class [[nodiscard]] cstring<0> {
public:
using value_type = const char;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using pointer = const char*;
using const_pointer = const char*;
using reference = const char&;
using const_reference = const char&;
using iterator = const char*;
using const_iterator = const char*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr explicit cstring(string_view) noexcept {}
constexpr cstring() = delete;
constexpr cstring(const cstring&) = default;
constexpr cstring(cstring&&) = default;
~cstring() = default;
cstring& operator=(const cstring&) = default;
cstring& operator=(cstring&&) = default;
[[nodiscard]] constexpr const_pointer data() const noexcept { return nullptr; }
[[nodiscard]] constexpr size_type size() const noexcept { return 0; }
[[nodiscard]] constexpr const_iterator begin() const noexcept { return nullptr; }
[[nodiscard]] constexpr const_iterator end() const noexcept { return nullptr; }
[[nodiscard]] constexpr const_iterator cbegin() const noexcept { return nullptr; }
[[nodiscard]] constexpr const_iterator cend() const noexcept { return nullptr; }
[[nodiscard]] constexpr const_reverse_iterator rbegin() const noexcept { return {}; }
[[nodiscard]] constexpr const_reverse_iterator rend() const noexcept { return {}; }
[[nodiscard]] constexpr const_reverse_iterator crbegin() const noexcept { return {}; }
[[nodiscard]] constexpr const_reverse_iterator crend() const noexcept { return {}; }
[[nodiscard]] constexpr size_type length() const noexcept { return 0; }
[[nodiscard]] constexpr bool empty() const noexcept { return true; }
[[nodiscard]] constexpr int compare(string_view str) const noexcept { return string_view{}.compare(str); }
[[nodiscard]] constexpr const char* c_str() const noexcept { return nullptr; }
[[nodiscard]] string str() const { return {}; }
[[nodiscard]] constexpr operator string_view() const noexcept { return {}; }
[[nodiscard]] constexpr explicit operator const_pointer() const noexcept { return nullptr; }
[[nodiscard]] explicit operator string() const { return {}; }
};
template <std::size_t N>
[[nodiscard]] constexpr bool operator==(const cstring<N>& lhs, string_view rhs) noexcept {
return lhs.compare(rhs) == 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator==(string_view lhs, const cstring<N>& rhs) noexcept {
return lhs.compare(rhs) == 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator!=(const cstring<N>& lhs, string_view rhs) noexcept {
return lhs.compare(rhs) != 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator!=(string_view lhs, const cstring<N>& rhs) noexcept {
return lhs.compare(rhs) != 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator>(const cstring<N>& lhs, string_view rhs) noexcept {
return lhs.compare(rhs) > 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator>(string_view lhs, const cstring<N>& rhs) noexcept {
return lhs.compare(rhs) > 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator>=(const cstring<N>& lhs, string_view rhs) noexcept {
return lhs.compare(rhs) >= 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator>=(string_view lhs, const cstring<N>& rhs) noexcept {
return lhs.compare(rhs) >= 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator<(const cstring<N>& lhs, string_view rhs) noexcept {
return lhs.compare(rhs) < 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator<(string_view lhs, const cstring<N>& rhs) noexcept {
return lhs.compare(rhs) < 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator<=(const cstring<N>& lhs, string_view rhs) noexcept {
return lhs.compare(rhs) <= 0;
}
template <std::size_t N>
[[nodiscard]] constexpr bool operator<=(string_view lhs, const cstring<N>& rhs) noexcept {
return lhs.compare(rhs) <= 0;
}
template <typename Char, typename Traits, std::size_t N>
std::basic_ostream<Char, Traits>& operator<<(std::basic_ostream<Char, Traits>& os, const cstring<N>& srt) {
for (const auto c : srt) {
os.put(c);
}
return os;
}
namespace detail {
constexpr string_view pretty_name(string_view name, bool remove_suffix = true) noexcept {
if (name.size() >= 1 && (name[0] == '"' || name[0] == '\'')) {
return {}; // Narrow multibyte string literal.
} else if (name.size() >= 2 && name[0] == 'R' && (name[1] == '"' || name[1] == '\'')) {
return {}; // Raw string literal.
} else if (name.size() >= 2 && name[0] == 'L' && (name[1] == '"' || name[1] == '\'')) {
return {}; // Wide string literal.
} else if (name.size() >= 2 && name[0] == 'U' && (name[1] == '"' || name[1] == '\'')) {
return {}; // UTF-32 encoded string literal.
} else if (name.size() >= 2 && name[0] == 'u' && (name[1] == '"' || name[1] == '\'')) {
return {}; // UTF-16 encoded string literal.
} else if (name.size() >= 3 && name[0] == 'u' && name[1] == '8' && (name[2] == '"' || name[2] == '\'')) {
return {}; // UTF-8 encoded string literal.
} else if (name.size() >= 1 && (name[0] >= '0' && name[0] <= '9')) {
return {}; // Invalid name.
}
for (std::size_t i = name.size(), h = 0, s = 0; i > 0; --i) {
if (name[i - 1] == ')') {
++h;
++s;
continue;
} else if (name[i - 1] == '(') {
--h;
++s;
continue;
}
if (h == 0) {
name.remove_suffix(s);
break;
} else {
++s;
continue;
}
}
std::size_t s = 0;
for (std::size_t i = name.size(), h = 0; i > 0; --i) {
if (name[i - 1] == '>') {
++h;
++s;
continue;
} else if (name[i - 1] == '<') {
--h;
++s;
continue;
}
if (h == 0) {
break;
} else {
++s;
continue;
}
}
for (std::size_t i = name.size() - s; i > 0; --i) {
if (!((name[i - 1] >= '0' && name[i - 1] <= '9') ||
(name[i - 1] >= 'a' && name[i - 1] <= 'z') ||
(name[i - 1] >= 'A' && name[i - 1] <= 'Z') ||
(name[i - 1] == '_'))) {
name.remove_prefix(i);
break;
}
}
if (remove_suffix) {
name.remove_suffix(s);
}
if (name.size() > 0 && ((name.front() >= 'a' && name.front() <= 'z') ||
(name.front() >= 'A' && name.front() <= 'Z') ||
(name.front() == '_'))) {
return name;
}
return {}; // Invalid name.
}
template <typename T, std::size_t N, std::size_t... I>
constexpr std::array<std::remove_cv_t<T>, N> to_array(T (&a)[N], std::index_sequence<I...>) {
return {{a[I]...}};
}
template <typename L, typename R>
constexpr bool cmp_less(L lhs, R rhs) noexcept {
static_assert(std::is_integral_v<L> && std::is_integral_v<R>, "nameof::detail::cmp_less requires integral type.");
if constexpr (std::is_signed_v<L> == std::is_signed_v<R>) {
// If same signedness (both signed or both unsigned).
return lhs < rhs;
} else if constexpr (std::is_same_v<L, bool>) { // bool special case
return static_cast<R>(lhs) < rhs;
} else if constexpr (std::is_same_v<R, bool>) { // bool special case
return lhs < static_cast<L>(rhs);
} else if constexpr (std::is_signed_v<R>) {
// If 'right' is negative, then result is 'false', otherwise cast & compare.
return rhs > 0 && lhs < static_cast<std::make_unsigned_t<R>>(rhs);
} else {
// If 'left' is negative, then result is 'true', otherwise cast & compare.
return lhs < 0 || static_cast<std::make_unsigned_t<L>>(lhs) < rhs;
}
}
template <typename I>
constexpr I log2(I value) noexcept {
static_assert(std::is_integral_v<I>, "nameof::detail::log2 requires integral type.");
if constexpr (std::is_same_v<I, bool>) { // bool special case
return assert(false), value;
} else {
auto ret = I{0};
for (; value > I{1}; value >>= I{1}, ++ret) {}
return ret;
}
}
template <typename T>
struct nameof_enum_supported
#if defined(NAMEOF_ENUM_SUPPORTED) && NAMEOF_ENUM_SUPPORTED || defined(NAMEOF_ENUM_NO_CHECK_SUPPORT)
: std::true_type {};
#else
: std::false_type {};
#endif
template <typename T, typename R>
using enable_if_enum_t = std::enable_if_t<std::is_enum_v<std::decay_t<T>>, R>;
template <typename T>
inline constexpr bool is_enum_v = std::is_enum_v<T> && std::is_same_v<T, std::decay_t<T>>;
template <typename E, E V>
constexpr auto n() noexcept {
static_assert(is_enum_v<E>, "nameof::detail::n requires enum type.");
[[maybe_unused]] constexpr auto custom_name = customize::enum_name<E>(V);
if constexpr (custom_name.empty() && nameof_enum_supported<E>::value) {
#if defined(__clang__) || defined(__GNUC__)
constexpr auto name = pretty_name({__PRETTY_FUNCTION__, sizeof(__PRETTY_FUNCTION__) - 2});
#elif defined(_MSC_VER)
constexpr auto name = pretty_name({__FUNCSIG__, sizeof(__FUNCSIG__) - 17});
#else
constexpr auto name = string_view{};
#endif
return cstring<name.size()>{name};
} else {
return cstring<custom_name.size()>{custom_name};
}
}
template <typename E, E V>
inline constexpr auto enum_name_v = n<E, V>();
template <typename E, auto V>
constexpr bool is_valid() noexcept {
static_assert(is_enum_v<E>, "nameof::detail::is_valid requires enum type.");
return n<E, static_cast<E>(V)>().size() != 0;
}
template <typename E, int O, bool IsFlags = false, typename U = std::underlying_type_t<E>>
constexpr E value(std::size_t i) noexcept {
static_assert(is_enum_v<E>, "nameof::detail::value requires enum type.");
if constexpr (std::is_same_v<U, bool>) { // bool special case
static_assert(O == 0, "nameof::detail::value requires valid offset.");
return static_cast<E>(i);
} else if constexpr (IsFlags) {
return static_cast<E>(U{1} << static_cast<U>(static_cast<int>(i) + O));
} else {
return static_cast<E>(static_cast<int>(i) + O);
}
}
template <typename E, bool IsFlags, typename U = std::underlying_type_t<E>>
constexpr int reflected_min() noexcept {
static_assert(is_enum_v<E>, "nameof::detail::reflected_min requires enum type.");
if constexpr (IsFlags) {
return 0;
} else {
constexpr auto lhs = customize::enum_range<E>::min;
constexpr auto rhs = (std::numeric_limits<U>::min)();
if constexpr (cmp_less(rhs, lhs)) {
return lhs;
} else {
return rhs;
}
}
}
template <typename E, bool IsFlags, typename U = std::underlying_type_t<E>>
constexpr int reflected_max() noexcept {
static_assert(is_enum_v<E>, "nameof::detail::reflected_max requires enum type.");
if constexpr (IsFlags) {
return std::numeric_limits<U>::digits - 1;
} else {
constexpr auto lhs = customize::enum_range<E>::max;
constexpr auto rhs = (std::numeric_limits<U>::max)();
if constexpr (cmp_less(lhs, rhs)) {
return lhs;
} else {
return rhs;
}
}
}
template <typename E, bool IsFlags = false>
inline constexpr auto reflected_min_v = reflected_min<E, IsFlags>();
template <typename E, bool IsFlags = false>
inline constexpr auto reflected_max_v = reflected_max<E, IsFlags>();
template <std::size_t N>
constexpr std::size_t values_count(const bool (&valid)[N]) noexcept {
auto count = std::size_t{0};
for (std::size_t i = 0; i < N; ++i) {
if (valid[i]) {
++count;
}
}
return count;
}
template <typename E, bool IsFlags, int Min, std::size_t... I>
constexpr auto values(std::index_sequence<I...>) noexcept {
static_assert(is_enum_v<E>, "nameof::detail::values requires enum type.");
constexpr bool valid[sizeof...(I)] = {is_valid<E, value<E, Min, IsFlags>(I)>()...};
constexpr std::size_t count = values_count(valid);
if constexpr (count > 0) {
E values[count] = {};
for (std::size_t i = 0, v = 0; v < count; ++i) {
if (valid[i]) {
values[v++] = value<E, Min, IsFlags>(i);
}
}
return to_array(values, std::make_index_sequence<count>{});
} else {
return std::array<E, 0>{};
}
}
template <typename E, bool IsFlags, typename U = std::underlying_type_t<E>>
constexpr auto values() noexcept {
static_assert(is_enum_v<E>, "nameof::detail::values requires enum type.");
constexpr auto min = reflected_min_v<E, IsFlags>;
constexpr auto max = reflected_max_v<E, IsFlags>;
constexpr auto range_size = max - min + 1;
static_assert(range_size > 0, "nameof::enum_range requires valid size.");
static_assert(range_size < (std::numeric_limits<std::uint16_t>::max)(), "nameof::enum_range requires valid size.");
return values<E, IsFlags, reflected_min_v<E, IsFlags>>(std::make_index_sequence<range_size>{});
}
template <typename E, bool IsFlags = false>
inline constexpr auto values_v = values<E, IsFlags>();
template <typename E, bool IsFlags = false, typename D = std::decay_t<E>>
using values_t = decltype((values_v<D, IsFlags>));
template <typename E, bool IsFlags = false>
inline constexpr auto count_v = values_v<E, IsFlags>.size();
template <typename E, bool IsFlags = false, typename U = std::underlying_type_t<E>>
inline constexpr auto min_v = (count_v<E, IsFlags> > 0) ? static_cast<U>(values_v<E, IsFlags>.front()) : U{0};
template <typename E, bool IsFlags = false, typename U = std::underlying_type_t<E>>
inline constexpr auto max_v = (count_v<E, IsFlags> > 0) ? static_cast<U>(values_v<E, IsFlags>.back()) : U{0};
template <typename E, bool IsFlags, typename U = std::underlying_type_t<E>>
constexpr std::size_t range_size() noexcept {
static_assert(is_enum_v<E>, "nameof::detail::range_size requires enum type.");
constexpr auto max = IsFlags ? log2(max_v<E, IsFlags>) : max_v<E, IsFlags>;
constexpr auto min = IsFlags ? log2(min_v<E, IsFlags>) : min_v<E, IsFlags>;
constexpr auto range_size = max - min + U{1};
static_assert(range_size > 0, "nameof::enum_range requires valid size.");
static_assert(range_size < (std::numeric_limits<std::uint16_t>::max)(), "nameof::enum_range requires valid size.");
return static_cast<std::size_t>(range_size);
}
template <typename E, bool IsFlags = false>
inline constexpr auto range_size_v = range_size<E, IsFlags>();
template <typename E, bool IsFlags = false>
using index_t = std::conditional_t<range_size_v<E, IsFlags> < (std::numeric_limits<std::uint8_t>::max)(), std::uint8_t, std::uint16_t>;
template <typename E, bool IsFlags = false>
inline constexpr auto invalid_index_v = (std::numeric_limits<index_t<E, IsFlags>>::max)();
template <typename E, bool IsFlags, std::size_t... I>
constexpr auto indexes(std::index_sequence<I...>) noexcept {
static_assert(is_enum_v<E>, "nameof::detail::indexes requires enum type.");
constexpr auto min = IsFlags ? log2(min_v<E, IsFlags>) : min_v<E, IsFlags>;
[[maybe_unused]] auto i = index_t<E, IsFlags>{0};
return std::array<decltype(i), sizeof...(I)>{{(is_valid<E, value<E, min, IsFlags>(I)>() ? i++ : invalid_index_v<E, IsFlags>)...}};
}
template <typename E, bool IsFlags = false>
inline constexpr auto indexes_v = indexes<E, IsFlags>(std::make_index_sequence<range_size_v<E, IsFlags>>{});
template <typename E, bool IsFlags, typename U = std::underlying_type_t<E>>
constexpr bool is_sparse() noexcept {
static_assert(is_enum_v<E>, "nameof::detail::is_sparse requires enum type.");
if constexpr (IsFlags) {
return (sizeof(const char*) * range_size_v<E, IsFlags>) > (sizeof(E) * count_v<E, IsFlags> + sizeof(const char*) * count_v<E, IsFlags>);
} else {
return (sizeof(const char*) * range_size_v<E, IsFlags>) > (sizeof(index_t<E>) * range_size_v<E, IsFlags> + sizeof(const char*) * count_v<E, IsFlags>);
}
}
template <typename E, bool IsFlags = false>
inline constexpr bool is_sparse_v = is_sparse<E, IsFlags>();
template <typename E, bool IsFlags, typename U = std::underlying_type_t<E>>
[[nodiscard]] constexpr E get_value(std::size_t i) noexcept {
static_assert(is_enum_v<E>, "nameof::detail::strings requires enum type.");
if constexpr (is_sparse_v<E, IsFlags>) {
return values_v<E, IsFlags>[i];
} else {
constexpr auto min = IsFlags ? log2(min_v<E, IsFlags>) : min_v<E, IsFlags>;
return value<E, min, IsFlags>(i);
}
}
template <typename E, bool IsFlags, std::size_t... I>
constexpr auto strings(std::index_sequence<I...>) noexcept {
static_assert(is_enum_v<E>, "nameof::detail::strings requires enum type.");
return std::array<const char*, sizeof...(I)>{{enum_name_v<E, get_value<E, IsFlags>(I)>.data()...}};
}
template <typename E, bool IsFlags>
constexpr auto strings() noexcept {
static_assert(is_enum_v<E>, "nameof::detail::strings requires enum type.");
constexpr auto count = is_sparse_v<E, IsFlags> ? count_v<E, IsFlags> : range_size_v<E, IsFlags>;
return strings<E, IsFlags>(std::make_index_sequence<count>{});
}
template <typename E, bool IsFlags = false>
inline static constexpr auto strings_v = strings<E, IsFlags>();
template <typename... T>
struct nameof_type_supported
#if defined(NAMEOF_TYPE_SUPPORTED) && NAMEOF_TYPE_SUPPORTED || defined(NAMEOF_TYPE_NO_CHECK_SUPPORT)
: std::true_type {};
#else
: std::false_type {};
#endif
template <typename... T>
struct nameof_type_rtti_supported
#if defined(NAMEOF_TYPE_RTTI_SUPPORTED) && NAMEOF_TYPE_RTTI_SUPPORTED || defined(NAMEOF_TYPE_NO_CHECK_SUPPORT)
: std::true_type {};
#else
: std::false_type {};
#endif
template <typename... T>
struct nameof_member_supported
#if defined(NAMEOF_MEMBER_SUPPORTED) && NAMEOF_MEMBER_SUPPORTED || defined(NAMEOF_TYPE_NO_CHECK_SUPPORT)
: std::true_type {};
#else
: std::false_type {};
#endif
#if defined(_MSC_VER) && !defined(__clang__)
template <typename T>
struct identity {
using type = T;
};
#else
template <typename T>
using identity = T;
#endif
template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
template <typename T, typename R>
using enable_if_has_short_name_t = std::enable_if_t<!std::is_array_v<T> && !std::is_pointer_v<T>, R>;
template <typename... T>
constexpr auto n() noexcept {
# if defined(_MSC_VER) && !defined(__clang__)
[[maybe_unused]] constexpr auto custom_name = customize::type_name<typename T::type...>();
#else
[[maybe_unused]] constexpr auto custom_name = customize::type_name<T...>();
# endif
if constexpr (custom_name.empty() && nameof_type_supported<T...>::value) {
#if defined(__clang__)
constexpr string_view name{__PRETTY_FUNCTION__ + 31, sizeof(__PRETTY_FUNCTION__) - 34};
#elif defined(__GNUC__)
constexpr string_view name{__PRETTY_FUNCTION__ + 46, sizeof(__PRETTY_FUNCTION__) - 49};
#elif defined(_MSC_VER)
constexpr string_view name{__FUNCSIG__ + 63, sizeof(__FUNCSIG__) - 81 - (__FUNCSIG__[sizeof(__FUNCSIG__) - 19] == ' ' ? 1 : 0)};
#else
constexpr auto name = string_view{};
#endif
return cstring<name.size()>{name};
} else {
return cstring<custom_name.size()>{custom_name};
}
}
template <typename... T>
inline constexpr auto type_name_v = n<T...>();
#if __has_include(<cxxabi.h>)
template <typename T>
string nameof_type_rtti(const char* tn) {
static_assert(nameof_type_rtti_supported<T>::value, "nameof::nameof_type_rtti unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
const auto dmg = abi::__cxa_demangle(tn, nullptr, nullptr, nullptr);
const auto name = string{dmg};
free(dmg);
assert(name.size() > 0 && "Type does not have a name.");
return name;
}
template <typename T>
string nameof_full_type_rtti(const char* tn) {
static_assert(nameof_type_rtti_supported<T>::value, "nameof::nameof_type_rtti unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
const auto dmg = abi::__cxa_demangle(tn, nullptr, nullptr, nullptr);
auto name = string{dmg};
free(dmg);
assert(name.size() > 0 && "Type does not have a name.");
if constexpr (std::is_const_v<std::remove_reference_t<T>>) {
name = "const " + name;
}
if constexpr (std::is_volatile_v<std::remove_reference_t<T>>) {
name = "volatile " + name;
}
if constexpr (std::is_lvalue_reference_v<T>) {
name += '&';
}
if constexpr (std::is_rvalue_reference_v<T>) {
name += "&&";
}
return name;
}
template <typename T, enable_if_has_short_name_t<T, int> = 0>
string nameof_short_type_rtti(const char* tn) {
static_assert(nameof_type_rtti_supported<T>::value, "nameof::nameof_type_rtti unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
const auto dmg = abi::__cxa_demangle(tn, nullptr, nullptr, nullptr);
const auto name = string{pretty_name(dmg)};
free(dmg);
assert(name.size() > 0 && "Type does not have a short name.");
return name;
}
#else
template <typename T>
string nameof_type_rtti(const char* tn) noexcept {
static_assert(nameof_type_rtti_supported<T>::value, "nameof::nameof_type_rtti unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
const auto name = string_view{tn};
assert(name.size() > 0 && "Type does not have a name.");
return {name.begin(), name.end()};
}
template <typename T>
string nameof_full_type_rtti(const char* tn) noexcept {
static_assert(nameof_type_rtti_supported<T>::value, "nameof::nameof_type_rtti unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
auto name = string{tn};
assert(name.size() > 0 && "Type does not have a name.");
if constexpr (std::is_const_v<std::remove_reference_t<T>>) {
name = "const " + name;
}
if constexpr (std::is_volatile_v<std::remove_reference_t<T>>) {
name = "volatile " + name;
}
if constexpr (std::is_lvalue_reference_v<T>) {
name += '&';
}
if constexpr (std::is_rvalue_reference_v<T>) {
name += "&&";
}
return name;
}
template <typename T, enable_if_has_short_name_t<T, int> = 0>
string nameof_short_type_rtti(const char* tn) noexcept {
static_assert(nameof_type_rtti_supported<T>::value, "nameof::nameof_type_rtti unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
const auto name = pretty_name(tn);
assert(name.size() > 0 && "Type does not have a short name.");
return {name.begin(), name.end()};
}
#endif
template <auto V, auto U = V>
constexpr auto n() noexcept {
[[maybe_unused]] constexpr auto custom_name = customize::member_name<V>();
if constexpr (custom_name.empty() && nameof_member_supported<decltype(V)>::value) {
#if defined(__clang__) || defined(__GNUC__)
constexpr auto name = pretty_name({__PRETTY_FUNCTION__, sizeof(__PRETTY_FUNCTION__) - 2});
#elif defined(_MSC_VER) && defined(_MSVC_LANG) && _MSVC_LANG >= 202002L
constexpr auto name = pretty_name({__FUNCSIG__, sizeof(__FUNCSIG__) - 17});
#else
constexpr auto name = string_view{};
#endif
return cstring<name.size()>{name};
} else {
return cstring<custom_name.size()>{custom_name};
}
}
#if defined(__clang__) || defined(__GNUC__)
template <auto V>
inline constexpr auto member_name_v = n<V>();
#elif defined(_MSC_VER) && defined(_MSVC_LANG) && _MSVC_LANG >= 202002L
template <typename From, typename Type>
From get_base_type(Type From::*);
template <typename T>
union union_type {
char c = {};
T f;
};
template <typename T>
inline constexpr auto static_v = T{};
template <auto V>
constexpr auto get_member_name() noexcept {
if constexpr (std::is_member_function_pointer_v<decltype(V)>) {
return n<V>();
} else {
return n<V, &(static_v<union_type<decltype(get_base_type(V))>>.f.*V)>();
}
}
template <auto V>
inline constexpr auto member_name_v = get_member_name<V>();
#else
template <auto V>
inline constexpr auto member_name_v = cstring<0>{string_view{}};
#endif
} // namespace nameof::detail
// Checks is nameof_type supported compiler.
inline constexpr bool is_nameof_type_supported = detail::nameof_type_supported<void>::value;
// Checks is nameof_type_rtti supported compiler.
inline constexpr bool is_nameof_type_rtti_supported = detail::nameof_type_rtti_supported<void>::value;
// Checks is nameof_member supported compiler.
inline constexpr bool is_nameof_member_supported = detail::nameof_member_supported<void>::value;
// Checks is nameof_enum supported compiler.
inline constexpr bool is_nameof_enum_supported = detail::nameof_enum_supported<void>::value;
// Obtains name of enum variable.
template <typename E>
[[nodiscard]] constexpr auto nameof_enum(E value) noexcept -> detail::enable_if_enum_t<E, string_view> {
using D = std::decay_t<E>;
using U = std::underlying_type_t<D>;
static_assert(detail::nameof_enum_supported<D>::value, "nameof::nameof_enum unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
static_assert(detail::count_v<D> > 0, "nameof::nameof_enum requires enum implementation and valid max and min.");
const bool valid = static_cast<U>(value) >= static_cast<U>(detail::min_v<D>) && static_cast<U>(value) <= static_cast<U>(detail::max_v<D>);
if (const auto i = static_cast<int>(value) - detail::min_v<D>; valid) {
if constexpr (detail::is_sparse_v<D>) {
if (const auto idx = detail::indexes_v<D>[i]; idx != detail::invalid_index_v<D>) {
return detail::strings_v<D>[idx];
}
} else {
return detail::strings_v<D>[static_cast<std::size_t>(i)];
}
}
return {}; // Value out of range.
}
// Obtains name of enum variable or default value if enum variable out of range.
template <typename E>
[[nodiscard]] auto nameof_enum_or(E value, string_view default_value) -> detail::enable_if_enum_t<E, string> {
using D = std::decay_t<E>;
if (auto v = nameof_enum<D>(value); !v.empty()) {
return string{v.data(), v.size()};
}
return string{default_value.data(), default_value.size()};
}
// Obtains name of enum-flags variable.
template <typename E>
[[nodiscard]] auto nameof_enum_flag(E value) -> detail::enable_if_enum_t<E, string> {
using D = std::decay_t<E>;
using U = std::underlying_type_t<D>;
static_assert(detail::nameof_enum_supported<D>::value, "nameof::nameof_enum_flag unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
static_assert(detail::count_v<D, true> > 0, "nameof::nameof_enum_flag requires enum-flags implementation.");
constexpr auto size = detail::is_sparse_v<D, true> ? detail::count_v<D, true> : detail::range_size_v<D, true>;
string name;
auto check_value = U{0};
for (std::size_t i = 0; i < size; ++i) {
if (const auto v = static_cast<U>(detail::get_value<D, true>(i)); (static_cast<U>(value) & v) != 0) {
if (const auto n = detail::strings_v<D, true>[i]; n != nullptr) {
check_value |= v;
if (!name.empty()) {
name.append(1, '|');
}
name.append(n);
} else {
return {}; // Value out of range.
}
}
}
const bool valid = check_value != 0 && check_value == static_cast<U>(value);
if (valid) {
return name;
}
return {}; // Invalid value or out of range.
}
// Obtains name of static storage enum variable.
// This version is much lighter on the compile times and is not restricted to the enum_range limitation.
template <auto V>
[[nodiscard]] constexpr auto nameof_enum() noexcept -> detail::enable_if_enum_t<decltype(V), string_view> {
using D = std::decay_t<decltype(V)>;
static_assert(detail::nameof_enum_supported<D>::value, "nameof::nameof_enum unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
constexpr string_view name = detail::enum_name_v<D, V>;
static_assert(name.size() > 0, "Enum value does not have a name.");
return name;
}
// Obtains name of type, reference and cv-qualifiers are ignored.
template <typename T>
[[nodiscard]] constexpr string_view nameof_type() noexcept {
static_assert(detail::nameof_type_supported<T>::value, "nameof::nameof_type unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
using U = detail::identity<detail::remove_cvref_t<T>>;
constexpr string_view name = detail::type_name_v<U>;
static_assert(name.size() > 0, "Type does not have a name.");
return name;
}
// Obtains full name of type, with reference and cv-qualifiers.
template <typename T>
[[nodiscard]] constexpr string_view nameof_full_type() noexcept {
static_assert(detail::nameof_type_supported<T>::value, "nameof::nameof_type unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
using U = detail::identity<T>;
constexpr string_view name = detail::type_name_v<U>;
static_assert(name.size() > 0, "Type does not have a full name.");
return name;
}
// Obtains short name of type.
template <typename T>
[[nodiscard]] constexpr auto nameof_short_type() noexcept -> detail::enable_if_has_short_name_t<T, string_view> {
static_assert(detail::nameof_type_supported<T>::value, "nameof::nameof_type unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
using U = detail::identity<detail::remove_cvref_t<T>>;
constexpr string_view name = detail::pretty_name(detail::type_name_v<U>);
static_assert(name.size() > 0, "Type does not have a short name.");
return name;
}
// Obtains name of member.
template <auto V>
[[nodiscard]] constexpr auto nameof_member() noexcept -> std::enable_if_t<std::is_member_pointer_v<decltype(V)>, string_view> {
static_assert(detail::nameof_member_supported<decltype(V)>::value, "nameof::nameof_memder unsupported compiler (https://github.com/Neargye/nameof#compiler-compatibility).");
constexpr string_view name = detail::member_name_v<V>;
static_assert(name.size() > 0, "Member does not have a name.");
return name;
}
} // namespace nameof
// Obtains name of variable, function, macro.
#define NAMEOF(...) []() constexpr noexcept { \
::std::void_t<decltype(__VA_ARGS__)>(); \
constexpr auto _name = ::nameof::detail::pretty_name(#__VA_ARGS__); \
static_assert(_name.size() > 0, "Expression does not have a name."); \
constexpr auto _size = _name.size(); \
constexpr auto _nameof = ::nameof::cstring<_size>{_name}; \
return _nameof; }()
// Obtains full name of variable, function, macro.
#define NAMEOF_FULL(...) []() constexpr noexcept { \
::std::void_t<decltype(__VA_ARGS__)>(); \
constexpr auto _name = ::nameof::detail::pretty_name(#__VA_ARGS__, false); \
static_assert(_name.size() > 0, "Expression does not have a name."); \
constexpr auto _size = _name.size(); \
constexpr auto _nameof_full = ::nameof::cstring<_size>{_name}; \
return _nameof_full; }()
// Obtains raw name of variable, function, macro.
#define NAMEOF_RAW(...) []() constexpr noexcept { \
::std::void_t<decltype(__VA_ARGS__)>(); \
constexpr auto _name = ::nameof::string_view{#__VA_ARGS__}; \
static_assert(_name.size() > 0, "Expression does not have a name."); \
constexpr auto _size = _name.size(); \
constexpr auto _nameof_raw = ::nameof::cstring<_size>{_name}; \
return _nameof_raw; }()
// Obtains name of enum variable.
#define NAMEOF_ENUM(...) ::nameof::nameof_enum<::std::decay_t<decltype(__VA_ARGS__)>>(__VA_ARGS__)
// Obtains name of enum variable or default value if enum variable out of range.
#define NAMEOF_ENUM_OR(...) ::nameof::nameof_enum_or(__VA_ARGS__)
// Obtains name of static storage enum variable.
// This version is much lighter on the compile times and is not restricted to the enum_range limitation.
#define NAMEOF_ENUM_CONST(...) ::nameof::nameof_enum<__VA_ARGS__>()
// Obtains name of enum-flags variable.
#define NAMEOF_ENUM_FLAG(...) ::nameof::nameof_enum_flag<::std::decay_t<decltype(__VA_ARGS__)>>(__VA_ARGS__)
// Obtains type name, reference and cv-qualifiers are ignored.
#define NAMEOF_TYPE(...) ::nameof::nameof_type<__VA_ARGS__>()
// Obtains full type name, with reference and cv-qualifiers.
#define NAMEOF_FULL_TYPE(...) ::nameof::nameof_full_type<__VA_ARGS__>()
// Obtains short type name.
#define NAMEOF_SHORT_TYPE(...) ::nameof::nameof_short_type<__VA_ARGS__>()
// Obtains type name of expression, reference and cv-qualifiers are ignored.
#define NAMEOF_TYPE_EXPR(...) ::nameof::nameof_type<decltype(__VA_ARGS__)>()
// Obtains full type name of expression, with reference and cv-qualifiers.
#define NAMEOF_FULL_TYPE_EXPR(...) ::nameof::nameof_full_type<decltype(__VA_ARGS__)>()
// Obtains short type name of expression.
#define NAMEOF_SHORT_TYPE_EXPR(...) ::nameof::nameof_short_type<decltype(__VA_ARGS__)>()
// Obtains type name, with reference and cv-qualifiers, using RTTI.
#define NAMEOF_TYPE_RTTI(...) ::nameof::detail::nameof_type_rtti<::std::void_t<decltype(__VA_ARGS__)>>(typeid(__VA_ARGS__).name())
// Obtains full type name, using RTTI.
#define NAMEOF_FULL_TYPE_RTTI(...) ::nameof::detail::nameof_full_type_rtti<decltype(__VA_ARGS__)>(typeid(__VA_ARGS__).name())
// Obtains short type name, using RTTI.
#define NAMEOF_SHORT_TYPE_RTTI(...) ::nameof::detail::nameof_short_type_rtti<decltype(__VA_ARGS__)>(typeid(__VA_ARGS__).name())
// Obtains name of member.
#define NAMEOF_MEMBER(...) ::nameof::nameof_member<__VA_ARGS__>()
#if defined(__clang__)
# pragma clang diagnostic pop
#elif defined(__GNUC__)
# pragma GCC diagnostic pop
#elif defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // NEARGYE_NAMEOF_HPP
|
028173f576b5f2364b800bbfca3dc6be8a238bc3
|
[
"CMake",
"Markdown",
"Makefile",
"C",
"C++",
"Shell"
] | 493
|
C++
|
zhllxt/asio2
|
ac8c79964d79020091e38fcbb4ae9dccccb3b03c
|
ca6f98b0c599ebb3eeb13cd79ddb9db6e8ca3666
|
refs/heads/master
|
<repo_name>milinsanke/feapder<file_sep>/tests/test_mongodb.py
import unittest
from feapder.db.mongodb import MongoDB
db = MongoDB(
ip="localhost", port=27017, db="feapder"
)
class TestMongoDB(unittest.TestCase):
def test_insert(self):
# 插入单条数据
r = db.add(table="test", data={'_id': '607c25761b698fa5b385f3b7', 'feapder': 123})
self.assertEqual(r, 1)
def test_insert_auto_update(self):
"""
插入单条数据,冲突时自动更新,即将重复数据替换为最新数据
"""
r = db.add(table="test", data={'_id': '607c25761b698fa5b385f3b7', 'feapder': 899, 'a': 1, 'b': 2},
auto_update=True)
self.assertEqual(r, 1)
def test_insert_columns(self):
"""
插入单条数据,发生冲突时,更新指定字段
"""
r = db.add(table="test", data={'_id': '607c25761b698fa5b385f3b7', 'a': 0}, update_columns=('a',))
self.assertEqual(r, 1)
def test_batch_insert(self):
items = [
{
'a': 1
},
{
'b': 2
},
{
'c': 3
}
]
add_count = db.add_batch('test', items)
datas_size = len(items)
print("共导出 %s 条数据 到 %s, 重复 %s 条" % (datas_size, 'test', datas_size - add_count))
def test_batch_insert_repeat(self):
items = [
{
'_id': '607c271885832edde1a805d2',
'a': 1
}
]
add_count = db.add_batch('test', items)
datas_size = len(items)
print("共导出 %s 条数据 到 %s, 重复 %s 条" % (datas_size, 'test', datas_size - add_count))
self.assertEqual(datas_size, 1)
self.assertEqual(add_count, 0)
def test_batch_insert_auto_update(self):
"""
当数据冲突时,替换这条数据
"""
items = [
{
'_id': '607c271885832edde1a805d2',
'a': 3,
'b': 2,
'c': 1,
'd': 0
}
]
add_count = db.add_batch('test', items, auto_update=True)
datas_size = len(items)
print("共导出 %s 条数据 到 %s, 重复 %s 条" % (datas_size, 'test', datas_size - add_count))
self.assertEqual(datas_size, 1)
self.assertEqual(add_count, 1)
def test_batch_insert_columns(self):
"""
指定columns及columns_value
当数据重复时插入指定字段
"""
items = [
{
'_id': '607c271885832edde1a805d2',
'a': 3,
'b': 2,
'c': 1
}
]
add_count = db.add_batch('test', items, update_columns=('b', 'c'), update_columns_value=('5', '6'))
datas_size = len(items)
print("共导出 %s 条数据 到 %s, 重复 %s 条" % (datas_size, 'test', datas_size - add_count))
self.assertEqual(datas_size, 1)
self.assertEqual(add_count, 1)
def test_update(self):
"""
测试数据更新
"""
data = {
'_id': '607c271885832edde1a805d2',
'a': 3,
'b': 2,
'c': 1
}
r = db.update('test', data, {'_id': '607c271885832edde1a805d2'})
self.assertEqual(r, True)
def test_delete(self):
r = db.delete('test', {'_id': '607c271885832edde1a805d2'})
self.assertEqual(r, True)
if __name__ == '__main__':
unittest.main()
<file_sep>/feapder/db/mongodb.py
# -*- coding: utf-8 -*-
"""
Created on 2021-04-18 14:12:21
---------
@summary: 操作mongo数据库
---------
@author: Mkdir700
@email: <EMAIL>
"""
from typing import List, Dict
from urllib import parse
import pymongo.errors
from pymongo import MongoClient
from pymongo.collection import Collection
import feapder.setting as setting
from feapder.utils.log import log
class MongoDB:
def __init__(
self, ip=None, port=None, db=None, user_name=None, user_pass=None, **kwargs
):
if not ip:
ip = setting.MONGO_IP
if not port:
port = setting.MONGO_PORT
if not db:
db = setting.MONGO_DB
if not user_name:
user_name = setting.MONGO_USER_NAME
if not user_pass:
user_pass = setting.MONGO_USER_PASS
self.client = MongoClient(
host=ip, port=port, username=user_name, password=<PASSWORD>_<PASSWORD>
)
self.db = self.client.get_database(db)
@classmethod
def from_url(cls, url, **kwargs):
# mongodb://username:password@ip:port/db
url_parsed = parse.urlparse(url)
db_type = url_parsed.scheme.strip()
if db_type != "mongodb":
raise Exception(
"url error, expect mongodb://username:password@ip:port/db, but get {}".format(
url
)
)
connect_params = {}
connect_params["ip"] = url_parsed.hostname.strip()
connect_params["port"] = url_parsed.port
connect_params["user_name"] = url_parsed.username.strip()
connect_params["user_pass"] = url_parsed.password.strip()
connect_params["db"] = url_parsed.path.strip("/").strip()
connect_params.update(kwargs)
return cls(**connect_params)
def get_collection(self, collection_name) -> Collection:
return self.db.get_collection(collection_name)
def find(self, table, condition=None, limit=0) -> List[Dict]:
"""
@summary:
无数据: 返回[]
有数据: [{'_id': 'xx', ...}, ...]
---------
@param filter:
@param limit:
---------
@result:
"""
condition = {} if condition is None else condition
collection = self.db.get_collection(table)
cursor = collection.find(condition)
result = list(cursor.limit(limit))
cursor.close()
return result
def add(self, table, data: Dict, **kwargs):
"""
Args:
table:
data:
kwargs:
auto_update: 覆盖更新,将替换唯一索引重复的数据,默认False
update_columns: 更新指定的列(如果数据的唯一索引存在,则更新指定字段,如 update_columns = ["name", "title"]
insert_ignore: 唯一索引冲突时是否忽略,默认为False
condition_fields: 用于条件查找的字段,默认以`_id`作为查找条件,默认:['_id']
exception_callfunc: 异常回调
Returns: 添加行数
"""
affect_count = 1
auto_update = kwargs.get("auto_update", False)
update_columns = kwargs.get("update_columns", ())
insert_ignore = kwargs.get("insert_ignore", False)
condition_fields = kwargs.get("condition_fields", ["_id"])
exception_callfunc = kwargs.get("exception_callfunc", None)
try:
collection = self.get_collection(table)
# 存在则更新
if update_columns:
if not isinstance(update_columns, (tuple, list)):
update_columns = [update_columns]
try:
collection.insert_one(data)
except pymongo.errors.DuplicateKeyError:
condition = {
condition_field: data[condition_field]
for condition_field in condition_fields
}
doc = {key: data[key] for key in update_columns}
collection.update_one(condition, {"$set": doc})
# 覆盖更新
elif auto_update:
condition = {
condition_field: data[condition_field]
for condition_field in condition_fields
}
# 替换已存在的数据
collection.replace_one(condition, data)
else:
try:
collection.insert_one(data)
except pymongo.errors.DuplicateKeyError as e:
if not insert_ignore:
raise e
else:
affect_count = 0
except Exception as e:
log.error("error: {}".format(e))
if exception_callfunc:
exception_callfunc(e)
affect_count = 0
return affect_count
def add_batch(self, table: str, datas: List[Dict], **kwargs):
"""
@summary: 批量添加数据
---------
@param command: 字典
@param datas: 列表 [[..], [...]]
@param **kwargs:
auto_update: 覆盖更新,将替换唯一索引重复的数据,默认False
update_columns: 更新指定的列(如果数据的唯一索引存在,则更新指定字段,如 update_columns = ["name", "title"]
update_columns_value: 指定更新的字段对应的值
condition_fields: 用于条件查找的字段,默认以`_id`作为查找条件,默认:['_id']
---------
@result: 添加行数
"""
if not datas:
return
affect_count = None
auto_update = kwargs.get("auto_update", False)
update_columns = kwargs.get("update_columns", ())
update_columns_value = kwargs.get("update_columns_value", ())
condition_fields = kwargs.get("condition_fields", ["_id"])
try:
collection = self.get_collection(table)
affect_count = 0
if update_columns:
if not isinstance(update_columns, (tuple, list)):
update_columns = [update_columns]
for data in datas:
try:
collection.insert_one(data)
except pymongo.errors.DuplicateKeyError:
# 数据冲突,只更新指定字段
condition = {
condition_field: data[condition_field]
for condition_field in condition_fields
}
doc = {
key: value
for key, value in zip(update_columns, update_columns_value)
}
collection.update_one(condition, {"$set": doc})
affect_count += 1
elif auto_update:
for data in datas:
condition = {
condition_field: data[condition_field]
for condition_field in condition_fields
}
# 如果找到就替换,否则插入
result = collection.find_one_and_replace(
condition, data, upsert=True
)
affect_count += 1
else:
for data in datas:
try:
collection.insert_one(data) # TODO 实现真正的批量插入
except pymongo.errors.DuplicateKeyError:
# 忽略冲突
continue
affect_count += 1
except Exception as e:
log.error("error:{}".format(e))
return affect_count
def update(self, table, data: Dict, condition: Dict):
"""
更新
Args:
table: 表名
data: 数据 {"xxx":"xxx"}
condition: 更新条件 {"_id": "xxxx"}
Returns: True / False
"""
try:
collection = self.get_collection(table)
collection.update_one(condition, {"$set": data})
except Exception as e:
log.error(
"""
error:{}
condition: {}
""".format(
e, condition
)
)
return False
else:
return True
def delete(self, table, condition: Dict):
"""
删除
Args:
table:
condition: 查找条件
Returns: True / False
"""
try:
collection = self.get_collection(table)
collection.delete_one(condition)
except Exception as e:
log.error(
"""
error:{}
condition: {}
""".format(
e, condition
)
)
return False
else:
return True
|
39d3e286c0ee30ba2266ec654ec39e08111a06be
|
[
"Python"
] | 2
|
Python
|
milinsanke/feapder
|
131c2e3672631f3a136f932c8062ff6c57d7859f
|
53299c036587b5ad2437c4278d6357b8a79bab82
|
HEAD
|
<repo_name>oggata/Cocos2dJSv3SampleGame<file_sep>/src/Layer/StageLayer.js
var StageLayer = cc.Layer.extend({
sprite:null,
ctor:function () {
this._super();
var size = cc.winSize;
/*
this.sprite = new cc.Sprite(res.HelloWorld_png);
this.sprite.setAnchorPoint(0,0);
this.addChild(this.sprite);
*/
this.rectBase = cc.LayerColor.create(cc.color(0,0,255),320,480);
this.rectBase.setPosition(0,0);
this.addChild(this.rectBase);
this.stage001Button = new ButtonSprite("ViewPortClippingON",15,cc.color(255,255,0),this.goToGameLayer001,this);
this.stage001Button.setAnchorPoint(0,0);
this.stage001Button.setPosition(100,300-50*0);
this.addChild(this.stage001Button);
this.stage002Button = new ButtonSprite("ViewPortClippingOFF",15,cc.color(255,255,0),this.goToGameLayer002,this);
this.stage002Button.setAnchorPoint(0,0);
this.stage002Button.setPosition(100,300-50*1);
this.addChild(this.stage002Button);
this.stage003Button = new ButtonSprite("Stage003",15,cc.color(255,255,0),this.goToGameLayer001,this);
this.stage003Button.setAnchorPoint(0,0);
this.stage003Button.setPosition(100,300-50*2);
this.addChild(this.stage003Button);
this.stage004Button = new ButtonSprite("Stage004",15,cc.color(255,255,0),this.goToGameLayer001,this);
this.stage004Button.setAnchorPoint(0,0);
this.stage004Button.setPosition(100,300-50*3);
this.addChild(this.stage004Button);
this.stage005Button = new ButtonSprite("Stage005",15,cc.color(255,255,0),this.goToGameLayer001,this);
this.stage005Button.setAnchorPoint(0,0);
this.stage005Button.setPosition(100,300-50*4);
this.addChild(this.stage005Button);
return true;
},
goToGameLayer:function () {
cc.LoaderScene.preload(g_resources, function () {
cc.director.runScene(new cc.TransitionFade(1.2,new GameLayerScene001()));
}, this);
},
goToGameLayer001:function () {
cc.LoaderScene.preload(g_resources, function () {
cc.director.runScene(new cc.TransitionFade(1.2,new GameLayerScene001()));
}, this);
},
goToGameLayer002:function () {
cc.LoaderScene.preload(g_resources, function () {
cc.director.runScene(new cc.TransitionFade(1.2,new GameLayerScene002()));
}, this);
}
});
var StageLayerScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new StageLayer();
this.addChild(layer);
}
});
<file_sep>/src/resource.js
var res = {
HelloWorld_png : "res/HelloWorld.png",
CloseNormal_png : "res/CloseNormal.png",
CloseSelected_png : "res/CloseSelected.png",
Button001Scale9_png : "res/button/button001_scale9.png",
s_chara007 : "res/sprite/chara007.png",
s_shadow : "res/sprite/shadow.png",
s_target_marker : "res/sprite/targetMarker.png",
s_field : "res/ui/field.jpg",
Loading_png : "res/loading.png",
Safe_png : "res/ui/safe.png",
Marker_png : "res/ui/marker.png"
};
var g_resources = [];
for (var i in res) {
g_resources.push(res[i]);
}<file_sep>/src/Layer/TopLayer.js
var TopLayer = cc.Layer.extend({
sprite:null,
ctor:function () {
this._super();
var size = cc.winSize;
/*
this.sprite = new cc.Sprite(res.HelloWorld_png);
this.sprite.setAnchorPoint(0,0);
this.addChild(this.sprite);
*/
this.rectBase = cc.LayerColor.create(cc.color(0,255,0),320,480);
this.rectBase.setPosition(0,0);
this.addChild(this.rectBase);
this.startButton = new ButtonSprite("Start Game",15,cc.color(255,255,0),this.goToStageLayer,this);
this.startButton.setAnchorPoint(0,0);
this.startButton.setPosition(100,100);
this.addChild(this.startButton);
return true;
},
goToStageLayer:function () {
cc.LoaderScene.preload(g_resources, function () {
cc.director.runScene(new cc.TransitionFade(1.2,new StageLayerScene()));
}, this);
}
});
var TopLayerScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new TopLayer();
this.addChild(layer);
}
});
<file_sep>/src/Sprite/Enemy.js
//
// Enemy.js
// Territory
//
// Created by <NAME> on 5/30/14.
// Copyright (c) 2014 http://oggata.github.io All rights reserved.
var Enemy = cc.Node.extend({
ctor:function (game) {
this._super();
this.game = game;
//initialize
this.initializeParam();
this.initSprite();
},
initializeParam:function(){
this.hp = 100;
this.maxHp = 100;
this.imagePath = "res/sprite/chara007.png";
this.imgWidth = 60/3;
this.imgHeight = 112/4;
this.walkSpeed = 5;
this.direction = "front";
//歩行方向
this.beforeX = this.getPosition().x;
this.beforeY = this.getPosition().y;
this.directionCnt = 0;
this.moveX = 1;
this.mapX = 0;
this.mapY = 0;
},
setPos:function(mapX,mapY){
this.mapX = mapX;
this.mapY = mapY;
//this.setPosition(mapX,mapY);
},
move:function(){
/*
if(this.getPosition().x > 1000){
this.moveX = -1;
}
if(this.getPosition().x < 0){
this.moveX = 1;
}*/
if(this.mapX > 1000) this.moveX = -1;
if(this.mapX < 0) this.moveX = 1;
this.mapX += this.moveX;
/*
this.setPosition(
this.getPosition().x + this.moveX,
this.getPosition().y
);*/
if(this.game.isCameraRange(this.mapX,this.mapY)){
this.setVisible(true);
this.setPosition(this.mapX,this.mapY);
}else{
this.setVisible(false);
}
},
update:function() {
this.move();
//方向制御
this.directionCnt++;
if(this.directionCnt >= 5){
this.directionCnt = 0;
this.setDirection(this.beforeX,this.beforeY);
this.beforeX = this.getPosition().x;
this.beforeY = this.getPosition().y;
}
return true;
},
setDirection:function(DX,DY){
//横の距離が大きいとき
var diffX = Math.floor(this.getPosition().x - DX);
var diffY = Math.floor(this.getPosition().y - DY);
if(diffX > 0 && diffY > 0){
this.walkRightUp();
}
if(diffX > 0 && diffY < 0){
this.walkRightDown();
}
if(diffX < 0 && diffY > 0){
this.walkLeftUp();
}
if(diffX < 0 && diffY < 0){
this.walkLeftDown();
}
},
initSprite:function(){
/*
//足下の影
this.shadow = cc.Sprite.create(s_shadow);
this.shadow.setPosition(0,-10);
this.shadow.setOpacity(255*0.4);
this.shadow.setScale(5,5);
this.addChild(this.shadow);
*/
var frameSeq = [];
for (var i = 0; i < 3; i++) {
var frame = cc.SpriteFrame.create(this.imagePath,cc.rect(this.imgWidth*i,this.imgHeight*0,this.imgWidth,this.imgHeight));
frameSeq.push(frame);
}
this.wa = cc.Animation.create(frameSeq,0.2);
this.ra = cc.RepeatForever.create(cc.Animate.create(this.wa));
this.sprite = cc.Sprite.create(this.imagePath,cc.rect(0,0,this.imgWidth,this.imgHeight));
this.sprite.setPosition(0,50);
this.sprite.runAction(this.ra);
this.sprite.setScale(1.4,1.4);
this.addChild(this.sprite);
},
walkLeftDown:function(){
if(this.direction != "front"){
this.direction = "front";
this.sprite.stopAllActions();
var frameSeq = [];
for (var i = 0; i < 3; i++) {
var frame = cc.SpriteFrame.create(this.imagePath,cc.rect(this.imgWidth*i,this.imgHeight*0,this.imgWidth,this.imgHeight));
frameSeq.push(frame);
}
this.wa = cc.Animation.create(frameSeq,0.2);
this.ra = cc.RepeatForever.create(cc.Animate.create(this.wa));
this.sprite.runAction(this.ra);
}
},
walkRightDown:function(){
if(this.direction != "left"){
this.direction = "left";
this.sprite.stopAllActions();
var frameSeq = [];
for (var i = 0; i < 3; i++) {
var frame = cc.SpriteFrame.create(this.imagePath,cc.rect(this.imgWidth*i,this.imgHeight*1,this.imgWidth,this.imgHeight));
frameSeq.push(frame);
}
this.wa = cc.Animation.create(frameSeq,0.2);
this.ra = cc.RepeatForever.create(cc.Animate.create(this.wa));
this.sprite.runAction(this.ra);
}
},
walkLeftUp:function(){
if(this.direction != "right"){
this.direction = "right";
this.sprite.stopAllActions();
var frameSeq = [];
for (var i = 0; i < 3; i++) {
var frame = cc.SpriteFrame.create(this.imagePath,cc.rect(this.imgWidth*i,this.imgHeight*2,this.imgWidth,this.imgHeight));
frameSeq.push(frame);
}
this.wa = cc.Animation.create(frameSeq,0.2);
this.ra = cc.RepeatForever.create(cc.Animate.create(this.wa));
this.sprite.runAction(this.ra);
}
},
walkRightUp:function(){
if(this.direction != "back"){
this.direction = "back";
this.sprite.stopAllActions();
var frameSeq = [];
for (var i = 0; i < 3; i++) {
var frame = cc.SpriteFrame.create(this.imagePath,cc.rect(this.imgWidth*i,this.imgHeight*3,this.imgWidth,this.imgHeight));
frameSeq.push(frame);
}
this.wa = cc.Animation.create(frameSeq,0.2);
this.ra = cc.RepeatForever.create(cc.Animate.create(this.wa));
this.sprite.runAction(this.ra);
}
},
});<file_sep>/src/Layer/GameLayer.js
var GameLayer = cc.Layer.extend({
sprite:null,
ctor:function (stageNum) {
cc.log(stageNum);
this.stageNum = stageNum;
this._super();
this.mapNode = cc.Node.create();
this.addChild(this.mapNode);
this.gameTime = 0;
var fieldSprite = new cc.Sprite("res/ui/field.jpg");
fieldSprite.setAnchorPoint(0,0);
this.mapNode.addChild(fieldSprite);
this.targetMarker = new cc.Sprite("res/sprite/targetMarker.png");
this.mapNode.addChild(this.targetMarker);
this.player = new Player(this);
this.mapNode.addChild(this.player);
this.enemies = [];
//initialize camera
this.cameraX = Math.floor(320/2 - this.player.getPosition().x);
this.cameraY = Math.floor(480/2 - this.player.getPosition().y);
this.playerCameraX = 320/2;
this.playerCameraY = 420/2;
this.mapNode.setPosition(
this.cameraX,
this.cameraY
);
//if( 'touches' in cc.sys.capabilities )
cc.eventManager.addListener(cc.EventListener.create({
event: cc.EventListener.TOUCH_ALL_AT_ONCE,
onTouchesBegan : function(touches, event){
event.getCurrentTarget().targetMarker.setPosition(
touches[0].getLocation().x - event.getCurrentTarget().cameraX,
touches[0].getLocation().y - event.getCurrentTarget().cameraY
);
},
onTouchesMoved : function(touches, event){},
onTouchesEnded:function (touches, event) {
if (touches.length <= 0)
return;
}
}), this);
//else if ('mouse' in cc.sys.capabilities )
/*
cc.eventManager.addListener({
event: cc.EventListener.MOUSE,
onMouseUp: function (event) {
//event.getCurrentTarget().moveSprite(event.getLocation());
}
}, this);
*/
//Safe_png
this.safeSprite = new cc.Sprite(res.Safe_png);
this.safeSprite.setAnchorPoint(0,0);
this.mapNode.addChild(this.safeSprite);
this.safeMarker001Sprite = new cc.Sprite(res.Marker_png);
this.mapNode.addChild(this.safeMarker001Sprite);
this.safeMarker002Sprite = new cc.Sprite(res.Marker_png);
this.mapNode.addChild(this.safeMarker002Sprite);
this.safeMarker003Sprite = new cc.Sprite(res.Marker_png);
this.mapNode.addChild(this.safeMarker003Sprite);
this.safeMarker004Sprite = new cc.Sprite(res.Marker_png);
this.mapNode.addChild(this.safeMarker004Sprite);
this._label = cc.LabelTTF.create("aaaaaaaaa","Arial",20);
this._label.setPosition(100,400);
this.addChild(this._label);
//_label.setFontFillColor(cc.c4b(255,255,255,255));
//_label.setAnchorPoint(0.5,0);
//_label.enableStroke(cc.c4b(0,0,0,255),1,false);
this.scheduleUpdate();
return true;
},
addEnemyByPos : function(posX,posY){
this.enemy = new Enemy(this);
this.enemy.setPos(posX,posY);
this.mapNode.addChild(this.enemy);
this.enemies.push(this.enemy);
},
isCameraRange:function(posX,posY){
//2面はビューポートクリッピングがOFFだから常にtrueを返して、スプライトの表示を行う
if(this.stageNum == 2) return true;
if(this.cameraX * -1 < posX && posX < this.cameraX * -1 + 320
&& this.cameraY * -1 < posY && posY < this.cameraY * -1 + 480
){
return true;
}
/*
if(this.cameraX * -1 + 60 < posX && posX < this.cameraX * -1 + 260
&& this.cameraY * -1 + 90 < posY && posY < this.cameraY * -1 + 390
){
return true;
}*/
return false;
},
update:function(dt){
this._label.setString("enemy×" + this.enemies.length + "");
this.safeSprite.setPosition(this.cameraX * -1,this.cameraY * -1);
//左上
this.safeMarker001Sprite.setPosition(this.cameraX * -1 + 60, this.cameraY * -1 + 390);
//右上
this.safeMarker002Sprite.setPosition(this.cameraX * -1 + 260,this.cameraY * -1 + 390);
//左下
this.safeMarker003Sprite.setPosition(this.cameraX * -1 + 60, this.cameraY * -1 + 90);
//右下
this.safeMarker004Sprite.setPosition(this.cameraX * -1 + 260,this.cameraY * -1 + 90);
this.gameTime++;
if(this.gameTime>=30){
this.gameTime = 0;
this.addEnemyByPos(
getRandNumberFromRange(0,1000),
getRandNumberFromRange(0,1000)
);
}
for(var i=0;i<this.enemies.length;i++){
this.enemies[i].update();
}
this.player.moveToTargetMarker(this.targetMarker);
this.player.setDirection(this.targetMarker);
this.moveCamera();
},
moveCamera:function(){
//cc.log(this.cameraX + "|" + this.cameraY);
//カメラ位置はプレイヤーを追いかける
this.playerCameraX = this.player.getPosition().x + this.cameraX;
this.playerCameraY = this.player.getPosition().y + this.cameraY;
//xの中心は320/2=16 +- 20
if(this.playerCameraX >= 320/2 + 20){
this.cameraX -= this.player.walkSpeed;
}
if(this.playerCameraX <= 320/2 - 20){
this.cameraX += this.player.walkSpeed;
}
//yの中心は420/2=210 +- 20
if(this.playerCameraY >= 420/2 - 20){
this.cameraY -= this.player.walkSpeed;
}
if(this.playerCameraY <= 420/2 + 20){
this.cameraY += this.player.walkSpeed;
}
if(this.cameraX < -1000) this.cameraX = -1000;
if(this.cameraX > -160) this.cameraX = -160;
if(this.cameraY < -230) this.cameraY = -230;
if(this.cameraY > 80) this.cameraY = 80;
this.mapNode.setPosition(
this.cameraX,
this.cameraY
);
},
});
var getRandNumberFromRange = function (min,max) {
var rand = min + Math.floor( Math.random() * (max - min));
return rand;
};
var GameLayerScene001 = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new GameLayer(1);
this.addChild(layer);
}
});
var GameLayerScene002 = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new GameLayer(2);
this.addChild(layer);
}
});
|
37706c6a01ae412681d3341c2acdeda0de4be1a9
|
[
"JavaScript"
] | 5
|
JavaScript
|
oggata/Cocos2dJSv3SampleGame
|
434ee16cf1a0b9cc08afdb01126f7902125508c7
|
a30db476de65eb669313b4da5e48def9a85ba33c
|
refs/heads/master
|
<file_sep>package com.jcedar.visibook.lautech.ui.view;
import android.content.Context;
import android.preference.PreferenceCategory;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.helper.AccountUtils;
/**
* Created by user1 on 18/08/2014.
*/
public class ProfileCategory extends PreferenceCategory {
TextView fullname;
TextView username;
TextView organisation;
private Context mContext;
public ProfileCategory(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
this.setLayoutResource(R.layout.fragment_profile_view);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
fullname = (TextView) view.findViewById(R.id.fullName);
fullname.setText(AccountUtils.getFullName(mContext));
username = (TextView) view.findViewById(R.id.username);
username.setText(AccountUtils.getChosenAccountName(mContext));
organisation = (TextView) view.findViewById(R.id.organization);
if(AccountUtils.getRole(mContext).equalsIgnoreCase("ServiceProvider")){
organisation.setText("Service Provider");
}else{
organisation.setText(AccountUtils.getRole(mContext));
}
}
}
<file_sep>package com.jcedar.visibook.lautech.io.jsonhandlers;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.os.RemoteException;
import com.jcedar.visibook.lautech.provider.DataContract;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by user1 on 13/08/2015.
*/
public abstract class JSONHandler {
protected static Context mContext;
public JSONHandler(Context context){
mContext = context;
}
public abstract ArrayList<ContentProviderOperation> parse(String json) throws IOException;
public final void parseAndApply(String json) throws IOException {
final ContentResolver resolver = mContext.getContentResolver();
try {
ArrayList<ContentProviderOperation> batch = parse(json);
resolver.applyBatch(DataContract.CONTENT_AUTHORITY, batch);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
}
<file_sep>package com.jcedar.visibook.lautech.io.jsonhandlers;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.jcedar.visibook.lautech.helper.Lists;
import com.jcedar.visibook.lautech.io.model.Student;
import com.jcedar.visibook.lautech.provider.DataContract;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by Afolayan on 13/10/2015.
*/
public class StudentHandler extends JSONHandler{
private static final String TAG = StudentHandler.class.getSimpleName();
private int studentCount;
public StudentHandler(Context context) {
super(context);
}
@Override
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
if(json == null){
return null;
}
Log.d(TAG, TextUtils.isEmpty(json) ? "Empty Json" : json);
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
Student[] currentStudent = Student.fromJson(json);
studentCount = currentStudent.length;
for ( Student student: currentStudent) {
try {
Uri uri = DataContract.addCallerIsSyncAdapterParameter(
DataContract.Students.CONTENT_URI);
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(uri)
.withValue(DataContract.Students.NAME, student.getName())
.withValue(DataContract.Students.GENDER, student.getGender())
.withValue(DataContract.Students.PHONE_NUMBER, student.getPhoneNumber())
.withValue(DataContract.Students.EMAIL, student.getEmail())
.withValue(DataContract.Students.CHAPTER, student.getChapter())
.withValue(DataContract.Students.COURSE, student.getCourse())
.withValue(DataContract.Students.DATE_OF_BIRTH, student.getDateOfBirth())
.withValue(DataContract.Students.DOB_NUMBER, student.getDobNumber())
.withValue(DataContract.Students.IS_ALUMNI, student.getIsAlumni())
.withValue(DataContract.Students.UPDATE_INFO, student.getUpdateInfo())
.withValue(DataContract.Students.IMAGE, student.getImage())
.withValue(DataContract.Students.UPDATED, String.valueOf( System.currentTimeMillis()));
Log.d(TAG, "Data from Json" + student.getName() + " " + student.getChapter());
batch.add(builder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
return batch;
}
public int getStudentCount() {
return studentCount;
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.gordonwong.materialsheetfab.MaterialSheetFab;
import com.gordonwong.materialsheetfab.MaterialSheetFabEventListener;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.helper.AccountUtils;
import com.jcedar.visibook.lautech.helper.AppSettings;
import com.jcedar.visibook.lautech.helper.MultipartEntity;
import com.jcedar.visibook.lautech.helper.PrefUtils;
import com.jcedar.visibook.lautech.helper.UIUtils;
import com.jcedar.visibook.lautech.ui.view.Fab;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import static com.jcedar.visibook.lautech.helper.AccountUtils.getFullName;
import static com.jcedar.visibook.lautech.helper.AccountUtils.getUserName;
import static com.jcedar.visibook.lautech.helper.PrefUtils.getPhoto;
/**
* Created by Seyi.Afolayan on 4/7/2016.
*/
public class ProfileFragment extends Fragment implements Toolbar.OnMenuItemClickListener {
private static final String TAG = "ProfileFragment";
private static final int REQUEST_CAMERA = 100;
private static final int REQUEST_FROM_FILE = 200;
private static final int REQUEST_FROM_FB = 300;
private static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Visibook";
private Toolbar toolbar;
private ImageView imageView;
private TextView fullName, emailView, dobView, courseView, numberView;
private Context context;
private Listener mCallback;
private Fab fab1;
private MaterialSheetFab<Fab> materialSheetFab;
LinearLayout changeImage;
LinearLayout changeProfile;
Uri selectedImageUri;
private ViewGroup container;
private String email, dob, course, phoneNumber, name;
private AlertDialog.Builder builder;
private RelativeLayout alertView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.layout_user_profile, container, false);
this.container = container;
context = getActivity();
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle(AccountUtils.getUserName(context));
toolbar.setOnMenuItemClickListener(this);
//setSupportActionBar(toolbar);
imageView = (ImageView) view.findViewById(R.id.my_profile_image);
fullName = (TextView) view.findViewById(R.id.fullNameProfile);
emailView = (TextView) view.findViewById(R.id.tvEmailProfile);
dobView = (TextView ) view.findViewById(R.id.tvDateOfBirthProfile);
courseView = (TextView) view.findViewById(R.id.tvCourseSchool);
numberView = (TextView) view.findViewById(R.id.tvPhoneNumberProfile);
CollapsingToolbarLayout toolbarLayout = (CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
toolbarLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
startActivity(new Intent(context, PicViewActivity.class));
return false;
}
});
Drawable d = new BitmapDrawable(getResources(), getPhoto(context));
toolbarLayout.setStatusBarScrim(d);
toolbarLayout.setStatusBarScrimColor(UIUtils.getDominantColor(getPhoto(context)));
imageView.setImageBitmap(getPhoto(context));
name = AccountUtils.getUserName(context);
fullName.setText(name);
email = AccountUtils.getUserEmail(context);
dob = AccountUtils.getUserDOB(context);
course = AccountUtils.getUserCourse(context);
phoneNumber = AccountUtils.getUserPhoneNumber(context);
emailView.setText( isNotNull(email));
dobView.setText( isNotNull(dob));
courseView.setText( isNotNull(course) );
numberView.setText(isNotNull(phoneNumber));
//getToolbar().setVisibility(View.GONE);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fabEditProfile);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id = AccountUtils.getId(getActivity());
UpdateFragment updateFragment = UpdateFragment.newInstance(Long.parseLong(id));
updateFragment.show(getFragmentManager(), "User");
}
});
fab.setVisibility(View.GONE);
fab1 = (Fab) view.findViewById(R.id.fab);
View sheetView = view.findViewById( R.id.fab_sheet);
View overlay = view.findViewById( R.id.overlay);
int sheetColor = getResources().getColor(R.color.sim_grey);
int fabColor = getResources().getColor(R.color.theme_accent_1);
materialSheetFab = new MaterialSheetFab<>(fab1, sheetView, overlay, sheetColor, fabColor);
materialSheetFab.setEventListener(new MaterialSheetFabEventListener() {
@Override
public void onShowSheet() {
super.onShowSheet();
}
@Override
public void onSheetHidden() {
super.onSheetHidden();
}
});
view.findViewById(R.id.change_image_layout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//show image choose dialog
Log.e(TAG, "inside change image layout");
fab1.hide();
openImageIntent();
}
});
view.findViewById(R.id.edit_profile_layout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fab1.hide();
String id = AccountUtils.getId(getActivity());
UpdateFragment updateFragment = UpdateFragment.newInstance(Long.parseLong(id));
updateFragment.show(getFragmentManager(), "User");
}
});
alertView = (RelativeLayout) view.findViewById(R.id.layout_alert);
return view;
}
private void openImageIntent() {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View view = inflater.inflate(R.layout.layout_choose_image, container, false);
view.findViewById(R.id.chooseCamera).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);*/
captureImage();
}
});
view.findViewById(R.id.chooseFile).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertView.setVisibility(View.GONE);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select File"), REQUEST_FROM_FILE);
}
});
view.findViewById(R.id.chooseFacebook).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Todo : Facebook login
//Todo: get picture from user's profile
alertView.setVisibility(View.GONE);
}
});
builder = new AlertDialog.Builder(getActivity()).setCancelable(true);
builder.create();
builder.setView(view)
.setTitle("Complete action using");
builder.show();
}
private String getUsername(){
return getFullName(getActivity()).replace(" ", "_");
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("file_uri", selectedImageUri);
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
selectedImageUri = savedInstanceState.getParcelable("file_uri");
}
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
selectedImageUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
// start the image capture Intent
startActivityForResult(intent, REQUEST_CAMERA);
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CAMERA) {
String path = selectedImageUri.getPath();
if( path != null){
previewImage(path);
}
//upload pix
}
}
private void previewImage(String path) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(path, options);
imageView.setImageBitmap(bitmap);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Do you want to save this image?")
.setNeutralButton("Try another", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
captureImage();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
PrefUtils.setPhoto(getActivity(), bitmap);
new UploadTask().execute(bitmap);
}
})
.create();
builder.show();
}
private static String isNotNull(String string){
return string != null ? string : "";
}
@Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
interface Listener {
void onFragmentDetached(Fragment fragment);
void onFragmentAttached(Fragment fragment);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Listener) {
mCallback = (Listener) activity;
mCallback.onFragmentAttached(this);
} else {
throw new ClassCastException(activity.toString()
+ " must implement fragments listener");
}
}
@Override
public void onDetach() {
super.onDetach();
super.onDetach();
if (getActivity() instanceof Listener) {
((Listener) getActivity()).onFragmentDetached(this);
}
}
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
protected Void doInBackground(Bitmap... bitmaps) {
if (bitmaps[0] == null)
return null;
Bitmap bitmap = bitmaps[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream
String user = getUserName(getActivity());
String id = AccountUtils.getId(getActivity());
Log.e(TAG, "user=="+user+"\nid=="+id);
user += ":"+id;
Log.e(TAG, "user=="+user);
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
AppSettings.SERVER_URL+"update.php"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("image", id + ".png", in);
httppost.setEntity(reqEntity);
Log.e(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
Log.e(TAG, "response "+response);
} catch (IOException e) {
e.printStackTrace();
}
try {
if (response != null)
Log.e(TAG, "response " + response.getStatusLine().toString());
} finally {
}
} finally {
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(getActivity(), R.string.uploaded, Toast.LENGTH_LONG).show();
}
}
}
<file_sep>package com.jcedar.visibook.lautech.io.model;
/**
* Created by Afolayan on 13/10/2015.
*/
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Student {
@Expose
@SerializedName("id")
private String id;
@Expose
@SerializedName("name")
private String name;
@Expose @SerializedName("gender")
private String gender;
@Expose @SerializedName("school")
private String chapter;
@Expose @SerializedName("email")
private String email;
@Expose @SerializedName("phone_number")
private String phoneNumber;
@Expose @SerializedName("course")
private String course;
@Expose @SerializedName("date_of_birth")
private String dateOfBirth;
@Expose @SerializedName("dobNumber")
private String dobNumber;
@Expose @SerializedName("updateInfo")
private String updateInfo;
@Expose @SerializedName("isAlumni")
private String isAlumni;
@Expose @SerializedName("image")
private String image;
public String getName() {
return name;
}
public String getId() {
return id;
}
public String getGender() {
return gender;
}
public String getChapter() {
return chapter;
}
public String getEmail() {
return email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getCourse() {
return course;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public String getDobNumber() {
return dobNumber;
}
public String getUpdateInfo() {
return updateInfo;
}
public String getIsAlumni() {
return isAlumni;
}
public String getImage() {
return image;
}
public static Student[] fromJson(String json){
return new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.create().fromJson(json, Student[].class);
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.facebook.appevents.AppEventsLogger;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.adapter.RecyclerCursorAdapter;
import com.jcedar.visibook.lautech.io.adapters.StudentCursorAdapter;
import com.jcedar.visibook.lautech.provider.DataContract;
import com.jcedar.visibook.lautech.ui.view.SimpleSectionedListAdapter;
public class StudentListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
protected static final String NAIRA = "\u20A6";
private static final String TAG = StudentListFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private int mPosition;
private String mParam2;
public static final String STUDENT_POSITION = "position";
private StudentCursorAdapter mAdapter;
private SimpleSectionedListAdapter sSectionAdapter;
private ListView listView;
private TextView tvError;
private Bundle mStudentBundle = Bundle.EMPTY;
private Listener mCallback;
private String context;
RecyclerView recyclerView;
RecyclerCursorAdapter resultsCursorAdapter;
public static StudentListFragment newInstance(int position) {
StudentListFragment fragment = new StudentListFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, position);
fragment.setArguments(args);
return fragment;
}
public StudentListFragment() {
// Required empty public constructor
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(0, null, this);
Loader loader = getLoaderManager().getLoader(0);
if (loader != null && !loader.isReset()) {
getLoaderManager().restartLoader(0, null, this);
} else {
getLoaderManager().initLoader(0, null, this);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPosition = getArguments().getInt(ARG_PARAM1);
}
mAdapter = new StudentCursorAdapter(getActivity(), null,
R.layout.list_n_item_student);
sSectionAdapter = new SimpleSectionedListAdapter(getActivity(),
R.layout.list_group_header, mAdapter);
context = getActivity().getClass().getSimpleName();
//setListAdapter(mAdapter);
// setListAdapter(sSectionAdapter);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
ViewGroup rootView;
if( !context.equalsIgnoreCase("StudentDetailsActivity")) {
rootView =
(ViewGroup) inflater.inflate(R.layout.fragment_dash, container, false);
} else {
rootView =
(ViewGroup) inflater.inflate(R.layout.fragment_home1, container, false);
}
tvError = (TextView) rootView.findViewById(R.id.tvErrorMag);
recyclerView = (RecyclerView) rootView.findViewById( R.id.recyclerview );
resultsCursorAdapter = new RecyclerCursorAdapter( getActivity() );
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//recyclerView.setLayoutManager(new WrappingLinearLayoutManager(getContext()));
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(false);
recyclerView.setAdapter(resultsCursorAdapter);
recyclerView.addItemDecoration( new VerticalSpaceItemDecoration(3) );
tvError = (TextView) rootView.findViewById(R.id.tvErrorMag);
resultsCursorAdapter.setOnItemClickListener(new RecyclerCursorAdapter.OnItemClickListener() {
@Override
public void onItemClicked(Cursor data) {
long Id = data.getLong(
data.getColumnIndex(DataContract.Students._ID));
Log.d(TAG, "selectedId = " + Id + STUDENT_POSITION);
// add position to bundle
//mHomeBundle.putInt(_POSITION, position);
mCallback.onSchoolSelected(Id);
}
});
return rootView;
}
public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration {
private final int mVerticalSpaceHeight;
public VerticalSpaceItemDecoration(int mVerticalSpaceHeight) {
this.mVerticalSpaceHeight = mVerticalSpaceHeight;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
outRect.bottom = mVerticalSpaceHeight;
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (Listener) activity;
mCallback.onFragmentAttached(this);
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement Listener");
}
activity.getContentResolver().registerContentObserver(
DataContract.StudentsChapter.CONTENT_URI, true, mObserver);
updateDashboard();
}
@Override
public void onDetach() {
super.onDetach();
if (getActivity() instanceof Listener) {
((Listener) getActivity()).onFragmentDetached(this);
}
getActivity().getContentResolver().unregisterContentObserver(mObserver);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = DataContract.StudentsChapter.CONTENT_URI;
CursorLoader cursorLoader = null;
return new CursorLoader(
getActivity(),
uri,
DataContract.StudentsChapter.PROJECTION_ALL,
null,
null,
null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
resultsCursorAdapter.swapCursor(data);
/*
Bundle bundle = new Bundle();
int count = 0;
if( data.moveToFirst() ) {
mAdapter.swapCursor(data);
mAdapter.notifyDataSetChanged();
data.moveToFirst();
while ( !data.isAfterLast()) {
long studentId = data.getLong(
data.getColumnIndexOrThrow(DataContract.Students._ID));
bundle.putLong(StudentDetailsActivity.ARG_STUDENT_LIST
+ Integer.toString(count++), studentId);
data.moveToNext();
}
this.mStudentBundle = bundle;
} else {
mAdapter.swapCursor(null);
tvError.setVisibility(View.VISIBLE);
tvError.setText("Error retrieving data");
}*/
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
resultsCursorAdapter.swapCursor(null);
}
/* @Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
final Cursor cursor = (Cursor) sSectionAdapter.getItem(position);
if (cursor != null) {
long Id = cursor.getLong(
cursor.getColumnIndex(DataContract.Students._ID));
Log.d(TAG, "selectedId = " + Id + STUDENT_POSITION);
// add position to bundle
mStudentBundle.putInt(STUDENT_POSITION, position);
mCallback.onSchoolSelected(Id);
}
}*/
interface Listener {
void onSchoolSelected(long studentId);
void onFragmentAttached(Fragment fragment);
void onFragmentDetached(Fragment fragment);
}
private final ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
if (!isAdded()) {
return;
}
getLoaderManager().restartLoader(0, null, StudentListFragment.this);
}
};
private void updateDashboard() {
// do work
try {
getLoaderManager().restartLoader(0, null, this);
} catch (Exception e) {
Log.e(TAG, "" + e);
}
}
@Override
public void onPause() {
super.onPause();
AppEventsLogger.activateApp( getActivity());
}
@Override
public void onResume() {
super.onResume();
AppEventsLogger.deactivateApp( getActivity());
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.helper.AccountUtils;
import com.jcedar.visibook.lautech.helper.AppSettings;
import com.jcedar.visibook.lautech.helper.FormatUtils;
import com.jcedar.visibook.lautech.helper.ServiceHandler;
import com.jcedar.visibook.lautech.helper.UIUtils;
import com.jcedar.visibook.lautech.provider.DataContract;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import java.util.Calendar;
import static com.jcedar.visibook.lautech.helper.PrefUtils.encodeTobase64;
import static com.jcedar.visibook.lautech.helper.PrefUtils.getPhoto;
public class UpdateFragment extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor>, DatePickerDialog.OnDateSetListener {
private static final String ARG_PARAM_ID = "_id";
private static final String TAG = UpdateFragment.class.getSimpleName();
// TODO: Rename and change types of parameters
private long student_id;
private TextView detail;
EditText name, email, course, phone_number, date;
RadioButton male, female;
SwitchCompat alumniSwitch;
String nameStr, emailStr, courseStr, phone_numberStr, gender, isAlumni;
private Calendar newCalendar = Calendar.getInstance();
private Calendar currentDate;
private String dobNumber, dobString;
private String dateStr;
private String oldDate;
private String id;
public UpdateFragment() {
// Required empty public constructor
}
public static UpdateFragment newInstance(long id) {
UpdateFragment fragment = new UpdateFragment();
Bundle args = new Bundle();
args.putLong(ARG_PARAM_ID, id);
Log.e(TAG, "id in here "+id);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
student_id = getArguments().getLong(ARG_PARAM_ID);
}
getLoaderManager().initLoader(1, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
ViewGroup rootView =
(ViewGroup) inflater.inflate(R.layout.fragment_update, container, false);
//detail = (TextView) rootView.findViewById( R.id.);
name = (EditText) rootView.findViewById( R.id.etName );
email = (EditText) rootView.findViewById( R.id.etEmail );
email.setEnabled(false); //dont make users edit their email
course = (EditText) rootView.findViewById( R.id.etCourse );
phone_number = (EditText) rootView.findViewById( R.id.etPhone );
date = (EditText) rootView.findViewById( R.id.etDOB );
date.setClickable(false);
male = (RadioButton) rootView.findViewById( R.id.rbMale );
female = (RadioButton) rootView.findViewById( R.id.rbFemale );
alumniSwitch = (SwitchCompat) rootView.findViewById( R.id.switch1 );
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
nameStr = name.getText().toString().trim();
emailStr = email.getText().toString().trim();
courseStr = course.getText().toString().trim();
phone_numberStr = phone_number.getText().toString().trim();
dateStr = date.getText().toString().trim();
gender = ( male.isChecked() ? "Male": "Female");
isAlumni = ( alumniSwitch.isChecked() ? "1": "0");
UIUtils.showToast( getActivity(), "Updating name");
/*updateThread.start();
try {
updateThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}*/
new PostUpdate().execute();
getActivity().getFragmentManager().popBackStack();
}
});
date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog dialog = DatePickerDialog.newInstance(UpdateFragment.this,
newCalendar.get(Calendar.YEAR),
newCalendar.get(Calendar.MONTH),
newCalendar.get(Calendar.DAY_OF_MONTH)
);
//initialize the current date
currentDate = Calendar.getInstance();
dialog.setOnDateSetListener(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePickerDialog datePickerDialog, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
dobNumber = FormatUtils.makeYearMonthDay(newDate.getTime());
dobString = FormatUtils.makeTrimmedYear(newDate.getTime());
date.setText( dobString );
}
});
dialog.setAccentColor(R.color.theme_primary);
dialog.dismissOnPause(true);
dialog.show(getActivity().getFragmentManager(), "DatePickerDialog");
}
});
getDialog().setTitle("Update names");
return rootView;
}
private class PostUpdate extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog = new ProgressDialog(getActivity());
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Updating the database...");
dialog.setTitle("Please Wait");
dialog.setCancelable(false);
dialog.setIndeterminate(true);
dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
updateExistingEntries(id, nameStr,
gender, emailStr, courseStr, FormatUtils.removeEscapeXters(phone_numberStr),
dateStr, dobNumber, isAlumni, encodeTobase64( getPhoto(getActivity())));
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if ( dialog.isShowing() ) dialog.dismiss();
UIUtils.showToast(getActivity(), "Please wait till you receive a notification");
getDialog().dismiss();
}
}
@Override
public void onPause() {
super.onPause();
getLoaderManager().destroyLoader(1);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = DataContract.Students.buildStudentUri(student_id);
return new CursorLoader( getActivity(),
uri,
DataContract.Students.PROJECTION_ALL,
null, null,
DataContract.Students.SORT_ORDER_DEFAULT);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
data.moveToFirst();
id = data.getString( data.getColumnIndex(DataContract.Students._ID));
name.setText(data.getString( data.getColumnIndex(DataContract.Students.NAME)));
email.setText(data.getString( data.getColumnIndex(DataContract.Students.EMAIL)));
course.setText(data.getString( data.getColumnIndex(DataContract.Students.COURSE)));
phone_number.setText(data.getString( data.getColumnIndex(DataContract.Students.PHONE_NUMBER)));
oldDate = data.getString( data.getColumnIndex(DataContract.Students.DATE_OF_BIRTH));
date.setText(oldDate);
String gender = data.getString( data.getColumnIndex(DataContract.Students.GENDER));
int alumni = data.getInt( data.getColumnIndex(DataContract.Students.IS_ALUMNI));
boolean isAlumni = ( alumni != 0 );
Log.e(TAG, alumni+ " is alumni "+isAlumni);
if (isAlumni) alumniSwitch.setChecked( true );
if ( gender.startsWith("M")) male.setChecked(true);
else female.setChecked(true);
Log.e(TAG, gender+ " gender ");
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
}
public void updateExistingEntries(String id, String name, String gender, String email,
String course, String phone_number, String dateStr,
String dobNumber, String isAlumni, String image){
String userId = AccountUtils.getId( getActivity() );
String userChapter = AccountUtils.getUserChapter( getActivity() );
Log.e(TAG, userId+" "+userChapter+" \n"+id+" "+name +" \n"+gender+ " "+email+" \n"
+course+" "+phone_number+" \n"+dateStr+" "+dobNumber+
" \n"+ isAlumni
);
if ( userId != null && userChapter != null ){
//if ( userChapter != null ){
Log.e(TAG, userId+"updating student "+name +"'s details ");
String url = String.format(AppSettings.SERVER_URL
+ "update.php?" +
"id=%s" +
"&name=%s" +
"&gender=%s" +
"&school=%s" +
"&course=%s" +
"&email=%s" +
"&phone_number=%s" +
"&dobNumber=%s" +
"&dobString=%s" +
"&userId=%s" +
"&isAlumni=%s" +
"&image=%s",
id, name, gender, userChapter,
course, email, phone_number,
dobNumber, dateStr, userId, isAlumni, image);
Log.e(TAG, "url=="+url);
String response = ServiceHandler.makeServiceCall (url, ServiceHandler.GET);
if(response == null){
return;
}
}
}
}<file_sep>package com.jcedar.visibook.lautech.helper;
import android.text.TextUtils;
import android.util.Log;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by Inbuilt on 6/2/2015.
*/
public class FormatUtils {
private static final String TAG = FormatUtils.class.getSimpleName();
// currency unicode values
public static final String NAIRA = "\u20A6";
public static final String DOLLAR = "\u20A6";
public static String makeMonthYear(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("MMMM yyyy");
String strVal = sdf.format(date);
return strVal;
}
public static String makeMonthYearWithComma(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("MMMM, yyyy");
String strVal = sdf.format(date);
return strVal;
}
public static String formatDate(Calendar dateTime){
String myFormat = "dd/MM/yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
return sdf.format(dateTime.getTime());
}
public static String millisToMachineDate(long instant) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
DateTime dt = new DateTime(instant);
return dt.toString(formatter);
}
public static String getCurrentDate() {
DateTime currentDate = new DateTime(DateTimeZone.getDefault());
String strDate = currentDate.toString();
return strDate;
}
public static long dateToMillis(String dateTime) {
if (TextUtils.isEmpty(dateTime)) return 0;
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
DateTime dt = formatter.parseDateTime(dateTime);
return dt.getMillis();
}
public static long getDateInMillis(String dateString) {
Date date = null;
try {
date = AppSettings.serverDateFormat.parse(dateString);
return date.getTime();
} catch (ParseException e) {
Log.e(TAG, "Error while parsing " + date + " to date");
e.printStackTrace();
return -1;
}
}
public static String formatMoney(double value) {
DecimalFormat formatter = new DecimalFormat("###,###,###.00");
return formatter.format(value);
}
public static String formatMoney(String value) {
BigDecimal bigDecimal = new BigDecimal(value);
DecimalFormat formatter = new DecimalFormat("###,###,###.00");
return formatter.format(bigDecimal);
}
public static String convertDate(String dateValue, String oldFormat, String newFormat){
DateTimeFormatter oldFormatter = DateTimeFormat.forPattern(oldFormat);
DateTime date = oldFormatter.parseDateTime(dateValue);
DateTimeFormatter newFormatter = DateTimeFormat.forPattern(newFormat);
return date.toString(newFormatter);
}
public static long yodaDateToMillis(String dateTime) {
Log.d(TAG, dateTime);
if (TextUtils.isEmpty(dateTime)) return 0;
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
DateTime dt = formatter.parseDateTime(dateTime);
return dt.getMillis();
}
public static String makeFriendlyDate(String instant) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM dd, yyyy");
DateTime dt = new DateTime(instant);
return dt.toString(formatter);
}
public static String ellipsize(String input) {
int maxLength = 25;
String ellip = "...";
if (input == null || input.length() <= maxLength
|| input.length() < ellip.length()) {
return input;
}
return input.substring(0, maxLength - ellip.length()).concat(ellip);
}
public static String toTwoDecimalPlaces(String credit_point){
DecimalFormat df = new DecimalFormat("#.##");
double point = Double.parseDouble(credit_point);
/* String out = df.format(point);
System.out.println("Value: " + out);
return out;*/
return String.format("%.2f", point);
}
public static String makeHumanFriendlyDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy", Locale.getDefault());
String strVal = sdf.format(date);
return strVal;
}
public static String makeYearMonthDay(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String strVal = sdf.format(date);
return strVal;
}
public static String makeTrimmedYear(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd", Locale.getDefault());
String strVal = sdf.format(date);
return strVal;
}
public static String removeEscapeXters(String string){
String ss="";
if(string != null ){
ss = string.replaceAll("\\n", "");
ss = ss.replaceAll("\\t", "");
ss = ss.replaceAll("\\r", "");
}
return ss;
}
}
<file_sep>package com.jcedar.visibook.lautech.ui.view.nav;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.jcedar.visibook.lautech.R;
public class NavMenuSection implements NavDrawerItem {
public static final int SECTION_TYPE = 0;
private int id;
private int label;
@Override
public int getType() {
return SECTION_TYPE;
}
public int getLabel() {
return label;
}
public void setLabel(int label) {
this.label = label;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public boolean updateActionBarTitle() {
return false;
}
@Override
public boolean isCheckable() {
return false;
}
public View getView( View convertView, ViewGroup parentView, NavDrawerItem navDrawerItem, LayoutInflater inflater ) {
NavMenuSection menuSection = (NavMenuSection) navDrawerItem ;
NavMenuSectionHolder navMenuItemHolder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.navdrawer_section, parentView, false);
/* TextView labelView = (TextView) convertView
.findViewById( R.id.navmenusection_label );*/
navMenuItemHolder = new NavMenuSectionHolder();
/*navMenuItemHolder.labelView = labelView ;*/
convertView.setTag(navMenuItemHolder);
}
return convertView ;
}
private class NavMenuSectionHolder {
//private TextView labelView;
private View view;
}
}
<file_sep>package com.jcedar.visibook.lautech.adapter;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.provider.DataContract;
import butterknife.Bind;
import butterknife.ButterKnife;
public class RecyclerCursorAdapter extends RecyclerViewCursorAdapter<RecyclerCursorAdapter.SearchResultViewHolder>
implements View.OnClickListener
{
private final LayoutInflater layoutInflater;
private OnItemClickListener onItemClickListener;
public RecyclerCursorAdapter(final Context context)
{
super();
this.layoutInflater = LayoutInflater.from(context);
setHasStableIds(true);
}
public void setOnItemClickListener(final OnItemClickListener onItemClickListener)
{
this.onItemClickListener = onItemClickListener;
}
@Override
public SearchResultViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType)
{
final View view = this.layoutInflater.inflate(R.layout.list_n_item_student, parent, false);
view.setOnClickListener(this);
return new SearchResultViewHolder(view);
}
@Override
public void onBindViewHolder(final SearchResultViewHolder holder, final Cursor cursor)
{
holder.bindData(cursor);
}
/*
* View.OnClickListener
*/
@Override
public void onClick(final View view)
{
if (this.onItemClickListener != null)
{
final RecyclerView recyclerView = (RecyclerView) view.getParent();
final int position = recyclerView.getChildLayoutPosition(view);
if (position != RecyclerView.NO_POSITION)
{
final Cursor cursor = this.getItem(position);
this.onItemClickListener.onItemClicked(cursor);
}
}
}
public static class SearchResultViewHolder extends RecyclerView.ViewHolder
{
@Bind(R.id.lblName)
TextView textViewName;
@Bind(R.id.lblCourse)
TextView textViewCourse;
@Bind(R.id.lblDoB)
TextView textViewDOB;
public SearchResultViewHolder(final View itemView)
{
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bindData(final Cursor cursor)
{
final String name = cursor.getString(cursor.getColumnIndex(DataContract.Students.NAME));
this.textViewName.setText(name);
final String course = cursor.getString(cursor.getColumnIndex(DataContract.Students.COURSE));
this.textViewCourse.setText(course);
final String dob = cursor.getString(cursor.getColumnIndex(DataContract.Students.DATE_OF_BIRTH));
this.textViewDOB.setText(dob);
}
}
public interface OnItemClickListener
{
void onItemClicked(Cursor cursor);
}
}<file_sep>package com.jcedar.visibook.lautech.ui;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import com.facebook.appevents.AppEventsLogger;
import com.jcedar.visibook.lautech.R;
public class Preference extends PreferenceFragment {
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
settings.registerOnSharedPreferenceChangeListener(mPrefChangeListener);
}
@Override
public void onDetach() {
super.onDetach();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
settings.unregisterOnSharedPreferenceChangeListener(mPrefChangeListener);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
/*EditTextPreference versionPref = (EditTextPreference)findPreference("version");
String version = null;
try {
version = getActivity().getPackageManager()
.getPackageInfo(getActivity().getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
versionPref.setTitle(getString(R.string.version) + ": " + version);
*/
EditTextPreference devPref = (EditTextPreference)findPreference("developer");
//devPref.setSummary("<NAME>");
devPref.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(android.preference.Preference preference) {
String url = "http://www.facebook.com/afolayanjeph";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
return false;
}
});
EditTextPreference desPref = (EditTextPreference)findPreference("designer");
//desPref.setSummary("<NAME>");
desPref.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(android.preference.Preference preference) {
String url = "http://www.facebook.com/obamisaye";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
return false;
}
});
}
private SharedPreferences.OnSharedPreferenceChangeListener mPrefChangeListener
= new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
onNotificationChanged(key);
}
};
private void onNotificationChanged(String key) {
if(key.equals("notification")){
SwitchPreference switchPreference = (SwitchPreference) findPreference(key);
if(null == switchPreference) return;
}
}
@Override
public void onPause() {
super.onPause();
AppEventsLogger.activateApp(getActivity());
}
@Override
public void onResume() {
super.onResume();
AppEventsLogger.deactivateApp( getActivity());
}
}<file_sep>package com.jcedar.visibook.lautech.sync;
import android.accounts.Account;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import com.jcedar.visibook.lautech.gcm.GcmIntentServices;
import com.jcedar.visibook.lautech.helper.AppHelper;
import com.jcedar.visibook.lautech.helper.AppSettings;
import com.jcedar.visibook.lautech.helper.PrefUtils;
import com.jcedar.visibook.lautech.helper.ServiceHandler;
import com.jcedar.visibook.lautech.helper.UIUtils;
import com.jcedar.visibook.lautech.io.jsonhandlers.StudentHandler;
import com.jcedar.visibook.lautech.io.jsonhandlers.StudentUpdateHandler;
import com.jcedar.visibook.lautech.provider.DataContract;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by Afolayan on 28/1/2016.
*/
public class SyncHelper {
public static final String GCM_TRIGGERED = "gcm_triggered";
public static final String NEW_STUDENT_COUNT = "new_student_count";
public static final String UPDATE_COUNT = "update_count";
private static final String TAG = SyncHelper.class.getSimpleName();
private Context mContext;
public static final String ACTION = "Action";
public SyncHelper(Context context) {
mContext = context;
}
public static void requestManualSync(Account chosenAccount) {
Bundle settings = new Bundle();
settings.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
settings.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
ContentResolver.requestSync(
chosenAccount,
DataContract.CONTENT_AUTHORITY, settings);
}
public Bundle performNewStudentSync(){
Log.d(TAG, "Syncing");
//Send lastId to /add.php
//get new chapter updates
ContentResolver resolver = mContext.getContentResolver();
ArrayList<ContentProviderOperation> batch
= new ArrayList<>();
long id=0;
Bundle syncSummary = new Bundle();
//SELECT id FROM naas ORDER BY id DESC LIMIT 0 , 1
if( isOnline() ){
Cursor cursor = resolver.query(
DataContract.Students.CONTENT_URI,
new String[]{ DataContract.Students._ID},
null, null,
DataContract.Students._ID+" DESC LIMIT 0, 1"
);
if (cursor != null) {
cursor.moveToFirst();
id = cursor.getLong(0);
Log.e(TAG, " id is "+id);
cursor.close();
}
if ( id > 0 ){
try{
String response = ServiceHandler.makeServiceCall
(AppSettings.SERVER_URL +"add.php?lastId="+id, ServiceHandler.GET);
if(!TextUtils.isEmpty( response )){
Log.e(TAG, response + " response for new update");
StudentHandler studentHandler = new StudentHandler(mContext);
ArrayList<ContentProviderOperation> operations =
studentHandler.parse(response);
syncSummary.putInt(NEW_STUDENT_COUNT, studentHandler.getStudentCount());
batch.addAll( operations );
/*if ( AccountUtils.getUserChapter(mContext) != null){
String chapter = AccountUtils.getUserChapter(mContext);
Log.e(TAG, chapter + " chapter for new update");
new AppHelper(mContext).pullAndSaveStudentChapterDataForSync();
}*/
new AppHelper().pullAndSaveStudentChapterDataForSync(mContext);
}
} catch (IOException e) {
e.printStackTrace();
}
if ( batch.size() > 0 ){
try {
resolver.applyBatch(DataContract.CONTENT_AUTHORITY, batch);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
throw new RuntimeException("Problem applying batch operation" + e);
}
}
}
}
Log.i(TAG, "Sync complete");
return syncSummary;
}
public Bundle performUpdateStudentSync( long lastId){
Log.d(TAG, "Syncing");
ContentResolver resolver = mContext.getContentResolver();
ArrayList<ContentProviderOperation> batch
= new ArrayList<>();
Bundle syncSummary = new Bundle();
if( isOnline() ){
try{
String response = ServiceHandler.makeServiceCall
(AppSettings.SERVER_URL +"update.php?updatedId="+lastId, ServiceHandler.GET);
if(!TextUtils.isEmpty( response )){
Log.e(TAG, response + " response for new update");
StudentUpdateHandler studentHandler = new StudentUpdateHandler(mContext);
ArrayList<ContentProviderOperation> operations =
studentHandler.parse(response);
syncSummary.putInt(UPDATE_COUNT, studentHandler.getStudentCount());
batch.addAll( operations );
/*if ( AccountUtils.getUserChapter(mContext) != null){
String chapter = AccountUtils.getUserChapter(mContext);
Log.e(TAG, chapter + " chapter for new update");
new AppHelper(mContext).pullAndSaveStudentChapterDataForSync(chapter);
}*/
new AppHelper().pullAndSaveStudentChapterDataForSync(mContext);
}
} catch (IOException e) {
e.printStackTrace();
}
if ( batch.size() > 0 ){
try {
resolver.applyBatch(DataContract.CONTENT_AUTHORITY, batch);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
throw new RuntimeException("Problem applying batch operation" + e);
}
}
}
Log.i(TAG, "Sync complete");
return syncSummary;
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(
Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null &&
cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
Bundle syncSummary;
public void requestManualSync(){
UIUtils.showToast(mContext, "Performing sync" );
GcmIntentServices u = new GcmIntentServices();
if ( isOnline() ) t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
int newStudentNo = syncSummary.getInt(SyncHelper.NEW_STUDENT_COUNT, 0);
if (newStudentNo != 0 && PrefUtils.hasNotification(mContext)) {
u.displayNotification(mContext, "", u.newStudent, newStudentNo, "New Student Added");
} else {
UIUtils.showAlert("Update", "No new names are added so far", mContext);
}
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
syncSummary = performNewStudentSync();
}
});
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import com.facebook.appevents.AppEventsLogger;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.helper.AccountUtils;
import static com.jcedar.visibook.lautech.helper.PrefUtils.getPhoto;
public class PicViewActivity extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic_view);
imageView = (ImageView) findViewById(R.id.profile_image);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setNavigationIcon(R.drawable.ic_up);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PicViewActivity.this.finish();
}
});
new Handler().post(new Runnable() {
@Override
public void run() {
toolbar.setTitle(AccountUtils.getUserName(PicViewActivity.this) != null
? AccountUtils.getUserName(PicViewActivity.this) : "Profile Picture");
}
});
}
imageView.setImageBitmap(getPhoto(this));
}
@Override
protected void onPause() {
super.onPause();
AppEventsLogger.activateApp(this);
}
@Override
protected void onResume() {
super.onResume();
AppEventsLogger.deactivateApp(this);
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.accounts.Account;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SyncStatusObserver;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.appevents.AppEventsLogger;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.helper.AccountUtils;
import com.jcedar.visibook.lautech.provider.DataContract;
import com.jcedar.visibook.lautech.ui.view.MultiSwipeRefreshLayout;
import java.util.ArrayList;
//import com.google.android.gcm.GCMRegistrar;
//import com.jcedar.visibook.lautech.gcm.ServerUtilities;
//import com.jcedar.visibook.lautech.sync.SyncHelper;
//import com.jcedar.visibook.lautech.util.PrefUtils;
//import static com.jcedar.visibook.lautech.helper.LogUtils.LOGI;
public abstract class BaseActivity extends ActionBarActivity implements
MultiSwipeRefreshLayout.CanChildScrollUpCallback {
protected static final String NAIRA = "\u20A6";
protected static final String UNIT = "KWh";
private static final String TAG = BaseActivity.class.getSimpleName();
// delay to launch nav drawer item, to allow close animation to play
private static final int NAVDRAWER_LAUNCH_DELAY = 250;
// fade in and fade out durations for the main content when switching between
// different Activities of the app through the Nav Drawer
private static final int MAIN_CONTENT_FADEOUT_DURATION = 150;
private static final int MAIN_CONTENT_FADEIN_DURATION = 250;
// SwipeRefreshLayout allows the user to swipe the screen down to trigger a manual refresh
private SwipeRefreshLayout mSwipeRefreshLayout;
private ViewGroup mDrawerItemsListContainer;
// Primary toolbar and drawer toggle
private Toolbar mActionBarToolbar;
private boolean mManualSyncRequest;
private SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {
@Override
public void onStatusChanged(int which) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String accountName = AccountUtils.getChosenAccountName(BaseActivity.this);
if (TextUtils.isEmpty(accountName)) {
onRefreshingStateChanged(false);
mManualSyncRequest = false;
return;
}
Account account = new Account(accountName, getResources().getString(R.string.account_type));
boolean syncActive = ContentResolver.isSyncActive(
account, DataContract.CONTENT_AUTHORITY);
boolean syncPending = ContentResolver.isSyncPending(
account, DataContract.CONTENT_AUTHORITY);
if (!syncActive && !syncPending) {
mManualSyncRequest = false;
}
onRefreshingStateChanged(syncActive || (mManualSyncRequest && syncPending));
}
});
}
};
// handle to our sync observer (that notifies us about changes in our sync state)
private Object mSyncObserverHandle;
// asynctask that performs GCM registration in the background
private AsyncTask<Void, Void, Void> mGCMRegisterTask;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
// Navigation drawer
private DrawerLayout mDrawerLayout;
private CharSequence mTitle;
private Handler mHandler;
private CallbackManager callbackManager;
private ProfileTracker profileTracker;
/**
* Converts an intent into a {@link Bundle} suitable for use as fragment arguments.
*/
protected static Bundle intentToFragmentArguments(Intent intent) {
Bundle arguments = new Bundle();
if (intent == null) {
return arguments;
}
final Uri data = intent.getData();
if (data != null) {
arguments.putParcelable("_uri", data);
}
final Bundle extras = intent.getExtras();
if (extras != null) {
arguments.putAll(intent.getExtras());
}
return arguments;
}
/**
* Converts a fragment arguments bundle into an intent.
*/
public static Intent fragmentArgumentsToIntent(Bundle arguments) {
Intent intent = new Intent();
if (arguments == null) {
return intent;
}
final Uri data = arguments.getParcelable("_uri");
if (data != null) {
intent.setData(data);
}
intent.putExtras(arguments);
intent.removeExtra("_uri");
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mHandler = new Handler();
// set orientation for screen sizes
/* if (getResources().getConfiguration().smallestScreenWidthDp <= 600) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}*/
if(!isFinishing()) {
registerGCMClient();
}
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
// App code
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.base, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
return super.onOptionsItemSelected(item);
}
public ArrayList<Long> convertToArray(Bundle bundle, String key) {
ArrayList<Long> items = new ArrayList<Long>();
int n = 0;
while (true) {
long item = bundle.getLong(key + Integer.toString(n++), -1);
// terminate once we cant retrieve items
if (item == -1) break;
items.add(item);
}
return items;
}
/*private void trySetupSwipeRefresh() {
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setColorSchemeResources(
R.color.refresh_progress_1,
R.color.refresh_progress_2,
R.color.refresh_progress_3,
R.color.refresh_progress_1);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestDataRefresh();
}
});
if (mSwipeRefreshLayout instanceof MultiSwipeRefreshLayout) {
MultiSwipeRefreshLayout mswrl = (MultiSwipeRefreshLayout) mSwipeRefreshLayout;
mswrl.setCanChildScrollUpCallback(this);
}
}
}*/
protected void onRefreshingStateChanged(boolean refreshing) {
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setRefreshing(refreshing);
}
}
protected void enableDisableSwipeRefresh(boolean enable) {
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setEnabled(enable);
}
}
@Override
public boolean canSwipeRefreshChildScrollUp() {
return true;
}
protected void requestDataRefresh() {
Account activeAccount = AccountUtils.getChosenAccount(this);
ContentResolver contentResolver = getContentResolver();
if (contentResolver.isSyncActive(activeAccount, DataContract.CONTENT_AUTHORITY)) {
Log.d(TAG, "Ignoring manual sync request because a sync is already in progress.");
return;
}
mManualSyncRequest = true;
Log.d(TAG, "Requesting manual data refresh.");
//SyncHelper.requestManualSync(activeAccount);
}
/**
* Returns the navigation drawer item that corresponds to this Activity. Subclasses
* of BaseActivity override this to indicate what nav drawer item corresponds to them
* Return NAVDRAWER_ITEM_INVALID to mean that this Activity should not have a Nav Drawer.
*/
protected int getSelfNavDrawerItem() {
return NavigationDrawerFragment.MenuConstants.NAVDRAWER_ITEM_INVALID;
}
private void trySetupNavDrawer() {
int selfItem = getSelfNavDrawerItem();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (mDrawerLayout == null) {
return;
}
mDrawerLayout.setStatusBarBackgroundColor(
getResources().getColor(R.color.theme_accent_1_light));
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
if (selfItem == NavigationDrawerFragment.MenuConstants.NAVDRAWER_ITEM_INVALID) {
// do not show a nav drawer
if (mNavigationDrawerFragment != null) {
// ((ViewGroup) mNavigationDrawerFragment.getParent()).removeView(navDrawer);
}
mDrawerLayout = null;
return;
}
if (mNavigationDrawerFragment != null) {
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
mNavigationDrawerFragment.setAccount();
// what nav drawer item should be selected?
mNavigationDrawerFragment.setSelection(getSelfNavDrawerItem());
}
if (mActionBarToolbar != null) {
mActionBarToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
@Override
protected void onResume() {
super.onResume();
//clear invoice count and notifications
//clearNotification();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancelAll();
// Watch for sync state changes
mSyncStatusObserver.onStatusChanged(0);
final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING |
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver);
// reset selection to correct item when fragment becomes visible again
if (mNavigationDrawerFragment != null) {
mNavigationDrawerFragment.setSelection(getSelfNavDrawerItem());
}
AppEventsLogger.activateApp(this);
}
/* private void clearNotification() {
PrefUtils.setDebitBatchApproval(this, 0);
PrefUtils.setCreditBatchApproval(this, 0);
PrefUtils.setSettlementApproval(this, 0);
PrefUtils.setCreditBatch(this, 0);
PrefUtils.setDebitBatch(this, 0);
PrefUtils.setSettlement(this, 0);
PrefUtils.setAccounts(this, 0);
PrefUtils.setWorkflow(this, 0);
PrefUtils.setParticipants(this, 0);
}*/
@Override
public void onStart() {
super.onStart();
//EasyTracker.getInstance(this).activityStart(this);
}
@Override
public void onStop() {
super.onStop();
//EasyTracker.getInstance(this).activityStop(this);
}
@Override
protected void onPause() {
super.onPause();
if (mSyncObserverHandle != null) {
ContentResolver.removeStatusChangeListener(mSyncObserverHandle);
mSyncObserverHandle = null;
}
AppEventsLogger.deactivateApp(this);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// trySetupSwipeRefresh();
trySetupNavDrawer();
/*View mainContent = findViewById(R.id.container);
if (mainContent != null) {
mainContent.setAlpha(0);
mainContent.animate().alpha(1).setDuration(MAIN_CONTENT_FADEIN_DURATION);
} else {
Log.w(TAG, "No view with ID main_content to fade in.");
}*/
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
ActionBar actionbar = getSupportActionBar();
if (actionbar != null)
super.setTitle(mTitle); // was getting a stackover flow error from recursion
// then decided to call super
}
protected boolean isNavDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
}
protected void closeNavDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
}
@Override
public void onBackPressed() {
if (isNavDrawerOpen()) {
closeNavDrawer();
} else {
super.onBackPressed(); // is this really needed
if (getSelfNavDrawerItem() == NavigationDrawerFragment.MenuConstants.NAVDRAWER_ITEM_INVALID) {
super.onBackPressed();
} else if (getSelfNavDrawerItem() == NavigationDrawerFragment.MenuConstants.NAVDRAWER_ITEM_DASHBOARD) {
finish();
} else {
startActivity(new Intent(this, DashboardActivity.class));
finish();
}
}
}
protected Toolbar getActionBarToolbar() {
if (mActionBarToolbar == null) {
mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mActionBarToolbar != null) {
setSupportActionBar(mActionBarToolbar);
}
}
return mActionBarToolbar;
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
getActionBarToolbar();
}
private void registerGCMClient() {
// GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// gcm.register()
/* GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
//Reg on Google
final String regId = GCMRegistrar.getRegistrationId(this);
if (TextUtils.isEmpty(regId)) {
// Automatically registers application on startup.
GCMRegistrar.register(this, AppSettings.GCM_SENDER_ID);
} else {
// Device is already registered on GCM, needs to check if it is
// registered on our server as well.
if (ServerUtilities.isRegisteredOnServer(this)) {
// Skips registration.
LOGI(TAG, "Already registered on the C2DM server");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
mGCMRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
boolean registered = ServerUtilities.register(BaseActivity.this, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(BaseActivity.this);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
mGCMRegisterTask = null;
}
};
mGCMRegisterTask.execute(null, null, null);
}
Log.d(TAG, "Device's registration id is " + regId);
}*/
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mGCMRegisterTask != null) {
Log.d(TAG, "Cancelling GCM registration task.");
mGCMRegisterTask.cancel(true);
}
profileTracker.stopTracking();
/*try {
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.w(TAG, "C2DM unregistration error", e);
}*/
}
public void hideSoftKeyboard() {
if (getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.appevents.AppEventsLogger;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.helper.AccountUtils;
import com.jcedar.visibook.lautech.helper.PrefUtils;
import com.jcedar.visibook.lautech.helper.UIUtils;
public class ProfileActivity extends BaseActivity {
private Toolbar toolbar;
private ImageView imageView;
private TextView fullName, emailView, dobView, courseView, numberView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(AccountUtils.getUserName(this));
setSupportActionBar(toolbar);
imageView = (ImageView) findViewById(R.id.my_profile_image);
fullName = (TextView) findViewById(R.id.fullNameProfile);
emailView = (TextView) findViewById(R.id.tvEmailProfile);
dobView = (TextView ) findViewById(R.id.tvDateOfBirthProfile);
courseView = (TextView) findViewById(R.id.tvCourseSchool);
numberView = (TextView) findViewById(R.id.tvPhoneNumberProfile);
CollapsingToolbarLayout toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
toolbarLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
startActivity(new Intent(ProfileActivity.this, PicViewActivity.class));
return false;
}
});
Drawable d = new BitmapDrawable(getResources(), PrefUtils.getPhoto(this));
toolbarLayout.setStatusBarScrim(d);
toolbarLayout.setStatusBarScrimColor(UIUtils.getDominantColor(PrefUtils.getPhoto(this)));
//imageView.setImageBitmap(UIUtils.getProfilePic(this));
fullName.setText(AccountUtils.getUserName(this));
emailView.setText(
AccountUtils.getUserEmail(this)
!= null ?
AccountUtils.getUserEmail(this) : " ");
dobView.setText(
AccountUtils.getUserDOB(this) != null
? AccountUtils.getUserDOB(this) :
" ");
courseView.setText(
AccountUtils.getUserCourse(this) != null
? AccountUtils.getUserCourse(this)
: " "
+ "( "
+ AccountUtils.getUserChapter(this) != null
? AccountUtils.getUserChapter(this)
: " " +" )");
numberView.setText(AccountUtils.getUserPhoneNumber(this) != null ? AccountUtils.getUserPhoneNumber(this) : " ");
/* int colorr = UIUtils.getDominantColor( UIUtils.getProfilePic(this));
toolbar.setBackgroundColor(colorr);*/
//School shld contain Chapter and Course
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_profile, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// @Override
// protected int getSelfNavDrawerItem() {
// return NavigationDrawerFragment.MenuConstants.NAVDRAWER_ITEM_PROFILE;
// }
@Override
protected void onPause() {
super.onPause();
AppEventsLogger.activateApp(this);
}
@Override
protected void onResume() {
super.onResume();
AppEventsLogger.deactivateApp(this);
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.app.ProgressDialog;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphRequestAsyncTask;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.gcm.RegisterApp;
import com.jcedar.visibook.lautech.helper.AccountUtils;
import com.jcedar.visibook.lautech.helper.AppSettings;
import com.jcedar.visibook.lautech.helper.ServiceHandler;
import com.jcedar.visibook.lautech.helper.UIUtils;
import com.jcedar.visibook.lautech.io.jsonhandlers.StudentChapterHandler;
import com.jcedar.visibook.lautech.io.jsonhandlers.StudentHandler;
import com.jcedar.visibook.lautech.io.model.Student;
import com.jcedar.visibook.lautech.provider.DataContract;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import static com.jcedar.visibook.lautech.helper.AccountUtils.LoadProfileImage;
public class FbActivity extends FragmentActivity {
private static final String TAG = FbActivity.class.getSimpleName();
private LoginButton loginBtn;
private TextView username;
private ImageView imageView;
private boolean isEmailChecked = false;
private Button checkPhoneNumber;
GoogleCloudMessaging gcm;
String regid, email;
ServiceHandler serviceHandler;
boolean hasGoneToFb = false;
Context context = FbActivity.this;
private CallbackManager callbackManager;
ProgressDialog dialog ;
private ProfileTracker profileTracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
if (!AccountUtils.isFirstRun(this)) {
startActivity(new Intent(this, DashboardActivity.class));
finish();
}
serviceHandler = new ServiceHandler();
setContentView(R.layout.activity_fb);
dialog = new ProgressDialog(FbActivity.this);
checkPhoneNumber = (Button) findViewById(R.id.checkPhoneNumber);
try {
//For key hashes
PackageInfo info = getPackageManager().getPackageInfo(
getPackageName(),
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
callbackManager = CallbackManager.Factory.create();
final LoginButton loginButton = (LoginButton) findViewById(R.id.fb_login_button);
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
if(newProfile != null){
Log.e(TAG+" profile: ", newProfile.getName());
}
}
};
profileTracker.startTracking();
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
}
//loginButton.setReadPermissions(Arrays.asList(new String[]{"public_profile", "email"}));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.e(TAG, "confirming in login result");
if (AccessToken.getCurrentAccessToken() != null) {
RequestData();
}
}
@Override
public void onCancel() {
LoginManager.getInstance().logOut();
}
@Override
public void onError(FacebookException error) {
Log.e(TAG, error.getMessage());
}
});
//checkPhoneNumber.setVisibility(View.GONE);
checkPhoneNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText et = (EditText) findViewById(R.id.etPhoneNumber);
String phone = et.getText().toString().trim();
/*if (email.toLowerCase().contains("@") && UIUtils.isOnline(FbActivity.this)) {
//check db
Toast.makeText(FbActivity.this, "Verifying email, please wait", Toast.LENGTH_SHORT).show();
new CheckUserEmail(email).execute();
} else {
et.setError("Enter a valid email address");
}*/
if( phone.length() > 11){
et.setError("Enter a valid phone number");
}else {
new CheckUserEmail(email).execute();
}
}
});
if (UIUtils.isOnline(this)) {
// do this if email is checked and found
/* loginBtn.setReadPermissions(Arrays.asList("email", "user_friends"));
loginBtn.registerCallback(new LoginButton.UserInfoChangedCallback() {
@Override
public void onUserInfoFetched(GraphUser graphUser) {
if (graphUser != null) {
AccountUtils.setUserId(FbActivity.this, graphUser.getId());
AccountUtils.setUserName(FbActivity.this, graphUser.getName());
String photoUrl = "https://graph.facebook.com/" + graphUser.getId() + "/picture?type=large";
Log.e(TAG, graphUser.getId() + " get id");
hasGoneToFb = true;
try {
LoadProfileImage ll = new LoadProfileImage();
Bitmap bb = ll.execute(photoUrl).get();
UIUtils.setProfilePic(FbActivity.this, bb);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
GetAllData allData = new GetAllData();
allData.execute();
*//* AppHelper.pullAndSaveAllStudentData();
AppHelper.pullAndSaveStudentChapterData();*//*
startActivity(new Intent(FbActivity.this, DashboardActivity.class));
AccountUtils.setFirstRun(false, FbActivity.this);
FbActivity.this.finish();
}
}
});*/
}
}
private void RequestData1() {
GraphRequestAsyncTask request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e(TAG+" email", object.optString("email"));
}
}).executeAsync();
}
public void RequestData(){
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject jsonObject = response.getJSONObject();
try{
if(jsonObject != null){
Log.e(TAG, jsonObject.toString());
Log.e(TAG, object.toString());
getFacebookData(jsonObject);
}
}catch (JSONException e) {
e.printStackTrace();
}
//get users for school
GetAllData allData = new GetAllData();
allData.execute();
startActivity(new Intent(FbActivity.this, DashboardActivity.class));
AccountUtils.setFirstRun(false, FbActivity.this);
FbActivity.this.finish();
}
});
Bundle param = new Bundle();
param.putString("fields", "id, email, name, link, picture");
request.setParameters(param);
request.executeAsync();
}
public void getFacebookData(JSONObject object) throws JSONException{
String id = object.getString("id");
String photoUrl = "https://graph.facebook.com/" + id
+ "/picture?type=large";
try {
LoadProfileImage ll = new LoadProfileImage();
Bitmap bb = ll.execute(photoUrl).get();
UIUtils.setProfilePic(FbActivity.this, bb);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
String name;
if (object.has("first_name") && object.has("last_name")) {
String fName = object.getString("first_name");
String lName = object.getString("last_name");
name = lName + fName;
AccountUtils.setUserName(FbActivity.this, name);
}Log.e(TAG, "confirming email");
if (object.has("email")) {
String email = object.getString("email");
Log.e(TAG, "email is: "+email);
setEmail(email);
//get user's basic info
new CheckUserEmail(email).execute();
}
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
Log.e(TAG, "email is "+email);
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
public class GetAllData extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
if( dialog != null )
dialog.setMessage("Getting Required Data....");
}
public GetAllData() {
}
@Override
protected Void doInBackground(Void... params) {
String result = "";
StudentChapterHandler ss1 = new StudentChapterHandler(context);
try {
String response = ServiceHandler.makeServiceCall
(AppSettings.SERVER_URL + "get_all_students.php", ServiceHandler.GET);
if (response == null) {
dialog.dismiss();
return null;
}
Log.e(TAG, response + " response");
ArrayList<ContentProviderOperation> operations =
new StudentHandler(context).parse(response);
if (operations.size() > 0) {
ContentResolver resolver = context.getContentResolver();
resolver.applyBatch(DataContract.CONTENT_AUTHORITY, operations);
}
} catch (IOException | OperationApplicationException | RemoteException e) {
e.printStackTrace();
}
try {
String chapter = "";
if (AccountUtils.getUserChapter(context) != null) {
chapter = AccountUtils.getUserChapter(context);
}
Log.e(TAG, "starting student chapter data response");
String response = ServiceHandler.makeServiceCall
(AppSettings.SERVER_URL + "get_user_chapter.php?chapter=" + chapter,
ServiceHandler.GET);
if (response == null) {
return null;
}
Log.e(TAG, response + " response");
ArrayList<ContentProviderOperation> operations = ss1.parse(response);
if (operations.size() > 0) {
ContentResolver resolver = context.getContentResolver();
resolver.applyBatch(DataContract.CONTENT_AUTHORITY, operations);
}
} catch (IOException | OperationApplicationException | RemoteException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
if ((dialog != null) && dialog.isShowing()) {
dialog.dismiss();
}
} catch (final Exception e) {
// Handle or log or ignore
} finally {
dialog = null;
}
}
}
public class CheckUserEmail extends AsyncTask<Void, Void, String> {
String emailS;
public CheckUserEmail(String email) {
emailS = email;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Verifying email address....");
dialog.setTitle("Please Wait");
dialog.setCancelable(false);
dialog.setIndeterminate(true);
dialog.show();
}
@Override
protected String doInBackground(Void... params) {
String result = "";
try {
String url = AppSettings.SERVER_URL + "check_user.php?phone_number=" + emailS;
result = ServiceHandler.makeServiceCall(url, ServiceHandler.GET);
Log.e(TAG, result + " json");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String jsonString) {
super.onPostExecute(jsonString);
Object json;
JSONObject jsonObject;
try {
json = new JSONTokener(jsonString).nextValue();
if (json instanceof JSONObject) {
//you have an object
jsonObject = new JSONObject(jsonString);
String ss = jsonObject.getString("status");
switch (ss) {
case "404":
Toast.makeText(FbActivity.this,
emailS + " is not found in the database", Toast.LENGTH_SHORT).show();
if (dialog.isShowing())
dialog.dismiss();
break;
case "101":
Toast.makeText(FbActivity.this,
"Enter a valid email address", Toast.LENGTH_SHORT).show();
if (dialog.isShowing())
dialog.dismiss();
break;
default:
break;
}
return;
} else if (json instanceof JSONArray) {
//you have an array
parseUserJson(jsonString);
isEmailChecked = true;
//loginBtn.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if ((dialog != null) && dialog.isShowing()) {
dialog.dismiss();
}
} catch (final Exception e) {
// Handle or log or ignore
} finally {
dialog = null;
}
}
}
@Override
protected void onResume() {
super.onResume();
AppEventsLogger.activateApp(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
AppEventsLogger.deactivateApp(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public void parseUserJson(String json) {
if (json == null) {
return;
}
Log.d(TAG, TextUtils.isEmpty(json) ? "Empty Student Json" : json);
Student[] student = Student.fromJson(json);
try {
AccountUtils.setId(this, student[0].getId());
AccountUtils.setUserGender(this, student[0].getGender());
AccountUtils.setUserChapter(this, student[0].getChapter());
AccountUtils.setUserEmail(this, student[0].getEmail());
AccountUtils.setUserCourse(this, student[0].getCourse());
AccountUtils.setUserPhoneNumber(this, student[0].getPhoneNumber());
AccountUtils.setUserDOB(this, student[0].getDateOfBirth());
Boolean b = Boolean.getBoolean(student[0].getIsAlumni());
AccountUtils.setIsAlumni(this, b);
Log.e(TAG, student[0].getChapter() + " chapter");
} catch (Exception e) {
e.printStackTrace();
} finally {
Log.d(TAG, "inside finally block!!!");
if (UIUtils.checkPlayServices(this)) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
regid = AccountUtils.getRegistrationId(getApplicationContext());
Log.e(TAG, regid);
if (regid.isEmpty()) {
new RegisterApp(getApplicationContext(), gcm, UIUtils.getAppVersion(getApplicationContext())).execute();
} else {
Toast.makeText(getApplicationContext(), "Device already Registered", Toast.LENGTH_SHORT).show();
}
} else {
Log.d(TAG, "No valid Google Play Services APK found.");
}
}
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.io.adapters.StudentCursorAdapter;
import com.jcedar.visibook.lautech.provider.DataContract;
public class SearchFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<Cursor>{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String TAG = SearchFragment.class.getSimpleName();
private static final String _POSITION = "POSITION";
private Listener mListener;
StudentCursorAdapter studentListAdapter;
Uri dataUri;
TextView error;
public SearchFragment() {
// Required empty public constructor
}
public static AllStudentListFragment newInstance(int position) {
AllStudentListFragment fragment = new AllStudentListFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, position);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
studentListAdapter = new StudentCursorAdapter(getActivity(), null, R.layout.list_n_item_student);
setListAdapter( studentListAdapter );
setHasOptionsMenu(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(2, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
ViewGroup rootView;
rootView =
(ViewGroup) inflater.inflate(R.layout.fragment_search, container, false);
ListView listView = (ListView) rootView.findViewById(android.R.id.list );
error = (TextView) rootView.findViewById(R.id.tvErrorMag);
listView.setItemsCanFocus(true);
listView.setDividerHeight(0);
listView.setCacheColorHint(Color.WHITE);
listView.setSelector(R.drawable.list_selector);
TextView emptyView = new TextView(getActivity(), null, android.R.attr.state_empty);
((ViewGroup) rootView.findViewById(android.R.id.empty)).addView(emptyView);
/* setOnItemClickListener(new RecyclerCursorAdapterAll.OnItemClickListener() {
@Override
public void onItemClicked(Cursor data) {
long Id = data.getLong(
data.getColumnIndex(DataContract.Students._ID));
Log.d(TAG, "selectedId = " + Id + _POSITION);
mListener.onListItemSelected(Id);
}
});*/
return rootView;
}
public void onButtonPressed(long id) {
if (mListener != null) {
mListener.onListItemSelected(id);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Listener) {
mListener = (Listener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement onListItemSelected");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri studenturi;
/*if( args != null) {
String uri = args.getString("uri");
studenturi = Uri.parse(uri);
Log.e(TAG, studenturi +" uri in oncreateloader");
} else {
studenturi = DataContract.Students.CONTENT_URI;
Log.e(TAG, studenturi +" uri in oncreateloader no bundle");
}
*/
Loader<Cursor> cursorLoader;
if (dataUri != null ){
Log.e(TAG, dataUri +" dataUri inside loader");
cursorLoader = new CursorLoader(getActivity(), dataUri,
DataContract.Students.PROJECTION_ALL,
null, null, DataContract.Students.NAME +" ASC");
return cursorLoader;
}
else {
cursorLoader = new CursorLoader(getActivity(), DataContract.Students.CONTENT_URI,
DataContract.Students.PROJECTION_ALL,
null, null, DataContract.Students.SORT_ORDER_DEFAULT);
}
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
studentListAdapter.swapCursor(data);
data.moveToFirst();
Log.e(TAG, data.getCount() +" cursor value");
if ( data.getCount() == 0){
error.setVisibility(View.VISIBLE);
error.setText("No result found");
}
/*while ( !data.isAfterLast()){
data.moveToNext();
} */
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
public void reloadFromArguments(Uri uri, String query) {
Log.d(TAG, "reloading fragment");
// Load new arguments
if(uri.toString() != null) {
Uri studenturi = uri;
dataUri = studenturi;
/*if (studenturi == null) {
studenturi = DataContract.Students.CONTENT_URI;
}*/
Log.e(TAG, studenturi.toString() + " uri search");
Bundle arguments = new Bundle();
arguments.putString("uri", studenturi.toString());
if(isAdded()){
getLoaderManager().restartLoader(2, arguments, this);
/*Cursor c = new DatabaseHelper(getActivity()).getSearch(query);
if (c.moveToFirst()) {
studentListAdapter.swapCursor(c);
Log.e(TAG, "I got something for "+query);
}c.close();*/
}
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (isAdded()){
Cursor cursor = (Cursor) studentListAdapter.getItem(position);
if( cursor != null ){
long studentId = cursor.getLong(
cursor.getColumnIndex( DataContract.Students._ID)
);
mListener.onListItemSelected(studentId);
}
}
}
public interface Listener {
void onListItemSelected(long studentId);
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.gcm.RegisterApp;
import com.jcedar.visibook.lautech.helper.AccountUtils;
import com.jcedar.visibook.lautech.helper.AppHelper;
import com.jcedar.visibook.lautech.helper.AppSettings;
import com.jcedar.visibook.lautech.helper.PrefUtils;
import com.jcedar.visibook.lautech.helper.ServiceHandler;
import com.jcedar.visibook.lautech.helper.UIUtils;
import com.jcedar.visibook.lautech.io.model.Student;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.InputStream;
import static com.jcedar.visibook.lautech.helper.PrefUtils.setPhoto;
/**
* Created by oluwafemi.bamisaye on 3/26/2016.
*/
public class GoogleSignIn extends FragmentActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {
private static final String TAG = GoogleSignIn.class.getSimpleName();
private Button checkPhoneNumber;
private SignInButton btnSignIn;
// CircularProgressButton btEnter;
private static int RC_SIGN_IN = 0;
private boolean isEmailChecked = false;
ProgressDialog dialog;
GoogleCloudMessaging gcm;
String regid, email;
Context context = GoogleSignIn.this;
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
String personPhotoUrl,personName;
static Bitmap bResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!AccountUtils.isFirstRun(this)) {
startActivity(new Intent(this, NewDashBoardActivity.class));
finish();
}
setContentView(R.layout.activity_google_signin);
dialog = new ProgressDialog(GoogleSignIn.this);
checkPhoneNumber = (Button) findViewById(R.id.checkPhoneNumber);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignIn.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// [END build_client]
checkPhoneNumber.setOnClickListener(this);
}
@Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
Log.d(TAG, "Got cached sign-in");
Intent dashbIntent = new Intent(this, NewDashBoardActivity.class);
dashbIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(dashbIntent);
}
}
private void signIn() {
ConnectivityManager cm =
(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (!isConnected){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No Internet Connectivity detected! Check your Internet Connectivity settings")
.setCancelable(false)
.setPositiveButton("Check Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(Settings.ACTION_SETTINGS));
}
})
.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
return;
}else
startActivityForResult(signInIntent, RC_SIGN_IN);
btnSignIn.setVisibility(View.GONE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("TEST", " is result code 0?: " + resultCode);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
if( acct != null) {
getUsersGoogleDetails(acct);
}
} else {
// Signed out, show unauthenticated UI.
Toast.makeText(this, "Ensure you are connected to a Network to be able to Sign In",Toast.LENGTH_SHORT).show();
RC_SIGN_IN++;
if (dialog != null){
dialog.dismiss();
}
btnSignIn.setVisibility(View.VISIBLE);
}
}
private void getUsersGoogleDetails(GoogleSignInAccount acct) {
String emailPref = acct.getEmail();
Log.d(TAG, " Handle signIn email of user" + emailPref);
PrefUtils.setEmail(this, emailPref);
//save Acct Name
String namePref = acct.getDisplayName();
PrefUtils.setPersonKey(this, namePref);
Uri mPhoto = acct.getPhotoUrl();
if (mPhoto != null) {
personPhotoUrl = mPhoto.toString();
Log.e(TAG, "Profile Image" + personPhotoUrl);
personPhotoUrl = personPhotoUrl.substring(0, personPhotoUrl.length() - 2) + PROFILE_PIC_SIZE;
new LoadProfileImage().execute(personPhotoUrl);
} else {
Bitmap def = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_default_user);
setPhoto(this, def);
UIUtils.setProfilePic(this, def);
}
new CheckUserEmail(emailPref).execute();
}
public class CheckUserEmail extends AsyncTask<Void, Void, String> {
String emailS;
public CheckUserEmail(String email) {
emailS = email;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Verifying email address....");
dialog.setTitle("Please Wait");
dialog.setCancelable(false);
dialog.setIndeterminate(true);
dialog.show();
}
@Override
protected String doInBackground(Void... params) {
String result = "";
try {
String url = AppSettings.SERVER_URL + "check_email.php?email=" + emailS;
result = ServiceHandler.makeServiceCall(url, ServiceHandler.GET);
Log.e(TAG, result + " json");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String jsonString) {
super.onPostExecute(jsonString);
Object json;
JSONObject jsonObject;
try {
json = new JSONTokener(jsonString).nextValue();
if (json instanceof JSONObject) {
//you have an object
Log.e(TAG, "json is json object "+jsonString);
jsonObject = new JSONObject(jsonString);
String ss = jsonObject.getString("status");
switch (ss) {
case "404":
Toast.makeText(GoogleSignIn.this,
emailS + " is not found in the database", Toast.LENGTH_SHORT).show();
if (dialog.isShowing())
dialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(GoogleSignIn.this);
builder.setMessage("Your email address is not registered on the server")
.setCancelable(false)
.setNeutralButton("Close App", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
case "101":
Toast.makeText(GoogleSignIn.this,
"Enter a valid email address", Toast.LENGTH_SHORT).show();
if (dialog.isShowing())
dialog.dismiss();
break;
default:
break;
}
return;
} else if (json instanceof JSONArray) {
//you have an array
Log.e(TAG, "json is json array "+jsonString);
parseUserJson(jsonString);
isEmailChecked = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if ((dialog != null) && dialog.isShowing()) {
dialog.dismiss();
}
} catch (final Exception e) {
// Handle or log or ignore
} finally {
dialog = null;
}
}
}
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
Bitmap bitmap = GoogleSignIn.bResult;
public LoadProfileImage() {
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if( dialog != null )
dialog.setMessage("Getting Required Data....");
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
Thread.sleep(1000);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
Log.e(TAG, "Bitmap returned" + mIcon11);
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
this.bitmap=result;
Log.e(TAG, "ONPOSTEXECUTE result " +result);
if (result != null){
setPhoto(GoogleSignIn.this, result);
UIUtils.setProfilePic(GoogleSignIn.this, result);
String m = PrefUtils.encodeTobase64(result);
Log.e(TAG, "Encoded Profile image " + m);
enterDashBoard();
}else {
}
}
}
public void parseUserJson(String json) {
if (json == null) {
return;
}
Log.d(TAG, TextUtils.isEmpty(json) ? "Empty Student Json" : json);
Student[] student = Student.fromJson(json);
try {
AccountUtils.setId(this, student[0].getId());
AccountUtils.setUserGender(this, student[0].getGender());
AccountUtils.setUserChapter(this, "Lautech");
//AccountUtils.setUserChapter(this, student[0].getChapter());
AccountUtils.setUserEmail(this, student[0].getEmail());
AccountUtils.setUserCourse(this, student[0].getCourse());
AccountUtils.setUserPhoneNumber(this, student[0].getPhoneNumber());
AccountUtils.setUserDOB(this, student[0].getDateOfBirth());
AccountUtils.setUserDOBNumber(this, student[0].getDobNumber());
Boolean b = Boolean.getBoolean(student[0].getIsAlumni());
AccountUtils.setUserName(this, student[0].getName());
String imageString = student[0].getImage();
if(imageString != null) {
//ToDo get image for this user
String url = String.format(AppSettings.SERVER_IMAGE_URL+"%s.png", student[0].getId());
new LoadProfileImage().execute(url);
}
AccountUtils.setIsAlumni(this, b);
Log.e(TAG, student[0].getChapter() + " chapter "+student[0].getId());
} catch (Exception e) {
e.printStackTrace();
} finally {
Log.d(TAG, "inside finally block!!!");
if (UIUtils.checkPlayServices(this)) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
regid = AccountUtils.getRegistrationId(getApplicationContext());
Log.e(TAG, regid);
if (regid.isEmpty()) {
new RegisterApp(getApplicationContext(), gcm, UIUtils.getAppVersion(getApplicationContext())).execute();
} else {
Toast.makeText(getApplicationContext(), "Device already Registered", Toast.LENGTH_SHORT).show();
}
} else {
Log.d(TAG, "No valid Google Play Services APK found.");
}
}
new GetAllData().execute();
enterDashBoard();
}
public class GetAllData extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
if( dialog != null )
dialog.setMessage("Getting Required Data....");
}
public GetAllData() {
}
@Override
protected Void doInBackground(Void... params) {
AppHelper.pullAndSaveAllStudentData(context);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
if ((dialog != null) && dialog.isShowing()) {
dialog.dismiss();
}
} catch (final Exception e) {
// Handle or log or ignore
} finally {
dialog = null;
}
}
}
@Override
public void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
public void enterDashBoard() {
startActivity(new Intent(GoogleSignIn.this, NewDashBoardActivity.class));
AccountUtils.setFirstRun(false, GoogleSignIn.this);
GoogleSignIn.this.finish();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_sign_in:
signIn();
break;
}
}
private void signOutUser() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
// [START_EXCLUDE]
// updateUI(false);
// [END_EXCLUDE]
}
});
btnSignIn.setVisibility(View.VISIBLE);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.helper.UIUtils;
import com.jcedar.visibook.lautech.provider.DataContract;
public class Details extends AppCompatActivity implements View.OnClickListener {
Toolbar toolbar;
private ImageView imgSendEmail, imgSendSms, imgCall;
private TextView name, gender, chapter, email, course, phoneNumber, dateOfBirth, description;
private String nameStr, emailAdd, phone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_up);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
imgSendEmail = (ImageView) findViewById(R.id.send_email);
imgSendSms = (ImageView) findViewById(R.id.send_message);
imgCall = (ImageView) findViewById(R.id.call_phone);
imgCall.setOnClickListener(this);
imgSendSms.setOnClickListener(this);
imgSendEmail.setOnClickListener(this);
name = (TextView) findViewById(R.id.tvName);
gender = (TextView) findViewById(R.id.tvGender);
chapter = (TextView) findViewById(R.id.tvChapter);
email = (TextView) findViewById(R.id.tvEmail);
course = (TextView) findViewById(R.id.tvCourse);
phoneNumber = (TextView) findViewById(R.id.tvPhoneNumber);
dateOfBirth = (TextView) findViewById(R.id.tvDateOfBirth);
description = (TextView) findViewById(R.id.tvDescription);
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
nameStr = bundle.getString(DataContract.StudentsChapter.NAME);
name.setText(nameStr);
new Handler().post(new Runnable() {
@Override
public void run() {
toolbar.setTitle(nameStr);
}
});
String genderStr1 = bundle.getString(DataContract.StudentsChapter.GENDER);
if (genderStr1.equalsIgnoreCase("M"))
gender.setText("Male");
else if (genderStr1.equalsIgnoreCase("F"))
gender.setText("Female");
chapter.setText(bundle.getString(DataContract.StudentsChapter.CHAPTER));
emailAdd = bundle.getString(DataContract.StudentsChapter.EMAIL);
email.setText(emailAdd);
course.setText(bundle.getString(DataContract.StudentsChapter.COURSE));
phone = bundle.getString(DataContract.StudentsChapter.PHONE_NUMBER);
phoneNumber.setText(phone);
dateOfBirth.setText(bundle.getString(DataContract.StudentsChapter.DATE_OF_BIRTH));
}
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.call_phone:
Log.e("TAG", "Name " + nameStr);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Call")
.setMessage("Do you want to make a call to " + nameStr + "?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (phone != null) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phone));
if (ActivityCompat.checkSelfPermission(Details.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startActivity(callIntent);
} else {
UIUtils.showToast(Details.this, "No number to call");
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
break;
case R.id.send_message:
AlertDialog dialog1 = new AlertDialog.Builder(this)
.setTitle("Call")
.setMessage("Do you want to send a message to "+nameStr +"?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (phone != null) {
Uri smsUri = Uri.parse("tel:" + phone);
Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
intent.putExtra("address", phone);
intent.putExtra("sms_body", "");
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
} else {
UIUtils.showToast(Details.this, "No message recipient");
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
break;
case R.id.send_email:
if (emailAdd != null) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", emailAdd, null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else {
Toast.makeText(this, "User has no email", Toast.LENGTH_LONG).show();
}
break;
}
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.io.adapters.UpdateCursorAdapter;
import com.jcedar.visibook.lautech.provider.DataContract;
public class AddUpdateFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private static final String TAG = AddUpdateFragment.class.getSimpleName();
UpdateCursorAdapter updateCursorAdapter;
ListView listView;
private Toolbar toolbar;
private Listener mCallback;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.layout_add_update, container, false);
listView = (ListView) view.findViewById(android.R.id.list);
listView.setItemsCanFocus(true);
listView.setDividerHeight(0);
listView.setVerticalScrollBarEnabled(false);
updateCursorAdapter = new UpdateCursorAdapter(getActivity(), null, R.layout.list_item_update);
listView.setAdapter( updateCursorAdapter );
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Cursor cursor = ((UpdateCursorAdapter) parent.getAdapter()).getCursor();
if(cursor != null) {
cursor.moveToPosition(position);
long student_id = cursor.getLong(
cursor.getColumnIndex(DataContract.StudentsChapter._ID));
UpdateFragment updateFragment = UpdateFragment.newInstance( student_id );
updateFragment.show( getFragmentManager(), "Update Dialog Fragment");
}
}
});
new Handler().post(new Runnable() {
@Override
public void run() {
getActivity().setTitle("Update Names");
}
});
setHasOptionsMenu(true);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoaderManager().initLoader(0, null, this);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_update, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if ( id == R.id.action_update ){
startActivity( new Intent( getActivity(), AddActivity.class));
}
return super.onOptionsItemSelected(item);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = DataContract.Students.CONTENT_URI;
return new CursorLoader(
getActivity(),
uri,
DataContract.Students.PROJECTION_ALL,
null,
null,
null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
updateCursorAdapter.swapCursor( data );
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
updateCursorAdapter.swapCursor(null);
}
interface Listener {
void onFragmentDetached(Fragment fragment);
void onFragmentAttached(Fragment fragment);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Listener) {
mCallback = (Listener) activity;
mCallback.onFragmentAttached(this);
} else {
throw new ClassCastException(activity.toString()
+ " must implement fragments listener");
}
}
@Override
public void onDetach() {
super.onDetach();
super.onDetach();
if (getActivity() instanceof Listener) {
((Listener) getActivity()).onFragmentDetached(this);
}
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.facebook.appevents.AppEventsLogger;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.provider.DataContract;
import java.util.ArrayList;
public class StudentDetailsActivity extends BaseActivity
implements StudentListFragment.Listener, StudentDetailsFragment.DetailsListener{
//ViewPagerAdapter detailsAdapter;
StudentListFragment mFragment = null;
private static final String TAG = StudentDetailsActivity.class.getSimpleName();
public ArrayList<Long> mStudents;
private ViewPager mPager;
Uri mSelectedStudent;
String phoneNumber, emailAddress, name;
boolean dualPanel;
public static String ARG_STUDENT_LIST = "ARG_STUDENT_LIST";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_details);
dualPanel = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
Intent intent = getIntent();
mSelectedStudent = intent.getData();
StudentDetailsFragment fragment = StudentDetailsFragment.newInstance(mSelectedStudent, this);
getSupportFragmentManager().beginTransaction()
.add(R.id.details, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
if ( dualPanel ){
if (getResources().getConfiguration().smallestScreenWidthDp <= 600) {
mFragment =
(StudentListFragment) getSupportFragmentManager()
.findFragmentById(R.id.studentFrag);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
mFragment =
(StudentListFragment) getSupportFragmentManager()
.findFragmentById(R.id.studentFrag);
}
}
/* if (findViewById(R.id.payItemDetailsPane) != null) {
mFragment =
(StudentDetailsFragment) getSupportFragmentManager()
.findFragmentById(R.id.studentDetailFrag);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Intent intent = getIntent();
if(intent != null){
mSelectedStudent = intent.getData();
if( mSelectedStudent == null ) {
return;
}
Bundle payItemBundle = intent.getBundleExtra(ARG_STUDENT_LIST);
if(payItemBundle != null){
mStudents = convertToArray(payItemBundle, ARG_STUDENT_LIST);
Log.d(TAG, "Student id bundle is not null: "
+ UIUtils.bundle2string(payItemBundle) + " "+mStudents);
}else {
Log.d(TAG, "Student id Bundle is null");
}
}
detailsAdapter = new ViewPagerAdapter(getSupportFragmentManager(),
mStudents.size());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(detailsAdapter);
int selectedIndex = mStudents.indexOf(
Long.parseLong(mSelectedStudent.getLastPathSegment()));
mPager.setCurrentItem(selectedIndex);
*/
final Toolbar toolbar = getActionBarToolbar();
if(toolbar == null) return;
toolbar.setNavigationIcon(R.drawable.ic_up);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
new Handler().post(new Runnable() {
@Override
public void run() {
toolbar.setTitle("Details");
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void fabClicked (View v){
int id = v.getId();
switch (id){
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_student_details, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSchoolSelected(long studentId) {
Log.d(TAG, studentId +" courseId");
/*mPager.setCurrentItem(mStudents.indexOf(courseId), true);*/
Uri uri = DataContract.StudentsChapter.buildStudentUri(studentId);
StudentDetailsFragment fragment = StudentDetailsFragment.newInstance(uri, this);
getSupportFragmentManager().beginTransaction()
.add(R.id.details, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
}
@Override
public void onFragmentAttached(Fragment fragment) {
}
@Override
public void onFragmentDetached(Fragment fragment) {
}
@Override
public void getUserData(String phoneNumber, String emailAddress, String name) {
setPhoneNumber(phoneNumber);
setEmailAddress(emailAddress);
setName(name);
}
/* private class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final int mSize;
public ViewPagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
Log.d( TAG, "Calling "+ViewPagerAdapter.class.getSimpleName());
}
@Override
public Fragment getItem(int position) {
return StudentDetailsFragment.newInstance(position, StudentDetailsActivity.this);
}
@Override
public int getCount() {
return mSize;
}
}*/
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected void onPause() {
super.onPause();
AppEventsLogger.activateApp(this);
}
@Override
protected void onResume() {
super.onResume();
AppEventsLogger.deactivateApp(this);
}
}
<file_sep>package com.jcedar.visibook.lautech.ui;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.jcedar.visibook.lautech.R;
import com.jcedar.visibook.lautech.helper.PrefUtils;
public class Settings extends AppCompatActivity
implements SharedPreferences.OnSharedPreferenceChangeListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (toolbar != null) {
toolbar.setNavigationIcon(R.drawable.ic_up);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
new Handler().post(new Runnable() {
@Override
public void run() {
if (toolbar != null) {
toolbar.setTitle(getString(R.string.title_activity_settings));
}
}
});
loadPreferences();
getFragmentManager().beginTransaction()
.add(R.id.container, new Preference())
.commit();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
loadPreferences();
}
private void loadPreferences() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean notificationState = settings.getBoolean(PrefUtils.NOTIFY_KEY, true);
settings.registerOnSharedPreferenceChangeListener(Settings.this);
}
}
|
310310843587eaaa2f928253a466206f50705649
|
[
"Java"
] | 22
|
Java
|
ph3mmy/Visibook
|
1c4facbc34cbe223b0ceb8d56565ccc88ff306af
|
cc7f2d33ec3328cc71e8dd256da299e4b9f89df0
|
refs/heads/master
|
<repo_name>AndresRendon1/mains_p3_info<file_sep>/main_decodificador.cpp
#include <iostream>
#include<fstream>
#include<math.h>
using namespace std;
//VARIABLES GLOBALES
fstream archivo_lectura,archivo_escritura;
int semilla;//valor en el que se va a dividir el binario para ser codificado
int numfilas;//numero de filas del archivo
int i;//variable que nos servira para capturar los caracteres del archivo
int numcaracteres;//variable que nos ayudara a identificar el numero de caracteres en el archivo
int ascii[3000]={};//arreglo para convertir las letras a ascii
int binario[3000]={};//arreglo para convertir los valores ascii a binario
string nombre,texto,contenido;
//PROTOTIPO DE FUNCIONES
void convertir_binario(int a, int b[]);
int contador_0s_1s(string a);
string igual_cantidad_0s_1s(string a, string b);
string mayor_cantidad1s(string a,string b);
string mayor_cantidad0s(string a, string b);
void decodificacion_metodo1();
int valor_ascii(string a);
void convertir_a_caracter();
int main()
{
cout << "Bienvenido al decodificador" << endl;
cout<<"Ingrese el nombre del archivo codificado que desea abrir: ";cin>>nombre;
archivo_lectura.open(nombre+".txt",ios::in);//abrir en modo lectura
if(archivo_lectura.is_open()){
cout<<" ->El archivo '"<<nombre<<".txt' ha sido cargado correctamente."<<endl<<endl;
while (!archivo_lectura.eof()){
getline(archivo_lectura,texto);
cout<<"El contenido del archivo '"<<nombre<<".txt' es: "<<endl<<texto<<endl<<endl;
}
archivo_lectura.close();
decodificacion_metodo1();
convertir_a_caracter();
}
return 0;
}
void convertir_binario(int a, int b[]){ //listo
int i=0;
int binario[8]={0,0,0,0,0,0,0,0};
while(a!=1){
binario[i]=a%2;
a=a/2;
i++;
}
binario[i]=a; // a siempre va a ser igual a 1
for(int j=7,i=0;j>=0;j--,i++){
b[i]=binario[j];
}
}
int contador_0s_1s(string a){ //listo
int tam,cont1=0,cont0=0;
tam=a.length();
for(int i=0;i<tam;i++){
if(a[i]=='1'){
cont1++;
}
else if(a[i]=='0'){
cont0++;
}
}
if(cont1>cont0){
return 1;
}
else if(cont0>cont1){
return 0;
}
else {
return 4;
}
}
string igual_cantidad_0s_1s(string a, string b){ //listo
int tam=0;
tam=a.length();
for(int i=0;i<tam;i++){
if(a[i]=='1'){b[i]='0';}
else if(a[i]=='0'){b[i]='1';}
}
return b;
}
string mayor_cantidad1s(string a, string b){ //listo
int tam=0;
tam=a.length();
for(int i=2;i<tam;i+=2){
if(a[i]=='0'){b[i]='1';}
else{b[i]='0';}
}
return b;
}
string mayor_cantidad0s(string a, string b){ //listo
int tam=0;
tam=a.length();
for(int i=1;i<tam;i+=2){
if(a[i]=='0'){b[i]='1';}
else{b[i]='0';}
}
return b;
}
void decodificacion_metodo1(){
string cadena,bin_modificado,bloque1,bloque2,nombre;
cout<<"Ingrese el nombre del archivo codificado que desea decodificar: ";
cin>>nombre;
archivo_lectura.open(nombre+".txt",ios::in);
if(archivo_lectura.is_open()){
cout<<" ->El archivo '"<<nombre<<".txt' ha sido cargado correctamente."<<endl<<endl;
while (!(archivo_lectura.eof())) {
archivo_lectura>>cadena;
}
cout<<"Ingrese nombre de salida para el archivo binario decodificado: ";cin>>nombre;
cout<<"Ingrese el valor de la semilla: ";cin>> semilla;
cout<<endl;
archivo_escritura.open(nombre+".txt",ios::out);
int tam=cadena.length();
bloque1=cadena.substr(0,semilla);
bin_modificado=igual_cantidad_0s_1s(bloque1,bloque1);
archivo_escritura<<bin_modificado;
for(int i=0;i<tam;i+=semilla){
if(contador_0s_1s(bin_modificado)==1){
bloque2=cadena.substr((i+semilla),semilla);
bin_modificado=mayor_cantidad1s(bloque2,bloque2);
archivo_escritura<<bin_modificado;
bloque1=bloque2;
}
else if(contador_0s_1s(bin_modificado)==0){
bloque2=cadena.substr((i+semilla),semilla);
bin_modificado=mayor_cantidad0s(bloque2,bloque2);
archivo_escritura<<bin_modificado;
bloque1=bloque2;
}
else if(contador_0s_1s(bin_modificado)==4){
bloque2=cadena.substr((i+semilla),semilla);
bin_modificado=igual_cantidad_0s_1s(bloque2,bloque2);
archivo_escritura<<bin_modificado;
bloque1=bloque2;
}
}
}
else{
cout<<"Lo siento,el archivo '"<<nombre<<"' no se pudo decodificar."<<endl;
}
archivo_escritura.close();
archivo_lectura.close();
}
void convertir_a_caracter(){
string nombre, subcadena,cadena,final;
int letras;
cout<<"Ingrese el nombre del archivo binario que desea abrir: ";cin>>nombre;
archivo_lectura.open(nombre+".txt",ios::in);
if(archivo_lectura.is_open()){
cout<<" ->El archivo '"<<nombre<<".txt' ha sido cargado correctamente."<<endl<<endl;
cout<<"Ingrese el nombre para el archivo de salida con el texto decodificado: ";cin>>nombre;
while (!(archivo_lectura.eof())) {
archivo_lectura>>cadena;
}
archivo_escritura.open(nombre+".txt",ios::out);
int tam=cadena.length();
for(int j=0; j<tam; j+=8){
subcadena=cadena.substr(j,8);
letras=valor_ascii(subcadena);
archivo_escritura<<(char)letras;
}cout<<" ->EL archivo '"<<nombre<<"' ha sido creado correctamente\n"<<endl;
}
else{
cout<<"Hubo un problema al cargar el archivo."<<endl;
}
archivo_lectura.close();
archivo_escritura.close();
}
int valor_ascii (string a){
int ascii=0;
for (int i=0,j=7; i<8; i++, j--){
ascii+=(((int)a[i])-48)*(pow(2,j));
}
return ascii;
}
<file_sep>/main_codificador.cpp
#include <iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
//VARIABLES GLOBALES
fstream archivo_lectura,archivo_escritura;
int semilla;//valor en el que se va a dividir el binario para ser codificado
int numfilas;//numero de filas del archivo
int i;//variable que nos servira para capturar los caracteres del archivo
int numcaracteres;//variable que nos ayudara a identificar el numero de caracteres en el archivo
int ascii[3000]={};//arreglo para convertir las letras a ascii
int binario[3000]={};//arreglo para convertir los valores ascii a binario
string nombre,texto,contenido;
//PROTOTIPO DE FUNCIONES
void convertir_binario(int a, int b[]);
int contador_0s_1s(string a);
string igual_cantidad_0s_1s(string a, string b);
string mayor_cantidad1s(string a,string b);
string mayor_cantidad0s(string a, string b);
void metodo_codificacion1();
int main()
{
cout<<"Bienvenido al codificador"<<endl<<endl;
cout << "Ingresa el nombre del archivo que deseas abrir: ";
cin>>nombre;
archivo_lectura.open(nombre+".txt",ios::in);
if(archivo_lectura.is_open()){
cout<<"El archivo se cargo sactisfactoriamente"<<endl<<endl;
cout<<"El contenido del archivo es: "<<endl<<endl;
while(!archivo_lectura.eof()){
getline(archivo_lectura,contenido);
texto+=contenido+'\n';
numfilas++;
}
cout<<texto<<endl;
cout<<endl<<"El archivo tiene "<<numfilas<<" filas"<<endl;
archivo_lectura.close();
archivo_lectura.open(nombre+".txt",ios::in);
while(!archivo_lectura.eof()){
ascii[i]=archivo_lectura.get();
i++;
}
numcaracteres=--i;
cout<<endl<<"la cantidad de caracteres es: "<<numcaracteres<<endl<<endl;
archivo_lectura.close();
archivo_escritura.open("archivo_binario.txt",ios::out);
for(int j=0; j<numcaracteres;j++){
convertir_binario(ascii[j],binario);
for(int i=0;i<8;i++){
archivo_escritura<<binario[i];
}
}
archivo_escritura.close();
cout<<"->encriptando...."<<endl<<endl;
metodo_codificacion1();
}
else if(!archivo_lectura.is_open()){
cout<<"No se pudo cargar el archivo"<<endl;
}
return 0;
}
//CUERPO DE LAS FUNCIONES
void convertir_binario(int a, int b[]){ //listo
int i=0;
int binario[8]={0,0,0,0,0,0,0,0};
while(a!=1){
binario[i]=a%2;
a=a/2;
i++;
}
binario[i]=a; // a siempre va a ser igual a 1
for(int j=7,i=0;j>=0;j--,i++){
b[i]=binario[j];
}
}
int contador_0s_1s(string a){ //listo
int tam,cont1=0,cont0=0;
tam=a.length();
for(int i=0;i<tam;i++){
if(a[i]=='1'){
cont1++;
}
else if(a[i]=='0'){
cont0++;
}
}
if(cont1>cont0){
return 1;
}
else if(cont0>cont1){
return 0;
}
else {
return 4;
}
}
string igual_cantidad_0s_1s(string a, string b){ //listo
int tam=0;
tam=a.length();
for(int i=0;i<tam;i++){
if(a[i]=='1'){b[i]='0';}
else if(a[i]=='0'){b[i]='1';}
}
return b;
}
string mayor_cantidad1s(string a, string b){ //listo
int tam=0;
tam=a.length();
for(int i=2;i<tam;i+=2){
if(a[i]=='0'){b[i]='1';}
else{b[i]='0';}
}
return b;
}
string mayor_cantidad0s(string a, string b){ //listo
int tam=0;
tam=a.length();
for(int i=1;i<tam;i+=2){
if(a[i]=='0'){b[i]='1';}
else{b[i]='0';}
}
return b;
}
void metodo_codificacion1(){
string cadena,bin_modificado,bloque1,bloque2,nombre;
int n;
cout<<"Ingrese un nombre para el archivo codificado: ";cin>>nombre;
cout<<"Ingrese el valor de la semilla: ";cin>> semilla;
archivo_lectura.open("archivo_binario.txt",ios::in);
if(archivo_lectura.is_open()){
while (!(archivo_lectura.eof())) {
archivo_lectura>>cadena;
}
archivo_escritura.open(nombre+".txt",ios::out);
n=cadena.length();
bloque1=cadena.substr(0,semilla);
bin_modificado=igual_cantidad_0s_1s(bloque1,bloque1);
archivo_escritura<<bin_modificado;
for(int i=0;i<n;i+=semilla){
if(contador_0s_1s(bloque1)==1){
bloque2=cadena.substr((i+semilla),semilla);
bin_modificado=mayor_cantidad1s(bloque2,bloque2);
archivo_escritura<<bin_modificado;
bloque1=bloque2;
}
else if(contador_0s_1s(bloque1)==0){
bloque2=cadena.substr((i+semilla),semilla);
bin_modificado=mayor_cantidad0s(bloque2,bloque2);
archivo_escritura<<bin_modificado;
bloque1=bloque2;
}
else if(contador_0s_1s(bloque1)==4){
bloque2=cadena.substr((i+semilla),semilla);
bin_modificado=igual_cantidad_0s_1s(bloque2,bloque2);
archivo_escritura<<bin_modificado;
bloque1=bloque2;
}
}
cout<<" ->El archivo '"<<nombre<<".txt' ha sido codificado correctamente."<<endl<<endl;
}
else{
cout<<"Lo siento,el archivo '"<<nombre<<"' no se pudo codificar."<<endl;
}
archivo_escritura.close();
archivo_lectura.close();
}
|
f47300aaba844b7d175bf58197cbfd9cea9cfa44
|
[
"C++"
] | 2
|
C++
|
AndresRendon1/mains_p3_info
|
d9909294c59a13b90427b4d0ef2da2f42e3eeaeb
|
82b7d3fd3c819e378b9829eb7cf2fdce9ed50b4f
|
refs/heads/master
|
<repo_name>ArchieTramp/HomeWork9<file_sep>/src/main/java/Main.java
/**
* Дан интерфейс
* public interface Worker {
* void doWork();
* }
* <p>
* Необходимо написать программу, выполняющую определенные задачи
*
* @author <NAME>
*/
import javax.tools.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
writeClass();
compileMyClass();
useMyClassLoader();
}
/**
* Метод компиляции нового класса до которого сам я бы не догадался, и, соответвенно,
* уверен что сделано все чрезмерно сложно, хотя как показывает практика есть
* ваританты намного проще. Списано с гугла :(
*/
private static void compileMyClass() throws IOException {
File loaderfile = new File("./Loader.java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
File parentDirectory = loaderfile.getParentFile();
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singletonList(parentDirectory));
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Collections.singletonList(loaderfile));
compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
fileManager.close();
}
/**
* Метод загрузки нового класса через класслоудер, аналогичен лекционному
*/
private static void useMyClassLoader() throws Exception {
ClassLoader classLoader = new MyClassLoader();
Class<?> kindClass = classLoader.loadClass("Loader");
Worker loader = (Worker) kindClass.newInstance();
loader.doWork();
}
/**
* Метод чтения с консоли нового класса,
* написан отвратительно криво, аж тошщно на него смотреть,
* но ничего лучше я не придумал.
*/
public static void writeClass() throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("что под саутами");
String text = scanner.nextLine();
String textagain = scanner.nextLine();
String starter = "public class Loader implements Worker {\n" +
" static {\n" +
" System.out.println(\"" + text + "\");\n" +
" }\n" +
"\n" +
" @Override\n" +
" public void doWork() {\n" +
" System.out.println(\"" + textagain + "\");\n" +
" }\n" +
"\n" +
"}";
byte[] ba = starter.getBytes();
FileOutputStream fos = new FileOutputStream("Loader.java");
fos.write(ba);
}
}
|
42b07816b288914752aae9b38a1b50a630abbf82
|
[
"Java"
] | 1
|
Java
|
ArchieTramp/HomeWork9
|
70f53e4fa1859c316eedfcc92cdb048d63bd95cd
|
4091d57056233b704e8371feaae2f2b65936baca
|
refs/heads/master
|
<repo_name>zongzhu321/learnning<file_sep>/websoket/README.md
# websokcet
1、open
2、close
3、error
4、message
5、connection
# 前端
1、open
2、close
3、error
4、message
1、entry.html -
Input username
localStorage to save the username
click for enter the chatting room
2、index.html
list - show messages list
input - message
btn - send message
# 后端
1、open
2、close
3、error
4、message
5、connection<file_sep>/js高级.md
## 一、预编译
### 1 概念
#### 1)什么是预编译
首先,我们知道JavaScript是解释性语言
- 解释性:逐行解析,逐行执行
那么,什么是预编译呢?
在JavaScript真正被解析之前,js解析引擎会首先把整个文件进行**预处理**,以消除一些歧义,这个预处理的过程就被称为**预编译**
> 示例
```js
console.log(a)
var a = 123
console.log(a)
function a() {
console.log(a)
}
a()
```
这是一段奇怪的代码,先思考一下,三个console.log 分别会打印出什么
如果要完全理解,我们就需要深入的分析 `js引擎` 到底是如何工作的
#### 2)全局对象GO
> 全局对象
全局对象(Global Object):
- <u>在浏览器环境中,`js引擎` 会整合 `<script>` 标签中的内容,产生 `window` 对象,这个window对象就是全局对象</u>
- 在node环境中,会产生 `global` 对象
##### 全局变量
在 `<script>` 标签中声明的变量为 `全局变量`,全局变量会作为 `window` 对象的属性存在
> 示例
```js
var a = 100;
console.log(a)
console.log(window.a)
```
这里打印 a 实际上相当于打印 `window` 对象的a属性
> 扩展
啥叫整合?
> 示例
```js
<script>
var a = 100
console.log(a)
console.log(window.a)
</script>
<script>
// 这里能访问到a吗???
console.log(a)
</script>
```
- 可以,因为j`s引擎` 会把所有的 `<script>` 标签整合到一起,生成一个 `window` 对象
##### 全局函数
在 `<script>` 标签中声明的函数为 `全局函数`,全局函数会作为 `window` 对象的方法存在!!
> 示例
```js
function a(){
console.log('1111')
}
console.log(window.a)
```
那么问题来了,当同时定义变量a和函数a时,会发生什么呢?
就像我们看到的奇怪代码里一样,而预编译就是为了处理类似的这些冲突
#### 3)活动对象AO
> 活动对象
活动对象(activation Object):也叫激活对象
- 在函数被调用时产生,用来保存当前函数内部的执行环境(Execution Context),也叫执行期上下文
- 在函数调用结束时销毁
##### 局部变量
在函数内部声明的变量叫 **局部变量**,局部变量作为 **AO对象**的属性存在
> 示例
```js
function a() {
var i = 0
console.log(i)
}
a()
```
> 如何理解局部变量
在`函数a` 的外部,不能访问的 `变量i` 只在`函数a` 的范围内才能使用,其实,这也就是作用域的由来
- 如果不执行函数,不会产生 `AO对象` ,就不会存在 `i属性`
- 如果执行函数,就会产生 `AO对象` ,并将 `变量i` 作为 `AO对象` 的属性
- 函数执行完后,AO对象被销毁,也就意味着不能使用 `i属性`
##### 局部函数
在函数内部声明的函数叫 **局部函数**,局部函数作为 **AO对象**的方法存在
> 示例
```js
function a(){
function b(){
console.log(222)
}
b()
}
a()
```
### 2 全局预编译
#### 1)流程
1. 查找变量声明,作为GO对象的属性名,值为undefined
2. 查找函数声明,作为GO对象的属性名,值为function
> 变量声明
通过 `var` 关键字声明变量
```js
var a // 变量声明
var a = 111 // 变量声明+变量赋值
```
> 函数声明
通过`function` 关键字声明函数
```js
function a(){} // 函数声明
var a = function() {} // 函数表达式 不是函数声明
```
> 示例
```js
console.log(a)
var a = 100
console.log(a)
function a(){
console.log(111)
}
console.log(a)
// 1、产生window对象
// 2、查找变量的声明,把a作为window对象的属性名,属性值为undefined
// 3、查找函数的声明,把函数名a作为window对象的属性名,属性值为function
// 全局预编译结束,结束后 代码从上到下依次执行
```
#### 2)结论
如果存在同名的变量和函数,函数的优先级高
### 3 函数预编译
#### 1)流程
1. 在函数被调用时,为当前函数产生 `AO对象`
2. 查找形参和变量声明作为 `AO对象` 的属性名,值为 undefined
3. 使用实参的值改变形参的值
4. 查找函数声明,作为 `AO对象` 的属性名,值为function
#### 2)示例
> 示例一
```js
function a(test){
var i = 0
function b() {
console.log(222)
}
b()
}
a(1)
// 1、产生window对象
// GO:1、查找变量的声明
// 2、查找函数的声明,将函数a作为window对象的属性名,值为function
// 全局预编译结束
// 执行代码
// 执行第8行,调用函数a,产生函数a的AO对象
// AO: 1、查找形参 test,变量i作为 AO对象的属性名,值为undefined
// 2、实参1赋值给test,test:1
// 3、查找局部函数b, b作为AO对象的属性名,值为function
// 函数预编译结束
// 执行
// i= 0
// 执行b 调用b函数
```
> 示例二
```js
function a(test){
console.log(b)
var b = 0;
console.log(b)
function b(){
console.log(2222)
}
}
a(1)
```
> 示例三
```js
function a(b,c){
console.log(b)
var b = 0
console.log(b)
function b(){
console.log(2222)
}
console.log(c)
}
a(1)
```
> 示例四
```js
function a(i){
// var i
console.log(i)
function i(){
}
}
a(1)
```
#### 3)结论
- 只要声明了局部函数,函数的优先级最高
- 没有声明局部函数,实参的优先级最高
- 整体来说: 局部函数 > 实参 > 形参
## 二、作用域与作用域链
### 1、概念
#### 1)作用域
> 域:范围,区域
>
> 作用域是根据名称查找变量的一套规则
在js中,作用域分为**全局作用域**和**局部作用域**
- 全局作用域:由 `<script>` 标签产生的区域,从计算机的角度可以理解为window 对象
- 局部作用域:由函数产生的区域,从计算机的角度可以理解为该函数的 AO对象
#### 2)作用域链
在js中,函数存在一个隐式属性 `[[scopes]]` ,这个属性用来保存当前函数在执行时的环境(上下文),由于在数据结构上是链式的,也被称为作用域链,我们可以把它理解成一个**数组**
> 函数类型存在 [[scopes]]属性
```js
function a(){}
console.dir(a) // 打印内部结构
```
- [[scopes]]属性在函数声明时产生,在函数被调用时更新
- [[scopes]]属性记录当前函数的执行环境
- 在函数被调用时,将该函数的AO对象压入到 [[scopes]]中
### 作用
作用域链有什么作用呢?
在访问变量或者函数时,会在作用域链上依次查找,最直观的表现是:
- 内部函数可以使用外部函数声明的变量
> 示例
```js
function a(){
var a = 111
function b(){
console.log(aa)
}
b()
}
a()
```
- 在函数a中声明定义了变量 aa
- 在函数b中没有声明,却可以使用
> 思考
如果在函数b中,也定义同名变量 aa会怎样
> 结论
内部函数可以使用外部函数的变量
外部函数不能使用内部函数的变量
## 三、闭包
如果在内部函数使用了外部函数的变量,就会形成闭包,闭包保留了外部环境的引用
如果内部函数被返回到了外部函数的外边,在外部函数执行完后,依然可以使用闭包里的值
### 1、闭包的形成
在内部函数使用外部函数的变量,就会形成闭包,闭包是当前作用域的延伸
> 示例
```js
function a(){
var aa = 100
function b(){
console.log(aa)
}
b()
}
a()
```
从代码的角度看,闭包也是一个对象,闭包里包含哪些东西呢?
在内部函数b中使用了外部函数a中的变量,这个变量就会作为闭包对象的属性!!
> 思考
```js
function a(){
var aa = 100
function b(){
console.log(b) // 形成闭包 执行完会销毁没有返回,有人也理解为没有形成闭包
}
b()
}
a()
// 1、产生aAO对象:{aa: 100, b: fun}
// 2、产生bAO对象
```
会形成闭包,由于b的声明时在外部函数a中的,在内部函数b中使用了b,会形成闭包
闭包里存放了一个属性,就是b函数
> 思考
```js
function a(){
var aa = 100
function b(){
var b = 200
console.log(b)
}
b()
}
a()
```
不会形成闭包,由于在b函数内部定义了变量b,打印时直接使用的是内部函数里的变量b,不会形成闭包
### 2、闭包的保持
如果希望在函数调用后,闭包依然保持,就需要将内部函数返回到外部函数的外部
> 示例
```js
function a(){
var num = 0
function b(){
console.log(num++) // 形成闭包
}
return b
}
var demo = a()
console.dir(demo)
a()()
a()()
demo()
demo()
```
第8行,调用a函数,将内部函数b返回,保存在函数a的外部
第9行,调用demo函数,实质上是调用内部函数,在函数b的[[scopes]]属性中可以找到闭包对象,从而访问到里面的值
### 3、总结
使用闭包要满足两个条件
1. 闭包要形成:在内部函数使用外部函数的变量
2. 闭包要保持:内部函数返回到外部函数的外面
## 四、闭包的应用
### 1、闭包的两面性
> 任何事物都有两面性
好处:一般来说,在函数外部是没办法访问函数内部的变量的,设计闭包最主要的作用就是为了解决这个问题。
坏处:有时不注意使用了闭包,会导致出现意想不到的结果
### 2、[闭包的应用](https://blog.csdn.net/abc1194474469/article/details/107465091)
1. 在函数外部访问私有变量
2. 实现封装
3. 防止污染全局变量
> 示例
在函数外部访问私有变量
```js
function a(){
var num = 0
function b(){
num++
}
return b
}
var demo = a()
demo()
```
本来在函数a的外部(全局)不能直接访问内部变量num,通过闭包就可以使用num变量了
> 示例
```js
function Person(){
var uname
function setName(uname){
this.uname = uname
}
function getName(){
console.log(this)
return this.uname
}
return {
getName: getName,
setName: setName
}
}
var xiaopang = Person()
xiangpang.setName('xiaopang')
var name = xiaopang.getName()
```
<file_sep>/websoket/chat/js/index.js
((doc, Socket) => {
const oList = doc.querySelector('#list')
const oMsg = doc.querySelector('#message');
const oSendBtn = doc.querySelector('#send');
const ws = new WebSocket("ws://localhost:8000"); //new WebSocket("ws://localhost:8000/ws")
const init = () => {
bindEvent()
}
init()
function bindEvent(){
oSendBtn.addEventListener('click', handleSendBtnClick, false);
ws.addEventListener('open', handleOpen, false);
ws.addEventListener('close', handleClose, false);
ws.addEventListener('error', handleError, false);
ws.addEventListener('message', handleMessage, false)
}
function handleSendBtnClick(){
console.log('send mesage')
}
function handleOpen(e){
console.log('websocket open11', e)
}
function handleClose(e){
console.log('websocket close11', e)
}
function handleError(e){
console.log('websocket error11', e)
}
function handleMessage(e){
console.log('websocket message11',e)
}
})(document, WebSocket)
// 放大模式<file_sep>/js面向对象.md
JavaScript面向对象编程
# 一、类和对象
## 1 对象的概念
> 对象:一个具体的实体
在现实世界中,对象随处可见,一个人,一个学生,一个杯子,一辆汽车,游戏里的一个英雄...都是一个对象
## 2 对象的组成
> 如何描述一个对象呢
比如
- 每个人都有**姓名**,**年龄**,**性别**,这些特征
- 游戏里的英雄都有**生命值**,**攻击力**,**防御力**这些特征
对象除了这些**特征**外,还有一些 **行为/动作**
比如
- 人可以 **吃饭,睡觉**
- 游戏里的英雄可以 **移动**,可以放 **技能**
在程序里
- 把对象的特征叫做**属性**,使用变量来描述
- 把对象的行为叫做**方法**,使用函数来描述
因此,我们得出一个重要结论:
> 对象是有属性和方法组成的
## 3 类的概念
> 类:具有相同特征的事物的集合
我们把具有相同特征和行为的实体抽象出来,就形成了一个类
比如:把人集合在一起就形成了人类,把游戏英雄集合起来,就形成了英雄类
- 每一个人类都有一些相同的特征,比如:姓名,性别,年龄,身高,体重等等
- 每一个英雄也有一些相同的特征,比如:生命值,攻击力,防御力 等等
## 4 程序中的类和对象
> 那么如何使用程序来描述这些相同特征呢?
可以定义一个**模板/规范/设计图纸**,然后通过这个 **模板/规范、设计图纸**来生产一个个的**实体**
比如:我们可以通过图纸 来生产一辆汽车
- 我们把定义的这个 **模板**叫做**类**
- 把生产出来的 **实体**叫做**对象**
- 把生产的过程叫做 **实例化**
## 5 类和对象的关系
类和对象的关系,可以认为是 **整体和个体,抽象和具体的关系**
通过上面的描述,总结来说就是
- 类是对象的集合
- 对象是类的实例化
## 6 小结
1. 对象是由属性和方法组成的
2. 属性就是变量,方法就是函数
3. 类是对象的集合,对象是类的实例化
补充:由于类是对象的集合,通常我们也可以说类由属性和方法组成
# 二、初步认识js中的类和对象
## 1 构造函数的定义
在js中,没有类(class)的概念,主要通过构造函数来模拟的
在 **es6** 中,js引入了class关键字来表示类
> 语法
```js
function 构造函数名(){
}
```
1. 使用 `function` 关键字表示定义一个构造函数
2. 构造函数名一般 首字母大写
> 示例
```js
function Person(){
}
```
通过以上方式就可以定义一个Person构造函数,相当于定义好了一个Person类
## 2 构造函数的作用
### 1)通过构造函数实例化对象
在js中,我们通过构造函数(类)来实例化对象
> 语法
```js
new 构造函数名()
```
> 通过构造函数来实例化对象
```js
// 定义一个构造函数
function Person(){
}
// 实例化一个对象,赋值给变量p
var p = new Person()
console.log(typeof p)
```
以上代码
- 通过`new` 关键字,产生一个对象,并赋值给变量p
- 通过 `typeof` p测试变量p的类型为 object,说明p是一个对象
### 2)在构造函数中定义属性
> 构造函数规定了由该类实例化出来的对象应该包含哪些属性
比如,由学生类实例化出来的学生对象都应该有**姓名**,**年龄**这些属性
```js
function Student(){
this.uname = null;
this.age = null;
}
```
在构造函数的内部,我们通过 `this.属性名` 的方式来定义属性
在这里,先把这个看作固定写法,后面在具体分析
> 构造函数虽然可以规定实例化对象应该包含哪些属性,但是并不能确定实例对象的属性值
比如 人类都应该有名字这个属性,但是具体叫什么名字,只有在一个人出生的时候才去确定
因此,在实例化对象的时候,需要将 具体的数据 传递给构造函数
```js
// 定义一个学生类
function Student(n,a){
this.name = n;
this.age = a;
}
// 实例化对象
var stu = new Student('小明', 20)
```
> 重要结论
构造函数主要完成属性的初始化!
# 三、对象的方法
## 1 方法的定义和使用
我们已经知道
1. 类由属性和方法组成
2. 在js中,通过构造函数定义类
3. 在构造函数中可以通过 `this.属性名` 来定义属性
那么,在构造函数中是否可以同过 `this.方法名` 定义方法呢?
### 1)在构造函数中定义方法
```js
function Student(name,age){
this.name = name;
this.age = age;
this.sayHi = function(){
console.log(this.name+ 'say hi')
}
}
```
### 2)方法的使用(调用)
> 语法
```js
对象.方法名()
```
## 2 使用构造函数定义方法的问题
虽然可以在构造函数中定义方法,但是一般不这么做,为什么?
看如下示例
```js
// 定义类
function Student(n,a){
this.name = n;
this.age = a;
this.sayHi = function(){
console.log(this.name + ' say hi')
}
}
// 实例化对象
var stu = new Student('dog', 20)
var stu1 = new Student('cat', 18)
// 判断stu.sayHi === stu1.sayHi? // false
// 方法名:表示内存中的首地址
// stu和stu1的sayH方法都需要分配不同的内存
```
- 上面这个比较表示 stu对象和stu1对象的sayHI方法在内存中的首地址是不同的!
方法名:表示内存中的首地址
# 四、对象实例化原理分析
## 1 引用数据类型
对象是一种特殊的数据,看如下代码
> 示例
```js
// 定义一个学生类
function Student(n, a){
this.name = n;
this.age = a
}
// 实例化对象
var stu = new Student('小明', 20)
```
- 这里并**不是**把所有的数据直接保存在变量中
- 而是先在堆区开辟一个空间,把这个空间的引用保存在变量中
- 在js中,**函数**和**对象**都是 **引用数据**类型

> 什么是引用呢,引用有什么用呢?
一句话解释:引用就是来找数据的
类似于路径的概念,就像我们可以通过路径 E:\document\......找到电脑中的一个文件
又或者酒店的房间号,通过房间号就可以找到房间
通过引用就可以找到内存中的数据
引用本质上是 **内存首地址**,通过这个地址可以找到对应的内存空间,进而获取数据
## 2 new实例化的步骤

## 3 为什么不在构造函数中定义方法
```js
// 定义一个学生类
function Student(n, a){
this.name = n;
this.age = a;
this.sayHi = function(){
}
}
// 实例化对象
var stu = new Student('小明', 20)
var stu1 = new Student('小刚', 30)
```
截屏2021-06-06 上午11.44.42
这就解释了前面的问题,虽然 **sayHi**方法的代码是相同的,但是每次实例化时会开辟一个新的内存空间,造成浪费
## 4 初步解决
既然方法是相同的,我们可不可以单独定义一个函数赋值给 sayHi呢?
> 示例
```js
// 初步解决方案
// 一、定义类
function Student(n, a){
this.name = n;
this.age = a;
this.sayHi = sayHi
}
function sayHi(){
console.log('大家好')
}
// 二、实例化对象
var stu = new Student('小明', 20)
var stu1 = new Student('xiaohong', 28)
console.log(stu.sayHi == stu1.sayHi) // true
```

这样做确实可以解决,但是这种做法很奇怪,一般不会使用,为什么这么说呢。
照理说, `sayHi` 函数应该仅仅是属于Student类,只有通过Student类实例化出来的对象可以调用。如果把`sayHi` 放在全局下,可以当成普通函数来调用。因此,我们称这种做法破坏了类的**封装性**
> 什么是**封装性**?
类的成员尽量封闭在类的内部,隐藏细节与实现
> 示例
```js
// 一、定义类
function Student(n, a){
this.name = n;
this.age = a;
this.sayHi = sayHi;
}
function sayHi(){
console.log('大家好,我叫' + this.name)
}
// 二、实例化对象
var stu = new Student('xiaoming', 20)
var stu1 = new Studnet('xiaohong', 38)
// 使用对象调用可以得到希望的结果
stu.sayHi(); // 大家好 我叫小红
// 当普通函数直接调用,会得到‘奇怪’的结果
sayHI(); // 大家好,我叫undefined
sayHI.call(stu)
```
为什么会出现这种'奇怪'的现象,要搞明白这个问题,就要了解js中的this指向
## 5 初步了解this指向
# 五、原型
前面,我们了解到属性可以定义在构造函数中,但是 **方法的定义**没有很好的解决方案
为了解决这个问题,体术了**原型模式**
或者,换句话说:**原型的产生主要是为了解决方法共享的问题**
## 1 什么是原型模式
系统在创建构造函数的同时,会自动在内存中生成一个与之相应的对象,这个对象就是 **原型对象**
比如:
```js
// 定义一个构造函数
function Person(){}
```
系统在创建Person构造函数的同时,自动在内存中生成一个与之对应的Person对象

由上图可知,构造函数与原型对象是两个**独立**的内存空间
## 2 构造函数与原型对象的关系
他们是相对独立的,但是又存在联系
> 示例
```js
// 一、构造函数
function Person(n){
this.name = n;
}
// 二、打印构造函数的结构
console.dir(Person);
```
在Person构造函数的内部存在一个属性 **Protype**指向Person的原型对象
在Person的原型对象的内部也存在一个属性**constructor**指向Person的构造函数

证明Person构造函数中 存在prototype属性
## 3 实例对象与原型对象的关系
在由Person类实例化出来的对象person1和person2中也有一个属性--proto--(**隐士原型**)指向原型对象
> 示例
```js
// 一、构造函数
function Person(n){
this.name = n
}
// 二、实例化对象
var person1 = new Person('xiaoming');
var person2 = new Person('xiaomei');
// 三、打印person1和person2的内部结构
console.dir(person1)
console.dir(person2)
```
## 4 三者的关系
**构造函数**的 `prototype` 属性和**实例对象**的 `--proto--` 属性指向同一个对象
只要是函数 都存在属性prototype;只要是对象都存在属性--proto--
> 示例
```js
// 一、定义构造函数
function Person(n){
this.name = n
}
// 二、实例化对象
var p = new Person('xiaoming')
// 三、测试
console.log(Person.prototype === p.__proto__); // true
```
> 图解

## 5 使用原型定义方法
我们先大致了解下如何通过原型模式定义方法,再具体分析
> 示例
```js
// 一、在构造函数中定义属性
function Student(n, a){
this.name = n;
this.age = a;
}
// 二、在原型中定义方法
Student.prototype.sayHi = function(){
console.log('大家好,我叫' + this.name)
}
// 三、实例化对象
var stu = new Student('xiaoming',20)
var stu1 = new Student('xiaomei',39)
// 比较不同的对象方法是否相同
console.log(stu.sayHi == stu1.sayHi); // true
// 我们并没有发现stu中有sayHi方法,为什么可用呢
```
## 6 小结
- 在构造函数中定义属性
- 在原型对象中定义方法
# 六、原型链
## 1 引用数据类型特性
**引用数据类型(数组、对象、函数)都可以自由的扩展成员(属性和方法)**
1. 只要是引用类型都存在 --proto--属性
2. 只要是函数类型都存在prototype属性
3. 引用数据类型都可以**自由的扩展成员**(属性和方法)
### 1)引用类型都存在--proto--
> 示例
```js
// 定义一个对象
var obj = {}
// 以上代码相当于
var obj = new Object();
```
- 通过obj.--proto--可以找到原型对象
- 再通过obj.--proto--.constructor 可以找到对应的构造函数
### 2)函数类型还存在prototype
函数类型是一种特殊的引用类型,除了具有所有引用类型的特点(--proto--)外,
还具有自己特有的prototype属性。
函数类型可以通过 typeof判断,得到的结论是 function
结论:
1. 函数时引用类型,因此存在--proto--属性
2. 函数类型还存在特有的prototype属性
> 思考
1. 函数的--proto--指向什么?
2. 函数的prototype指向什么?
> 示例
```js
// 一、定义一个函数
function Foo(){}
// 通过Foo.prototype找到Foo的原型函数
// 通过Foo的原型对象的constructor可以找到构造函数
console.log(Foo.prototype.constructor === Foo); // true
// 通过Foo.--proto--找到Function的原型对象
console.log(Foo.__proto__ == Function.prototype) // true
```

1. Foo作为对象,可以看做是由Function构造函数实例化的一个对象,因此--proto--指向Function的原型
2. Foo本身作为构造函数,prototype指向Foo的原型
### 3) 引用类型可以扩展成员
先从熟悉的对象入手
> 示例
```js
// 定义一个对象
var obj = {}
// 以上代码相当于
// var obj = new Object()
// 先打印obj的内容
console.dir(obj)
// 给对象扩展属性和方法
obj.name = 'xiaoming'
obj.sayHi = function(){
console.log('dajiahao')
}
// 再次打印obj的内容
console.dir(obj)
```
> 示例
定义一个普通函数,尝试给函数扩展
事实上,函数时一种
<file_sep>/面试题.md
## 一、JavaScript Event Loop(事件循环/事件轮询)
### 1、Event Loop
- 浏览器是多线程 JS是单线程运行的
- 异步要基于回调来实现
- event loop就是异步回调的实现原理
> js如何执行?
- 从前到后,一行一行执行
- 如果某一行执行报错,则停止下面代码的执行
- 先把同步代码执行完,在执行异步
> 总结 event loop过程1
- 同步代码,一行一行放在 Call Stack(调用栈)执行
- 遇到异步,会先“记录”下,等待时机(定时,网络请求等)
- 时机到了(定时,请求成功,DOM事件),就移动到Callback Queue
- 如Call Stack为空(即同步代码执行完毕)Event Loop开始工作
- 轮询查找 Callback Queue,如有则移动到Call Stack 执行
- 然后继续轮询查找
> js是单线程
>
> 异步(setTimeout, ajax等)使用回调,基于event loop
>
> DOM事件也使用回调,基于event loop
### 2 、宏任务macroTask和微任务microTask
- 宏任务: setTimeout, setInterval, Ajax, Dom事件
- 微任务: Promise async/await
- 微任务执行时比宏任务要早
#### event loop和DOM渲染
- js是单线程的,而且和DOM渲染共用一个线程
- js执行的时候,得留一些时机供DOM渲染
- 每次Call Stack清空(即每次轮询结束),即同步任务执行完
- 都是DOM重新渲染的机会,DOM结构如有改变则重新渲染
- 然后再去触发下一次Event Loop
> 宏任务和微任务触发节点
- 宏任务:DOM渲染后触发,如setTimeout
- 微任务:DOM渲染钱触发,如Promise

微任务是ES6语法规定的 放到 MicroTask Queue(微任务队列)
宏任务是浏览器规定的,放到 Message Queue(消息队列)
## 二、节流防抖
> 防抖或是节流:限制函数的执行次数
防抖:通过setTimeout的方式,在一定的时间间隔内,将多次触发变成一次触发
节流:减少一段时间内的触发频率
> 防抖
```js
const button = document.querySelector('input')
function payMoney(){
console.log('已剁手');
console.log(this)
}
function debounce(func,delay){
let timer
return function(){
clearTimeout(timer)
timer = setTimeout(() => {
func()
}, delay)
}
}
button.onclick = debounce(payMoney,1000)
```
> 节流
```js
const but = document.querySelector('input')
function submit(){
}
function throttle(fn, delay){
var begin = 0
return function(){
var cur = new Date().getTime()
if(cur - begin > delay){
fn();
begin = cur
}
}
}
btn.onclick = throttle(submit,2000)
```
## 三、手写深拷贝
```js
const oldDate = {
name: 'xiaogou',
age: 20,
friend: {
name: 'ergou',
age: 18
}
}
function deepClone(obj){
if(typeof obj !== 'object' || obj == null){
return obj
}
let result;
if(obj instanceof Array){
result = []
}else{
result = {}
}
for(let key in obj){
if(obj.hasOwnProperty(key)){
result[key] = deepClone(obj[key])
}
}
return result
}
var newDate = deepClone(oldDate);
function deepClone(obj){
if(typeof obj !== 'object' || typeof obj == 'function' || obj === null){
return obj
}
if(obj instanceof RegExp){
return new RegExp(obj)
}
if(obj instanceof Date){
return new Date(obj)
}
let newObj = new obj.constructor();
for (let key in obj){
if(obj.hasOwnProperty(key)){
newObj[key] = deepClone(obj[key])
}
}
console.log(newObj)
}
```
## 四、大前端时代需要掌握的技术栈
https://leeguoo.com/archives/%E9%9D%A2%E8%AF%95%E9%A2%98
#### 1、HTML5
- 语义化标签类
- 音视频处理
- canvas/webGL
- history API
- requestAnimationFrame
- 地理位置
- web scoket
- ....
#### 2、CSS3
- 常规
- 动画
- 盒子模型
- 响应式布局
- ....
#### 3、javascript
- ECMAScript 3/5/6/7/8/9
- DOM
- BOM
- 设计模式
- 底层原理
- 堆栈内存
- 闭包作用域AO/VO/GO/EC/ECSTACK
- 面向对象OOP
- THIS
- EventLoop
- 浏览器渲染原理
- 回流重绘
- ........
#### 4、网络通信层
- AJAX/ Fetch / axios
- HTTP1.0 / 2.0
- TCP
- 跨域处理方案
- 性能优化
- .....
#### 5、Hybrid或者APP再或者小程序
- Hybrid
- uni-app
- RN
- Flutter
- 小程序 MPVUE
- Weex
- PWA
#### 6、工程化方面
- webpack
- Git
- Linux/Nginx
#### 7、框架方面
- Angular
- Vue
- 基础知识
- 核心原理
- Vue-router
- Vue-cli
- vuex
- Element ui
- vant
- cube
- SSR
- 优化
- ...
- React
- 基础知识
- 核心原理
- react-router-dom
- redux
- React-redux
- dva
- umi
- mobix
- antd
- Antd pro
- SSR
- 优化
- ...
- #### 7、游戏方向
- #### 8、可视化或者AI方向
- ....
> 水品垂直居中的5大方案
- 绝对定位 已知宽高:margin; 未知宽高:translate(-50%, -50%)
- flex布局 display:flex; justify-content: center; align-items: center
- grid布局
- Table-cell布局 display: table display: table-cell;vertical-align:middle text-algin:center
- js计算
> 盒子模型
>
> ***\*w3c盒子模型的范围包括margin、border、padding、content\****
- 标准盒子模型 ( IE盒模型 )
给一个标签添加:box-sizing:content-box;(元素默认) 这个标签就转换为了w3c盒模型 标签得实际宽度 = 设置的宽度 + border宽度 + padding的宽度
- 怪异盒子模型
给一个标签添加:box-sizing:border-box; 这个标签就转换为了怪异盒模型 标签得实际宽度 = 设置的宽度 如果设置了padding和border就是从设置的实际宽高中减去,减去后才是内容的宽高。
- flex弹性盒子模型
> 圣杯布局,双飞翼布局
- 经典布局
- 定位布局
- flex布局
> 移动端响应式布局开发的三大方案
- media (pc移动 用一套项目)
- rem em:相对浏览器默认字体尺寸(16px 1em=16px;)https://zhuanlan.zhihu.com/p/30413803
- flex
- Vh / vw
> z-index的工作原理
- 文档流 (脱离文档流 定位 float,transform也类似)
- 定位
> 谈谈对HTML5的理解
> css选择器 渲染从右向左 a{} 比 .box a{}渲染性能高
## 五、HTML+CSS
### 1、flex布局和grid布局
## 六、堆栈内存及闭包作用域
### 1、js中8中数据类型及区别
基本类型和引用类型
基本类型:number、string、Boolean、null、undefined
引用类型:Object,Function
特殊类型:symbol
装箱拆箱
alert输出的 结果toString
内存回收机制
### 2、JS堆栈内存的运行机制
### 3、变量提升机制
### 4、作用域和作用域链
### 5、闭包的两大作用:保存、保护
### 6、JS编译机制:VO/AO/GO
### 7、JS高阶编程技巧:惰性函数/柯理化函数/高阶函数
### 8、BAT经典面试题
## 七、JS面相对像(OOP)和 this处理
### 1、单例设计模式
### 2、类和实例
### 3、原型和原型链
### 4、new运算符的实现机制
### 5、Call/apply/bind
### 6、constructor构造函数模式
### 7、JS中this五种情况的综合梳理
### 8、JS中的四大数据类型检测方案
### 9、JS中的四大继承方案(含深浅拷贝)
### 10、BAT经典面试讲解
## 八、JS DOM/BOM及事件处理机制
### 1、BOM/DOM的核心操作
### 2、事件对象
### 3、拖拽及拖拽插件封装
### 4、发布订阅设计模式
### 5、深度剖析JQ源码
### 6、事件传播机制和事件代理
### 7、DOM2级事件的核心运行机制
### 8、touch/gesture事件及封装处理
### 9、浏览器底层渲染机制和DOM的回流重绘
### 10、DIALOG模态框组件的封装
## 九、ES6、ES7的核心知识
### 1、let/const及和var的区别
### 2、箭头函数ArrowFunction
### 3、结构赋值和拓展运算符
### 4、Set/Map数据结构
### 5、Promise设计模式
### 6、async/await及实现原理
### 7、Generator生成函数
### 8、Promise A+规范 (手写promise源码)
### 9、JS底层运行机制:单线程和同步异步编程
### 10、JS底层运行机制:微任务宏任务和事件循环机制
### 11、interator迭代器和for of循环
## 十、AJAX/HTTp前后端数据交互
### 1、AJAX核心四部操作
### 2、GET/POST核心机制与区别
### 3、TCP三次握手和四次挥手
### 4、axios库和源码剖析
### 5、fetch基础和实战应用
### 6、前端开发中的9种跨域方案
### 7、HTTP网络状态和实战中的处理方案
### 8、前端性能优化汇总(包含强缓存和弱缓存)
## 十一、面试题
```js
function Foo(){
getName = function(){
console.log(1)
}
return this
}
Foo.getName = function(){
console.log(2)
}
Foo.prototype.getName = function(){
console.log(3)
}
var getName = function (){
console.log(4)
}
function getName() {
console.log(5)
}
Foo.getName()
getName()
Foo().getName()
getName()
new Foo.getName()
new Foo().getName() // 先执行 new Foo()
new new Foo().getName()
```
```
async function async1(){
console.log('async1 start')
await async2();
console.log('async1 end')
}
async function async2(){
console.log('async2')
}
console.log('script start')
setTimeout(function(){
console.log('setTimeout')
},0)
async1();
new Promise(function (resolve){
console.log('promise1')
resolve();
}).then(function(){
console.log('promise2')
});
console.log('script end')
```
<file_sep>/websoket/server/index.js
const ws = require('ws')
;((ws) => {
const server = new ws.Server({
port: 8000
});
const init = () => {
bindEvent();
}
function bindEvent(){
server.on('open', handleOpen);
server.on('close', handleClose);
server.on('error', handleError);
server.on('connect', handleConnect)
}
init();
function handleOpen(e){
console.log('open',e)
}
function handleClose(e){
console.log('close',e)
}
function handleError(e){
console.log('error',e)
}
function handleConnect(ws){
console.log('connect',ws);
ws.on('message', handleMessage)
}
function handleMessage(msg){
console.log(msg)
}
})(ws)<file_sep>/promise详解.md
# 一. Promise
## 1、 为什么需要 promise
> 需求
后面的请求依赖前面请求的返回结果
> 回调地狱
在回调函数中嵌套回调
promise解决了回调地域问题
## 2、Promise的基本使用
Promise是一个构造函数,通过`new`关键字实例化对象
> 语法
```javascript
new Promise((resolve, reject) => {})
```
- `Promise` 接受一个函数作为参数
- 在参数函数中接受两个参数
- resolve
- reject
> Promise 实例
`promise` 实例有两个属性
- state:状态
- result:结果
### 1)promise状态
第一种状态:pending(准备,待解决,进行中)
第二种状态:fulfilled(已完成,成功)
第三种状态:rejected(已拒绝,失败)
### 2)promise状态的改变
通过调用 resolve() 和 reject() 改变promise对象的状态
> 示例
```javascript
const p = new Promise((resolve, reject) => {
// resolve(): 调用函数,是当前promise对象的状态改成fulfilled
// reject(): 调用函数,使当前promise对象的状态改成rejected
resolve()
})
```
- resolve(): 调用函数,使当前promise对象的状态改成fulfilled
- reject(): 调用函数,使当前promise对象的状态改成rejected
> promise状态的改变是一次性的
### 3)promise 结果
通过调用resolve(),reject(),传递函数,改变 当前promise对象的结果
> 示例
```javascript
const p = new Promise((resolve, reject) => {
resolve('成功的结果')
// reject('失败的结果')
})
```
## 3、Promise的方法
### 1)then 方法
> 示例
```javascript
const p = new Promise((resolve, reject) => {
// 通过调用resolve、reject,传递参数,改变当前对象的结果
resolve('成功的结果')
// reject(‘失败的结果’)
})
// then方法函数
// 参数
// 1、是一个函数
// 2、还是一个函数
// 返回值:是一个promise对象
p.then((value) => {
// 当promise的状态是fulfilled时,执行
}, (reason) => {
// 当promise的状态是rejected时,执行
})
```
- 在then方法的参数函数中,通过形参使用promise对象的结果
> then方法返回一个新的promise实例 状态为pending
> promise的状态不改变,不会执行then里面的方法
> 在then方法中,通过return将 返回的promise实例改为fulfilled状态
```javascript
const p = new Promise((resolve,reject) => {
resolve()
})
const t = p.then((val)=> {
// 使用return 可以将t实例的状态改成fulfilled
// return 123
// 如果这里的代码出错,会将t实例状态改成rejected
console.log(a)
}, () => {
})
t.then((val) => {
console.logn(val)
}, (reason) => {
console.logn(reason)
})
```
### 2)catch方法
> 示例
```javascript
const p = new Promise((resolve, reject) => {
reject('失败')
throw new Error('出错了')
})
// catch中的参数函数在什么时候被执行?
// 1、当promise的状态改成rejected时,被执行
// 2、当promise执行体中出现代码错误时,被执行
p.catch((reason) => {
})
```
## 4、promise.all 和 promise.race方法
### 1)promise.all
> Promise.all 方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。
```javascript
var p = Promise.all([p1,p2,p3]);
```
上面代码中,Promise.all 方法接受一个数组作为参数,p1、p2、p3 都是 Promise 对象的实例。(Promise.all 方法的参数不一定是数组,但是必须具有 iterator 接口,且返回的每个成员都是 Promise 实例。)
p 的状态由 p1、p2、p3 决定,分成两种情况。
- 只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。
- 只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。
### 2)promise.race
> Promise.race 方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例。
```js
var p = Promise.race([p1,p2,p3]);
```
上面代码中,只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的Promise实例的返回值,就传递给p的返回值。
如果Promise.all方法和Promise.race方法的参数,不是Promise实例,就会先调用下面讲到的Promise.resolve方法,将参数转为Promise实例,再进一步处理。
## Promise 优缺点
有了 Promise 对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。此外,Promise 对象提供统一的接口,使得控制异步操作更加容易。
Promise 也有一些缺点。首先,无法取消 Promise,一旦新建它就会立即执行,无法中途取消。其次,如果不设置回调函数,Promise 内部抛出的错误,不会反应到外部。第三,当处于 Pending 状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成)。
> Promise 对象的错误具有"冒泡"性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个 catch 语句捕获。
|
bf1e6cafe3d640dfeef14006a74358d6e938d05d
|
[
"Markdown",
"JavaScript"
] | 7
|
Markdown
|
zongzhu321/learnning
|
73d782ce6052a233f979362f5638c1e3b243c1bf
|
0424c83dde299c54713ac6fbceb1f7451ee2124e
|
refs/heads/master
|
<repo_name>lexicon-java-lang/projects<file_sep>/Builderkitchen/src/Noah.java
public class Noah implements Kitchen {
@Override
public void report() {
System.out.println("Jag vill titta på Film och jag vill spela spel ");
}
}
<file_sep>/untitled/src/Personal.java
public class Personal {
public static void main(String[] args) {
Kitchen callKichine=Kitchen.getInstance();
callKichine.dishwasher();
}
}
<file_sep>/src/Contract.java
public interface Contract {
public void calculateAmt();
public void setnumbers(double princ, double rate);
}
<file_sep>/untitled1/src/StudentDao.java
import java.util.ArrayList;
import java.util.List;
public interface StudentDao {
public List<Student> getAllStudents();
public Student getStudent(int rollno);
public void updateStudent(Student student);
public void delStudent(Student student);
}
<file_sep>/untitled1/src/StudentDaoImp.java
import java.util.ArrayList;
import java.util.List;
public class StudentDaoImp implements StudentDao {
List<Student> students;
public StudentDaoImp(){
students=new ArrayList<Student>();
Student student1=new Student("Biniam",01);
Student student2=new Student("Eden",02);
Student student3=new Student("Noah",03);
students.add(student1);
students.add(student2);
students.add(student3);
}
@Override
public List<Student> getAllStudents() {
return students;
}
@Override
public Student getStudent(int rollno) {
return students.get(rollno);
}
@Override
public void updateStudent(Student student) {
students.get(student.getRollno()).setName(student.getName());
}
@Override
public void delStudent(Student student) {
students.remove(student.getRollno());
System.out.println("studen [Rollno:"+student.getRollno()+"] is deleted from database ");
}
}
<file_sep>/src/Main.java
public class Main {
public static void main(String[] args) {
Contract call=new Sub();
call.setnumbers(10000,0.01);
Main call1=new Main();
call1.dowhile();
}
public void dowhile(){
int counter=0;
do {
System.out.print(counter);
counter++;
}while(counter <10);
}
}
<file_sep>/untitled2/src/Runninga.java
public class Runninga {
public static void main(String[] args) throws InterruptedException {
Första a=new Första();
Runnable r1=()->a.a();
Runnable r2=()->a.b();
Thread t1=new Thread(r1);
t1.start();
Thread t2=new Thread(r2);
t2.start();
t1.join();
t2.join();
}
}
<file_sep>/Builderkitchen/src/Eden.java
public class Eden implements Kitchen {
@Override
public void report() {
System.out.println("i am björn, and my work is washing goods and preparing food for my family");
}
}
|
58fc1b1230ae5b2d2f98288ebcb271defdd73c77
|
[
"Java"
] | 8
|
Java
|
lexicon-java-lang/projects
|
a441583e66a3f6ddd200f23c9ad0062723262271
|
bfa57da12f4bd7b99e55d79f549501cb27a52b39
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.